Eluza133 commited on
Commit
0609403
·
verified ·
1 Parent(s): 8c07211

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +985 -452
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,14 +13,15 @@ import requests
12
  from io import BytesIO
13
 
14
  app = Flask(__name__)
15
- app.secret_key = os.getenv("FLASK_SECRET_KEY", "supersecretkey")
16
  DATA_FILE = 'cloud_data.json'
17
  REPO_ID = "Eluza133/Z1e1u"
18
  HF_TOKEN_WRITE = os.getenv("HF_TOKEN")
19
  HF_TOKEN_READ = os.getenv("HF_TOKEN_READ") or HF_TOKEN_WRITE
 
20
 
21
  cache = Cache(app, config={'CACHE_TYPE': 'simple'})
22
- logging.basicConfig(level=logging.INFO)
23
 
24
  @cache.memoize(timeout=300)
25
  def load_data():
@@ -28,28 +30,41 @@ 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):
 
42
  try:
43
- with open(DATA_FILE, 'w', encoding='utf-8') as file:
44
  json.dump(data, file, ensure_ascii=False, indent=4)
 
45
  upload_db_to_hf()
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 +73,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,
@@ -72,168 +93,294 @@ def download_db_from_hf():
72
  repo_type="dataset",
73
  token=HF_TOKEN_READ,
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
- --background: #0a1128;
101
- --primary: #00a8cc;
102
- --secondary: #f8f9fa;
103
- --accent: #6a4a4a;
104
- --text-primary: #ffffff;
105
- --text-secondary: #c0c0c0;
106
- --card-background: #1e2d4e;
107
- --button-primary: #007bff;
108
- --button-primary-hover: #0056b3;
109
- --button-secondary: #6c757d;
110
- --button-secondary-hover: #5a6268;
111
- --input-background: #343a40;
112
- --input-text: #ffffff;
113
- --border-color: #495057;
114
- --shadow-color: rgba(0, 0, 0, 0.5);
115
- --transition-duration: 0.3s;
116
- --font-family: 'Roboto', sans-serif;
 
 
 
 
 
 
 
 
 
 
 
 
 
117
  }
118
 
119
- body {
120
- font-family: var(--font-family);
121
- background-color: var(--background);
122
- color: var(--text-primary);
123
  margin: 0;
124
  padding: 0;
125
- display: flex;
126
- justify-content: center;
127
- align-items: center;
 
 
 
 
 
 
128
  min-height: 100vh;
 
 
129
  }
130
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
131
  .container {
132
- background-color: var(--card-background);
133
- padding: 40px;
134
- border-radius: 15px;
135
- box-shadow: 0 10px 30px var(--shadow-color);
136
- width: 90%;
137
- max-width: 1200px;
138
- text-align: center;
 
 
 
 
 
 
 
 
139
  }
140
 
141
  h1 {
142
- color: var(--primary);
143
- font-size: 2.5em;
144
- margin-bottom: 20px;
145
- text-shadow: 2px 2px 3px var(--shadow-color);
 
 
 
 
146
  }
147
 
148
  h2 {
149
- color: var(--secondary);
150
- margin-top: 30px;
151
  font-size: 1.8em;
 
 
 
 
 
152
  }
153
 
154
- p {
155
- color: var(--text-secondary);
156
- line-height: 1.7;
157
- margin-bottom: 20px;
158
  }
159
 
160
- a {
161
- color: var(--primary);
162
- text-decoration: none;
163
- transition: color var(--transition-duration) ease;
 
 
 
 
 
 
 
164
  }
165
 
166
- a:hover {
167
- color: var(--accent);
 
 
 
 
 
 
168
  }
169
 
170
- .flash {
171
- background-color: rgba(255, 0, 0, 0.1);
172
- color: #ff6f61;
173
- padding: 15px;
174
- border-radius: 8px;
175
- margin-bottom: 20px;
176
- border: 1px solid rgba(255, 0, 0, 0.3);
177
  }
178
 
179
- input[type="text"],
180
- input[type="password"],
181
  input[type="file"] {
182
- width: calc(100% - 30px);
183
- padding: 15px;
184
- margin: 10px 0;
185
- border-radius: 8px;
186
- border: 1px solid var(--border-color);
187
- background-color: var(--input-background);
188
- color: var(--input-text);
189
- font-size: 1em;
190
- transition: border-color var(--transition-duration) ease;
191
- }
192
-
193
- input[type="text"]:focus,
194
- input[type="password"]:focus,
195
- input[type="file"]:focus {
196
- outline: none;
197
- border-color: var(--primary);
198
- box-shadow: 0 0 0 2px rgba(0, 123, 255, 0.25);
 
 
199
  }
200
 
201
  .btn {
202
- display: inline-block;
203
- padding: 15px 30px;
 
204
  border: none;
205
- border-radius: 8px;
206
- background-color: var(--button-primary);
207
- color: var(--text-primary);
208
- font-size: 1.1em;
209
  cursor: pointer;
210
- transition: background-color var(--transition-duration) ease, transform 0.2s ease;
211
- box-shadow: 0 5px 15px rgba(0, 0, 0, 0.2);
212
- margin-top: 10px;
 
 
213
  text-decoration: none;
 
 
 
214
  }
215
 
216
  .btn:hover {
217
- background-color: var(--button-primary-hover);
218
- transform: scale(1.05);
 
 
 
 
 
219
  }
220
 
221
- .btn-secondary {
222
- background-color: var(--button-secondary);
 
 
 
 
 
 
 
 
 
223
  }
 
 
224
 
225
- .btn-secondary:hover {
226
- background-color: var(--button-secondary-hover);
 
 
 
 
 
 
 
227
  }
228
 
229
- .btn-delete {
230
- background-color: #dc3545;
 
 
231
  }
232
 
233
- .btn-delete:hover {
234
- background-color: #c82333;
 
 
 
 
 
 
 
235
  }
236
 
 
237
  .file-grid {
238
  display: grid;
239
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
@@ -241,657 +388,1043 @@ input[type="file"]:focus {
241
  margin-top: 30px;
242
  }
243
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
244
  .file-item {
245
- background-color: var(--card-background);
246
- border-radius: 12px;
247
- padding: 20px;
248
- box-shadow: 0 5px 20px var(--shadow-color);
249
- transition: transform 0.3s ease;
 
 
 
 
 
 
 
 
 
 
 
 
250
  }
251
 
252
  .file-item:hover {
253
- transform: translateY(-7px);
 
 
 
 
254
  }
255
 
256
- .file-preview {
257
- max-width: 100%;
258
- max-height: 220px;
259
- object-fit: cover;
260
- border-radius: 10px;
261
  margin-bottom: 15px;
 
 
 
 
 
 
 
 
 
 
 
 
262
  display: block;
263
- margin-left: auto;
264
- margin-right: auto;
 
 
 
265
  }
266
 
267
- .file-item p {
268
- color: var(--text-secondary);
269
- font-size: 0.95em;
270
- margin: 10px 0;
271
  }
272
 
273
- .download-btn {
274
- background-color: #28a745;
 
 
 
 
 
 
 
 
 
 
275
  }
276
 
277
- .download-btn:hover {
278
- background-color: #218838;
 
279
  }
280
 
281
- .delete-btn {
282
- background-color: #dc3545;
 
 
 
283
  }
284
 
285
- .delete-btn:hover {
286
- background-color: #c82333;
 
 
287
  }
288
 
289
  .modal {
290
  display: none;
291
  position: fixed;
292
- z-index: 1000;
293
- left: 0;
294
  top: 0;
 
295
  width: 100%;
296
  height: 100%;
297
- overflow: auto;
298
- background-color: rgba(0,0,0,0.9);
299
  justify-content: center;
300
  align-items: center;
301
- padding: 40px;
302
- box-sizing: border-box;
303
  }
304
 
305
  .modal-content {
306
- background-color: var(--card-background);
307
- margin: auto;
 
 
 
 
 
 
 
 
308
  display: block;
309
- max-width: 90%;
310
- max-height: 90%;
311
- border-radius: 10px;
 
 
312
  }
313
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
314
  #progress-container {
315
  width: 100%;
316
- background: var(--input-background);
317
- border-radius: 8px;
318
- margin: 15px 0;
319
- height: 25px;
320
  overflow: hidden;
321
  display: none;
 
 
 
 
 
322
  }
323
 
324
  #progress-bar {
325
  width: 0%;
326
- height: 100%;
327
- background-color: var(--primary);
328
- transition: width 0.2s ease;
 
 
 
 
 
 
329
  }
330
 
331
- .user-list {
332
- margin-top: 20px;
333
- display: grid;
334
- grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
335
- gap: 20px;
 
 
 
336
  }
337
-
338
- .user-item {
339
- padding: 20px;
340
- background-color: var(--card-background);
341
- border-radius: 10px;
342
- box-shadow: 0 3px 10px var(--shadow-color);
343
- transition: transform 0.3s ease;
344
  }
345
 
346
- .user-item:hover {
347
- transform: translateY(-5px);
 
348
  }
349
 
350
- .user-item a {
351
- color: var(--primary);
352
- font-weight: bold;
353
  text-decoration: none;
354
- display: block;
355
- margin-bottom: 10px;
 
 
356
  }
357
 
358
- .user-item p {
359
- color: var(--text-secondary);
360
- font-size: 0.9em;
361
- margin: 5px 0;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
362
  }
363
  '''
364
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
365
  @app.route('/register', methods=['GET', 'POST'])
366
  def register():
367
  if request.method == 'POST':
368
- username = request.form.get('username')
369
  password = request.form.get('password')
 
 
 
 
 
 
 
 
 
370
 
371
  data = load_data()
372
 
373
  if username in data['users']:
374
- flash('Пользователь с таким логином уже существует!')
375
  return redirect(url_for('register'))
376
 
377
- if not username or not password:
378
- flash('Логин и пароль обязательны!')
379
- return redirect(url_for('register'))
 
380
 
381
  data['users'][username] = {
382
- 'password': password,
383
  'created_at': datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
384
  'files': []
385
  }
386
- save_data(data)
387
- session['username'] = username
388
- flash('Регистрация успешна!')
389
- return redirect(url_for('dashboard'))
 
 
 
 
 
390
 
391
  html = '''
392
  <!DOCTYPE html>
393
- <html lang="en">
394
  <head>
395
  <meta charset="UTF-8">
396
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
397
  <title>Регистрация - Zeus Cloud</title>
398
- <link href="https://fonts.googleapis.com/css2?family=Roboto:wght@400;700&display=swap" rel="stylesheet">
399
- <style>''' + BASE_STYLE + '''</style>
400
  </head>
401
  <body>
 
402
  <div class="container">
403
  <h1>Регистрация в Zeus Cloud</h1>
404
- {% with messages = get_flashed_messages() %}
405
- {% if messages %}
406
- {% for message in messages %}
407
- <div class="flash">{{ message }}</div>
408
- {% endfor %}
409
- {% endif %}
410
- {% endwith %}
411
  <form method="POST" id="register-form">
412
- <input type="text" name="username" placeholder="Введите логин" required>
413
- <input type="password" name="password" placeholder="Введите пароль" required>
 
414
  <button type="submit" class="btn">Зарегистрироваться</button>
415
  </form>
416
- <p style="margin-top: 20px;">Уже есть аккаунт? <a href="{{ url_for('login') }}">Войдите</a></p>
417
  </div>
 
418
  </body>
419
  </html>
420
- '''
421
  return render_template_string(html)
422
 
423
  @app.route('/', methods=['GET', 'POST'])
424
  def login():
 
 
 
425
  if request.method == 'POST':
426
  username = request.form.get('username')
427
  password = request.form.get('password')
428
  data = load_data()
429
 
 
 
 
430
  if username in data['users'] and data['users'][username]['password'] == password:
431
  session['username'] = username
 
 
432
  return jsonify({'status': 'success', 'redirect': url_for('dashboard')})
433
  else:
434
  return jsonify({'status': 'error', 'message': 'Неверный логин или пароль!'})
435
 
436
  html = '''
437
  <!DOCTYPE html>
438
- <html lang="en">
439
  <head>
440
  <meta charset="UTF-8">
441
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
442
- <title>Zeus Cloud</title>
443
- <link href="https://fonts.googleapis.com/css2?family=Roboto:wght@400;700&display=swap" rel="stylesheet">
444
- <style>''' + BASE_STYLE + '''</style>
445
  </head>
446
  <body>
 
447
  <div class="container">
448
  <h1>Zeus Cloud</h1>
449
  <div id="flash-messages">
450
- {% with messages = get_flashed_messages() %}
451
- {% if messages %}
452
- {% for message in messages %}
453
- <div class="flash">{{ message }}</div>
454
- {% endfor %}
455
- {% endif %}
456
- {% endwith %}
457
  </div>
458
  <form method="POST" id="login-form">
459
  <input type="text" name="username" placeholder="Введите логин" required>
460
  <input type="password" name="password" placeholder="Введите пароль" required>
461
  <button type="submit" class="btn">Войти</button>
462
  </form>
463
- <p style="margin-top: 20px;">Нет аккаунта? <a href="{{ url_for('register') }}">Зарегистрируйтесь</a></p>
464
  </div>
 
465
  <script>
466
  const savedCredentials = JSON.parse(localStorage.getItem('zeusCredentials'));
467
  if (savedCredentials) {
468
- fetch('/', {
469
  method: 'POST',
470
- headers: {
471
  'Content-Type': 'application/x-www-form-urlencoded',
472
- },
473
- body: `username=${encodeURIComponent(savedCredentials.username)}&password=${encodeURIComponent(savedCredentials.password)}`
474
- })
475
  .then(response => response.json())
476
- .then(data => {
477
- if (data.status === 'success') {
478
  window.location.href = data.redirect;
479
- }
480
- })
481
- .catch(error => console.error('Ошибка автоматического входа:', error));
 
 
 
 
 
 
482
  }
483
 
484
- document.getElementById('login-form').addEventListener('submit', function(e) {
485
  e.preventDefault();
486
  const formData = new FormData(this);
487
- fetch('/', {
 
 
 
488
  method: 'POST',
489
  body: formData
490
- })
491
  .then(response => response.json())
492
- .then(data => {
493
- if (data.status === 'success') {
494
  const username = formData.get('username');
495
  const password = formData.get('password');
496
- localStorage.setItem('zeusCredentials', JSON.stringify({ username, password }));
 
497
  window.location.href = data.redirect;
498
- } else {
499
- document.getElementById('flash-messages').innerHTML = `<div class="flash">${data.message}</div>`;
500
- }
501
- })
502
- .catch(error => {
503
- document.getElementById('flash-messages').innerHTML = `<div class="flash">Ошибка соединения!</div>`;
504
- });
505
- });
506
  </script>
507
  </body>
508
  </html>
509
- '''
510
  return render_template_string(html)
511
 
512
  @app.route('/dashboard', methods=['GET', 'POST'])
513
  def dashboard():
514
  if 'username' not in session:
515
- flash('Пожалуйста, войдите!')
516
  return redirect(url_for('login'))
517
 
518
  username = session['username']
519
  data = load_data()
520
  if username not in data['users']:
521
  session.pop('username', None)
522
- flash('Пользователь не найден!')
523
  return redirect(url_for('login'))
524
 
525
- user_files = sorted(data['users'][username]['files'], key=lambda x: x['upload_date'], reverse=True)
526
-
527
  if request.method == 'POST':
528
  files = request.files.getlist('files')
529
- if files and len(files) > 20:
530
- flash('Максимум 20 файлов за раз!')
 
 
 
 
531
  return redirect(url_for('dashboard'))
532
 
533
- if files:
534
- os.makedirs('uploads', exist_ok=True)
535
- api = HfApi()
536
- temp_files = []
537
 
538
- for file in files:
539
- if file and file.filename:
540
- filename = secure_filename(file.filename)
541
- temp_path = os.path.join('uploads', filename)
 
 
 
 
 
 
 
 
 
 
 
542
  file.save(temp_path)
543
- temp_files.append((temp_path, filename))
544
-
545
- for temp_path, filename in temp_files:
546
- file_path = f"cloud_files/{username}/{filename}"
547
- api.upload_file(
548
- path_or_fileobj=temp_path,
549
- path_in_repo=file_path,
550
- repo_id=REPO_ID,
551
- repo_type="dataset",
552
- token=HF_TOKEN_WRITE,
553
- commit_message=f"Загружен файл для {username}"
554
- )
555
-
556
- file_info = {
557
- 'filename': filename,
558
- 'path': file_path,
559
- 'type': get_file_type(filename),
560
- 'upload_date': datetime.now().strftime('%Y-%m-%d %H:%M:%S')
561
- }
562
- data['users'][username]['files'].append(file_info)
563
-
564
- if os.path.exists(temp_path):
565
- os.remove(temp_path)
566
-
567
- save_data(data)
568
- flash('Файлы успешно загружены!')
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
569
 
570
  return redirect(url_for('dashboard'))
571
 
 
 
 
572
  html = '''
573
  <!DOCTYPE html>
574
- <html lang="en">
575
  <head>
576
  <meta charset="UTF-8">
577
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
578
- <title>Dashboard - Zeus Cloud</title>
579
- <link href="https://fonts.googleapis.com/css2?family=Roboto:wght@400;700&display=swap" rel="stylesheet">
580
- <style>''' + BASE_STYLE + '''</style>
581
  </head>
582
  <body>
 
583
  <div class="container">
584
- <h1>Панель управления Zeus Cloud</h1>
585
- <p>Пользователь: {{ username }}</p>
586
- {% with messages = get_flashed_messages() %}
587
- {% if messages %}
588
- {% for message in messages %}
589
- <div class="flash">{{ message }}</div>
590
- {% endfor %}
591
- {% endif %}
592
- {% endwith %}
593
- <form id="upload-form" method="POST" enctype="multipart/form-data">
594
- <input type="file" name="files" multiple required accept="image/*,video/*">
595
- <button type="submit" class="btn" id="upload-btn">Загрузить файлы</button>
 
596
  </form>
597
  <div id="progress-container">
598
- <div id="progress-bar"></div>
599
  </div>
 
600
  <h2>Ваши файлы</h2>
601
  <div class="file-grid">
602
- {% for file in user_files %}
603
  <div class="file-item">
604
- {% if file['type'] == 'video' %}
605
- <video class="file-preview" preload="metadata" muted loading="lazy" onclick="openModal('https://huggingface.co/datasets/{{ repo_id }}/resolve/main/{{ file['path'] }}', true)">
606
- <source src="https://huggingface.co/datasets/{{ repo_id }}/resolve/main/{{ file['path'] }}" type="video/mp4">
 
 
607
  </video>
608
- {% elif file['type'] == 'image' %}
609
- <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)">
610
- {% else %}
611
- <p>{{ file['filename'] }}</p>
612
- {% endif %}
613
- <p>{{ file['upload_date'] }}</p>
614
- <a href="{{ url_for('download_file', file_path=file['path'], filename=file['filename']) }}" class="btn download-btn">Скачать</a>
615
- <a href="{{ url_for('delete_file', file_path=file['path']) }}" class="btn delete-btn" onclick="return confirm('Вы уверены, что хотите удалить этот файл?');">Удалить</a>
 
 
 
 
616
  </div>
617
- {% endfor %}
618
- {% if not user_files %}
619
- <p>У вас пока нет загруженных файлов.</p>
620
- {% endif %}
621
  </div>
622
- <a href="{{ url_for('logout') }}" class="btn btn-secondary" style="margin-top: 20px;" id="logout-btn">Выйти</a>
623
  </div>
624
- <div class="modal" id="mediaModal" onclick="closeModal(event)">
625
- <div id="modalContent"></div>
 
626
  </div>
627
- <script>
628
- function openModal(src, isVideo) {
629
- const modal = document.getElementById('mediaModal');
630
- const modalContent = document.getElementById('modalContent');
631
- if (isVideo) {
632
- modalContent.innerHTML = `<video controls class="modal-content"><source src="${src}" type="video/mp4"></video>`;
633
- } else {
634
- modalContent.innerHTML = `<img class="modal-content" src="${src}">`;
635
- }
636
- modal.style.display = 'flex';
637
- }
638
- function closeModal(event) {
639
- if (event.target === document.getElementById('mediaModal')) {
640
- const modal = document.getElementById('mediaModal');
641
- modal.style.display = 'none';
642
- modal.innerHTML = '<div id="modalContent"></div>';
643
- }
644
- }
645
 
 
 
646
  const form = document.getElementById('upload-form');
647
  const progressBar = document.getElementById('progress-bar');
648
  const progressContainer = document.getElementById('progress-container');
649
  const uploadBtn = document.getElementById('upload-btn');
 
650
 
651
- form.addEventListener('submit', function(e) {
652
  e.preventDefault();
653
- const files = form.querySelector('input[type="file"]').files;
654
- if (files.length > 20) {
 
 
 
 
655
  alert('Максимум 20 файлов за раз!');
656
  return;
657
- }
658
 
659
  const formData = new FormData(form);
660
  progressContainer.style.display = 'block';
661
  progressBar.style.width = '0%';
 
662
  uploadBtn.disabled = true;
 
 
663
 
664
  const xhr = new XMLHttpRequest();
665
  xhr.open('POST', '/dashboard', true);
666
 
667
- xhr.upload.onprogress = function(event) {
668
- if (event.lengthComputable) {
669
- const percent = (event.loaded / event.total) * 100;
670
  progressBar.style.width = percent + '%';
671
- }
672
- };
673
-
674
- xhr.onload = function() {
675
- if (xhr.status === 200) {
676
- location.reload();
677
- } else {
678
- alert('Ошибка загрузки!');
679
- progressContainer.style.display = 'none';
680
- uploadBtn.disabled = false;
681
- }
682
- };
683
-
684
- xhr.onerror = function() {
685
- alert('Ошибка соединения!');
686
  progressContainer.style.display = 'none';
687
  uploadBtn.disabled = false;
688
- };
 
689
 
690
  xhr.send(formData);
691
- });
692
 
693
- document.getElementById('logout-btn').addEventListener('click', function(e) {
694
  e.preventDefault();
695
- localStorage.removeItem('zeusCredentials');
696
- window.location.href = '/logout';
697
- });
698
  </script>
699
  </body>
700
  </html>
701
- '''
702
  return render_template_string(html, username=username, user_files=user_files, repo_id=REPO_ID)
703
 
 
704
  @app.route('/download/<path:file_path>/<filename>')
705
  def download_file(file_path, filename):
706
  if 'username' not in session:
707
- flash('Пожалуйста, войдите!')
708
  return redirect(url_for('login'))
709
 
710
  username = session['username']
711
  data = load_data()
712
  if username not in data['users']:
713
  session.pop('username', None)
714
- flash('Пользователь не найден!')
715
  return redirect(url_for('login'))
716
 
717
- user_files = data['users'][username]['files']
718
- if not any(file['path'] == file_path for file in user_files):
719
- flash('У вас нет доступа к этому файлу!')
 
 
 
 
720
  return redirect(url_for('dashboard'))
721
 
722
- file_url = f"https://huggingface.co/datasets/{REPO_ID}/resolve/main/{file_path}"
723
- response = requests.get(file_url)
 
 
 
724
 
725
- if response.status_code == 200:
726
- file_content = BytesIO(response.content)
 
 
 
 
 
 
 
 
 
 
 
727
  return send_file(
728
- file_content,
729
  as_attachment=True,
730
- download_name=filename,
731
- mimetype='application/octet-stream'
732
  )
733
- else:
734
- flash('Ошибка при скачивании файла!')
735
- return redirect(url_for('dashboard'))
 
 
 
 
736
 
737
  @app.route('/delete/<path:file_path>')
738
  def delete_file(file_path):
739
  if 'username' not in session:
740
- flash('Пожалуйста, войдите!')
741
  return redirect(url_for('login'))
742
 
743
  username = session['username']
744
  data = load_data()
745
  if username not in data['users']:
746
  session.pop('username', None)
747
- flash('Пользователь не найден!')
748
  return redirect(url_for('login'))
749
 
750
- user_files = data['users'][username]['files']
751
- file_to_delete = next((file for file in user_files if file['path'] == file_path), None)
752
 
753
  if not file_to_delete:
754
- flash('Файл не найден!')
 
 
 
 
 
755
  return redirect(url_for('dashboard'))
756
 
757
  try:
 
758
  api = HfApi()
759
  api.delete_file(
760
  path_in_repo=file_path,
761
  repo_id=REPO_ID,
762
  repo_type="dataset",
763
- token=HF_TOKEN_WRITE,
764
- commit_message=f"Удален файл {file_path} для {username}"
765
  )
 
 
 
766
  data['users'][username]['files'] = [f for f in user_files if f['path'] != file_path]
767
  save_data(data)
768
- flash('Файл успешно удален!')
 
769
  except Exception as e:
770
- logging.error(f"Ошибка при удалении файла: {e}")
771
- flash('Ошибка при удалении файла!')
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
772
 
773
  return redirect(url_for('dashboard'))
774
 
775
  @app.route('/logout')
776
  def logout():
777
  session.pop('username', None)
 
 
778
  return redirect(url_for('login'))
779
 
780
  @app.route('/admhosto')
781
  def admin_panel():
 
 
 
 
782
  data = load_data()
783
- users = data['users']
784
 
785
  html = '''
786
  <!DOCTYPE html>
787
- <html lang="en">
788
  <head>
789
  <meta charset="UTF-8">
790
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
791
  <title>Админ-панель - Zeus Cloud</title>
792
- <link href="https://fonts.googleapis.com/css2?family=Roboto:wght@400;700&display=swap" rel="stylesheet">
793
- <style>''' + BASE_STYLE + '''</style>
794
  </head>
795
  <body>
 
796
  <div class="container">
797
  <h1>Админ-панель Zeus Cloud</h1>
798
  <h2>Список пользователей</h2>
799
  <div class="user-list">
800
- {% for username, user_data in users.items() %}
801
  <div class="user-item">
802
- <a href="{{ url_for('admin_user_files', username=username) }}">{{ username }}</a>
803
- <p>Дата регистрации: {{ user_data['created_at'] }}</p>
804
- <p>Количество файлов: {{ user_data['files'] | length }}</p>
 
805
  </div>
806
- {% endfor %}
807
- {% if not users %}
808
- <p>Пользователей пока нет.</p>
809
- {% endif %}
810
  </div>
 
811
  </div>
 
812
  </body>
813
  </html>
814
- '''
815
  return render_template_string(html, users=users)
816
 
817
  @app.route('/admhosto/user/<username>')
818
  def admin_user_files(username):
 
 
 
819
  data = load_data()
820
- if username not in data['users']:
821
- flash('Пользователь не найден!')
822
  return redirect(url_for('admin_panel'))
823
 
824
- user_files = sorted(data['users'][username]['files'], key=lambda x: x['upload_date'], reverse=True)
825
 
826
  html = '''
827
  <!DOCTYPE html>
828
- <html lang="en">
829
  <head>
830
  <meta charset="UTF-8">
831
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
832
  <title>Файлы пользователя {{ username }} - Zeus Cloud</title>
833
- <link href="https://fonts.googleapis.com/css2?family=Roboto:wght@400;700&display=swap" rel="stylesheet">
834
- <style>''' + BASE_STYLE + '''</style>
835
  </head>
836
  <body>
 
837
  <div class="container">
838
  <h1>Файлы пользователя: {{ username }}</h1>
839
- {% with messages = get_flashed_messages() %}
840
- {% if messages %}
841
- {% for message in messages %}
842
- <div class="flash">{{ message }}</div>
843
- {% endfor %}
844
- {% endif %}
845
- {% endwith %}
846
  <div class="file-grid">
847
- {% for file in user_files %}
848
  <div class="file-item">
849
- {% if file['type'] == 'video' %}
850
- <video class="file-preview" preload="metadata" muted loading="lazy" onclick="openModal('https://huggingface.co/datasets/{{ repo_id }}/resolve/main/{{ file['path'] }}', true)">
851
- <source src="https://huggingface.co/datasets/{{ repo_id }}/resolve/main/{{ file['path'] }}" type="video/mp4">
 
 
852
  </video>
853
- {% elif file['type'] == 'image' %}
854
- <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)">
855
- {% else %}
856
- <p>{{ file['filename'] }}</p>
857
- {% endif %}
858
- <p>{{ file['upload_date'] }}</p>
859
- <a href="{{ url_for('download_file', file_path=file['path'], filename=file['filename']) }}" class="btn download-btn">Скачать</a>
 
 
 
 
 
 
 
860
  </div>
861
- {% endfor %}
862
- {% if not user_files %}
863
- <p>У пользователя пока нет файлов.</p>
864
- {% endif %}
865
  </div>
866
- <a href="{{ url_for('admin_panel') }}" class="btn btn-secondary" style="margin-top: 20px;">Назад к списку пользователей</a>
867
  </div>
868
- <div class="modal" id="mediaModal" onclick="closeModal(event)">
869
- <div id="modalContent"></div>
870
  </div>
871
- <script>
872
- function openModal(src, isVideo) {
873
- const modal = document.getElementById('mediaModal');
874
- const modalContent = document.getElementById('modalContent');
875
- if (isVideo) {
876
- modalContent.innerHTML = `<video controls class="modal-content"><source src="${src}" type="video/mp4"></video>`;
877
- } else {
878
- modalContent.innerHTML = `<img class="modal-content" src="${src}">`;
879
- }
880
- modal.style.display = 'flex';
881
- }
882
- function closeModal(event) {
883
- if (event.target === document.getElementById('mediaModal')) {
884
- const modal = document.getElementById('mediaModal');
885
- modal.style.display = 'none';
886
- modal.innerHTML = '<div id="modalContent"></div>';
887
- }
888
- }
889
- </script>
890
  </body>
891
  </html>
892
- '''
893
  return render_template_string(html, username=username, user_files=user_files, repo_id=REPO_ID)
894
 
 
895
  if __name__ == '__main__':
896
- threading.Thread(target=periodic_backup, daemon=True).start()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
897
  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_please_change") # Ensure a strong, unique secret key in production
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
+ # REGISTRATION_CODE is removed as requested
22
 
23
  cache = Cache(app, config={'CACHE_TYPE': 'simple'})
24
+ logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
25
 
26
  @cache.memoize(timeout=300)
27
  def load_data():
 
30
  with open(DATA_FILE, 'r', encoding='utf-8') as file:
31
  data = json.load(file)
32
  if not isinstance(data, dict):
33
+ logging.warning("Data file is not a dictionary, initializing empty structure.")
34
  return {'users': {}, 'files': {}}
35
  data.setdefault('users', {})
36
  data.setdefault('files', {})
37
+ logging.info("Data loaded successfully.")
38
  return data
39
+ except FileNotFoundError:
40
+ logging.warning(f"{DATA_FILE} not found. Initializing empty structure.")
41
+ return {'users': {}, 'files': {}}
42
+ except json.JSONDecodeError:
43
+ logging.error(f"Error decoding JSON from {DATA_FILE}. Initializing empty structure.")
44
+ return {'users': {}, 'files': {}}
45
  except Exception as e:
46
+ logging.error(f"Error loading data: {e}")
47
  return {'users': {}, 'files': {}}
48
 
49
  def save_data(data):
50
+ temp_file = DATA_FILE + '.tmp'
51
  try:
52
+ with open(temp_file, 'w', encoding='utf-8') as file:
53
  json.dump(data, file, ensure_ascii=False, indent=4)
54
+ os.replace(temp_file, DATA_FILE)
55
  upload_db_to_hf()
56
  cache.clear()
57
+ logging.info("Data saved successfully and scheduled for HF upload.")
58
  except Exception as e:
59
+ logging.error(f"Error saving data: {e}")
60
+ if os.path.exists(temp_file):
61
+ os.remove(temp_file)
62
  raise
63
 
64
  def upload_db_to_hf():
65
+ if not HF_TOKEN_WRITE:
66
+ logging.warning("HF_TOKEN_WRITE not set. Skipping Hugging Face upload.")
67
+ return
68
  try:
69
  api = HfApi()
70
  api.upload_file(
 
73
  repo_id=REPO_ID,
74
  repo_type="dataset",
75
  token=HF_TOKEN_WRITE,
76
+ commit_message=f"Backup {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}"
77
  )
78
+ logging.info("Database uploaded to Hugging Face.")
79
  except Exception as e:
80
+ logging.error(f"Error uploading database to Hugging Face: {e}")
81
 
82
  def download_db_from_hf():
83
+ if not HF_TOKEN_READ:
84
+ logging.warning("HF_TOKEN_READ not set. Skipping Hugging Face download.")
85
+ if not os.path.exists(DATA_FILE):
86
+ with open(DATA_FILE, 'w', encoding='utf-8') as f:
87
+ json.dump({'users': {}, 'files': {}}, f)
88
+ return
89
  try:
90
  hf_hub_download(
91
  repo_id=REPO_ID,
 
93
  repo_type="dataset",
94
  token=HF_TOKEN_READ,
95
  local_dir=".",
96
+ local_dir_use_symlinks=False,
97
+ force_download=True # Ensure we get the latest version
98
  )
99
+ logging.info("Database downloaded from Hugging Face.")
100
  except Exception as e:
101
+ logging.error(f"Error downloading database from Hugging Face: {e}")
102
  if not os.path.exists(DATA_FILE):
103
+ logging.info("Creating empty database file as download failed and file doesn't exist.")
104
  with open(DATA_FILE, 'w', encoding='utf-8') as f:
105
  json.dump({'users': {}, 'files': {}}, f)
106
 
107
  def periodic_backup():
108
  while True:
109
+ time.sleep(1800) # Backup every 30 minutes
110
+ logging.info("Initiating periodic backup...")
111
+ try:
112
+ data = load_data.sync() # Use sync version if available or handle async appropriately
113
+ save_data(data) # This already includes the HF upload
114
+ except Exception as e:
115
+ logging.error(f"Error during periodic backup: {e}")
116
+
117
 
118
  def get_file_type(filename):
119
+ video_extensions = ('.mp4', '.mov', '.avi', '.webm', '.mkv', '.flv', '.wmv')
120
+ image_extensions = ('.jpg', '.jpeg', '.png', '.gif', '.bmp', '.svg', '.webp')
121
+ filename_lower = filename.lower()
122
+ if filename_lower.endswith(video_extensions):
123
  return 'video'
124
+ elif filename_lower.endswith(image_extensions):
125
  return 'image'
126
  return 'other'
127
 
128
  BASE_STYLE = '''
129
+ @import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;600;800&display=swap');
130
+
131
  :root {
132
+ --primary-hue: 345;
133
+ --secondary-hue: 185;
134
+ --accent-hue: 260;
135
+
136
+ --primary-color: hsl(var(--primary-hue), 100%, 60%);
137
+ --secondary-color: hsl(var(--secondary-hue), 100%, 45%);
138
+ --accent-color: hsl(var(--accent-hue), 80%, 65%);
139
+
140
+ --bg-light: #f8f9fa;
141
+ --bg-dark: #121212;
142
+ --card-bg-light: rgba(255, 255, 255, 0.9);
143
+ --card-bg-dark: rgba(28, 28, 30, 0.85);
144
+ --text-light: #212529;
145
+ --text-dark: #e4e6eb;
146
+ --border-light: rgba(0, 0, 0, 0.1);
147
+ --border-dark: rgba(255, 255, 255, 0.15);
148
+
149
+ --shadow-light: 0 10px 30px rgba(0, 0, 0, 0.1);
150
+ --shadow-dark: 0 10px 30px rgba(0, 0, 0, 0.4);
151
+ --glass-bg-light: rgba(255, 255, 255, 0.2);
152
+ --glass-bg-dark: rgba(50, 50, 50, 0.3);
153
+
154
+ --delete-color: hsl(0, 80%, 60%);
155
+ --download-color: hsl(145, 63%, 49%);
156
+
157
+ --transition-fast: all 0.2s ease-out;
158
+ --transition-medium: all 0.4s cubic-bezier(0.25, 0.8, 0.25, 1);
159
+ --border-radius-sm: 8px;
160
+ --border-radius-md: 16px;
161
+ --border-radius-lg: 24px;
162
  }
163
 
164
+ *, *::before, *::after {
 
 
 
165
  margin: 0;
166
  padding: 0;
167
+ box-sizing: border-box;
168
+ }
169
+
170
+ body {
171
+ font-family: 'Inter', sans-serif;
172
+ background: var(--bg-light);
173
+ color: var(--text-light);
174
+ line-height: 1.7;
175
+ transition: background 0.3s ease, color 0.3s ease;
176
  min-height: 100vh;
177
+ padding-top: 20px;
178
+ padding-bottom: 50px;
179
  }
180
 
181
+ body.dark {
182
+ background: var(--bg-dark);
183
+ color: var(--text-dark);
184
+ }
185
+
186
+ .theme-toggle {
187
+ position: fixed;
188
+ top: 15px;
189
+ right: 15px;
190
+ background: var(--card-bg-light);
191
+ border: 1px solid var(--border-light);
192
+ color: var(--text-light);
193
+ padding: 8px 12px;
194
+ border-radius: var(--border-radius-sm);
195
+ cursor: pointer;
196
+ z-index: 1001;
197
+ transition: var(--transition-medium);
198
+ box-shadow: var(--shadow-light);
199
+ }
200
+
201
+ body.dark .theme-toggle {
202
+ background: var(--card-bg-dark);
203
+ border-color: var(--border-dark);
204
+ color: var(--text-dark);
205
+ box-shadow: var(--shadow-dark);
206
+ }
207
+
208
+ .theme-toggle:hover {
209
+ transform: scale(1.05);
210
+ box-shadow: 0 5px 15px rgba(0, 0, 0, 0.15);
211
+ }
212
+
213
+ body.dark .theme-toggle:hover {
214
+ box-shadow: 0 5px 15px rgba(0, 0, 0, 0.5);
215
+ }
216
+
217
+
218
  .container {
219
+ margin: 20px auto;
220
+ max-width: 1300px;
221
+ padding: 30px 40px;
222
+ background: var(--card-bg-light);
223
+ border-radius: var(--border-radius-lg);
224
+ box-shadow: var(--shadow-light);
225
+ backdrop-filter: blur(10px);
226
+ border: 1px solid transparent;
227
+ transition: var(--transition-medium);
228
+ }
229
+
230
+ body.dark .container {
231
+ background: var(--card-bg-dark);
232
+ box-shadow: var(--shadow-dark);
233
+ border: 1px solid var(--border-dark);
234
  }
235
 
236
  h1 {
237
+ font-size: 2.8em;
238
+ font-weight: 800;
239
+ text-align: center;
240
+ margin-bottom: 35px;
241
+ background: linear-gradient(135deg, var(--primary-color), var(--accent-color));
242
+ -webkit-background-clip: text;
243
+ color: transparent;
244
+ letter-spacing: -1px;
245
  }
246
 
247
  h2 {
 
 
248
  font-size: 1.8em;
249
+ margin-top: 40px;
250
+ margin-bottom: 15px;
251
+ color: var(--primary-color);
252
+ padding-bottom: 5px;
253
+ border-bottom: 2px solid hsla(var(--primary-hue), 100%, 60%, 0.3);
254
  }
255
 
256
+ body.dark h2 {
257
+ color: var(--primary-color);
258
+ border-bottom-color: hsla(var(--primary-hue), 100%, 60%, 0.5);
 
259
  }
260
 
261
+ input[type="text"], input[type="password"], input[type="file"], textarea {
262
+ width: 100%;
263
+ padding: 16px 18px;
264
+ margin: 10px 0 20px 0;
265
+ border: 1px solid var(--border-light);
266
+ border-radius: var(--border-radius-md);
267
+ background: var(--glass-bg-light);
268
+ color: var(--text-light);
269
+ font-size: 1.1em;
270
+ transition: var(--transition-fast);
271
+ box-shadow: inset 0 2px 4px rgba(0, 0, 0, 0.06);
272
  }
273
 
274
+ body.dark input[type="text"],
275
+ body.dark input[type="password"],
276
+ body.dark input[type="file"],
277
+ body.dark textarea {
278
+ background: var(--glass-bg-dark);
279
+ color: var(--text-dark);
280
+ border-color: var(--border-dark);
281
+ box-shadow: inset 0 2px 4px rgba(0, 0, 0, 0.2);
282
  }
283
 
284
+ input:focus, textarea:focus {
285
+ outline: none;
286
+ border-color: var(--primary-color);
287
+ box-shadow: 0 0 0 3px hsla(var(--primary-hue), 100%, 60%, 0.3);
 
 
 
288
  }
289
 
 
 
290
  input[type="file"] {
291
+ padding: 12px 18px;
292
+ cursor: pointer;
293
+ }
294
+
295
+ input[type="file"]::file-selector-button {
296
+ margin-right: 15px;
297
+ border: none;
298
+ background: linear-gradient(135deg, var(--secondary-color), var(--accent-color));
299
+ padding: 10px 18px;
300
+ border-radius: var(--border-radius-sm);
301
+ color: white;
302
+ cursor: pointer;
303
+ transition: var(--transition-fast);
304
+ box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
305
+ }
306
+
307
+ input[type="file"]::file-selector-button:hover {
308
+ transform: translateY(-1px);
309
+ box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
310
  }
311
 
312
  .btn {
313
+ padding: 15px 35px;
314
+ background: linear-gradient(135deg, var(--primary-color), hsl(var(--primary-hue), 100%, 50%));
315
+ color: white;
316
  border: none;
317
+ border-radius: var(--border-radius-md);
 
 
 
318
  cursor: pointer;
319
+ font-size: 1.15em;
320
+ font-weight: 600;
321
+ transition: var(--transition-medium);
322
+ box-shadow: 0 4px 15px hsla(var(--primary-hue), 100%, 50%, 0.3);
323
+ display: inline-block;
324
  text-decoration: none;
325
+ text-align: center;
326
+ margin-top: 10px;
327
+ margin-right: 10px;
328
  }
329
 
330
  .btn:hover {
331
+ transform: translateY(-3px) scale(1.03);
332
+ box-shadow: 0 8px 25px hsla(var(--primary-hue), 100%, 50%, 0.4);
333
+ }
334
+
335
+ .btn:active {
336
+ transform: translateY(0px) scale(1);
337
+ box-shadow: 0 4px 15px hsla(var(--primary-hue), 100%, 50%, 0.3);
338
  }
339
 
340
+ .download-btn {
341
+ background: linear-gradient(135deg, var(--download-color), hsl(145, 63%, 39%));
342
+ box-shadow: 0 4px 15px hsla(145, 63%, 49%, 0.3);
343
+ }
344
+ .download-btn:hover { box-shadow: 0 8px 25px hsla(145, 63%, 49%, 0.4); }
345
+ .download-btn:active { box-shadow: 0 4px 15px hsla(145, 63%, 49%, 0.3); }
346
+
347
+
348
+ .delete-btn {
349
+ background: linear-gradient(135deg, var(--delete-color), hsl(0, 80%, 50%));
350
+ box-shadow: 0 4px 15px hsla(0, 80%, 60%, 0.3);
351
  }
352
+ .delete-btn:hover { box-shadow: 0 8px 25px hsla(0, 80%, 60%, 0.4); }
353
+ .delete-btn:active { box-shadow: 0 4px 15px hsla(0, 80%, 60%, 0.3); }
354
 
355
+ .flash {
356
+ padding: 15px 20px;
357
+ margin-bottom: 20px;
358
+ border-radius: var(--border-radius-md);
359
+ text-align: center;
360
+ font-weight: 600;
361
+ background-color: hsla(var(--secondary-hue), 80%, 85%, 0.8);
362
+ color: hsl(var(--secondary-hue), 100%, 25%);
363
+ border: 1px solid hsla(var(--secondary-hue), 100%, 45%, 0.3);
364
  }
365
 
366
+ body.dark .flash {
367
+ background-color: hsla(var(--secondary-hue), 50%, 30%, 0.7);
368
+ color: hsl(var(--secondary-hue), 100%, 85%);
369
+ border-color: hsla(var(--secondary-hue), 100%, 45%, 0.5);
370
  }
371
 
372
+ .flash.error {
373
+ background-color: hsla(var(--primary-hue), 80%, 85%, 0.8);
374
+ color: hsl(var(--primary-hue), 100%, 25%);
375
+ border: 1px solid hsla(var(--primary-hue), 100%, 60%, 0.3);
376
+ }
377
+ body.dark .flash.error {
378
+ background-color: hsla(var(--primary-hue), 50%, 30%, 0.7);
379
+ color: hsl(var(--primary-hue), 100%, 85%);
380
+ border-color: hsla(var(--primary-hue), 100%, 60%, 0.5);
381
  }
382
 
383
+
384
  .file-grid {
385
  display: grid;
386
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
 
388
  margin-top: 30px;
389
  }
390
 
391
+ .user-list {
392
+ margin-top: 20px;
393
+ display: grid;
394
+ grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
395
+ gap: 20px;
396
+ }
397
+
398
+ .user-item {
399
+ padding: 20px 25px;
400
+ background: var(--card-bg-light);
401
+ border-radius: var(--border-radius-md);
402
+ margin-bottom: 10px;
403
+ box-shadow: var(--shadow-light);
404
+ transition: var(--transition-medium);
405
+ border: 1px solid var(--border-light);
406
+ }
407
+
408
+ body.dark .user-item {
409
+ background: var(--card-bg-dark);
410
+ border-color: var(--border-dark);
411
+ box-shadow: var(--shadow-dark);
412
+ }
413
+
414
+ .user-item:hover {
415
+ transform: translateY(-5px);
416
+ box-shadow: 0 15px 35px rgba(0, 0, 0, 0.15);
417
+ }
418
+
419
+ body.dark .user-item:hover {
420
+ box-shadow: 0 15px 35px rgba(0, 0, 0, 0.5);
421
+ }
422
+
423
+
424
+ .user-item a {
425
+ color: var(--primary-color);
426
+ text-decoration: none;
427
+ font-weight: 600;
428
+ font-size: 1.2em;
429
+ display: block;
430
+ margin-bottom: 8px;
431
+ }
432
+
433
+ .user-item a:hover {
434
+ color: var(--accent-color);
435
+ }
436
+
437
+ .user-item p {
438
+ font-size: 0.9em;
439
+ color: var(--text-light);
440
+ opacity: 0.8;
441
+ }
442
+ body.dark .user-item p {
443
+ color: var(--text-dark);
444
+ }
445
+
446
  .file-item {
447
+ background: var(--card-bg-light);
448
+ padding: 15px;
449
+ border-radius: var(--border-radius-md);
450
+ box-shadow: var(--shadow-light);
451
+ text-align: center;
452
+ transition: var(--transition-medium);
453
+ display: flex;
454
+ flex-direction: column;
455
+ justify-content: space-between;
456
+ overflow: hidden;
457
+ border: 1px solid var(--border-light);
458
+ }
459
+
460
+ body.dark .file-item {
461
+ background: var(--card-bg-dark);
462
+ border-color: var(--border-dark);
463
+ box-shadow: var(--shadow-dark);
464
  }
465
 
466
  .file-item:hover {
467
+ transform: translateY(-8px) scale(1.02);
468
+ box-shadow: 0 18px 40px rgba(0, 0, 0, 0.18);
469
+ }
470
+ body.dark .file-item:hover {
471
+ box-shadow: 0 18px 40px rgba(0, 0, 0, 0.5);
472
  }
473
 
474
+ .file-preview-container {
475
+ width: 100%;
476
+ height: 200px; /* Fixed height container */
 
 
477
  margin-bottom: 15px;
478
+ border-radius: var(--border-radius-sm);
479
+ overflow: hidden;
480
+ background-color: rgba(0,0,0,0.05); /* Placeholder bg */
481
+ display: flex;
482
+ align-items: center;
483
+ justify-content: center;
484
+ }
485
+ body.dark .file-preview-container {
486
+ background-color: rgba(255,255,255,0.05);
487
+ }
488
+
489
+ .file-preview {
490
  display: block;
491
+ width: 100%;
492
+ height: 100%;
493
+ object-fit: cover; /* Cover the container */
494
+ cursor: pointer;
495
+ transition: transform 0.3s ease;
496
  }
497
 
498
+ .file-item:hover .file-preview {
499
+ transform: scale(1.05);
 
 
500
  }
501
 
502
+
503
+ .file-item p {
504
+ font-size: 0.9em;
505
+ margin: 8px 0;
506
+ word-wrap: break-word;
507
+ }
508
+ .file-item p.filename {
509
+ font-weight: 600;
510
+ color: var(--text-light);
511
+ }
512
+ body.dark .file-item p.filename {
513
+ color: var(--text-dark);
514
  }
515
 
516
+ .file-item p.date {
517
+ font-size: 0.8em;
518
+ opacity: 0.7;
519
  }
520
 
521
+ .file-item .actions {
522
+ margin-top: 15px;
523
+ display: flex;
524
+ justify-content: space-around;
525
+ gap: 10px;
526
  }
527
 
528
+ .file-item .actions .btn {
529
+ padding: 8px 15px;
530
+ font-size: 0.9em;
531
+ flex-grow: 1;
532
  }
533
 
534
  .modal {
535
  display: none;
536
  position: fixed;
 
 
537
  top: 0;
538
+ left: 0;
539
  width: 100%;
540
  height: 100%;
541
+ background: rgba(0, 0, 0, 0.9);
542
+ z-index: 2000;
543
  justify-content: center;
544
  align-items: center;
545
+ padding: 20px;
546
+ cursor: pointer;
547
  }
548
 
549
  .modal-content {
550
+ position: relative;
551
+ max-width: 95%;
552
+ max-height: 95%;
553
+ display: flex;
554
+ justify-content: center;
555
+ align-items: center;
556
+ cursor: default;
557
+ }
558
+
559
+ .modal img, .modal video {
560
  display: block;
561
+ max-width: 100%;
562
+ max-height: 100%;
563
+ object-fit: contain;
564
+ border-radius: var(--border-radius-md);
565
+ box-shadow: 0 20px 50px rgba(0, 0, 0, 0.5);
566
  }
567
 
568
+ .modal-close {
569
+ position: absolute;
570
+ top: -35px;
571
+ right: -25px;
572
+ color: #fff;
573
+ font-size: 2.5em;
574
+ font-weight: bold;
575
+ cursor: pointer;
576
+ transition: transform 0.2s ease;
577
+ line-height: 1;
578
+ }
579
+ .modal-close:hover {
580
+ transform: scale(1.1);
581
+ color: var(--primary-color);
582
+ }
583
+
584
+
585
  #progress-container {
586
  width: 100%;
587
+ background: var(--glass-bg-light);
588
+ border-radius: var(--border-radius-md);
589
+ margin: 20px 0;
 
590
  overflow: hidden;
591
  display: none;
592
+ border: 1px solid var(--border-light);
593
+ }
594
+ body.dark #progress-container {
595
+ background: var(--glass-bg-dark);
596
+ border: 1px solid var(--border-dark);
597
  }
598
 
599
  #progress-bar {
600
  width: 0%;
601
+ height: 25px;
602
+ background: linear-gradient(90deg, var(--secondary-color), var(--accent-color));
603
+ border-radius: var(--border-radius-md) 0 0 var(--border-radius-md);
604
+ transition: width 0.4s ease;
605
+ text-align: center;
606
+ line-height: 25px;
607
+ color: white;
608
+ font-weight: 600;
609
+ font-size: 0.9em;
610
  }
611
 
612
+ form#login-form, form#register-form {
613
+ max-width: 450px;
614
+ margin: 30px auto;
615
+ padding: 30px;
616
+ background: var(--card-bg-light);
617
+ border-radius: var(--border-radius-lg);
618
+ box-shadow: var(--shadow-light);
619
+ border: 1px solid var(--border-light);
620
  }
621
+ body.dark form#login-form, body.dark form#register-form {
622
+ background: var(--card-bg-dark);
623
+ box-shadow: var(--shadow-dark);
624
+ border: 1px solid var(--border-dark);
 
 
 
625
  }
626
 
627
+ form#login-form p, form#register-form p {
628
+ text-align: center;
629
+ margin-top: 25px;
630
  }
631
 
632
+ form#login-form a, form#register-form a {
633
+ color: var(--primary-color);
634
+ font-weight: 600;
635
  text-decoration: none;
636
+ }
637
+ form#login-form a:hover, form#register-form a:hover {
638
+ text-decoration: underline;
639
+ color: var(--accent-color);
640
  }
641
 
642
+
643
+ @media (max-width: 768px) {
644
+ .container { padding: 20px; }
645
+ h1 { font-size: 2.2em; margin-bottom: 25px;}
646
+ h2 { font-size: 1.5em; }
647
+ .file-grid { grid-template-columns: repeat(auto-fill, minmax(220px, 1fr)); gap: 15px;}
648
+ .file-item { padding: 10px; }
649
+ .file-preview-container { height: 160px; }
650
+ .btn { padding: 12px 25px; font-size: 1em; }
651
+ .file-item .actions .btn { font-size: 0.8em; padding: 6px 10px;}
652
+ .theme-toggle { padding: 6px 10px; font-size: 0.9em;}
653
+ }
654
+
655
+ @media (max-width: 480px) {
656
+ h1 { font-size: 1.8em; }
657
+ .file-grid { grid-template-columns: 1fr; gap: 20px;}
658
+ .file-item { padding: 15px; }
659
+ .file-preview-container { height: 180px; }
660
+ .btn { width: 100%; margin-right: 0; margin-bottom: 10px; }
661
+ .file-item .actions { flex-direction: column; }
662
+ .file-item .actions .btn { width: auto;}
663
+ form#login-form, form#register-form { padding: 20px; }
664
+ .modal-close { top: 5px; right: 5px; font-size: 2em; }
665
  }
666
  '''
667
 
668
+ GLOBAL_JAVASCRIPT = '''
669
+ <script>
670
+ const themeToggle = document.getElementById('themeToggle');
671
+ const body = document.body;
672
+
673
+ function applyTheme(theme) {
674
+ if (theme === 'dark') {
675
+ body.classList.add('dark');
676
+ if(themeToggle) themeToggle.textContent = 'Light Mode';
677
+ localStorage.setItem('theme', 'dark');
678
+ } else {
679
+ body.classList.remove('dark');
680
+ if(themeToggle) themeToggle.textContent = 'Dark Mode';
681
+ localStorage.setItem('theme', 'light');
682
+ }
683
+ }
684
+
685
+ if (themeToggle) {
686
+ themeToggle.addEventListener('click', () => {
687
+ const currentTheme = localStorage.getItem('theme') || (window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light');
688
+ applyTheme(currentTheme === 'dark' ? 'light' : 'dark');
689
+ });
690
+ }
691
+
692
+ // Apply saved theme or system preference on initial load
693
+ const savedTheme = localStorage.getItem('theme');
694
+ const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
695
+ applyTheme(savedTheme || (prefersDark ? 'dark' : 'light'));
696
+
697
+ function openModal(src, isVideo) {
698
+ const modal = document.getElementById('mediaModal');
699
+ if (!modal) return;
700
+ const modalContent = document.getElementById('modalContent');
701
+ let contentHTML = '';
702
+ if (isVideo) {
703
+ contentHTML = `<video controls autoplay playsinline><source src="${src}" type="video/mp4">Your browser does not support the video tag.</video>`;
704
+ } else {
705
+ contentHTML = `<img src="${src}" alt="Preview">`;
706
+ }
707
+ modalContent.innerHTML = contentHTML + '<span class="modal-close" onclick="closeModal(event)">×</span>';
708
+ modal.style.display = 'flex';
709
+ // Add event listener to close modal on Escape key press
710
+ document.addEventListener('keydown', handleEscKey);
711
+ }
712
+
713
+ function closeModal(event) {
714
+ // Check if the click was directly on the modal backdrop or the close button
715
+ if (event.target.id === 'mediaModal' || event.target.classList.contains('modal-close')) {
716
+ const modal = document.getElementById('mediaModal');
717
+ if (!modal) return;
718
+ modal.style.display = 'none';
719
+ // Stop video playback if any
720
+ const video = modal.querySelector('video');
721
+ if (video) {
722
+ video.pause();
723
+ video.removeAttribute('src'); // detach the source
724
+ video.load();
725
+ }
726
+ modal.querySelector('#modalContent').innerHTML = ''; // Clear content
727
+ document.removeEventListener('keydown', handleEscKey); // Remove listener
728
+ event.stopPropagation(); // Prevent event bubbling if needed
729
+ }
730
+ }
731
+
732
+ function handleEscKey(event) {
733
+ if (event.key === 'Escape') {
734
+ closeModal({ target: document.getElementById('mediaModal') }); // Simulate click on backdrop
735
+ }
736
+ }
737
+
738
+ // Add event listener for clicks outside the modal content but within the modal area
739
+ const modalElement = document.getElementById('mediaModal');
740
+ if(modalElement) {
741
+ modalElement.addEventListener('click', closeModal);
742
+ }
743
+
744
+
745
+ </script>
746
+ '''
747
+
748
  @app.route('/register', methods=['GET', 'POST'])
749
  def register():
750
  if request.method == 'POST':
751
+ username = request.form.get('username', '').strip()
752
  password = request.form.get('password')
753
+ # code = request.form.get('code') # Removed as requested
754
+
755
+ if not username or not password:
756
+ flash('Логин и пароль обязательны!', 'error')
757
+ return redirect(url_for('register'))
758
+
759
+ if len(username) < 3 or len(password) < 6:
760
+ flash('Логин должен быть не менее 3 символов, пароль не менее 6 символов.', 'error')
761
+ return redirect(url_for('register'))
762
 
763
  data = load_data()
764
 
765
  if username in data['users']:
766
+ flash('Пользователь с таким логином уже существует!', 'error')
767
  return redirect(url_for('register'))
768
 
769
+ # Removed registration code check
770
+ # if code != REGISTRATION_CODE:
771
+ # flash('Неверный регистрационный код!')
772
+ # return redirect(url_for('register'))
773
 
774
  data['users'][username] = {
775
+ 'password': password, # In a real app, HASH the password!
776
  'created_at': datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
777
  'files': []
778
  }
779
+ try:
780
+ save_data(data)
781
+ session['username'] = username
782
+ flash('Регистрация успешна!', 'success')
783
+ return redirect(url_for('dashboard'))
784
+ except Exception as e:
785
+ flash('Ошибка при сохранении данных регистрации.', 'error')
786
+ logging.error(f"Registration save error for {username}: {e}")
787
+ return redirect(url_for('register'))
788
 
789
  html = '''
790
  <!DOCTYPE html>
791
+ <html lang="ru">
792
  <head>
793
  <meta charset="UTF-8">
794
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
795
  <title>Регистрация - Zeus Cloud</title>
796
+ <style>{style}</style>
 
797
  </head>
798
  <body>
799
+ <button id="themeToggle">Dark Mode</button>
800
  <div class="container">
801
  <h1>Регистрация в Zeus Cloud</h1>
802
+ {{% with messages = get_flashed_messages(with_categories=true) %}}
803
+ {{% if messages %}}
804
+ {{% for category, message in messages %}}
805
+ <div class="flash {{ category }}">{{ message }}</div>
806
+ {{% endfor %}}
807
+ {{% endif %}}
808
+ {{% endwith %}}
809
  <form method="POST" id="register-form">
810
+ <input type="text" name="username" placeholder="Придумайте логин (мин. 3 символа)" required minlength="3">
811
+ <input type="password" name="password" placeholder="Придумайте пароль (мин. 6 символов)" required minlength="6">
812
+ <!-- Removed registration code input -->
813
  <button type="submit" class="btn">Зарегистрироваться</button>
814
  </form>
815
+ <p>Уже есть аккаунт? <a href="{{{{ url_for('login') }}}}">Войдите</a></p>
816
  </div>
817
+ {global_js}
818
  </body>
819
  </html>
820
+ '''.format(style=BASE_STYLE, global_js=GLOBAL_JAVASCRIPT)
821
  return render_template_string(html)
822
 
823
  @app.route('/', methods=['GET', 'POST'])
824
  def login():
825
+ if 'username' in session:
826
+ return redirect(url_for('dashboard')) # Redirect if already logged in
827
+
828
  if request.method == 'POST':
829
  username = request.form.get('username')
830
  password = request.form.get('password')
831
  data = load_data()
832
 
833
+ # IMPORTANT: Use password hashing in a real application!
834
+ # Example: from werkzeug.security import check_password_hash
835
+ # if username in data['users'] and check_password_hash(data['users'][username]['password_hash'], password):
836
  if username in data['users'] and data['users'][username]['password'] == password:
837
  session['username'] = username
838
+ session.permanent = True # Make session persistent
839
+ app.permanent_session_lifetime = timedelta(days=30) # Example: 30 days
840
  return jsonify({'status': 'success', 'redirect': url_for('dashboard')})
841
  else:
842
  return jsonify({'status': 'error', 'message': 'Неверный логин или пароль!'})
843
 
844
  html = '''
845
  <!DOCTYPE html>
846
+ <html lang="ru">
847
  <head>
848
  <meta charset="UTF-8">
849
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
850
+ <title>Вход - Zeus Cloud</title>
851
+ <style>{style}</style>
 
852
  </head>
853
  <body>
854
+ <button id="themeToggle">Dark Mode</button>
855
  <div class="container">
856
  <h1>Zeus Cloud</h1>
857
  <div id="flash-messages">
858
+ {{% with messages = get_flashed_messages(with_categories=true) %}}
859
+ {{% if messages %}}
860
+ {{% for category, message in messages %}}
861
+ <div class="flash {{ category }}">{{ message }}</div>
862
+ {{% endfor %}}
863
+ {{% endif %}}
864
+ {{% endwith %}}
865
  </div>
866
  <form method="POST" id="login-form">
867
  <input type="text" name="username" placeholder="Введите логин" required>
868
  <input type="password" name="password" placeholder="Введите пароль" required>
869
  <button type="submit" class="btn">Войти</button>
870
  </form>
871
+ <p>Нет аккаунта? <a href="{{{{ url_for('register') }}}}">Зарегистрируйтесь</a></p>
872
  </div>
873
+ {global_js}
874
  <script>
875
  const savedCredentials = JSON.parse(localStorage.getItem('zeusCredentials'));
876
  if (savedCredentials) {
877
+ fetch('/', {{
878
  method: 'POST',
879
+ headers: {{
880
  'Content-Type': 'application/x-www-form-urlencoded',
881
+ }},
882
+ body: `username=${{encodeURIComponent(savedCredentials.username)}}&password=${{encodeURIComponent(savedCredentials.password)}}`
883
+ }})
884
  .then(response => response.json())
885
+ .then(data => {{
886
+ if (data.status === 'success') {{
887
  window.location.href = data.redirect;
888
+ }} else {{
889
+ // Clear invalid credentials if auto-login fails
890
+ localStorage.removeItem('zeusCredentials');
891
+ }}
892
+ }})
893
+ .catch(error => {{
894
+ console.error('Ошибка автоматического входа:', error);
895
+ localStorage.removeItem('zeusCredentials');
896
+ }});
897
  }
898
 
899
+ document.getElementById('login-form').addEventListener('submit', function(e) {{
900
  e.preventDefault();
901
  const formData = new FormData(this);
902
+ const flashContainer = document.getElementById('flash-messages');
903
+ flashContainer.innerHTML = ''; // Clear previous messages
904
+
905
+ fetch('/', {{
906
  method: 'POST',
907
  body: formData
908
+ }})
909
  .then(response => response.json())
910
+ .then(data => {{
911
+ if (data.status === 'success') {{
912
  const username = formData.get('username');
913
  const password = formData.get('password');
914
+ // Consider security implications before storing credentials.
915
+ // localStorage.setItem('zeusCredentials', JSON.stringify({{ username, password }}));
916
  window.location.href = data.redirect;
917
+ }} else {{
918
+ flashContainer.innerHTML = `<div class="flash error">${{data.message}}</div>`;
919
+ }}
920
+ }})
921
+ .catch(error => {{
922
+ flashContainer.innerHTML = `<div class="flash error">Ошибка соединения! Попробуйте позже.</div>`;
923
+ }});
924
+ }});
925
  </script>
926
  </body>
927
  </html>
928
+ '''.format(style=BASE_STYLE, global_js=GLOBAL_JAVASCRIPT)
929
  return render_template_string(html)
930
 
931
  @app.route('/dashboard', methods=['GET', 'POST'])
932
  def dashboard():
933
  if 'username' not in session:
934
+ flash('Пожалуйста, войдите!', 'error')
935
  return redirect(url_for('login'))
936
 
937
  username = session['username']
938
  data = load_data()
939
  if username not in data['users']:
940
  session.pop('username', None)
941
+ flash('Пользователь не найден! Пожалуйста, войдите снова.', 'error')
942
  return redirect(url_for('login'))
943
 
 
 
944
  if request.method == 'POST':
945
  files = request.files.getlist('files')
946
+ if not files or not files[0].filename:
947
+ flash('Не выбраны файлы для загрузки.', 'error')
948
+ return redirect(url_for('dashboard'))
949
+
950
+ if len(files) > 20:
951
+ flash('Можно загрузить не более 20 файлов за раз!', 'error')
952
  return redirect(url_for('dashboard'))
953
 
954
+ if not HF_TOKEN_WRITE:
955
+ flash('О��ибка конфигурации сервера: загрузка файлов невозможна.', 'error')
956
+ logging.error("HF_TOKEN_WRITE is not configured for file upload.")
957
+ return redirect(url_for('dashboard'))
958
 
959
+ upload_dir = 'uploads'
960
+ os.makedirs(upload_dir, exist_ok=True)
961
+ api = HfApi()
962
+ files_uploaded_info = []
963
+ errors_occurred = False
964
+
965
+ for file in files:
966
+ if file and file.filename:
967
+ original_filename = secure_filename(file.filename)
968
+ # Create a unique filename to avoid conflicts (e.g., user_timestamp_filename)
969
+ timestamp = datetime.now().strftime("%Y%m%d%H%M%S%f")
970
+ unique_filename = f"{timestamp}_{original_filename}"
971
+ temp_path = os.path.join(upload_dir, unique_filename)
972
+
973
+ try:
974
  file.save(temp_path)
975
+ file_size = os.path.getsize(temp_path)
976
+ # Add size check if needed (e.g., max 100MB per file)
977
+ # if file_size > 100 * 1024 * 1024:
978
+ # flash(f'Файл {original_filename} слишком большой!', 'error')
979
+ # os.remove(temp_path)
980
+ # continue
981
+
982
+ hf_file_path = f"cloud_files/{username}/{unique_filename}"
983
+ logging.info(f"Uploading {original_filename} to {hf_file_path}")
984
+ api.upload_file(
985
+ path_or_fileobj=temp_path,
986
+ path_in_repo=hf_file_path,
987
+ repo_id=REPO_ID,
988
+ repo_type="dataset",
989
+ token=HF_TOKEN_WRITE
990
+ # Removed commit message for potentially faster uploads
991
+ )
992
+ logging.info(f"Successfully uploaded {original_filename} to HF.")
993
+
994
+ file_info = {
995
+ 'filename': original_filename, # Store original name for display
996
+ 'hf_filename': unique_filename, # Store unique name used in HF
997
+ 'path': hf_file_path,
998
+ 'type': get_file_type(original_filename),
999
+ 'upload_date': datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
1000
+ 'size': file_size # Optionally store file size
1001
+ }
1002
+ files_uploaded_info.append(file_info)
1003
+
1004
+ except Exception as e:
1005
+ logging.error(f"Error uploading file {original_filename} for {username}: {e}")
1006
+ errors_occurred = True
1007
+ flash(f'Ошибка при загрузке файла: {original_filename}', 'error')
1008
+ finally:
1009
+ if os.path.exists(temp_path):
1010
+ try:
1011
+ os.remove(temp_path)
1012
+ except OSError as e:
1013
+ logging.error(f"Error removing temporary file {temp_path}: {e}")
1014
+
1015
+
1016
+ if files_uploaded_info:
1017
+ data['users'][username]['files'].extend(files_uploaded_info)
1018
+ try:
1019
+ save_data(data)
1020
+ if not errors_occurred:
1021
+ flash('Файлы успешно загружены!', 'success')
1022
+ else:
1023
+ flash('Часть файлов загружена, но произошли ошибки.', 'warning')
1024
+ except Exception as e:
1025
+ flash('Ошибка при сохранении информации о файлах.', 'error')
1026
+ logging.error(f"Error saving file metadata after upload for {username}: {e}")
1027
 
1028
  return redirect(url_for('dashboard'))
1029
 
1030
+
1031
+ user_files = sorted(data['users'][username].get('files', []), key=lambda x: x['upload_date'], reverse=True)
1032
+
1033
  html = '''
1034
  <!DOCTYPE html>
1035
+ <html lang="ru">
1036
  <head>
1037
  <meta charset="UTF-8">
1038
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
1039
+ <title>Панель управления - Zeus Cloud</title>
1040
+ <style>{style}</style>
 
1041
  </head>
1042
  <body>
1043
+ <button id="themeToggle">Dark Mode</button>
1044
  <div class="container">
1045
+ <h1>Zeus Cloud</h1>
1046
+ <p style="text-align: center; margin-bottom: 20px; font-size: 1.1em;">Пользователь: <strong>{{ username }}</strong></p>
1047
+ {{% with messages = get_flashed_messages(with_categories=true) %}}
1048
+ {{% if messages %}}
1049
+ {{% for category, message in messages %}}
1050
+ <div class="flash {{ category }}">{{ message }}</div>
1051
+ {{% endfor %}}
1052
+ {{% endif %}}
1053
+ {{% endwith %}}
1054
+
1055
+ <form id="upload-form" method="POST" enctype="multipart/form-data" style="margin-bottom: 30px;">
1056
+ <input type="file" name="files" multiple required accept="image/*,video/*,.pdf,.doc,.docx,.xls,.xlsx,.ppt,.pptx,.zip,.rar,.txt">
1057
+ <button type="submit" class="btn" id="upload-btn">Загрузить файлы (макс 20)</button>
1058
  </form>
1059
  <div id="progress-container">
1060
+ <div id="progress-bar">0%</div>
1061
  </div>
1062
+
1063
  <h2>Ваши файлы</h2>
1064
  <div class="file-grid">
1065
+ {{% for file in user_files %}}
1066
  <div class="file-item">
1067
+ <div class="file-preview-container">
1068
+ {{% set file_url = "https://huggingface.co/datasets/{repo_id}/resolve/main/{path}".format(repo_id=repo_id, path=file.path) %}}
1069
+ {{% if file['type'] == 'video' %}}
1070
+ <video class="file-preview" preload="metadata" muted loading="lazy" onclick="openModal('{file_url}', true)">
1071
+ <source src="{file_url}" type="video/mp4">
1072
  </video>
1073
+ {{% elif file['type'] == 'image' %}}
1074
+ <img class="file-preview" src="{file_url}" alt="{{{{ file.filename }}}}" loading="lazy" onclick="openModal(this.src, false)">
1075
+ {{% else %}}
1076
+ <p style="align-self: center; padding: 20px; font-size: 1.2em; color: var(--secondary-color);">📄</p> {# Generic file icon #}
1077
+ {{% endif %}}
1078
+ </div>
1079
+ <p class="filename">{{{{ file.filename }}}}</p>
1080
+ <p class="date">{{{{ file.upload_date }}}}</p>
1081
+ <div class="actions">
1082
+ <a href="{{{{ url_for('download_file', file_path=file.path, filename=file.filename) }}}}" class="btn download-btn">Скачать</a>
1083
+ <a href="{{{{ url_for('delete_file', file_path=file.path) }}}}" class="btn delete-btn" onclick="return confirm('Вы уверены, что хотите удалить файл \\'{{{{ file.filename }}}}\\'? Это действие необратимо.');">Удалить</a>
1084
+ </div>
1085
  </div>
1086
+ {{% endfor %}}
1087
+ {{% if not user_files %}}
1088
+ <p style="grid-column: 1 / -1; text-align: center; margin-top: 20px; opacity: 0.8;">У вас пока нет загруженных файлов.</p>
1089
+ {{% endif %}}
1090
  </div>
1091
+ <a href="#" class="btn" style="margin-top: 40px;" id="logout-btn">Выйти</a>
1092
  </div>
1093
+
1094
+ <div class="modal" id="mediaModal">
1095
+ <div id="modalContent" class="modal-content"></div>
1096
  </div>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1097
 
1098
+ {global_js}
1099
+ <script>
1100
  const form = document.getElementById('upload-form');
1101
  const progressBar = document.getElementById('progress-bar');
1102
  const progressContainer = document.getElementById('progress-container');
1103
  const uploadBtn = document.getElementById('upload-btn');
1104
+ const fileInput = form.querySelector('input[type="file"]');
1105
 
1106
+ form.addEventListener('submit', function(e) {{
1107
  e.preventDefault();
1108
+ const files = fileInput.files;
1109
+ if (files.length === 0) {{
1110
+ alert('Пожалуйста, выберите файлы для загрузки.');
1111
+ return;
1112
+ }}
1113
+ if (files.length > 20) {{
1114
  alert('Максимум 20 файлов за раз!');
1115
  return;
1116
+ }}
1117
 
1118
  const formData = new FormData(form);
1119
  progressContainer.style.display = 'block';
1120
  progressBar.style.width = '0%';
1121
+ progressBar.textContent = '0%';
1122
  uploadBtn.disabled = true;
1123
+ uploadBtn.textContent = 'Загрузка...';
1124
+
1125
 
1126
  const xhr = new XMLHttpRequest();
1127
  xhr.open('POST', '/dashboard', true);
1128
 
1129
+ xhr.upload.onprogress = function(event) {{
1130
+ if (event.lengthComputable) {{
1131
+ const percent = Math.round((event.loaded / event.total) * 100);
1132
  progressBar.style.width = percent + '%';
1133
+ progressBar.textContent = percent + '%';
1134
+ }}
1135
+ }};
1136
+
1137
+ xhr.onload = function() {{
1138
+ // Reload the page regardless of success or error to show flash messages
1139
+ // Server-side handles flash messages for success/partial success/failure
1140
+ progressBar.textContent = 'Завершено';
1141
+ setTimeout(() => {{ window.location.reload(); }}, 500); // Reload after a short delay
1142
+
1143
+ }};
1144
+
1145
+ xhr.onerror = function() {{
1146
+ alert('Ошибка соединения! Не удалось загрузить файлы.');
 
1147
  progressContainer.style.display = 'none';
1148
  uploadBtn.disabled = false;
1149
+ uploadBtn.textContent = 'Загрузить файлы (макс 20)';
1150
+ }};
1151
 
1152
  xhr.send(formData);
1153
+ }});
1154
 
1155
+ document.getElementById('logout-btn').addEventListener('click', function(e) {{
1156
  e.preventDefault();
1157
+ localStorage.removeItem('zeusCredentials'); // Clear any saved credentials on logout
1158
+ window.location.href = '{{{{ url_for('logout') }}}}';
1159
+ }});
1160
  </script>
1161
  </body>
1162
  </html>
1163
+ '''.format(style=BASE_STYLE, global_js=GLOBAL_JAVASCRIPT)
1164
  return render_template_string(html, username=username, user_files=user_files, repo_id=REPO_ID)
1165
 
1166
+
1167
  @app.route('/download/<path:file_path>/<filename>')
1168
  def download_file(file_path, filename):
1169
  if 'username' not in session:
1170
+ flash('Пожалуйста, войдите!', 'error')
1171
  return redirect(url_for('login'))
1172
 
1173
  username = session['username']
1174
  data = load_data()
1175
  if username not in data['users']:
1176
  session.pop('username', None)
1177
+ flash('Пользователь не найден!', 'error')
1178
  return redirect(url_for('login'))
1179
 
1180
+ # Verify if the file belongs to the user OR if the user is admin (implement admin check later if needed)
1181
+ user_files = data['users'][username].get('files', [])
1182
+ is_owner = any(file['path'] == file_path for file in user_files)
1183
+ # is_admin = session.get('is_admin', False) # Placeholder for admin logic
1184
+
1185
+ if not is_owner: # and not is_admin: # Add admin check here if needed
1186
+ flash('У вас нет доступа к этому файлу!', 'error')
1187
  return redirect(url_for('dashboard'))
1188
 
1189
+ if not HF_TOKEN_READ:
1190
+ flash('Ошибка конфигурации сервера: скачивание файлов недоступно.', 'error')
1191
+ logging.error("HF_TOKEN_READ is not configured for file download.")
1192
+ return redirect(request.referrer or url_for('dashboard'))
1193
+
1194
 
1195
+ # Use hf_hub_download to get the file content
1196
+ try:
1197
+ logging.info(f"Attempting to download {file_path} for user {username}")
1198
+ downloaded_file_path = hf_hub_download(
1199
+ repo_id=REPO_ID,
1200
+ filename=file_path,
1201
+ repo_type="dataset",
1202
+ token=HF_TOKEN_READ
1203
+ )
1204
+ logging.info(f"File {file_path} downloaded to {downloaded_file_path}")
1205
+
1206
+ # It's generally safer to send the file from the downloaded path
1207
+ # rather than reading it all into memory if files can be large.
1208
  return send_file(
1209
+ downloaded_file_path,
1210
  as_attachment=True,
1211
+ download_name=filename # Use the original filename for the user
1212
+ # mimetype can be guessed by send_file or set explicitly if needed
1213
  )
1214
+
1215
+ except Exception as e:
1216
+ logging.error(f"Error downloading file {file_path} from HF: {e}")
1217
+ flash('Ошибка при скачивании файла с сервера.', 'error')
1218
+ # Redirect back to where the user came from, or dashboard as fallback
1219
+ return redirect(request.referrer or url_for('dashboard'))
1220
+
1221
 
1222
  @app.route('/delete/<path:file_path>')
1223
  def delete_file(file_path):
1224
  if 'username' not in session:
1225
+ flash('Пожалуйста, войдите!', 'error')
1226
  return redirect(url_for('login'))
1227
 
1228
  username = session['username']
1229
  data = load_data()
1230
  if username not in data['users']:
1231
  session.pop('username', None)
1232
+ flash('Пользователь не найден!', 'error')
1233
  return redirect(url_for('login'))
1234
 
1235
+ user_files = data['users'][username].get('files', [])
1236
+ file_to_delete = next((f for f in user_files if f['path'] == file_path), None)
1237
 
1238
  if not file_to_delete:
1239
+ flash('Файл не найден или у вас нет прав на его удаление!', 'error')
1240
+ return redirect(url_for('dashboard'))
1241
+
1242
+ if not HF_TOKEN_WRITE:
1243
+ flash('Ошибка конфигурации сервера: удаление файлов невозможно.', 'error')
1244
+ logging.error("HF_TOKEN_WRITE is not configured for file deletion.")
1245
  return redirect(url_for('dashboard'))
1246
 
1247
  try:
1248
+ logging.info(f"Attempting to delete file {file_path} for user {username}")
1249
  api = HfApi()
1250
  api.delete_file(
1251
  path_in_repo=file_path,
1252
  repo_id=REPO_ID,
1253
  repo_type="dataset",
1254
+ token=HF_TOKEN_WRITE
1255
+ # commit_message=f"Deleted file {file_path} for {username}" # Optional
1256
  )
1257
+ logging.info(f"Successfully deleted file {file_path} from HF.")
1258
+
1259
+ # Update the local data file
1260
  data['users'][username]['files'] = [f for f in user_files if f['path'] != file_path]
1261
  save_data(data)
1262
+ flash(f'Файл "{file_to_delete["filename"]}" успешно удален!', 'success')
1263
+
1264
  except Exception as e:
1265
+ logging.error(f"Error deleting file {file_path} from HF or updating data: {e}")
1266
+ # Check if the error is file not found on HF, maybe it was already deleted?
1267
+ if "404 Client Error" in str(e):
1268
+ logging.warning(f"File {file_path} not found on HF during deletion attempt, possibly already deleted. Removing from local data.")
1269
+ # Still try to remove from local data if it exists there
1270
+ if any(f['path'] == file_path for f in data['users'][username]['files']):
1271
+ data['users'][username]['files'] = [f for f in user_files if f['path'] != file_path]
1272
+ try:
1273
+ save_data(data)
1274
+ flash(f'Файл "{file_to_delete["filename"]}" удален (возможно, уже был удален с хранилища).', 'warning')
1275
+ except Exception as save_err:
1276
+ logging.error(f"Error saving data after confirming HF deletion failed for {file_path}: {save_err}")
1277
+ flash('Ошибка при обновлении списка файлов после удаления.', 'error')
1278
+ else:
1279
+ flash('Файл не найден.', 'error')
1280
+
1281
+ else:
1282
+ flash('Ошибка при удалении файла.', 'error')
1283
 
1284
  return redirect(url_for('dashboard'))
1285
 
1286
  @app.route('/logout')
1287
  def logout():
1288
  session.pop('username', None)
1289
+ # session.pop('is_admin', None) # Clear admin status if used
1290
+ flash('Вы успешно вышли из системы.', 'success')
1291
  return redirect(url_for('login'))
1292
 
1293
  @app.route('/admhosto')
1294
  def admin_panel():
1295
+ # Add authentication/authorization check here!
1296
+ # Example: if not session.get('is_admin'): abort(403)
1297
+ # For now, it's open, which is insecure.
1298
+
1299
  data = load_data()
1300
+ users = data.get('users', {})
1301
 
1302
  html = '''
1303
  <!DOCTYPE html>
1304
+ <html lang="ru">
1305
  <head>
1306
  <meta charset="UTF-8">
1307
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
1308
  <title>Админ-панель - Zeus Cloud</title>
1309
+ <style>{style}</style>
 
1310
  </head>
1311
  <body>
1312
+ <button id="themeToggle">Dark Mode</button>
1313
  <div class="container">
1314
  <h1>Админ-панель Zeus Cloud</h1>
1315
  <h2>Список пользователей</h2>
1316
  <div class="user-list">
1317
+ {{% for username, user_data in users.items() %}}
1318
  <div class="user-item">
1319
+ <a href="{{{{ url_for('admin_user_files', username=username) }}}}">{{ username }}</a>
1320
+ <p>Дата регистрации: {{ user_data.get('created_at', 'N/A') }}</p>
1321
+ <p>Количество файлов: {{ user_data.get('files', []) | length }}</p>
1322
+ {# Add more user info or actions here if needed #}
1323
  </div>
1324
+ {{% endfor %}}
1325
+ {{% if not users %}}
1326
+ <p style="grid-column: 1 / -1; text-align: center; opacity: 0.8;">Пользователей пока нет.</p>
1327
+ {{% endif %}}
1328
  </div>
1329
+ {# Add more admin features here: server status, settings, etc. #}
1330
  </div>
1331
+ {global_js}
1332
  </body>
1333
  </html>
1334
+ '''.format(style=BASE_STYLE, global_js=GLOBAL_JAVASCRIPT)
1335
  return render_template_string(html, users=users)
1336
 
1337
  @app.route('/admhosto/user/<username>')
1338
  def admin_user_files(username):
1339
+ # Add authentication/authorization check here!
1340
+ # Example: if not session.get('is_admin'): abort(403)
1341
+
1342
  data = load_data()
1343
+ if username not in data.get('users', {}):
1344
+ flash('Пользователь не найден!', 'error')
1345
  return redirect(url_for('admin_panel'))
1346
 
1347
+ user_files = sorted(data['users'][username].get('files', []), key=lambda x: x.get('upload_date', ''), reverse=True)
1348
 
1349
  html = '''
1350
  <!DOCTYPE html>
1351
+ <html lang="ru">
1352
  <head>
1353
  <meta charset="UTF-8">
1354
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
1355
  <title>Файлы пользователя {{ username }} - Zeus Cloud</title>
1356
+ <style>{style}</style>
 
1357
  </head>
1358
  <body>
1359
+ <button id="themeToggle">Dark Mode</button>
1360
  <div class="container">
1361
  <h1>Файлы пользователя: {{ username }}</h1>
1362
+ {{% with messages = get_flashed_messages(with_categories=true) %}}
1363
+ {{% if messages %}}
1364
+ {{% for category, message in messages %}}
1365
+ <div class="flash {{ category }}">{{ message }}</div>
1366
+ {{% endfor %}}
1367
+ {{% endif %}}
1368
+ {{% endwith %}}
1369
  <div class="file-grid">
1370
+ {{% for file in user_files %}}
1371
  <div class="file-item">
1372
+ <div class="file-preview-container">
1373
+ {{% set file_url = "https://huggingface.co/datasets/{repo_id}/resolve/main/{path}".format(repo_id=repo_id, path=file.path) %}}
1374
+ {{% if file['type'] == 'video' %}}
1375
+ <video class="file-preview" preload="metadata" muted loading="lazy" onclick="openModal('{file_url}', true)">
1376
+ <source src="{file_url}" type="video/mp4">
1377
  </video>
1378
+ {{% elif file['type'] == 'image' %}}
1379
+ <img class="file-preview" src="{file_url}" alt="{{{{ file.filename }}}}" loading="lazy" onclick="openModal(this.src, false)">
1380
+ {{% else %}}
1381
+ <p style="align-self: center; padding: 20px; font-size: 1.2em; color: var(--secondary-color);">📄</p>
1382
+ {{% endif %}}
1383
+ </div>
1384
+ <p class="filename">{{{{ file.filename }}}}</p>
1385
+ <p class="date">{{{{ file.upload_date }}}}</p>
1386
+ <div class="actions">
1387
+ {# Admin might have different actions, e.g., only download or delete with confirmation #}
1388
+ <a href="{{{{ url_for('download_file', file_path=file.path, filename=file.filename) }}}}" class="btn download-btn">Скачать</a>
1389
+ {# Maybe add admin-specific delete here, possibly requiring extra confirmation #}
1390
+ {# <a href="{{ url_for('admin_delete_file', username=username, file_path=file['path']) }}" class="btn delete-btn" onclick="return confirm('ADMIN: Удалить файл пользователя {{ username }}?');">Удалить (Админ)</a> #}
1391
+ </div>
1392
  </div>
1393
+ {{% endfor %}}
1394
+ {{% if not user_files %}}
1395
+ <p style="grid-column: 1 / -1; text-align: center; margin-top: 20px; opacity: 0.8;">У этого пользователя нет файлов.</p>
1396
+ {{% endif %}}
1397
  </div>
1398
+ <a href="{{{{ url_for('admin_panel') }}}}" class="btn" style="margin-top: 40px;">Назад к списку пользователей</a>
1399
  </div>
1400
+ <div class="modal" id="mediaModal">
1401
+ <div id="modalContent" class="modal-content"></div>
1402
  </div>
1403
+ {global_js}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1404
  </body>
1405
  </html>
1406
+ '''.format(style=BASE_STYLE, global_js=GLOBAL_JAVASCRIPT)
1407
  return render_template_string(html, username=username, user_files=user_files, repo_id=REPO_ID)
1408
 
1409
+
1410
  if __name__ == '__main__':
1411
+ # Make sure necessary tokens are available
1412
+ if not HF_TOKEN_WRITE or not HF_TOKEN_READ:
1413
+ logging.warning("HF_TOKEN_WRITE or HF_TOKEN_READ environment variables are not set. File operations might fail.")
1414
+
1415
+ # Initial download of the database on startup
1416
+ logging.info("Performing initial database download...")
1417
+ download_db_from_hf()
1418
+
1419
+ # Start periodic backup in a background thread
1420
+ backup_thread = threading.Thread(target=periodic_backup, daemon=True)
1421
+ backup_thread.start()
1422
+ logging.info("Periodic backup thread started.")
1423
+
1424
+ # Use waitress or gunicorn for production instead of Flask's built-in server
1425
+ # Example using waitress:
1426
+ # from waitress import serve
1427
+ # serve(app, host='0.0.0.0', port=7860)
1428
+
1429
+ # For development/testing:
1430
  app.run(debug=False, host='0.0.0.0', port=7860)