Eluza133 commited on
Commit
345fd63
·
verified ·
1 Parent(s): b8f7fe6

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +882 -466
app.py CHANGED
@@ -1,3 +1,4 @@
 
1
  from flask import Flask, render_template_string, request, redirect, url_for, session, flash, send_file, jsonify
2
  from flask_caching import Cache
3
  import json
@@ -12,12 +13,12 @@ import requests
12
  from io import BytesIO
13
 
14
  app = Flask(__name__)
15
-
16
- app.secret_key = os.getenv("FLASK_SECRET_KEY", "supersecretkey")
17
- DATA_FILE = 'cloud_data.json'
18
  REPO_ID = "Eluza133/Z1e1u"
19
  HF_TOKEN_WRITE = os.getenv("HF_TOKEN")
20
  HF_TOKEN_READ = os.getenv("HF_TOKEN_READ") or HF_TOKEN_WRITE
 
21
  cache = Cache(app, config={'CACHE_TYPE': 'simple'})
22
  logging.basicConfig(level=logging.INFO)
23
 
@@ -28,14 +29,14 @@ def load_data():
28
  with open(DATA_FILE, 'r', encoding='utf-8') as file:
29
  data = json.load(file)
30
  if not isinstance(data, dict):
31
- logging.warning("Данные не в формате dict, инициализация пустой базы")
32
  return {'users': {}, 'files': {}}
33
  data.setdefault('users', {})
34
  data.setdefault('files', {})
35
  logging.info("Данные успешно загружены")
36
  return data
37
  except Exception as e:
38
- logging.error(f"Ошибка при загрузке данных: {e}")
39
  return {'users': {}, 'files': {}}
40
 
41
  def save_data(data):
@@ -46,10 +47,13 @@ def save_data(data):
46
  cache.clear()
47
  logging.info("Данные сохранены и загружены на HF")
48
  except Exception as e:
49
- logging.error(f"Ошибка при сохранении данных: {e}")
50
  raise
51
 
52
  def upload_db_to_hf():
 
 
 
53
  try:
54
  api = HfApi()
55
  api.upload_file(
@@ -58,13 +62,19 @@ def upload_db_to_hf():
58
  repo_id=REPO_ID,
59
  repo_type="dataset",
60
  token=HF_TOKEN_WRITE,
61
- commit_message=f"Бэкап {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}"
62
  )
63
  logging.info("База данных загружена на Hugging Face")
64
  except Exception as e:
65
- logging.error(f"Ошибка при загрузке базы данных: {e}")
66
 
67
  def download_db_from_hf():
 
 
 
 
 
 
68
  try:
69
  hf_hub_download(
70
  repo_id=REPO_ID,
@@ -74,256 +84,395 @@ def download_db_from_hf():
74
  local_dir=".",
75
  local_dir_use_symlinks=False
76
  )
77
- logging.info("База данных скачана с Hugging Face")
78
  except Exception as e:
79
- logging.error(f"Ошибка при скачивании базы данных: {e}")
80
  if not os.path.exists(DATA_FILE):
81
  with open(DATA_FILE, 'w', encoding='utf-8') as f:
82
  json.dump({'users': {}, 'files': {}}, f)
 
 
83
 
84
  def periodic_backup():
85
  while True:
86
- upload_db_to_hf()
87
  time.sleep(1800)
 
 
 
 
 
 
 
88
 
89
  def get_file_type(filename):
90
- video_extensions = ('.mp4', '.mov', '.avi')
91
- image_extensions = ('.jpg', '.jpeg', '.png', '.gif')
92
- if filename.lower().endswith(video_extensions):
 
93
  return 'video'
94
- elif filename.lower().endswith(image_extensions):
95
  return 'image'
96
  return 'other'
97
 
98
  BASE_STYLE = '''
 
 
99
  :root {
100
- --primary: #6C63FF;
101
- --secondary: #00E1D4;
102
- --accent: #FF6B6B;
103
- --background: #0F0C29;
104
- --card-bg: rgba(30, 27, 75, 0.95);
105
- --text: #E0E7FF;
106
- --shadow: 0 15px 40px rgba(0, 0, 0, 0.4);
107
- --glass-bg: rgba(255, 255, 255, 0.1);
108
- --transition: all 0.4s cubic-bezier(0.68, -0.55, 0.265, 1.55);
 
 
 
 
 
 
 
 
109
  }
110
 
111
- * {
112
- margin: 0;
113
- padding: 0;
114
- box-sizing: border-box;
115
- }
116
 
117
  body {
118
- font-family: 'Poppins', sans-serif;
119
- background: linear-gradient(135deg, #0F0C29, #302B63);
120
- color: var(--text);
121
- line-height: 1.8;
122
- min-height: 100vh;
123
- overflow-x: hidden;
 
 
 
 
124
  }
125
 
126
  .container {
127
- margin: 40px auto;
128
- max-width: 1400px;
129
- padding: 30px;
130
  background: var(--card-bg);
131
- border-radius: 25px;
132
  box-shadow: var(--shadow);
133
- backdrop-filter: blur(10px);
134
- position: relative;
135
- z-index: 1;
 
 
 
 
 
136
  }
137
 
138
  h1 {
139
- font-size: 3em;
140
- font-weight: 900;
141
  text-align: center;
142
- margin-bottom: 30px;
143
  background: linear-gradient(135deg, var(--primary), var(--secondary));
144
  -webkit-background-clip: text;
145
  color: transparent;
146
- text-shadow: 0 5px 15px rgba(0, 0, 0, 0.3);
147
  }
148
 
149
  h2 {
150
- font-size: 2em;
151
- margin: 40px 0 20px;
152
- color: var(--text);
 
153
  font-weight: 600;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
154
  }
155
 
 
156
  input, textarea {
157
  width: 100%;
158
- padding: 16px;
159
- margin: 15px 0;
160
- border: 2px solid transparent;
161
- border-radius: 15px;
162
  background: var(--glass-bg);
163
- color: var(--text);
164
- font-size: 1.2em;
165
  transition: var(--transition);
166
- backdrop-filter: blur(5px);
 
 
 
 
 
 
 
167
  }
168
 
169
  input:focus, textarea:focus {
170
  outline: none;
171
  border-color: var(--primary);
172
- box-shadow: 0 0 15px var(--primary);
 
 
 
 
 
173
  }
174
 
175
  .btn {
176
- padding: 16px 32px;
177
- background: var(--primary);
178
- color: var(--text);
179
  border: none;
180
- border-radius: 15px;
181
  cursor: pointer;
182
- font-size: 1.2em;
183
- font-weight: 700;
184
  transition: var(--transition);
185
- box-shadow: var(--shadow);
186
  display: inline-block;
187
  text-decoration: none;
188
- position: relative;
189
- overflow: hidden;
190
- }
191
-
192
- .btn::before {
193
- content: '';
194
- position: absolute;
195
- top: 0;
196
- left: -100%;
197
- width: 100%;
198
- height: 100%;
199
- background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.3), transparent);
200
- transition: var(--transition);
201
- }
202
-
203
- .btn:hover::before {
204
- left: 100%;
205
  }
206
 
207
  .btn:hover {
208
- transform: translateY(-5px);
209
- background: var(--secondary);
210
- box-shadow: 0 20px 50px rgba(0, 0, 0, 0.5);
211
  }
212
 
213
  .download-btn {
214
- background: var(--secondary);
215
  }
216
-
217
  .download-btn:hover {
218
- background: var(--accent);
219
  }
220
 
221
  .delete-btn {
222
- background: var(--accent);
223
  }
224
-
225
  .delete-btn:hover {
226
- background: #FF4B4B;
227
  }
228
 
229
  .flash {
230
- color: var(--secondary);
231
- text-align: center;
232
  margin-bottom: 20px;
233
- font-size: 1.2em;
234
- animation: fadeIn 0.5s ease;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
235
  }
236
 
 
237
  .file-grid {
238
  display: grid;
239
- grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
240
  gap: 25px;
241
- margin-top: 30px;
242
  }
243
 
244
  .user-list {
245
- margin-top: 30px;
 
 
 
246
  }
247
 
248
  .user-item {
249
- padding: 20px;
250
- background: var(--glass-bg);
251
- border-radius: 20px;
252
- margin-bottom: 15px;
253
  box-shadow: var(--shadow);
254
  transition: var(--transition);
 
 
 
 
 
 
 
255
  }
256
 
257
  .user-item:hover {
258
- transform: translateY(-10px);
259
- box-shadow: 0 20px 50px rgba(0, 0, 0, 0.5);
260
  }
 
 
 
 
261
 
262
  .user-item a {
263
  color: var(--primary);
264
  text-decoration: none;
265
- font-weight: 600;
266
- font-size: 1.3em;
 
 
 
 
 
267
  }
268
 
269
  .user-item a:hover {
270
- color: var(--secondary);
271
  }
 
 
 
 
 
 
272
 
273
  @media (max-width: 768px) {
274
  .file-grid {
275
- grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
276
  }
 
 
 
277
  }
278
 
279
  @media (max-width: 480px) {
280
  .file-grid {
281
  grid-template-columns: 1fr;
282
  }
 
 
 
 
283
  }
284
 
285
  .file-item {
286
- background: var(--glass-bg);
287
- padding: 20px;
288
- border-radius: 20px;
289
  box-shadow: var(--shadow);
290
  text-align: center;
291
  transition: var(--transition);
292
- backdrop-filter: blur(8px);
 
 
 
 
 
 
 
 
 
293
  }
294
 
295
  .file-item:hover {
296
- transform: translateY(-10px);
297
- box-shadow: 0 20px 50px rgba(0, 0, 0, 0.5);
 
 
 
298
  }
299
 
300
- .file-preview {
301
- max-width: 100%;
302
- max-height: 250px;
303
- object-fit: cover;
304
- border-radius: 15px;
305
  margin-bottom: 15px;
306
- transition: var(--transition);
 
 
 
 
 
307
  cursor: pointer;
308
  }
 
 
 
309
 
310
- .file-preview:hover {
311
- transform: scale(1.05);
 
 
 
 
312
  }
313
 
314
- .file-item p {
315
- font-size: 1em;
316
- margin: 8px 0;
317
  }
318
 
319
- .file-item a {
 
 
 
 
 
 
 
 
 
320
  color: var(--primary);
321
- text-decoration: none;
 
 
 
322
  }
323
 
324
- .file-item a:hover {
325
- color: var(--secondary);
 
 
 
 
326
  }
 
 
 
 
 
 
 
327
 
328
  .modal {
329
  display: none;
@@ -336,52 +485,73 @@ input:focus, textarea:focus {
336
  z-index: 2000;
337
  justify-content: center;
338
  align-items: center;
339
- backdrop-filter: blur(5px);
 
 
 
 
 
 
 
 
 
 
340
  }
341
 
342
  .modal img, .modal video {
343
- max-width: 90%;
344
- max-height: 90%;
345
  object-fit: contain;
346
- border-radius: 25px;
347
- box-shadow: var(--shadow);
348
- animation: zoomIn 0.5s ease;
 
 
 
349
  }
350
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
351
  #progress-container {
352
  width: 100%;
 
353
  background: var(--glass-bg);
354
- border-radius: 15px;
355
  margin: 20px 0;
356
- display: none;
 
 
 
 
 
 
357
  }
358
 
359
  #progress-bar {
360
  width: 0%;
361
- height: 25px;
362
- background: linear-gradient(90deg, var(--primary), var(--secondary));
363
- border-radius: 15px;
364
- transition: width 0.5s ease;
365
- }
366
-
367
- @keyframes fadeIn {
368
- from { opacity: 0; }
369
- to { opacity: 1; }
370
- }
371
-
372
- @keyframes zoomIn {
373
- from { transform: scale(0.8); opacity: 0; }
374
- to { transform: scale(1); opacity: 1; }
375
- }
376
-
377
- .particles {
378
- position: fixed;
379
- top: 0;
380
- left: 0;
381
- width: 100%;
382
  height: 100%;
383
- pointer-events: none;
384
- z-index: 0;
 
 
 
 
 
 
385
  }
386
  '''
387
 
@@ -390,75 +560,59 @@ def register():
390
  if request.method == 'POST':
391
  username = request.form.get('username')
392
  password = request.form.get('password')
393
-
394
  data = load_data()
395
-
396
  if username in data['users']:
397
- flash('Пользователь с таким логином уже существует!')
398
  return redirect(url_for('register'))
399
-
400
  if not username or not password:
401
- flash('Логин и пароль обязательны!')
402
  return redirect(url_for('register'))
403
-
404
  data['users'][username] = {
405
  'password': password,
406
  'created_at': datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
407
  'files': []
408
  }
409
- save_data(data)
410
- session['username'] = username
411
- flash('Регистрация успешна!')
412
- return redirect(url_for('dashboard'))
413
-
 
 
 
 
414
  html = '''
415
  <!DOCTYPE html>
416
- <html lang="en">
417
  <head>
418
  <meta charset="UTF-8">
419
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
420
  <title>Регистрация - Zeus Cloud</title>
421
- <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;600;800&display=swap" rel="stylesheet">
422
  <style>''' + BASE_STYLE + '''</style>
423
  </head>
424
  <body>
425
- <div class="particles" id="particles-js"></div>
426
  <div class="container">
427
- <h1>Создать аккаунт</h1>
428
- {% with messages = get_flashed_messages() %}
 
429
  {% if messages %}
430
- {% for message in messages %}
431
- <div class="flash">{{ message }}</div>
432
  {% endfor %}
433
  {% endif %}
434
  {% endwith %}
435
  <form method="POST" id="register-form">
436
- <input type="text" name="username" placeholder="Логин" required>
437
- <input type="password" name="password" placeholder="Пароль" required>
438
  <button type="submit" class="btn">Зарегистрироваться</button>
439
  </form>
440
- <p style="margin-top: 25px; text-align: center;">Уже есть аккаунт? <a href="{{ url_for('login') }}">Войти</a></p>
441
  </div>
442
- <script src="https://cdn.jsdelivr.net/particles.js/2.0.0/particles.min.js"></script>
443
- <script>
444
- particlesJS("particles-js", {
445
- particles: {
446
- number: { value: 80, density: { enable: true, value_area: 800 } },
447
- color: { value: "#6C63FF" },
448
- shape: { type: "circle" },
449
- opacity: { value: 0.5, random: true },
450
- size: { value: 3, random: true },
451
- line_linked: { enable: true, distance: 150, color: "#00E1D4", opacity: 0.4, width: 1 },
452
- move: { enable: true, speed: 2, direction: "none", random: true }
453
- },
454
- interactivity: {
455
- detect_on: "canvas",
456
- events: { onhover: { enable: true, mode: "grab" }, onclick: { enable: true, mode: "push" } },
457
- modes: { grab: { distance: 200, line_linked: { opacity: 1 } }, push: { particles_nb: 4 } }
458
- },
459
- retina_detect: true
460
- });
461
- </script>
462
  </body>
463
  </html>
464
  '''
@@ -470,62 +624,44 @@ def login():
470
  username = request.form.get('username')
471
  password = request.form.get('password')
472
  data = load_data()
473
-
474
- if username in data['users'] and data['users'][username]['password'] == password:
475
  session['username'] = username
476
  return jsonify({'status': 'success', 'redirect': url_for('dashboard')})
477
  else:
478
- return jsonify({'status': 'error', 'message': 'Неверный логин или пароль!'})
479
-
480
  html = '''
481
  <!DOCTYPE html>
482
- <html lang="en">
483
  <head>
484
  <meta charset="UTF-8">
485
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
486
- <title>Zeus Cloud</title>
487
- <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;600;800&display=swap" rel="stylesheet">
488
  <style>''' + BASE_STYLE + '''</style>
489
  </head>
490
  <body>
491
- <div class="particles" id="particles-js"></div>
492
  <div class="container">
493
  <h1>Zeus Cloud</h1>
 
494
  <div id="flash-messages">
495
- {% with messages = get_flashed_messages() %}
496
  {% if messages %}
497
- {% for message in messages %}
498
- <div class="flash">{{ message }}</div>
499
  {% endfor %}
500
  {% endif %}
501
  {% endwith %}
502
  </div>
503
  <form method="POST" id="login-form">
504
- <input type="text" name="username" placeholder="Логин" required>
505
- <input type="password" name="password" placeholder="Пароль" required>
506
  <button type="submit" class="btn">Войти</button>
507
  </form>
508
- <p style="margin-top: 25px; text-align: center;">Нет аккаунта? <a href="{{ url_for('register') }}">Зарегистрироваться</a></p>
509
  </div>
510
- <script src="https://cdn.jsdelivr.net/particles.js/2.0.0/particles.min.js"></script>
511
  <script>
512
- particlesJS("particles-js", {
513
- particles: {
514
- number: { value: 80, density: { enable: true, value_area: 800 } },
515
- color: { value: "#6C63FF" },
516
- shape: { type: "circle" },
517
- opacity: { value: 0.5, random: true },
518
- size: { value: 3, random: true },
519
- line_linked: { enable: true, distance: 150, color: "#00E1D4", opacity: 0.4, width: 1 },
520
- move: { enable: true, speed: 2, direction: "none", random: true }
521
- },
522
- interactivity: {
523
- detect_on: "canvas",
524
- events: { onhover: { enable: true, mode: "grab" }, onclick: { enable: true, mode: "push" } },
525
- modes: { grab: { distance: 200, line_linked: { opacity: 1 } }, push: { particles_nb: 4 } }
526
- },
527
- retina_detect: true
528
- });
529
 
530
  const savedCredentials = JSON.parse(localStorage.getItem('zeusCredentials'));
531
  if (savedCredentials) {
@@ -542,12 +678,15 @@ def login():
542
  window.location.href = data.redirect;
543
  }
544
  })
545
- .catch(error => console.error('Ошибка автоматического входа:', error));
546
  }
547
 
548
  document.getElementById('login-form').addEventListener('submit', function(e) {
549
  e.preventDefault();
550
  const formData = new FormData(this);
 
 
 
551
  fetch('/', {
552
  method: 'POST',
553
  body: formData
@@ -560,11 +699,11 @@ def login():
560
  localStorage.setItem('zeusCredentials', JSON.stringify({ username, password }));
561
  window.location.href = data.redirect;
562
  } else {
563
- document.getElementById('flash-messages').innerHTML = `<div class="flash">${data.message}</div>`;
564
  }
565
  })
566
  .catch(error => {
567
- document.getElementById('flash-messages').innerHTML = `<div class="flash">Ошибка соединения!</div>`;
568
  });
569
  });
570
  </script>
@@ -573,159 +712,276 @@ def login():
573
  '''
574
  return render_template_string(html)
575
 
 
576
  @app.route('/dashboard', methods=['GET', 'POST'])
577
  def dashboard():
578
  if 'username' not in session:
579
- flash('Пожалуйста, войдите!')
580
  return redirect(url_for('login'))
581
-
582
  username = session['username']
583
  data = load_data()
584
- if username not in data['users']:
585
  session.pop('username', None)
586
- flash('Пользователь не найден!')
 
587
  return redirect(url_for('login'))
588
-
589
- user_files = sorted(data['users'][username]['files'], key=lambda x: x['upload_date'], reverse=True)
590
 
591
  if request.method == 'POST':
592
  files = request.files.getlist('files')
593
- if files and len(files) > 20:
594
- flash('Максимум 20 файлов за раз!')
 
 
 
 
595
  return redirect(url_for('dashboard'))
596
-
597
- if files:
598
- os.makedirs('uploads', exist_ok=True)
599
- api = HfApi()
600
- temp_files = []
601
-
602
- for file in files:
603
- if file and file.filename:
604
- filename = secure_filename(file.filename)
605
- temp_path = os.path.join('uploads', filename)
 
 
 
 
 
 
606
  file.save(temp_path)
607
- temp_files.append((temp_path, filename))
608
-
609
- for temp_path, filename in temp_files:
610
- file_path = f"cloud_files/{username}/{filename}"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
611
  api.upload_file(
612
  path_or_fileobj=temp_path,
613
- path_in_repo=file_path,
614
  repo_id=REPO_ID,
615
  repo_type="dataset",
616
  token=HF_TOKEN_WRITE,
617
- commit_message=f"Загружен файл для {username}"
618
  )
619
-
620
  file_info = {
621
  'filename': filename,
622
- 'path': file_path,
623
  'type': get_file_type(filename),
624
  'upload_date': datetime.now().strftime('%Y-%m-%d %H:%M:%S')
625
  }
626
- data['users'][username]['files'].append(file_info)
627
-
 
 
 
 
 
 
 
 
 
628
  if os.path.exists(temp_path):
629
- os.remove(temp_path)
630
-
631
- save_data(data)
632
- flash('Файлы успешно загружены!')
633
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
634
  return redirect(url_for('dashboard'))
635
 
 
 
 
 
636
  html = '''
637
  <!DOCTYPE html>
638
- <html lang="en">
639
  <head>
640
  <meta charset="UTF-8">
641
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
642
- <title>Dashboard - Zeus Cloud</title>
643
- <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;600;800&display=swap" rel="stylesheet">
644
  <style>''' + BASE_STYLE + '''</style>
645
  </head>
646
  <body>
647
- <div class="particles" id="particles-js"></div>
648
  <div class="container">
649
- <h1>Zeus Cloud Dashboard</h1>
650
- <p style="font-size: 1.2em;">Добро пожаловать, {{ username }}</p>
651
- {% with messages = get_flashed_messages() %}
 
 
 
652
  {% if messages %}
653
- {% for message in messages %}
654
- <div class="flash">{{ message }}</div>
655
  {% endfor %}
656
  {% endif %}
657
  {% endwith %}
658
- <form id="upload-form" method="POST" enctype="multipart/form-data">
659
- <input type="file" name="files" multiple required accept="image/*,video/*">
660
- <button type="submit" class="btn" id="upload-btn">Загрузить файлы</button>
 
 
 
661
  </form>
 
662
  <div id="progress-container">
663
- <div id="progress-bar"></div>
664
  </div>
 
665
  <h2>Ваши файлы</h2>
666
  <div class="file-grid">
667
  {% for file in user_files %}
668
  <div class="file-item">
669
- {% if file['type'] == 'video' %}
670
- <video class="file-preview" preload="metadata" muted loading="lazy" onclick="openModal('https://huggingface.co/datasets/{{ repo_id }}/resolve/main/{{ file['path'] }}', true)">
671
- <source src="https://huggingface.co/datasets/{{ repo_id }}/resolve/main/{{ file['path'] }}" type="video/mp4">
672
- </video>
673
- {% elif file['type'] == 'image' %}
674
- <img class="file-preview" src="https://huggingface.co/datasets/{{ repo_id }}/resolve/main/{{ file['path'] }}" alt="{{ file['filename'] }}" loading="lazy" onclick="openModal(this.src, false)">
675
- {% else %}
676
- <p>{{ file['filename'] }}</p>
677
- {% endif %}
678
- <p>{{ file['upload_date'] }}</p>
679
- <a href="{{ url_for('download_file', file_path=file['path'], filename=file['filename']) }}" class="btn download-btn">Скачать</a>
680
- <a href="{{ url_for('delete_file', file_path=file['path']) }}" class="btn delete-btn" onclick="return confirm('Вы уверены, что хотите удалить этот файл?');">Удалить</a>
 
 
 
 
 
 
 
 
 
681
  </div>
682
  {% endfor %}
683
  {% if not user_files %}
684
- <p>У вас пока нет загруженных файлов.</p>
685
  {% endif %}
686
  </div>
687
- <a href="{{ url_for('logout') }}" class="btn" style="margin-top: 30px;" id="logout-btn">Выйти</a>
688
  </div>
689
- <div class="modal" id="mediaModal" onclick="closeModal(event)">
690
- <div id="modalContent"></div>
 
 
 
 
691
  </div>
692
- <script src="https://cdn.jsdelivr.net/particles.js/2.0.0/particles.min.js"></script>
693
  <script>
694
- particlesJS("particles-js", {
695
- particles: {
696
- number: { value: 80, density: { enable: true, value_area: 800 } },
697
- color: { value: "#6C63FF" },
698
- shape: { type: "circle" },
699
- opacity: { value: 0.5, random: true },
700
- size: { value: 3, random: true },
701
- line_linked: { enable: true, distance: 150, color: "#00E1D4", opacity: 0.4, width: 1 },
702
- move: { enable: true, speed: 2, direction: "none", random: true }
703
- },
704
- interactivity: {
705
- detect_on: "canvas",
706
- events: { onhover: { enable: true, mode: "grab" }, onclick: { enable: true, mode: "push" } },
707
- modes: { grab: { distance: 200, line_linked: { opacity: 1 } }, push: { particles_nb: 4 } }
708
- },
709
- retina_detect: true
 
710
  });
711
 
712
- function openModal(src, isVideo) {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
713
  const modal = document.getElementById('mediaModal');
714
- const modalContent = document.getElementById('modalContent');
715
- if (isVideo) {
716
- modalContent.innerHTML = `<video controls><source src="${src}" type="video/mp4"></video>`;
 
 
 
 
717
  } else {
718
- modalContent.innerHTML = `<img src="${src}">`;
 
 
719
  }
720
  modal.style.display = 'flex';
 
721
  }
722
- function closeModal(event) {
723
- if (event.target.tagName !== 'IMG' && event.target.tagName !== 'VIDEO') {
724
- const modal = document.getElementById('mediaModal');
725
- modal.style.display = 'none';
726
- modal.innerHTML = '<div id="modalContent"></div>';
727
- }
 
728
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
729
 
730
  const form = document.getElementById('upload-form');
731
  const progressBar = document.getElementById('progress-bar');
@@ -734,41 +990,51 @@ def dashboard():
734
 
735
  form.addEventListener('submit', function(e) {
736
  e.preventDefault();
737
- const files = form.querySelector('input[type="file"]').files;
 
 
 
 
738
  if (files.length > 20) {
739
- alert('Максимум 20 файлов за раз!');
740
  return;
741
  }
742
 
743
  const formData = new FormData(form);
744
  progressContainer.style.display = 'block';
745
  progressBar.style.width = '0%';
 
746
  uploadBtn.disabled = true;
 
 
747
 
748
  const xhr = new XMLHttpRequest();
749
  xhr.open('POST', '/dashboard', true);
750
 
751
  xhr.upload.onprogress = function(event) {
752
  if (event.lengthComputable) {
753
- const percent = (event.loaded / event.total) * 100;
754
  progressBar.style.width = percent + '%';
 
755
  }
756
  };
757
 
758
  xhr.onload = function() {
759
- if (xhr.status === 200) {
760
- location.reload();
761
- } else {
762
- alert('Ошибка загрузки!');
763
- progressContainer.style.display = 'none';
764
- uploadBtn.disabled = false;
765
- }
 
766
  };
767
 
768
  xhr.onerror = function() {
769
- alert('Ошибка соединения!');
770
  progressContainer.style.display = 'none';
771
  uploadBtn.disabled = false;
 
772
  };
773
 
774
  xhr.send(formData);
@@ -776,8 +1042,8 @@ def dashboard():
776
 
777
  document.getElementById('logout-btn').addEventListener('click', function(e) {
778
  e.preventDefault();
779
- localStorage.removeItem('zeusCredentials');
780
- window.location.href = '/logout';
781
  });
782
  </script>
783
  </body>
@@ -785,108 +1051,200 @@ def dashboard():
785
  '''
786
  return render_template_string(html, username=username, user_files=user_files, repo_id=REPO_ID)
787
 
 
788
  @app.route('/download/<path:file_path>/<filename>')
789
  def download_file(file_path, filename):
790
  if 'username' not in session:
791
- flash('Пожалуйста, войдите!')
792
  return redirect(url_for('login'))
793
-
794
  username = session['username']
795
  data = load_data()
796
- if username not in data['users']:
797
  session.pop('username', None)
798
- flash('Пользователь не найден!')
 
799
  return redirect(url_for('login'))
800
-
801
- user_files = data['users'][username]['files']
802
- if not any(file['path'] == file_path for file in user_files):
803
- flash('У вас нет доступа к этому файлу!')
 
 
 
 
 
 
 
 
 
 
804
  return redirect(url_for('dashboard'))
805
-
 
 
 
 
 
806
  file_url = f"https://huggingface.co/datasets/{REPO_ID}/resolve/main/{file_path}"
807
- response = requests.get(file_url)
808
-
809
- if response.status_code == 200:
810
- file_content = BytesIO(response.content)
811
- return send_file(
812
- file_content,
813
- as_attachment=True,
814
- download_name=filename,
815
- mimetype='application/octet-stream'
816
- )
817
- else:
818
- flash('Ошибка при скачивании файла!')
819
- return redirect(url_for('dashboard'))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
820
 
821
  @app.route('/delete/<path:file_path>')
822
  def delete_file(file_path):
823
  if 'username' not in session:
824
- flash('Пожалуйста, войдите!')
825
  return redirect(url_for('login'))
826
-
827
  username = session['username']
828
  data = load_data()
829
- if username not in data['users']:
830
  session.pop('username', None)
831
- flash('Пользователь не найден!')
 
832
  return redirect(url_for('login'))
833
-
834
- user_files = data['users'][username]['files']
835
- file_to_delete = next((file for file in user_files if file['path'] == file_path), None)
836
-
837
- if not file_to_delete:
838
- flash('Файл не найден!')
 
 
 
 
839
  return redirect(url_for('dashboard'))
840
-
 
 
 
 
 
 
 
841
  try:
842
  api = HfApi()
 
843
  api.delete_file(
844
  path_in_repo=file_path,
845
  repo_id=REPO_ID,
846
  repo_type="dataset",
847
  token=HF_TOKEN_WRITE,
848
- commit_message=f"Удален файл {file_path} для {username}"
849
  )
850
- data['users'][username]['files'] = [f for f in user_files if f['path'] != file_path]
 
 
 
851
  save_data(data)
852
- flash('Файл успешно удален!')
 
853
  except Exception as e:
854
- logging.error(f"Ошибка при удалении файла: {e}")
855
- flash('Ошибка при удалении файла!')
856
-
 
 
 
 
 
 
 
 
 
 
 
 
857
  return redirect(url_for('dashboard'))
858
 
859
  @app.route('/logout')
860
  def logout():
861
  session.pop('username', None)
 
 
862
  return redirect(url_for('login'))
863
 
 
864
  @app.route('/admhosto')
865
  def admin_panel():
 
 
 
866
  data = load_data()
867
- users = data['users']
868
-
 
 
 
869
  html = '''
870
  <!DOCTYPE html>
871
- <html lang="en">
872
  <head>
873
  <meta charset="UTF-8">
874
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
875
- <title>Админ-панель - Zeus Cloud</title>
876
- <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;600;800&display=swap" rel="stylesheet">
877
  <style>''' + BASE_STYLE + '''</style>
878
  </head>
879
  <body>
880
- <div class="particles" id="particles-js"></div>
881
  <div class="container">
882
- <h1>Админ-панель Zeus Cloud</h1>
883
- <h2>Пользователи</h2>
 
884
  <div class="user-list">
885
  {% for username, user_data in users.items() %}
886
  <div class="user-item">
887
  <a href="{{ url_for('admin_user_files', username=username) }}">{{ username }}</a>
888
- <p>Дата регистрации: {{ user_data['created_at'] }}</p>
889
- <p>Файлов: {{ user_data['files'] | length }}</p>
 
890
  </div>
891
  {% endfor %}
892
  {% if not users %}
@@ -894,25 +1252,28 @@ def admin_panel():
894
  {% endif %}
895
  </div>
896
  </div>
897
- <script src="https://cdn.jsdelivr.net/particles.js/2.0.0/particles.min.js"></script>
898
- <script>
899
- particlesJS("particles-js", {
900
- particles: {
901
- number: { value: 80, density: { enable: true, value_area: 800 } },
902
- color: { value: "#6C63FF" },
903
- shape: { type: "circle" },
904
- opacity: { value: 0.5, random: true },
905
- size: { value: 3, random: true },
906
- line_linked: { enable: true, distance: 150, color: "#00E1D4", opacity: 0.4, width: 1 },
907
- move: { enable: true, speed: 2, direction: "none", random: true }
908
- },
909
- interactivity: {
910
- detect_on: "canvas",
911
- events: { onhover: { enable: true, mode: "grab" }, onclick: { enable: true, mode: "push" } },
912
- modes: { grab: { distance: 200, line_linked: { opacity: 1 } }, push: { particles_nb: 4 } }
913
- },
914
- retina_detect: true
 
 
915
  });
 
916
  </script>
917
  </body>
918
  </html>
@@ -921,102 +1282,157 @@ def admin_panel():
921
 
922
  @app.route('/admhosto/user/<username>')
923
  def admin_user_files(username):
 
924
  data = load_data()
925
- if username not in data['users']:
926
- flash('Пользователь не найден!')
927
  return redirect(url_for('admin_panel'))
928
-
929
- user_files = sorted(data['users'][username]['files'], key=lambda x: x['upload_date'], reverse=True)
930
-
 
931
  html = '''
932
  <!DOCTYPE html>
933
- <html lang="en">
934
  <head>
935
  <meta charset="UTF-8">
936
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
937
  <title>Файлы пользователя {{ username }} - Zeus Cloud</title>
938
- <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;600;800&display=swap" rel="stylesheet">
939
- <style>''' + BASE_STYLE + '''</style>
940
  </head>
941
  <body>
942
- <div class="particles" id="particles-js"></div>
943
  <div class="container">
944
- <h1>Файлы пользователя: {{ username }}</h1>
945
- {% with messages = get_flashed_messages() %}
 
946
  {% if messages %}
947
- {% for message in messages %}
948
- <div class="flash">{{ message }}</div>
949
  {% endfor %}
950
  {% endif %}
951
  {% endwith %}
 
952
  <div class="file-grid">
953
  {% for file in user_files %}
954
- <div class="file-item">
955
- {% if file['type'] == 'video' %}
956
- <video class="file-preview" preload="metadata" muted loading="lazy" onclick="openModal('https://huggingface.co/datasets/{{ repo_id }}/resolve/main/{{ file['path'] }}', true)">
957
- <source src="https://huggingface.co/datasets/{{ repo_id }}/resolve/main/{{ file['path'] }}" type="video/mp4">
958
- </video>
959
- {% elif file['type'] == 'image' %}
960
- <img class="file-preview" src="https://huggingface.co/datasets/{{ repo_id }}/resolve/main/{{ file['path'] }}" alt="{{ file['filename'] }}" loading="lazy" onclick="openModal(this.src, false)">
961
- {% else %}
962
- <p>{{ file['filename'] }}</p>
963
- {% endif %}
964
- <p>{{ file['upload_date'] }}</p>
965
- <a href="{{ url_for('download_file', file_path=file['path'], filename=file['filename']) }}" class="btn download-btn">Скачать</a>
 
 
 
 
 
 
 
 
 
 
 
966
  </div>
967
  {% endfor %}
968
  {% if not user_files %}
969
- <p>У пользователя пока нет файлов.</p>
970
  {% endif %}
971
  </div>
972
- <a href="{{ url_for('admin_panel') }}" class="btn" style="margin-top: 30px;">Назад</a>
973
  </div>
974
- <div class="modal" id="mediaModal" onclick="closeModal(event)">
975
- <div id="modalContent"></div>
 
 
 
 
976
  </div>
977
- <script src="https://cdn.jsdelivr.net/particles.js/2.0.0/particles.min.js"></script>
978
- <script>
979
- particlesJS("particles-js", {
980
- particles: {
981
- number: { value: 80, density: { enable: true, value_area: 800 } },
982
- color: { value: "#6C63FF" },
983
- shape: { type: "circle" },
984
- opacity: { value: 0.5, random: true },
985
- size: { value: 3, random: true },
986
- line_linked: { enable: true, distance: 150, color: "#00E1D4", opacity: 0.4, width: 1 },
987
- move: { enable: true, speed: 2, direction: "none", random: true }
988
- },
989
- interactivity: {
990
- detect_on: "canvas",
991
- events: { onhover: { enable: true, mode: "grab" }, onclick: { enable: true, mode: "push" } },
992
- modes: { grab: { distance: 200, line_linked: { opacity: 1 } }, push: { particles_nb: 4 } }
993
- },
994
- retina_detect: true
995
- });
996
 
997
- function openModal(src, isVideo) {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
998
  const modal = document.getElementById('mediaModal');
999
- const modalContent = document.getElementById('modalContent');
1000
- if (isVideo) {
1001
- modalContent.innerHTML = `<video controls><source src="${src}" type="video/mp4"></video>`;
 
 
 
 
1002
  } else {
1003
- modalContent.innerHTML = `<img src="${src}">`;
1004
  }
1005
  modal.style.display = 'flex';
 
1006
  }
1007
- function closeModal(event) {
1008
- if (event.target.tagName !== 'IMG' && event.target.tagName !== 'VIDEO') {
1009
- const modal = document.getElementById('mediaModal');
1010
- modal.style.display = 'none';
1011
- modal.innerHTML = '<div id="modalContent"></div>';
1012
- }
 
1013
  }
 
 
 
 
 
 
 
 
 
 
1014
  </script>
1015
  </body>
1016
  </html>
1017
  '''
1018
  return render_template_string(html, username=username, user_files=user_files, repo_id=REPO_ID)
1019
 
 
1020
  if __name__ == '__main__':
1021
- threading.Thread(target=periodic_backup, daemon=True).start()
1022
- app.run(debug=False, host='0.0.0.0', port=7860)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
  from flask import Flask, render_template_string, request, redirect, url_for, session, flash, send_file, jsonify
3
  from flask_caching import Cache
4
  import json
 
13
  from io import BytesIO
14
 
15
  app = Flask(__name__)
16
+ app.secret_key = os.getenv("FLASK_SECRET_KEY", "supersecretkey_but_in_russian")
17
+ DATA_FILE = 'cloudeng_data.json'
 
18
  REPO_ID = "Eluza133/Z1e1u"
19
  HF_TOKEN_WRITE = os.getenv("HF_TOKEN")
20
  HF_TOKEN_READ = os.getenv("HF_TOKEN_READ") or HF_TOKEN_WRITE
21
+
22
  cache = Cache(app, config={'CACHE_TYPE': 'simple'})
23
  logging.basicConfig(level=logging.INFO)
24
 
 
29
  with open(DATA_FILE, 'r', encoding='utf-8') as file:
30
  data = json.load(file)
31
  if not isinstance(data, dict):
32
+ logging.warning("Данные не в формате dict, инициализация пустой базы данных")
33
  return {'users': {}, 'files': {}}
34
  data.setdefault('users', {})
35
  data.setdefault('files', {})
36
  logging.info("Данные успешно загружены")
37
  return data
38
  except Exception as e:
39
+ logging.error(f"Ошибка загрузки данных: {e}")
40
  return {'users': {}, 'files': {}}
41
 
42
  def save_data(data):
 
47
  cache.clear()
48
  logging.info("Данные сохранены и загружены на HF")
49
  except Exception as e:
50
+ logging.error(f"Ошибка сохранения данных: {e}")
51
  raise
52
 
53
  def upload_db_to_hf():
54
+ if not HF_TOKEN_WRITE:
55
+ logging.warning("HF_TOKEN (write) не установлен. Пропуск загрузки на Hugging Face.")
56
+ return
57
  try:
58
  api = HfApi()
59
  api.upload_file(
 
62
  repo_id=REPO_ID,
63
  repo_type="dataset",
64
  token=HF_TOKEN_WRITE,
65
+ commit_message=f"Резервная копия {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}"
66
  )
67
  logging.info("База данных загружена на Hugging Face")
68
  except Exception as e:
69
+ logging.error(f"Ошибка загрузки базы данных: {e}")
70
 
71
  def download_db_from_hf():
72
+ if not HF_TOKEN_READ:
73
+ logging.warning("HF_TOKEN_READ не установлен. Пропуск загрузки с Hugging Face.")
74
+ if not os.path.exists(DATA_FILE):
75
+ with open(DATA_FILE, 'w', encoding='utf-8') as f:
76
+ json.dump({'users': {}, 'files': {}}, f)
77
+ return
78
  try:
79
  hf_hub_download(
80
  repo_id=REPO_ID,
 
84
  local_dir=".",
85
  local_dir_use_symlinks=False
86
  )
87
+ logging.info("База данных загружена с Hugging Face")
88
  except Exception as e:
89
+ logging.error(f"Ошибка загрузки базы данных: {e}")
90
  if not os.path.exists(DATA_FILE):
91
  with open(DATA_FILE, 'w', encoding='utf-8') as f:
92
  json.dump({'users': {}, 'files': {}}, f)
93
+ logging.info("Создан пустой файл базы данных.")
94
+
95
 
96
  def periodic_backup():
97
  while True:
 
98
  time.sleep(1800)
99
+ logging.info("Запуск периодического резервного копирования...")
100
+ try:
101
+ data = load_data()
102
+ save_data(data)
103
+ except Exception as e:
104
+ logging.error(f"Ошибка во время периодического резервного копирования: {e}")
105
+
106
 
107
  def get_file_type(filename):
108
+ video_extensions = ('.mp4', '.mov', '.avi', '.webm', '.mkv')
109
+ image_extensions = ('.jpg', '.jpeg', '.png', '.gif', '.bmp', '.webp')
110
+ filename_lower = filename.lower()
111
+ if filename_lower.endswith(video_extensions):
112
  return 'video'
113
+ elif filename_lower.endswith(image_extensions):
114
  return 'image'
115
  return 'other'
116
 
117
  BASE_STYLE = '''
118
+ @import url('https://fonts.googleapis.com/css2?family=Montserrat:wght@400;600;700&display=swap');
119
+
120
  :root {
121
+ --primary: #6a11cb; /* Deep purple */
122
+ --secondary: #2575fc; /* Bright blue */
123
+ --accent: #fcb045; /* Gold accent */
124
+ --background-light: #f0f2f5; /* Softer light background */
125
+ --background-dark: #121212; /* True dark background */
126
+ --card-bg: #ffffff;
127
+ --card-bg-dark: #1e1e1e; /* Slightly lighter dark card */
128
+ --text-light: #333333;
129
+ --text-dark: #e0e0e0;
130
+ --shadow: 0 12px 28px rgba(0, 0, 0, 0.12), 0 8px 10px rgba(0, 0, 0, 0.1);
131
+ --shadow-dark: 0 12px 28px rgba(0, 0, 0, 0.3), 0 8px 10px rgba(0, 0, 0, 0.25);
132
+ --glass-bg: rgba(255, 255, 255, 0.3);
133
+ --glass-bg-dark: rgba(40, 40, 40, 0.4);
134
+ --transition: all 0.35s cubic-bezier(0.25, 0.8, 0.25, 1);
135
+ --delete-color: #ff4d4f; /* Ant Design Red */
136
+ --border-radius-main: 16px;
137
+ --border-radius-small: 12px;
138
  }
139
 
140
+ * { margin: 0; padding: 0; box-sizing: border-box; }
 
 
 
 
141
 
142
  body {
143
+ font-family: 'Montserrat', sans-serif;
144
+ background: linear-gradient(135deg, var(--background-light), #e6e9ed);
145
+ color: var(--text-light);
146
+ line-height: 1.7;
147
+ transition: background 0.3s, color 0.3s;
148
+ }
149
+
150
+ body.dark {
151
+ background: linear-gradient(135deg, var(--background-dark), #1c1c1c);
152
+ color: var(--text-dark);
153
  }
154
 
155
  .container {
156
+ margin: 30px auto;
157
+ max-width: 1300px;
158
+ padding: 35px 40px;
159
  background: var(--card-bg);
160
+ border-radius: var(--border-radius-main);
161
  box-shadow: var(--shadow);
162
+ transition: var(--transition);
163
+ border: 1px solid rgba(0, 0, 0, 0.05);
164
+ }
165
+
166
+ body.dark .container {
167
+ background: var(--card-bg-dark);
168
+ box-shadow: var(--shadow-dark);
169
+ border: 1px solid rgba(255, 255, 255, 0.1);
170
  }
171
 
172
  h1 {
173
+ font-size: 2.8em;
174
+ font-weight: 700;
175
  text-align: center;
176
+ margin-bottom: 20px;
177
  background: linear-gradient(135deg, var(--primary), var(--secondary));
178
  -webkit-background-clip: text;
179
  color: transparent;
180
+ padding-bottom: 10px; /* Space for slogan */
181
  }
182
 
183
  h2 {
184
+ font-size: 1.8em;
185
+ margin-top: 35px;
186
+ margin-bottom: 15px;
187
+ color: var(--text-light);
188
  font-weight: 600;
189
+ border-bottom: 2px solid var(--primary);
190
+ padding-bottom: 8px;
191
+ display: inline-block;
192
+ }
193
+
194
+ body.dark h2 {
195
+ color: var(--text-dark);
196
+ border-bottom-color: var(--secondary);
197
+ }
198
+
199
+ .slogan {
200
+ text-align: center;
201
+ margin-top: -15px; /* Position under h1 */
202
+ margin-bottom: 30px;
203
+ font-style: italic;
204
+ opacity: 0.7;
205
+ font-weight: 400;
206
+ font-size: 1.1em;
207
+ color: var(--primary);
208
+ }
209
+ body.dark .slogan {
210
+ color: var(--secondary);
211
+ opacity: 0.8;
212
  }
213
 
214
+
215
  input, textarea {
216
  width: 100%;
217
+ padding: 16px 18px;
218
+ margin: 14px 0;
219
+ border: 1px solid #ddd;
220
+ border-radius: var(--border-radius-small);
221
  background: var(--glass-bg);
222
+ color: var(--text-light);
223
+ font-size: 1.1em;
224
  transition: var(--transition);
225
+ box-shadow: inset 0 2px 4px rgba(0, 0, 0, 0.06);
226
+ }
227
+
228
+ body.dark input, body.dark textarea {
229
+ color: var(--text-dark);
230
+ background: var(--glass-bg-dark);
231
+ border-color: #444;
232
+ box-shadow: inset 0 2px 4px rgba(0, 0, 0, 0.15);
233
  }
234
 
235
  input:focus, textarea:focus {
236
  outline: none;
237
  border-color: var(--primary);
238
+ box-shadow: 0 0 0 3px rgba(106, 17, 203, 0.2); /* Focus ring */
239
+ }
240
+
241
+ body.dark input:focus, body.dark textarea:focus {
242
+ border-color: var(--secondary);
243
+ box-shadow: 0 0 0 3px rgba(37, 117, 252, 0.25);
244
  }
245
 
246
  .btn {
247
+ padding: 15px 35px;
248
+ background: linear-gradient(135deg, var(--primary), var(--secondary));
249
+ color: white;
250
  border: none;
251
+ border-radius: var(--border-radius-small);
252
  cursor: pointer;
253
+ font-size: 1.15em;
254
+ font-weight: 600;
255
  transition: var(--transition);
256
+ box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
257
  display: inline-block;
258
  text-decoration: none;
259
+ text-align: center;
260
+ margin-right: 10px; /* Spacing between buttons */
261
+ margin-bottom: 10px;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
262
  }
263
 
264
  .btn:hover {
265
+ transform: translateY(-3px) scale(1.03);
266
+ box-shadow: 0 8px 25px rgba(106, 17, 203, 0.3);
267
+ filter: brightness(1.1);
268
  }
269
 
270
  .download-btn {
271
+ background: linear-gradient(135deg, #00c6ff, #0072ff); /* Blue gradient */
272
  }
 
273
  .download-btn:hover {
274
+ box-shadow: 0 8px 25px rgba(0, 114, 255, 0.3);
275
  }
276
 
277
  .delete-btn {
278
+ background: linear-gradient(135deg, #ff758c, var(--delete-color)); /* Red/Pink gradient */
279
  }
 
280
  .delete-btn:hover {
281
+ box-shadow: 0 8px 25px rgba(255, 77, 79, 0.3);
282
  }
283
 
284
  .flash {
285
+ padding: 15px 20px;
 
286
  margin-bottom: 20px;
287
+ border-radius: var(--border-radius-small);
288
+ text-align: center;
289
+ font-weight: 600;
290
+ background-color: rgba(37, 117, 252, 0.1); /* Light blue bg */
291
+ color: var(--secondary);
292
+ border: 1px solid rgba(37, 117, 252, 0.3);
293
+ }
294
+ body.dark .flash {
295
+ background-color: rgba(37, 117, 252, 0.2);
296
+ border-color: rgba(37, 117, 252, 0.5);
297
+ }
298
+ .flash.error {
299
+ background-color: rgba(255, 77, 79, 0.1);
300
+ color: var(--delete-color);
301
+ border-color: rgba(255, 77, 79, 0.3);
302
+ }
303
+ body.dark .flash.error {
304
+ background-color: rgba(255, 77, 79, 0.2);
305
+ border-color: rgba(255, 77, 79, 0.5);
306
  }
307
 
308
+
309
  .file-grid {
310
  display: grid;
311
+ grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
312
  gap: 25px;
313
+ margin-top: 25px;
314
  }
315
 
316
  .user-list {
317
+ margin-top: 25px;
318
+ display: grid;
319
+ grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
320
+ gap: 20px;
321
  }
322
 
323
  .user-item {
324
+ padding: 20px 25px;
325
+ background: var(--card-bg);
326
+ border-radius: var(--border-radius-main);
327
+ margin-bottom: 10px;
328
  box-shadow: var(--shadow);
329
  transition: var(--transition);
330
+ border-left: 5px solid var(--primary);
331
+ }
332
+
333
+ body.dark .user-item {
334
+ background: var(--card-bg-dark);
335
+ box-shadow: var(--shadow-dark);
336
+ border-left-color: var(--secondary);
337
  }
338
 
339
  .user-item:hover {
340
+ transform: translateY(-5px) scale(1.02);
341
+ box-shadow: 0 15px 30px rgba(0, 0, 0, 0.15);
342
  }
343
+ body.dark .user-item:hover {
344
+ box-shadow: 0 15px 30px rgba(0, 0, 0, 0.35);
345
+ }
346
+
347
 
348
  .user-item a {
349
  color: var(--primary);
350
  text-decoration: none;
351
+ font-weight: 700;
352
+ font-size: 1.2em;
353
+ display: block;
354
+ margin-bottom: 8px;
355
+ }
356
+ body.dark .user-item a {
357
+ color: var(--secondary);
358
  }
359
 
360
  .user-item a:hover {
361
+ text-decoration: underline;
362
  }
363
+ .user-item p {
364
+ font-size: 0.95em;
365
+ opacity: 0.8;
366
+ margin-bottom: 4px;
367
+ }
368
+
369
 
370
  @media (max-width: 768px) {
371
  .file-grid {
372
+ grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));
373
  }
374
+ .container { padding: 25px; }
375
+ h1 { font-size: 2.2em; }
376
+ h2 { font-size: 1.5em; }
377
  }
378
 
379
  @media (max-width: 480px) {
380
  .file-grid {
381
  grid-template-columns: 1fr;
382
  }
383
+ .container { padding: 20px 15px; }
384
+ h1 { font-size: 1.8em; }
385
+ .slogan { font-size: 1em; }
386
+ .btn { width: 100%; margin-right: 0; } /* Stack buttons */
387
  }
388
 
389
  .file-item {
390
+ background: var(--card-bg);
391
+ padding: 15px;
392
+ border-radius: var(--border-radius-main);
393
  box-shadow: var(--shadow);
394
  text-align: center;
395
  transition: var(--transition);
396
+ overflow: hidden; /* Ensure preview fits */
397
+ display: flex;
398
+ flex-direction: column;
399
+ justify-content: space-between; /* Push buttons down */
400
+ }
401
+
402
+ body.dark .file-item {
403
+ background: var(--card-bg-dark);
404
+ box-shadow: var(--shadow-dark);
405
+ border: 1px solid rgba(255, 255, 255, 0.08);
406
  }
407
 
408
  .file-item:hover {
409
+ transform: translateY(-8px);
410
+ box-shadow: 0 18px 35px rgba(0, 0, 0, 0.15);
411
+ }
412
+ body.dark .file-item:hover {
413
+ box-shadow: 0 18px 35px rgba(0, 0, 0, 0.4);
414
  }
415
 
416
+ .file-preview-container {
417
+ width: 100%;
418
+ height: 200px; /* Fixed height for consistency */
 
 
419
  margin-bottom: 15px;
420
+ background-color: #eee; /* Placeholder bg */
421
+ border-radius: var(--border-radius-small);
422
+ overflow: hidden;
423
+ display: flex;
424
+ align-items: center;
425
+ justify-content: center;
426
  cursor: pointer;
427
  }
428
+ body.dark .file-preview-container {
429
+ background-color: #333;
430
+ }
431
 
432
+ .file-preview {
433
+ width: 100%;
434
+ height: 100%;
435
+ object-fit: cover; /* Cover the area */
436
+ display: block;
437
+ border-radius: var(--border-radius-small); /* Match container */
438
  }
439
 
440
+ .file-item .file-info {
441
+ margin-bottom: 15px; /* Space before buttons */
442
+ word-break: break-all; /* Prevent long names overflowing */
443
  }
444
 
445
+
446
+ .file-item p {
447
+ font-size: 0.9em;
448
+ margin: 5px 0;
449
+ opacity: 0.8;
450
+ }
451
+ .file-item .filename {
452
+ font-weight: 600;
453
+ opacity: 1;
454
+ font-size: 1em;
455
  color: var(--primary);
456
+ margin-bottom: 8px;
457
+ }
458
+ body.dark .file-item .filename {
459
+ color: var(--secondary);
460
  }
461
 
462
+
463
+ .file-item .actions {
464
+ margin-top: auto; /* Pushes actions to the bottom */
465
+ display: flex;
466
+ justify-content: space-around; /* Evenly space buttons */
467
+ flex-wrap: wrap; /* Wrap if needed */
468
  }
469
+ .file-item .actions .btn {
470
+ padding: 8px 15px; /* Smaller buttons for cards */
471
+ font-size: 0.9em;
472
+ flex-grow: 1; /* Make buttons share space */
473
+ margin: 5px; /* Spacing around buttons */
474
+ }
475
+
476
 
477
  .modal {
478
  display: none;
 
485
  z-index: 2000;
486
  justify-content: center;
487
  align-items: center;
488
+ padding: 20px;
489
+ cursor: pointer;
490
+ }
491
+
492
+ .modal-content {
493
+ max-width: 95%;
494
+ max-height: 95%;
495
+ display: flex; /* Center content */
496
+ justify-content: center;
497
+ align-items: center;
498
+ position: relative;
499
  }
500
 
501
  .modal img, .modal video {
502
+ max-width: 100%;
503
+ max-height: 100%;
504
  object-fit: contain;
505
+ border-radius: var(--border-radius-small);
506
+ box-shadow: 0 20px 50px rgba(0, 0, 0, 0.5);
507
+ cursor: default; /* Default cursor over media */
508
+ }
509
+ .modal video {
510
+ outline: none;
511
  }
512
 
513
+ .modal-close {
514
+ position: absolute;
515
+ top: -30px;
516
+ right: -10px;
517
+ color: #fff;
518
+ font-size: 3em;
519
+ font-weight: bold;
520
+ cursor: pointer;
521
+ opacity: 0.8;
522
+ transition: opacity 0.2s;
523
+ }
524
+ .modal-close:hover {
525
+ opacity: 1;
526
+ }
527
+
528
+
529
  #progress-container {
530
  width: 100%;
531
+ height: 25px;
532
  background: var(--glass-bg);
533
+ border-radius: var(--border-radius-small);
534
  margin: 20px 0;
535
+ overflow: hidden;
536
+ display: none; /* Hidden by default */
537
+ border: 1px solid rgba(0,0,0,0.1);
538
+ }
539
+ body.dark #progress-container {
540
+ background: var(--glass-bg-dark);
541
+ border: 1px solid rgba(255,255,255,0.15);
542
  }
543
 
544
  #progress-bar {
545
  width: 0%;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
546
  height: 100%;
547
+ background: linear-gradient(90deg, var(--primary), var(--secondary));
548
+ border-radius: var(--border-radius-small);
549
+ transition: width 0.4s ease;
550
+ text-align: center;
551
+ line-height: 25px;
552
+ color: white;
553
+ font-weight: 600;
554
+ font-size: 0.9em;
555
  }
556
  '''
557
 
 
560
  if request.method == 'POST':
561
  username = request.form.get('username')
562
  password = request.form.get('password')
563
+
564
  data = load_data()
565
+
566
  if username in data['users']:
567
+ flash('Пользователь с таким именем уже существует!', 'error')
568
  return redirect(url_for('register'))
569
+
570
  if not username or not password:
571
+ flash('Требуется имя пользователя и пароль!', 'error')
572
  return redirect(url_for('register'))
573
+
574
  data['users'][username] = {
575
  'password': password,
576
  'created_at': datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
577
  'files': []
578
  }
579
+ try:
580
+ save_data(data)
581
+ session['username'] = username
582
+ flash('Регистрация прошла успешно!')
583
+ return redirect(url_for('dashboard'))
584
+ except Exception as e:
585
+ flash(f'Ошибка сохранения данных: {e}', 'error')
586
+ return redirect(url_for('register'))
587
+
588
  html = '''
589
  <!DOCTYPE html>
590
+ <html lang="ru">
591
  <head>
592
  <meta charset="UTF-8">
593
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
594
  <title>Регистрация - Zeus Cloud</title>
 
595
  <style>''' + BASE_STYLE + '''</style>
596
  </head>
597
  <body>
 
598
  <div class="container">
599
+ <h1>Регистрация в Zeus Cloud</h1>
600
+ <p class="slogan">Ваши файлы под надежной защитой квантовой криптографии</p>
601
+ {% with messages = get_flashed_messages(with_categories=true) %}
602
  {% if messages %}
603
+ {% for category, message in messages %}
604
+ <div class="flash {{ category }}">{{ message }}</div>
605
  {% endfor %}
606
  {% endif %}
607
  {% endwith %}
608
  <form method="POST" id="register-form">
609
+ <input type="text" name="username" placeholder="Введите имя пользователя" required>
610
+ <input type="password" name="password" placeholder="Введите пароль" required>
611
  <button type="submit" class="btn">Зарегистрироваться</button>
612
  </form>
613
+ <p style="margin-top: 20px; text-align: center;">Уже есть аккаунт? <a href="{{ url_for('login') }}" style="color: var(--primary); font-weight: 600;">Войти</a></p>
614
  </div>
615
+ <script> document.body.classList.toggle('dark', localStorage.getItem('theme') === 'dark'); </script>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
616
  </body>
617
  </html>
618
  '''
 
624
  username = request.form.get('username')
625
  password = request.form.get('password')
626
  data = load_data()
627
+
628
+ if username in data.get('users', {}) and data['users'][username]['password'] == password:
629
  session['username'] = username
630
  return jsonify({'status': 'success', 'redirect': url_for('dashboard')})
631
  else:
632
+ return jsonify({'status': 'error', 'message': 'Неверное имя пользователя или пароль!'})
633
+
634
  html = '''
635
  <!DOCTYPE html>
636
+ <html lang="ru">
637
  <head>
638
  <meta charset="UTF-8">
639
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
640
+ <title>Вход - Zeus Cloud</title>
 
641
  <style>''' + BASE_STYLE + '''</style>
642
  </head>
643
  <body>
 
644
  <div class="container">
645
  <h1>Zeus Cloud</h1>
646
+ <p class="slogan">Ваши файлы под надежной защитой квантовой криптографии</p>
647
  <div id="flash-messages">
648
+ {% with messages = get_flashed_messages(with_categories=true) %}
649
  {% if messages %}
650
+ {% for category, message in messages %}
651
+ <div class="flash {{ category }}">{{ message }}</div>
652
  {% endfor %}
653
  {% endif %}
654
  {% endwith %}
655
  </div>
656
  <form method="POST" id="login-form">
657
+ <input type="text" name="username" placeholder="Введите имя пользователя" required>
658
+ <input type="password" name="password" placeholder="Введите пароль" required>
659
  <button type="submit" class="btn">Войти</button>
660
  </form>
661
+ <p style="margin-top: 20px; text-align: center;">Нет аккаунта? <a href="{{ url_for('register') }}" style="color: var(--primary); font-weight: 600;">Зарегистрироваться</a></p>
662
  </div>
 
663
  <script>
664
+ document.body.classList.toggle('dark', localStorage.getItem('theme') === 'dark');
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
665
 
666
  const savedCredentials = JSON.parse(localStorage.getItem('zeusCredentials'));
667
  if (savedCredentials) {
 
678
  window.location.href = data.redirect;
679
  }
680
  })
681
+ .catch(error => console.error('Ошибка авто-входа:', error));
682
  }
683
 
684
  document.getElementById('login-form').addEventListener('submit', function(e) {
685
  e.preventDefault();
686
  const formData = new FormData(this);
687
+ const flashContainer = document.getElementById('flash-messages');
688
+ flashContainer.innerHTML = '';
689
+
690
  fetch('/', {
691
  method: 'POST',
692
  body: formData
 
699
  localStorage.setItem('zeusCredentials', JSON.stringify({ username, password }));
700
  window.location.href = data.redirect;
701
  } else {
702
+ flashContainer.innerHTML = `<div class="flash error">${data.message}</div>`;
703
  }
704
  })
705
  .catch(error => {
706
+ flashContainer.innerHTML = `<div class="flash error">Ошибка соединения!</div>`;
707
  });
708
  });
709
  </script>
 
712
  '''
713
  return render_template_string(html)
714
 
715
+
716
  @app.route('/dashboard', methods=['GET', 'POST'])
717
  def dashboard():
718
  if 'username' not in session:
719
+ flash('Пожалуйста, войдите!', 'error')
720
  return redirect(url_for('login'))
721
+
722
  username = session['username']
723
  data = load_data()
724
+ if username not in data.get('users', {}):
725
  session.pop('username', None)
726
+ localStorage.removeItem('zeusCredentials') # Clear local storage too
727
+ flash('Пользователь не найден! Пожалуйста, войдите снова.', 'error')
728
  return redirect(url_for('login'))
 
 
729
 
730
  if request.method == 'POST':
731
  files = request.files.getlist('files')
732
+ if not files or not files[0].filename:
733
+ flash('Файлы для загрузки не выбраны!', 'error')
734
+ return redirect(url_for('dashboard'))
735
+
736
+ if len(files) > 20:
737
+ flash('Максимум 20 файлов за раз!', 'error')
738
  return redirect(url_for('dashboard'))
739
+
740
+ if not HF_TOKEN_WRITE:
741
+ flash('Ошибка конфигурации сервера: Токен для записи отсутствует.', 'error')
742
+ return redirect(url_for('dashboard'))
743
+
744
+ os.makedirs('uploads', exist_ok=True)
745
+ api = HfApi()
746
+ temp_files_info = []
747
+ upload_successful = True
748
+
749
+ # First save files locally
750
+ for file in files:
751
+ if file and file.filename:
752
+ filename = secure_filename(file.filename)
753
+ temp_path = os.path.join('uploads', f"{username}_{int(time.time())}_{filename}")
754
+ try:
755
  file.save(temp_path)
756
+ temp_files_info.append({'temp_path': temp_path, 'filename': filename})
757
+ except Exception as e:
758
+ logging.error(f"Ошибка сохранения временного файла {filename}: {e}")
759
+ flash(f'Ошибка сохранения файла {filename} локально.', 'error')
760
+ upload_successful = False
761
+ # Clean up already saved temp files for this request
762
+ for info in temp_files_info:
763
+ if os.path.exists(info['temp_path']):
764
+ os.remove(info['temp_path'])
765
+ return redirect(url_for('dashboard'))
766
+
767
+
768
+ # Then upload to HF and update DB
769
+ current_files = data['users'][username].setdefault('files', [])
770
+ newly_added_files = []
771
+
772
+ for info in temp_files_info:
773
+ temp_path = info['temp_path']
774
+ filename = info['filename']
775
+ file_path_in_repo = f"cloud_files/{username}/{filename}"
776
+
777
+ try:
778
  api.upload_file(
779
  path_or_fileobj=temp_path,
780
+ path_in_repo=file_path_in_repo,
781
  repo_id=REPO_ID,
782
  repo_type="dataset",
783
  token=HF_TOKEN_WRITE,
784
+ commit_message=f"Загружен файл {filename} для {username}"
785
  )
786
+
787
  file_info = {
788
  'filename': filename,
789
+ 'path': file_path_in_repo,
790
  'type': get_file_type(filename),
791
  'upload_date': datetime.now().strftime('%Y-%m-%d %H:%M:%S')
792
  }
793
+ newly_added_files.append(file_info)
794
+ logging.info(f"Файл {filename} успешно загружен на HF.")
795
+
796
+ except Exception as e:
797
+ logging.error(f"Ошибка загрузки файла {filename} на HF: {e}")
798
+ flash(f'Ошибка загрузки файла {filename} на облако.', 'error')
799
+ upload_successful = False
800
+ # Potential: Implement retry or specific error handling here
801
+
802
+ finally:
803
+ # Clean up the local temp file regardless of upload success
804
  if os.path.exists(temp_path):
805
+ try:
806
+ os.remove(temp_path)
807
+ except Exception as e_rem:
808
+ logging.error(f"Ошибка удаления временного файла {temp_path}: {e_rem}")
809
+
810
+
811
+ if newly_added_files:
812
+ data['users'][username]['files'].extend(newly_added_files)
813
+ try:
814
+ save_data(data)
815
+ if upload_successful:
816
+ flash('Файлы успешно загружены!')
817
+ else:
818
+ flash('Некоторые файлы не удалось загрузить. Проверьте ошибки выше.', 'error')
819
+ except Exception as e_save:
820
+ logging.error(f"Критическая ошибка сохранения данных после загрузки: {e_save}")
821
+ flash('Критическая ошибка: не удалось обновить базу данных после загрузки файлов!', 'error')
822
+
823
+ elif not upload_successful:
824
+ flash('Ни один файл не был успешно загружен.', 'error')
825
+
826
+ # No need for manual cleanup here anymore, done in the loop
827
  return redirect(url_for('dashboard'))
828
 
829
+
830
+ user_files_data = data['users'][username].get('files', [])
831
+ user_files = sorted(user_files_data, key=lambda x: x.get('upload_date', '1970-01-01 00:00:00'), reverse=True)
832
+
833
  html = '''
834
  <!DOCTYPE html>
835
+ <html lang="ru">
836
  <head>
837
  <meta charset="UTF-8">
838
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
839
+ <title>Панель управления - Zeus Cloud</title>
 
840
  <style>''' + BASE_STYLE + '''</style>
841
  </head>
842
  <body>
 
843
  <div class="container">
844
+ <h1>Панель управления Zeus Cloud</h1>
845
+ <p class="slogan">Ваши файлы под надежной защитой квантовой криптографии</p>
846
+ <p style="text-align: right; margin-bottom: 15px; font-weight: 600;">Пользователь: {{ username }}
847
+ <button id="theme-toggle" class="btn" style="padding: 5px 10px; font-size: 0.8em; margin-left: 10px;">🌙</button>
848
+ </p>
849
+ {% with messages = get_flashed_messages(with_categories=true) %}
850
  {% if messages %}
851
+ {% for category, message in messages %}
852
+ <div class="flash {{ category }}">{{ message }}</div>
853
  {% endfor %}
854
  {% endif %}
855
  {% endwith %}
856
+
857
+ <form id="upload-form" method="POST" enctype="multipart/form-data" style="margin-bottom: 25px; background: rgba(0,0,0,0.03); padding: 20px; border-radius: var(--border-radius-small);">
858
+ <label for="file-input" class="btn" style="background: linear-gradient(135deg, var(--accent), #fca045); cursor: pointer;">Выберите файлы (макс. 20)</label>
859
+ <input type="file" id="file-input" name="files" multiple required accept="image/*,video/*,audio/*,.pdf,.doc,.docx,.xls,.xlsx,.ppt,.pptx,.zip,.rar,.txt" style="display: none;">
860
+ <span id="file-names" style="margin-left: 15px; font-style: italic; opacity: 0.8;">Файлы не выбраны</span>
861
+ <button type="submit" class="btn" id="upload-btn">Загрузить</button>
862
  </form>
863
+
864
  <div id="progress-container">
865
+ <div id="progress-bar">0%</div>
866
  </div>
867
+
868
  <h2>Ваши файлы</h2>
869
  <div class="file-grid">
870
  {% for file in user_files %}
871
  <div class="file-item">
872
+ <div class="file-preview-container" onclick="openModal('https://huggingface.co/datasets/{{ repo_id }}/resolve/main/{{ file['path'] }}', '{{ file['type'] }}')">
873
+ {% if file['type'] == 'video' %}
874
+ <video class="file-preview" preload="metadata" muted loading="lazy">
875
+ <source src="https://huggingface.co/datasets/{{ repo_id }}/resolve/main/{{ file['path'] }}#t=0.5" type="video/mp4"> <!-- #t=0.5 для превью -->
876
+ Ваш браузер не поддерживает видео.
877
+ </video>
878
+ {% elif file['type'] == 'image' %}
879
+ <img class="file-preview" src="https://huggingface.co/datasets/{{ repo_id }}/resolve/main/{{ file['path'] }}" alt="{{ file['filename'] }}" loading="lazy">
880
+ {% else %}
881
+ <div style="font-size: 3em; color: #aaa;">📄</div> <!-- Иконка для других файлов -->
882
+ {% endif %}
883
+ </div>
884
+ <div class="file-info">
885
+ <p class="filename">{{ file['filename'] }}</p>
886
+ <p>Тип: {{ file['type'] }}</p>
887
+ <p>Загружено: {{ file['upload_date'] }}</p>
888
+ </div>
889
+ <div class="actions">
890
+ <a href="{{ url_for('download_file', file_path=file['path']|urlencode, filename=file['filename']) }}" class="btn download-btn">Скачать</a>
891
+ <a href="{{ url_for('delete_file', file_path=file['path']|urlencode) }}" class="btn delete-btn" onclick="return confirm('Вы уверены, что хотите удалить этот файл: {{ file['filename'] }}?');">Удалить</a>
892
+ </div>
893
  </div>
894
  {% endfor %}
895
  {% if not user_files %}
896
+ <p style="grid-column: 1 / -1; text-align: center; margin-top: 30px; font-size: 1.1em; opacity: 0.7;">Вы еще не загрузили ни одного файла.</p>
897
  {% endif %}
898
  </div>
899
+ <a href="{{ url_for('logout') }}" class="btn" style="margin-top: 30px; background: linear-gradient(135deg, #aaa, #888);" id="logout-btn">Выйти</a>
900
  </div>
901
+
902
+ <div class="modal" id="mediaModal" onclick="closeModalOnClick(event)">
903
+ <span class="modal-close" onclick="closeModal()">×</span>
904
+ <div class="modal-content" onclick="event.stopPropagation()"> <!-- Предотвратить закрытие при клике на контент -->
905
+ <div id="modalBody"></div>
906
+ </div>
907
  </div>
908
+
909
  <script>
910
+ // Theme toggle
911
+ const themeToggle = document.getElementById('theme-toggle');
912
+ const currentTheme = localStorage.getItem('theme');
913
+ if (currentTheme === 'dark') {
914
+ document.body.classList.add('dark');
915
+ themeToggle.textContent = '☀️';
916
+ }
917
+ themeToggle.addEventListener('click', () => {
918
+ document.body.classList.toggle('dark');
919
+ let theme = 'light';
920
+ if (document.body.classList.contains('dark')) {
921
+ theme = 'dark';
922
+ themeToggle.textContent = '☀️';
923
+ } else {
924
+ themeToggle.textContent = '🌙';
925
+ }
926
+ localStorage.setItem('theme', theme);
927
  });
928
 
929
+ // File input name display
930
+ const fileInput = document.getElementById('file-input');
931
+ const fileNamesSpan = document.getElementById('file-names');
932
+ fileInput.addEventListener('change', () => {
933
+ if (fileInput.files.length > 0) {
934
+ let names = Array.from(fileInput.files).map(f => f.name).join(', ');
935
+ if (names.length > 50) names = names.substring(0, 47) + '...';
936
+ fileNamesSpan.textContent = names;
937
+ fileNamesSpan.style.fontStyle = 'normal';
938
+ fileNamesSpan.style.opacity = '1';
939
+ } else {
940
+ fileNamesSpan.textContent = 'Файлы не выбраны';
941
+ fileNamesSpan.style.fontStyle = 'italic';
942
+ fileNamesSpan.style.opacity = '0.8';
943
+ }
944
+ });
945
+
946
+
947
+ function openModal(src, type) {
948
  const modal = document.getElementById('mediaModal');
949
+ const modalBody = document.getElementById('modalBody');
950
+ modalBody.innerHTML = ''; // Clear previous content
951
+
952
+ if (type === 'video') {
953
+ modalBody.innerHTML = `<video controls autoplay style="max-width: 100%; max-height: 100%; outline: none;"><source src="${src}" type="video/mp4">Ваш браузер не поддерживает встроенное видео.</video>`;
954
+ } else if (type === 'image') {
955
+ modalBody.innerHTML = `<img src="${src}" alt="Просмотр изображения" style="max-width: 100%; max-height: 100%;">`;
956
  } else {
957
+ // For other types, maybe show a message or icon? Or just don't open modal.
958
+ // For now, we allow opening but show a generic message/icon
959
+ modalBody.innerHTML = `<div style="color: #fff; font-size: 1.2em; text-align: center;">Предпросмотр для этого типа файла недоступен.<br><a href='${src}' download style='color: #aaf; margin-top:10px; display: inline-block;'>Скачать файл</a></div>`;
960
  }
961
  modal.style.display = 'flex';
962
+ document.body.style.overflow = 'hidden'; // Prevent background scrolling
963
  }
964
+
965
+ function closeModal() {
966
+ const modal = document.getElementById('mediaModal');
967
+ const modalBody = document.getElementById('modalBody');
968
+ modal.style.display = 'none';
969
+ modalBody.innerHTML = ''; // Clear content to stop video/audio
970
+ document.body.style.overflow = 'auto'; // Restore scrolling
971
  }
972
+ function closeModalOnClick(event) {
973
+ // Close only if clicked on the background overlay itself
974
+ if (event.target.id === 'mediaModal') {
975
+ closeModal();
976
+ }
977
+ }
978
+ // Optional: Close modal with Escape key
979
+ document.addEventListener('keydown', function(event) {
980
+ if (event.key === "Escape") {
981
+ closeModal();
982
+ }
983
+ });
984
+
985
 
986
  const form = document.getElementById('upload-form');
987
  const progressBar = document.getElementById('progress-bar');
 
990
 
991
  form.addEventListener('submit', function(e) {
992
  e.preventDefault();
993
+ const files = fileInput.files;
994
+ if (files.length === 0) {
995
+ alert('Пожалуйста, выберите файлы для загрузки.');
996
+ return;
997
+ }
998
  if (files.length > 20) {
999
+ alert('Вы можете загружать не более 20 файлов за раз!');
1000
  return;
1001
  }
1002
 
1003
  const formData = new FormData(form);
1004
  progressContainer.style.display = 'block';
1005
  progressBar.style.width = '0%';
1006
+ progressBar.textContent = '0%';
1007
  uploadBtn.disabled = true;
1008
+ uploadBtn.textContent = 'Загрузка...';
1009
+
1010
 
1011
  const xhr = new XMLHttpRequest();
1012
  xhr.open('POST', '/dashboard', true);
1013
 
1014
  xhr.upload.onprogress = function(event) {
1015
  if (event.lengthComputable) {
1016
+ const percent = Math.round((event.loaded / event.total) * 100);
1017
  progressBar.style.width = percent + '%';
1018
+ progressBar.textContent = percent + '%';
1019
  }
1020
  };
1021
 
1022
  xhr.onload = function() {
1023
+ // Regardless of status, reload to show flashes or updated file list
1024
+ window.location.reload();
1025
+ // We could parse response to be smarter, but reload is simplest for now
1026
+ // Need to enable button again in case reload fails? Probably not necessary.
1027
+ // uploadBtn.disabled = false;
1028
+ // uploadBtn.textContent = 'Загрузить';
1029
+ // progressContainer.style.display = 'none';
1030
+
1031
  };
1032
 
1033
  xhr.onerror = function() {
1034
+ alert('Ошибка сети или соединения!');
1035
  progressContainer.style.display = 'none';
1036
  uploadBtn.disabled = false;
1037
+ uploadBtn.textContent = 'Загрузить';
1038
  };
1039
 
1040
  xhr.send(formData);
 
1042
 
1043
  document.getElementById('logout-btn').addEventListener('click', function(e) {
1044
  e.preventDefault();
1045
+ localStorage.removeItem('zeusCredentials'); // Clear saved credentials on logout
1046
+ window.location.href = this.href; // Proceed to logout route
1047
  });
1048
  </script>
1049
  </body>
 
1051
  '''
1052
  return render_template_string(html, username=username, user_files=user_files, repo_id=REPO_ID)
1053
 
1054
+
1055
  @app.route('/download/<path:file_path>/<filename>')
1056
  def download_file(file_path, filename):
1057
  if 'username' not in session:
1058
+ flash('Пожалуйста, войдите!', 'error')
1059
  return redirect(url_for('login'))
1060
+
1061
  username = session['username']
1062
  data = load_data()
1063
+ if username not in data.get('users', {}):
1064
  session.pop('username', None)
1065
+ localStorage.removeItem('zeusCredentials')
1066
+ flash('Пользователь не найден!', 'error')
1067
  return redirect(url_for('login'))
1068
+
1069
+ user_files = data['users'][username].get('files', [])
1070
+ # Check if the user owns the file OR if the user is an admin accessing via admin panel (future enhancement?)
1071
+ # For now, only check ownership
1072
+ if not any(file.get('path') == file_path for file in user_files):
1073
+ # Allow download from admin panel even without session (more complex check needed)
1074
+ # Simple check for now: is the request coming from the admin view?
1075
+ # This is insecure, needs proper admin auth. For now, assume admin doesn't use this route directly.
1076
+ # So if not in user's file list, deny.
1077
+ flash('У вас нет доступа к этому файлу или он не найден!', 'error')
1078
+ # Redirect back if possible, otherwise dashboard
1079
+ referer = request.headers.get("Referer")
1080
+ if referer and '/admhosto/user/' in referer:
1081
+ return redirect(referer)
1082
  return redirect(url_for('dashboard'))
1083
+
1084
+
1085
+ if not HF_TOKEN_READ:
1086
+ flash('Ошибка конфигурации сервера: Токен для чтения отсутствует.', 'error')
1087
+ return redirect(url_for('dashboard')) # Or referer?
1088
+
1089
  file_url = f"https://huggingface.co/datasets/{REPO_ID}/resolve/main/{file_path}"
1090
+ logging.info(f"Попытка скачивания файла: {file_url}")
1091
+
1092
+ try:
1093
+ # Use token for potentially private repos
1094
+ headers = {"Authorization": f"Bearer {HF_TOKEN_READ}"}
1095
+ response = requests.get(file_url, headers=headers, stream=True) # stream=True for large files
1096
+
1097
+ if response.status_code == 200:
1098
+ # Try to determine a reasonable mime type, default to octet-stream
1099
+ mimetype = 'application/octet-stream'
1100
+ if '.' in filename:
1101
+ ext = filename.rsplit('.', 1)[1].lower()
1102
+ common_mimetypes = {
1103
+ 'txt': 'text/plain', 'pdf': 'application/pdf', 'png': 'image/png', 'jpg': 'image/jpeg',
1104
+ 'jpeg': 'image/jpeg', 'gif': 'image/gif', 'mp4': 'video/mp4', 'zip': 'application/zip',
1105
+ 'doc': 'application/msword', 'docx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
1106
+ 'xls': 'application/vnd.ms-excel', 'xlsx': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
1107
+ 'ppt': 'application/vnd.ms-powerpoint', 'pptx': 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
1108
+ }
1109
+ mimetype = common_mimetypes.get(ext, 'application/octet-stream')
1110
+
1111
+ # Stream the download
1112
+ return send_file(
1113
+ BytesIO(response.content), # Read content for send_file from BytesIO
1114
+ as_attachment=True,
1115
+ download_name=filename,
1116
+ mimetype=mimetype
1117
+ )
1118
+ # For true streaming with Response:
1119
+ # headers = { 'Content-Disposition': f'attachment; filename="{filename}"', 'Content-Type': mimetype }
1120
+ # return Response(response.iter_content(chunk_size=8192), headers=headers, status=response.status_code)
1121
+
1122
+ elif response.status_code == 404:
1123
+ flash('Ошибка: Файл не найден на сервере хранилища.', 'error')
1124
+ logging.error(f"Файл не найден на HF: {file_url} (status 404)")
1125
+ return redirect(request.referrer or url_for('dashboard'))
1126
+ else:
1127
+ flash(f'Ошибка скачивания файла ({response.status_code})!', 'error')
1128
+ logging.error(f"Ошибка скачивания файла с HF: {file_url} (status {response.status_code})")
1129
+ return redirect(request.referrer or url_for('dashboard'))
1130
+
1131
+ except requests.exceptions.RequestException as e:
1132
+ logging.error(f"Ошибка сети при скачивании файла {file_path}: {e}")
1133
+ flash('Ошибка сети при попытке скачивания файла.', 'error')
1134
+ return redirect(request.referrer or url_for('dashboard'))
1135
+ except Exception as e:
1136
+ logging.error(f"Неожиданная ошибка при скачивании файла {file_path}: {e}")
1137
+ flash('Произошла непредвиденная ошибка при скачивании.', 'error')
1138
+ return redirect(request.referrer or url_for('dashboard'))
1139
+
1140
 
1141
  @app.route('/delete/<path:file_path>')
1142
  def delete_file(file_path):
1143
  if 'username' not in session:
1144
+ flash('Пожалуйста, войдите!', 'error')
1145
  return redirect(url_for('login'))
1146
+
1147
  username = session['username']
1148
  data = load_data()
1149
+ if username not in data.get('users', {}):
1150
  session.pop('username', None)
1151
+ localStorage.removeItem('zeusCredentials')
1152
+ flash('Пользователь не найден!', 'error')
1153
  return redirect(url_for('login'))
1154
+
1155
+ user_files = data['users'][username].get('files', [])
1156
+ file_to_delete_index = -1
1157
+ for i, file in enumerate(user_files):
1158
+ if file.get('path') == file_path:
1159
+ file_to_delete_index = i
1160
+ break
1161
+
1162
+ if file_to_delete_index == -1:
1163
+ flash('Файл не найден в вашем списке!', 'error')
1164
  return redirect(url_for('dashboard'))
1165
+
1166
+ file_info = user_files[file_to_delete_index]
1167
+ filename = file_info.get('filename', 'неизвестный файл')
1168
+
1169
+ if not HF_TOKEN_WRITE:
1170
+ flash('Ошибка конфигурации сервера: Токен для записи отсутствует.', 'error')
1171
+ return redirect(url_for('dashboard'))
1172
+
1173
  try:
1174
  api = HfApi()
1175
+ logging.info(f"Попытка удаления файла с HF: {file_path}")
1176
  api.delete_file(
1177
  path_in_repo=file_path,
1178
  repo_id=REPO_ID,
1179
  repo_type="dataset",
1180
  token=HF_TOKEN_WRITE,
1181
+ commit_message=f"Удален файл {filename} ({file_path}) пользователем {username}"
1182
  )
1183
+ logging.info(f"Файл {file_path} успешно удален с HF.")
1184
+
1185
+ # Remove from local data only after successful deletion from HF
1186
+ del data['users'][username]['files'][file_to_delete_index]
1187
  save_data(data)
1188
+ flash(f'Файл "{filename}" успешно удален!')
1189
+
1190
  except Exception as e:
1191
+ # More specific error handling for HF deletions might be needed (e.g., file not found on HF)
1192
+ logging.error(f"Ошибка удаления файла {file_path} с HF: {e}")
1193
+ # Check if the error indicates the file was already gone from HF
1194
+ if "404" in str(e) or "not found" in str(e).lower():
1195
+ logging.warning(f"Файл {file_path} не найден на HF при попытке удаления, возможно, уже удален. Удаляем из базы данных.")
1196
+ try:
1197
+ del data['users'][username]['files'][file_to_delete_index]
1198
+ save_data(data)
1199
+ flash(f'Файл "{filename}" уже был удален из хранилища, запись удалена из базы данных.', 'warning')
1200
+ except Exception as e_save:
1201
+ logging.error(f"Ошибка сохранения данных после подтверждения удаления отсутствующего файла: {e_save}")
1202
+ flash('Ошибка: Не удалось обновить базу данных после удаления файла.', 'error')
1203
+ else:
1204
+ flash(f'Ошибка при удалении файла "{filename}" из облака!', 'error')
1205
+
1206
  return redirect(url_for('dashboard'))
1207
 
1208
  @app.route('/logout')
1209
  def logout():
1210
  session.pop('username', None)
1211
+ # No need to explicitly call localStorage.removeItem here, handled by client-side logout button JS
1212
+ flash('Вы успешно вышли из системы.')
1213
  return redirect(url_for('login'))
1214
 
1215
+
1216
  @app.route('/admhosto')
1217
  def admin_panel():
1218
+ # WARNING: No authentication implemented for admin panel!
1219
+ # This is highly insecure and should be protected in a real application
1220
+ # (e.g., check session for a specific admin user, IP check, separate login)
1221
  data = load_data()
1222
+ users_data = data.get('users', {})
1223
+ # Sort users alphabetically by username for consistency
1224
+ users = dict(sorted(users_data.items()))
1225
+
1226
+
1227
  html = '''
1228
  <!DOCTYPE html>
1229
+ <html lang="ru">
1230
  <head>
1231
  <meta charset="UTF-8">
1232
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
1233
+ <title>Панель администратора - Zeus Cloud</title>
 
1234
  <style>''' + BASE_STYLE + '''</style>
1235
  </head>
1236
  <body>
 
1237
  <div class="container">
1238
+ <h1>Панель администратора Zeus Cloud</h1>
1239
+ <button id="theme-toggle" class="btn" style="padding: 5px 10px; font-size: 0.8em; position: absolute; top: 20px; right: 20px;">🌙</button>
1240
+ <h2>Список пользователей</h2>
1241
  <div class="user-list">
1242
  {% for username, user_data in users.items() %}
1243
  <div class="user-item">
1244
  <a href="{{ url_for('admin_user_files', username=username) }}">{{ username }}</a>
1245
+ <p>Дата регистрации: {{ user_data.get('created_at', 'Неизвестно') }}</p>
1246
+ <p>Количество файлов: {{ user_data.get('files', []) | length }}</p>
1247
+ <!-- Add admin actions here if needed, e.g., Delete User -->
1248
  </div>
1249
  {% endfor %}
1250
  {% if not users %}
 
1252
  {% endif %}
1253
  </div>
1254
  </div>
1255
+ <script>
1256
+ const themeToggle = document.getElementById('theme-toggle');
1257
+ const currentTheme = localStorage.getItem('theme');
1258
+ if (currentTheme === 'dark') {
1259
+ document.body.classList.add('dark');
1260
+ themeToggle.textContent = '☀️';
1261
+ } else {
1262
+ document.body.classList.remove('dark');
1263
+ themeToggle.textContent = '🌙';
1264
+ }
1265
+ themeToggle.addEventListener('click', () => {
1266
+ document.body.classList.toggle('dark');
1267
+ let theme = 'light';
1268
+ if (document.body.classList.contains('dark')) {
1269
+ theme = 'dark';
1270
+ themeToggle.textContent = '☀️';
1271
+ } else {
1272
+ themeToggle.textContent = '🌙';
1273
+ }
1274
+ localStorage.setItem('theme', theme);
1275
  });
1276
+ document.body.classList.toggle('dark', localStorage.getItem('theme') === 'dark');
1277
  </script>
1278
  </body>
1279
  </html>
 
1282
 
1283
  @app.route('/admhosto/user/<username>')
1284
  def admin_user_files(username):
1285
+ # WARNING: No authentication!
1286
  data = load_data()
1287
+ if username not in data.get('users', {}):
1288
+ flash('Пользователь не найден!', 'error')
1289
  return redirect(url_for('admin_panel'))
1290
+
1291
+ user_files_data = data['users'][username].get('files', [])
1292
+ user_files = sorted(user_files_data, key=lambda x: x.get('upload_date', '1970-01-01 00:00:00'), reverse=True)
1293
+
1294
  html = '''
1295
  <!DOCTYPE html>
1296
+ <html lang="ru">
1297
  <head>
1298
  <meta charset="UTF-8">
1299
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
1300
  <title>Файлы пользователя {{ username }} - Zeus Cloud</title>
1301
+ <style>''' + BASE_STYLE + '''</style>
 
1302
  </head>
1303
  <body>
 
1304
  <div class="container">
1305
+ <h1>Файлы пользователя: {{ username }}</h1>
1306
+ <button id="theme-toggle" class="btn" style="padding: 5px 10px; font-size: 0.8em; position: absolute; top: 20px; right: 20px;">🌙</button>
1307
+ {% with messages = get_flashed_messages(with_categories=true) %}
1308
  {% if messages %}
1309
+ {% for category, message in messages %}
1310
+ <div class="flash {{ category }}">{{ message }}</div>
1311
  {% endfor %}
1312
  {% endif %}
1313
  {% endwith %}
1314
+
1315
  <div class="file-grid">
1316
  {% for file in user_files %}
1317
+ <div class="file-item">
1318
+ <div class="file-preview-container" onclick="openModal('https://huggingface.co/datasets/{{ repo_id }}/resolve/main/{{ file['path'] }}', '{{ file['type'] }}')">
1319
+ {% if file['type'] == 'video' %}
1320
+ <video class="file-preview" preload="metadata" muted loading="lazy">
1321
+ <source src="https://huggingface.co/datasets/{{ repo_id }}/resolve/main/{{ file['path'] }}#t=0.5" type="video/mp4">
1322
+ Ваш браузер не поддерживает видео.
1323
+ </video>
1324
+ {% elif file['type'] == 'image' %}
1325
+ <img class="file-preview" src="https://huggingface.co/datasets/{{ repo_id }}/resolve/main/{{ file['path'] }}" alt="{{ file['filename'] }}" loading="lazy">
1326
+ {% else %}
1327
+ <div style="font-size: 3em; color: #aaa;">📄</div>
1328
+ {% endif %}
1329
+ </div>
1330
+ <div class="file-info">
1331
+ <p class="filename">{{ file['filename'] }}</p>
1332
+ <p>Тип: {{ file['type'] }}</p>
1333
+ <p>Загружено: {{ file['upload_date'] }}</p>
1334
+ </div>
1335
+ <div class="actions">
1336
+ <a href="{{ url_for('download_file', file_path=file['path']|urlencode, filename=file['filename']) }}" class="btn download-btn">Скачать</a>
1337
+ <!-- Add Admin Delete Here - Needs separate endpoint or logic -->
1338
+ <!-- <a href="{{ url_for('admin_delete_file', username=username, file_path=file['path']|urlencode) }}" class="btn delete-btn" onclick="return confirm('Удалить этот файл пользователя {{ username }}?');">Удалить (Админ)</a> -->
1339
+ </div>
1340
  </div>
1341
  {% endfor %}
1342
  {% if not user_files %}
1343
+ <p style="grid-column: 1 / -1; text-align: center; margin-top: 30px; font-size: 1.1em; opacity: 0.7;">У этого пользователя пока нет файлов.</p>
1344
  {% endif %}
1345
  </div>
1346
+ <a href="{{ url_for('admin_panel') }}" class="btn" style="margin-top: 30px; background: linear-gradient(135deg, #aaa, #888);">Назад к списку пользователей</a>
1347
  </div>
1348
+
1349
+ <div class="modal" id="mediaModal" onclick="closeModalOnClick(event)">
1350
+ <span class="modal-close" onclick="closeModal()">×</span>
1351
+ <div class="modal-content" onclick="event.stopPropagation()">
1352
+ <div id="modalBody"></div>
1353
+ </div>
1354
  </div>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1355
 
1356
+ <script>
1357
+ // Theme toggle (duplicate from dashboard, could be DRYed up)
1358
+ const themeToggle = document.getElementById('theme-toggle');
1359
+ const currentTheme = localStorage.getItem('theme');
1360
+ if (currentTheme === 'dark') {
1361
+ document.body.classList.add('dark');
1362
+ themeToggle.textContent = '☀️';
1363
+ } else {
1364
+ document.body.classList.remove('dark');
1365
+ themeToggle.textContent = '🌙';
1366
+ }
1367
+ themeToggle.addEventListener('click', () => {
1368
+ document.body.classList.toggle('dark');
1369
+ let theme = 'light';
1370
+ if (document.body.classList.contains('dark')) {
1371
+ theme = 'dark';
1372
+ themeToggle.textContent = '☀️';
1373
+ } else {
1374
+ themeToggle.textContent = '🌙';
1375
+ }
1376
+ localStorage.setItem('theme', theme);
1377
+ });
1378
+ document.body.classList.toggle('dark', localStorage.getItem('theme') === 'dark');
1379
+
1380
+ // Modal functions (duplicate from dashboard)
1381
+ function openModal(src, type) {
1382
  const modal = document.getElementById('mediaModal');
1383
+ const modalBody = document.getElementById('modalBody');
1384
+ modalBody.innerHTML = '';
1385
+
1386
+ if (type === 'video') {
1387
+ modalBody.innerHTML = `<video controls autoplay style="max-width: 100%; max-height: 100%; outline: none;"><source src="${src}" type="video/mp4">Ваш браузер не поддерживает встроенное видео.</video>`;
1388
+ } else if (type === 'image') {
1389
+ modalBody.innerHTML = `<img src="${src}" alt="Просмотр изображения" style="max-width: 100%; max-height: 100%;">`;
1390
  } else {
1391
+ modalBody.innerHTML = `<div style="color: #fff; font-size: 1.2em; text-align: center;">Предпросмотр для этого типа файла недоступен.<br><a href='${src}' download style='color: #aaf; margin-top:10px; display: inline-block;'>Скачать файл</a></div>`;
1392
  }
1393
  modal.style.display = 'flex';
1394
+ document.body.style.overflow = 'hidden';
1395
  }
1396
+
1397
+ function closeModal() {
1398
+ const modal = document.getElementById('mediaModal');
1399
+ const modalBody = document.getElementById('modalBody');
1400
+ modal.style.display = 'none';
1401
+ modalBody.innerHTML = '';
1402
+ document.body.style.overflow = 'auto';
1403
  }
1404
+ function closeModalOnClick(event) {
1405
+ if (event.target.id === 'mediaModal') {
1406
+ closeModal();
1407
+ }
1408
+ }
1409
+ document.addEventListener('keydown', function(event) {
1410
+ if (event.key === "Escape") {
1411
+ closeModal();
1412
+ }
1413
+ });
1414
  </script>
1415
  </body>
1416
  </html>
1417
  '''
1418
  return render_template_string(html, username=username, user_files=user_files, repo_id=REPO_ID)
1419
 
1420
+
1421
  if __name__ == '__main__':
1422
+ # Initial download before starting app and backup thread
1423
+ print("Загрузка начальной базы данных перед запуском...")
1424
+ download_db_from_hf()
1425
+
1426
+ # Start periodic backup in a separate thread
1427
+ # Only start if write token exists
1428
+ if HF_TOKEN_WRITE:
1429
+ backup_thread = threading.Thread(target=periodic_backup, daemon=True)
1430
+ backup_thread.start()
1431
+ print("Поток периодического резервного копирования запущен.")
1432
+ else:
1433
+ print("Токен для записи HF_TOKEN не найден, периодическое резервное копирование отключено.")
1434
+
1435
+ # Run Flask app
1436
+ print("Запуск Flask приложения...")
1437
+ port = int(os.environ.get("PORT", 7860))
1438
+ app.run(debug=False, host='0.0.0.0', port=port)