Eluza133 commited on
Commit
d3c6a9c
·
verified ·
1 Parent(s): 0895e7e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +342 -319
app.py CHANGED
@@ -13,7 +13,6 @@ import requests
13
  from io import BytesIO
14
  import uuid
15
  from functools import wraps
16
- import urllib.parse
17
 
18
  app = Flask(__name__)
19
  app.secret_key = os.getenv("FLASK_SECRET_KEY", "supersecretkey_folders_unique_tma")
@@ -175,10 +174,10 @@ def calculate_current_storage_usage(filesystem_node):
175
  total_size = 0
176
  if not filesystem_node:
177
  return 0
178
-
179
  if filesystem_node.get('type') == 'file':
180
  return filesystem_node.get('size_bytes', 0)
181
-
182
  if filesystem_node.get('type') == 'folder' and 'children' in filesystem_node:
183
  for child in filesystem_node['children']:
184
  total_size += calculate_current_storage_usage(child)
@@ -189,9 +188,10 @@ def initialize_user_filesystem_tma(user_data, tma_user_id_str):
189
  user_data['filesystem'] = {
190
  "type": "folder", "id": "root", "name": "root", "children": []
191
  }
192
-
193
  user_data.setdefault('storage_limit_gb', DEFAULT_STORAGE_LIMIT_GB)
194
  user_data.setdefault('unlimited_storage', False)
 
195
  user_data.setdefault('storage_used_bytes', 0)
196
 
197
  if 'files' in user_data and isinstance(user_data['files'], list):
@@ -202,10 +202,10 @@ def initialize_user_filesystem_tma(user_data, tma_user_id_str):
202
  name_part, ext_part = os.path.splitext(original_filename)
203
  unique_suffix = uuid.uuid4().hex[:8]
204
  unique_filename = f"{name_part}_{unique_suffix}{ext_part}"
205
-
206
- estimated_size = 0
207
-
208
- existing_path = old_file.get('path')
209
  if not existing_path:
210
  existing_path = f"cloud_files/{tma_user_id_str}/root/{unique_filename}"
211
 
@@ -231,10 +231,8 @@ def load_data():
231
  data = {'users': {}, 'promocodes': {}}
232
  data.setdefault('users', {})
233
  data.setdefault('promocodes', {})
234
-
235
  for tma_user_id_str, user_data_item in data['users'].items():
236
- user_data_item.setdefault('storage_limit_gb', DEFAULT_STORAGE_LIMIT_GB)
237
- user_data_item.setdefault('unlimited_storage', False)
238
  initialize_user_filesystem_tma(user_data_item, tma_user_id_str)
239
  user_data_item['storage_used_bytes'] = calculate_current_storage_usage(user_data_item['filesystem'])
240
 
@@ -357,53 +355,6 @@ TMA_ENTRY_HTML = '''
357
  </script></body></html>
358
  '''
359
 
360
- @app.route('/tma')
361
- def tma_entry_page():
362
- return render_template_string(TMA_ENTRY_HTML)
363
-
364
- @app.route('/')
365
- def root_redirect():
366
- return redirect(url_for('tma_entry_page'))
367
-
368
-
369
- @app.route('/auth_via_telegram', methods=['POST'])
370
- def auth_via_telegram():
371
- try:
372
- payload = request.json
373
- tg_user_data = payload.get('user')
374
-
375
- if not tg_user_data or not tg_user_data.get('id'):
376
- return jsonify({'status': 'error', 'message': 'Отсутствуют данные пользователя Telegram.'}), 400
377
-
378
- tma_user_id_str = str(tg_user_data['id'])
379
- data = load_data()
380
-
381
- if tma_user_id_str not in data['users']:
382
- data['users'][tma_user_id_str] = {
383
- 'telegram_id': tg_user_data['id'],
384
- 'telegram_username': tg_user_data.get('username'),
385
- 'first_name': tg_user_data.get('first_name'),
386
- 'last_name': tg_user_data.get('last_name'),
387
- 'created_at': datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
388
- 'filesystem': {"type": "folder", "id": "root", "name": "root", "children": []}
389
- }
390
- initialize_user_filesystem_tma(data['users'][tma_user_id_str], tma_user_id_str)
391
- try:
392
- save_data(data)
393
- except Exception as e:
394
- logging.error(f"Save data error for new TMA user {tma_user_id_str}: {e}")
395
- return jsonify({'status': 'error', 'message': 'Ошибка сохранения данных нового пользователя.'}), 500
396
-
397
- session['telegram_user_id'] = tma_user_id_str
398
- display_name = tg_user_data.get('first_name') or tg_user_data.get('username') or f"User {tma_user_id_str}"
399
- session['telegram_display_name'] = display_name
400
-
401
- return jsonify({'status': 'success', 'redirect_url': url_for('tma_dashboard')})
402
-
403
- except Exception as e:
404
- logging.error(f"Error in auth_via_telegram: {e}")
405
- return jsonify({'status': 'error', 'message': 'Внутренняя ошибка сервера при авторизации.'}), 500
406
-
407
  TMA_DASHBOARD_HTML_TEMPLATE = '''
408
  <!DOCTYPE html><html lang="ru"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0">
409
  <title>Zeus Cloud</title><link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600;800&display=swap" rel="stylesheet">
@@ -412,20 +363,20 @@ TMA_DASHBOARD_HTML_TEMPLATE = '''
412
  <h1>Zeus Cloud</h1><p>Пользователь: {{ display_name }}</p>
413
  <p>
414
  {% if user_data.unlimited_storage %}
415
- Память: Безлимитно (Использовано: {{ storage_used_formatted }})
 
416
  {% else %}
417
  Память: {{ storage_used_formatted }} из {{ user_data.storage_limit_gb }} ГБ
418
  {% endif %}
419
  </p>
420
  {% if not user_data.unlimited_storage %}
421
- <div style="margin-bottom: 20px; display: flex; flex-wrap: wrap; gap: 10px; align-items: center;">
422
- <a href="https://t.me/morshenkhan?text={{ 'здравствуйте , хочу приобрести полный доступ на zeuscloud' | urlencode }}" target="_blank" class="btn" style="background: var(--secondary); margin: 0;">Приобрести безлимит ($20)</a>
423
- <form method="POST" action="{{ url_for('activate_promo_tma') }}" style="display: contents; flex-grow: 1;">
424
- <input type="text" name="promo_code" placeholder="Введите промокод" required style="margin: 0;">
425
- <button type="submit" class="btn" style="margin: 0;">Активировать</button>
426
- </form>
427
- </div>
428
  {% endif %}
 
429
  {% with messages = get_flashed_messages(with_categories=true) %}{% if messages %}
430
  {% for category, message in messages %}<div class="flash {{ category }}">{{ message }}</div>{% endfor %}
431
  {% endif %}{% endwith %}
@@ -565,6 +516,221 @@ TMA_DASHBOARD_HTML_TEMPLATE = '''
565
  </script></body></html>
566
  '''
567
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
568
  @app.route('/tma_dashboard', methods=['GET', 'POST'])
569
  def tma_dashboard():
570
  if 'telegram_user_id' not in session:
@@ -594,7 +760,7 @@ def tma_dashboard():
594
  flash('Критическая ошибка: корневая папка не найдена.', 'error')
595
  session.clear()
596
  return redirect(url_for('tma_entry_page'))
597
-
598
  items_in_folder = sorted(current_folder.get('children', []), key=lambda x: (x['type'] != 'folder', x.get('name', x.get('original_filename', '')).lower()))
599
 
600
  if request.method == 'POST':
@@ -623,7 +789,7 @@ def tma_dashboard():
623
  file_obj.seek(0, os.SEEK_END)
624
  total_new_files_size += file_obj.tell()
625
  file_obj.seek(0)
626
-
627
  if user_data['storage_used_bytes'] + total_new_files_size > user_data['storage_limit_gb'] * BYTES_IN_GB:
628
  flash(f'Недостаточно места! Ваш лимит {user_data["storage_limit_gb"]} ГБ, использовано {format_bytes(user_data["storage_used_bytes"])}. '
629
  f'Эти файлы слишком большие ({format_bytes(total_new_files_size)}).', 'error')
@@ -641,7 +807,7 @@ def tma_dashboard():
641
  file_id = uuid.uuid4().hex
642
  hf_path = f"cloud_files/{tma_user_id}/{target_folder_id}/{unique_filename}"
643
  temp_path = os.path.join(UPLOAD_FOLDER, f"{file_id}_{unique_filename}")
644
-
645
  file_obj.save(temp_path)
646
  file_size = os.path.getsize(temp_path)
647
 
@@ -700,18 +866,17 @@ def tma_dashboard():
700
  is_tma_user_admin_flag=is_admin_tma(),
701
  user_data=user_data, storage_used_formatted=storage_used_formatted)
702
 
703
-
704
- @app.route('/activate_promo_tma', methods=['POST'])
705
- def activate_promo_tma():
706
  if 'telegram_user_id' not in session:
707
  flash('Пожалуйста, авторизуйтесь.', 'error')
708
  return redirect(url_for('tma_entry_page'))
709
 
710
  tma_user_id = session['telegram_user_id']
711
- promo_code = request.form.get('promo_code', '').strip()
712
 
713
- if not promo_code:
714
- flash('Пожалуйста, введите промокод.', 'error')
715
  return redirect(url_for('tma_dashboard'))
716
 
717
  data = load_data()
@@ -724,37 +889,42 @@ def activate_promo_tma():
724
  return redirect(url_for('tma_entry_page'))
725
 
726
  if user_data.get('unlimited_storage'):
727
- flash('У вас уже есть безлимитное хранилище.', 'info')
 
 
 
 
728
  return redirect(url_for('tma_dashboard'))
729
 
730
- promo_data = promocodes.get(promo_code)
731
- if not promo_data:
732
- flash('Неверный промокод.', 'error')
 
733
  return redirect(url_for('tma_dashboard'))
734
 
735
- if promo_data.get('remaining_activations', 0) <= 0:
736
- flash('Этот промокод больше не действителен.', 'error')
737
  return redirect(url_for('tma_dashboard'))
738
 
739
- user_data['unlimited_storage'] = True
740
- promo_data['remaining_activations'] -= 1
741
- if 'activated_by' not in promo_data:
742
- promo_data['activated_by'] = []
743
- promo_data['activated_by'].append({
744
  'user_id': tma_user_id,
745
- 'display_name': session.get('telegram_display_name', f'User {tма_user_id}'),
746
  'activation_date': datetime.now().strftime('%Y-%m-%d %H:%M:%S')
747
  })
 
 
 
748
 
749
  try:
750
  save_data(data)
751
- flash('Промокод успешно активирован! Безлимитное хранилище включено.', 'success')
752
  except Exception as e:
753
- flash(f'Ошибка сохранения данных при активации промокода: {e}', 'error')
754
-
755
  return redirect(url_for('tma_dashboard'))
756
 
757
-
758
  @app.route('/create_folder_tma', methods=['POST'])
759
  def create_folder_tma():
760
  if 'telegram_user_id' not in session:
@@ -763,7 +933,7 @@ def create_folder_tma():
763
  tma_user_id = session['telegram_user_id']
764
  data = load_data()
765
  user_data = data['users'].get(tma_user_id)
766
- if not user_data:
767
  flash('Пользователь не найден', 'error')
768
  return redirect(url_for('tma_entry_page'))
769
 
@@ -788,10 +958,10 @@ def create_folder_tma():
788
  def download_tma(file_id):
789
  current_tma_user_id = session.get('telegram_user_id')
790
  is_browser_admin_session = session.get('admin_browser_logged_in', False)
791
-
792
  data = load_data()
793
  file_node = None
794
-
795
  if is_browser_admin_session:
796
  for uid_str_iter, udata_iter in data.get('users', {}).items():
797
  node, _ = find_node_by_id(udata_iter.get('filesystem', {}), file_id)
@@ -816,11 +986,11 @@ def download_tma(file_id):
816
  else:
817
  return Response("Unauthorized", status=401, mimetype='text/plain')
818
 
819
-
820
  redirect_url_fallback = url_for('tma_dashboard')
821
  if is_browser_admin_session:
822
  redirect_url_fallback = url_for('admin_panel')
823
-
824
  redirect_url = request.referrer or redirect_url_fallback
825
 
826
 
@@ -838,14 +1008,14 @@ def download_tma(file_id):
838
  try:
839
  req_headers = {}
840
  if HF_TOKEN_READ: req_headers["authorization"] = f"Bearer {HF_TOKEN_READ}"
841
-
842
  r = requests.get(file_url, headers=req_headers, stream=True)
843
  r.raise_for_status()
844
 
845
  def generate_chunks():
846
  for chunk in r.iter_content(chunk_size=8192):
847
  yield chunk
848
-
849
  mimetype = 'application/octet-stream'
850
  if '.' in original_filename:
851
  ext = original_filename.rsplit('.', 1)[1].lower()
@@ -878,7 +1048,7 @@ def delete_file_tma():
878
  if 'telegram_user_id' not in session:
879
  flash('Пожалуйста, авторизуйтесь.', 'error')
880
  return redirect(url_for('tma_entry_page'))
881
-
882
  file_id = request.view_args.get('file_id')
883
 
884
  tma_user_id = session['telegram_user_id']
@@ -954,7 +1124,7 @@ def delete_folder_tma(folder_id):
954
  def get_text_content_tma(file_id):
955
  current_tma_user_id = session.get('telegram_user_id')
956
  is_browser_admin_session = session.get('admin_browser_logged_in', False)
957
-
958
  data = load_data()
959
  file_node = None
960
 
@@ -975,14 +1145,14 @@ def get_text_content_tma(file_id):
975
  file_node = node; break
976
  else:
977
  return Response("Не авторизован", status=401)
978
-
979
  if not file_node or file_node.get('type') != 'file' or file_node.get('file_type') != 'text':
980
  return Response("Текстовый файл не найден", status=404)
981
  hf_path = file_node.get('path')
982
  if not hf_path: return Response("Ошибка: путь к файлу отсутствует", status=500)
983
  file_url = f"https://huggingface.co/datasets/{REPO_ID}/resolve/main/{hf_path}?download=true"
984
  try:
985
- req_headers = {};
986
  if HF_TOKEN_READ: req_headers["authorization"] = f"Bearer {HF_TOKEN_READ}"
987
  response = requests.get(file_url, headers=req_headers)
988
  response.raise_for_status()
@@ -999,38 +1169,6 @@ def tma_logout():
999
  flash('Вы вышли из сессии приложения.')
1000
  return redirect(url_for('tma_entry_page'))
1001
 
1002
-
1003
- ADMIN_LOGIN_HTML_TEMPLATE = '''
1004
- <!DOCTYPE html><html lang="ru"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0">
1005
- <title>Admin Login</title><link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600;800&display=swap" rel="stylesheet">
1006
- <style>
1007
- {{ admin_base_style_css }}
1008
- body { display: flex; justify-content: center; align-items: center; height: 100vh; background: var(--background-dark); }
1009
- .login-container { text-align: center; padding: 40px; background: var(--card-bg-dark); border-radius: 20px; box-shadow: var(--shadow); width: 100%; max-width: 400px; }
1010
- h1 { color: var(--primary); margin-bottom: 20px; }
1011
- input[type="text"], input[type="password"] { background: rgba(255,255,255,0.1); color: var(--text-dark); margin-bottom: 20px; }
1012
- .btn { background: var(--accent); width: 100%; }
1013
- </style>
1014
- </head><body class="dark">
1015
- <div class="login-container">
1016
- <h1>Admin Login</h1>
1017
- {% with messages = get_flashed_messages(with_categories=true) %}
1018
- {% if messages %}
1019
- {% for category, message in messages %}
1020
- <div class="flash {{ category }}">{{ message }}</div>
1021
- {% endfor %}
1022
- {% endif %}
1023
- {% endwith %}
1024
- <form method="POST" action="{{ url_for('admin_login') }}">
1025
- <input type="hidden" name="next" value="{{ request.args.get('next', '') }}">
1026
- <input type="text" name="username" placeholder="Username" required>
1027
- <input type="password" name="password" placeholder="Password" required>
1028
- <button type="submit" class="btn">Login</button>
1029
- </form>
1030
- </div>
1031
- </body></html>
1032
- '''
1033
-
1034
  @app.route('/admin/login', methods=['GET', 'POST'])
1035
  def admin_login():
1036
  if request.method == 'POST':
@@ -1054,74 +1192,25 @@ def admin_logout():
1054
  flash('Вы вышли из админ-панели.', 'success')
1055
  return redirect(url_for('admin_login'))
1056
 
1057
- ADMIN_PANEL_HTML_TEMPLATE = '''
1058
- <!DOCTYPE html><html lang="ru"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0">
1059
- <title>Админ-панель</title><link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600;800&display=swap" rel="stylesheet">
1060
- <style>''' + BASE_STYLE + '''</style></head><body class="dark"><div class="container"><h1>Админ-панель</h1>
1061
- <a href="{{ url_for('admin_logout') }}" class="btn" style="margin-bottom:20px; background-color: var(--accent);">Выйти из админ-панели</a>
1062
- <a href="{{ url_for('tma_dashboard') }}" class="btn" style="margin-bottom:20px;">В приложение (если TMA сессия есть)</a>
1063
- {% with messages = get_flashed_messages(with_categories=true) %}{% if messages %}{% for category, message in messages %}<div class="flash {{ category }}">{{ message }}</div>{% endfor %}{% endif %}{% endwith %}
1064
-
1065
- <h2>Управление промокодами</h2>
1066
- <form method="POST" action="{{ url_for('admin_create_promo') }}" style="margin-bottom: 20px;">
1067
- <input type="text" name="promo_code" placeholder="Новый промокод" required>
1068
- <input type="number" name="activations" placeholder="Количество активаций" required min="1">
1069
- <button type="submit" class="btn">Создать промокод</button>
1070
- </form>
1071
- <div class="user-list">
1072
- {% for code, details in promocodes.items() %}
1073
- <div class="user-item">
1074
- <div style="display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap;">
1075
- <p><b>Код: {{ code }}</b> (Активаций: {{ (details.total_activations or 0) - (details.remaining_activations or 0) }} / {{ details.total_activations or 'N/A' }})</p>
1076
- <form method="POST" action="{{ url_for('admin_delete_promo', code=code) }}" style="display:inline;" onsubmit="return confirm('Удалить промокод {{ code }}?')">
1077
- <button type="submit" class="btn delete-btn" style="padding: 5px 10px; font-size: 0.9em;">Удалить</button>
1078
- </form>
1079
- </div>
1080
- {% if details.activated_by %}
1081
- <h4 style="margin-top:10px;">Активировали:</h4>
1082
- <ul style="font-size: 0.9em;">
1083
- {% for activator in details.activated_by %}
1084
- <li>{{ activator.display_name }} (ID: {{ activator.user_id }}) - {{ activator.activation_date }}</li>
1085
- {% endfor %}
1086
- </ul>
1087
- {% endif %}
1088
- </div>
1089
- {% else %}
1090
- <p>Промокодов нет.</p>
1091
- {% endfor %}
1092
- </div>
1093
-
1094
- <h2>Пользователи</h2><div class="user-list">
1095
- {% for user in user_details %}
1096
- <div class="user-item">
1097
- <a href="{{ url_for('admin_user_files', tma_user_id_str=user.id_key) }}">{{ user.display_name }} (ID: {{user.id_key}})</a>
1098
- <p>Зарегистрирован: {{ user.created_at }}</p><p>Файлов: {{ user.file_count }}</p>
1099
- <p>Память: {% if user.unlimited_storage %}Безлимитно ({{ user.storage_used_formatted }}){% else %}{{ user.storage_used_formatted }} из {{ user.storage_limit_gb }} ГБ{% endif %}</p>
1100
- <form method="POST" action="{{ url_for('admin_delete_user', tma_user_id_str=user.id_key) }}" style="display: inline; margin-left: 10px;" onsubmit="return confirm('УДАЛИТЬ пользователя {{ user.display_name }} и ВСЕ его файлы? НЕОБРАТИМО!');">
1101
- <button type="submit" class="btn delete-btn" style="padding: 5px 10px; font-size: 0.9em;">Удалить</button>
1102
- </form>
1103
- </div>
1104
- {% else %}<p>Пользователей нет.</p>{% endfor %}</div></div></body></html>'''
1105
-
1106
  @app.route('/admhosto')
1107
  @admin_browser_login_required
1108
  def admin_panel():
1109
  data = load_data()
1110
  users = data.get('users', {})
1111
- promocodes = data.get('promocodes', {})
1112
  user_details = []
1113
  for tma_id_str, udata in users.items():
1114
  user_details.append({
1115
  'id_key': tma_id_str,
1116
  'display_name': udata.get('first_name', udata.get('telegram_username', f"User {tma_id_str}")),
1117
- 'created_at': udata.get('created_at', 'N/A'),
1118
  'file_count': sum(1 for _, node in get_all_nodes(udata.get('filesystem', {})) if node.get('type') == 'file'),
1119
  'storage_limit_gb': udata.get('storage_limit_gb', DEFAULT_STORAGE_LIMIT_GB),
1120
  'storage_used_formatted': format_bytes(udata.get('storage_used_bytes', 0)),
1121
- 'unlimited_storage': udata.get('unlimited_storage', False)
 
1122
  })
1123
  user_details.sort(key=lambda x: x.get('created_at', ''), reverse=True)
1124
- return render_template_string(ADMIN_PANEL_HTML_TEMPLATE, user_details=user_details, promocodes=promocodes)
1125
 
1126
  def get_all_nodes(filesystem):
1127
  queue = [filesystem]
@@ -1132,73 +1221,6 @@ def get_all_nodes(filesystem):
1132
  for child in current_node['children']:
1133
  queue.append(child)
1134
 
1135
- ADMIN_USER_FILES_HTML_TEMPLATE = '''
1136
- <!DOCTYPE html><html lang="ru"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0">
1137
- <title>Файлы {{ display_name_admin_view }}</title><link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600;800&display=swap" rel="stylesheet">
1138
- <style>''' + BASE_STYLE + '''
1139
- .file-item { background: var(--card-bg-dark); padding: 15px; border-radius: 16px; box-shadow: var(--shadow); transition: var(--transition); display: flex; flex-direction: column; justify-content: space-between; }
1140
- .file-preview { max-width: 100%; height: 100px; object-fit: contain; border-radius: 10px; margin-bottom: 10px; display: block; margin-left: auto; margin-right: auto; }
1141
- .admin-file-actions { margin-top: 10px; display: flex; flex-wrap: wrap; gap: 5px; justify-content: center; }
1142
- .admin-file-actions .btn { font-size: 0.8em; padding: 4px 8px; margin: 0; }
1143
- </style></head><body class="dark"><div class="container"><h1>Файлы пользователя: {{ display_name_admin_view }} (ID: {{ tma_user_id_str_admin_view }})</h1>
1144
- <a href="{{ url_for('admin_panel') }}" class="btn" style="margin-bottom: 20px;">Назад к пользователям</a>
1145
- <p>Лимит памяти:
1146
- {% if user_data_admin_view.unlimited_storage %}Безлимитно (Использовано: {{ storage_used_formatted_admin_view }})
1147
- {% else %}{{ storage_used_formatted_admin_view }} из {{ user_data_admin_view.storage_limit_gb }} ГБ
1148
- {% endif %}
1149
- </p>
1150
- <form method="POST" action="{{ url_for('admin_toggle_unlimited_storage', tma_user_id_str=tma_user_id_str_admin_view) }}" style="display: inline-block;">
1151
- <button type="submit" class="btn" style="background: var(--accent);">
1152
- {{ 'Отключить безлимит' if user_data_admin_view.unlimited_storage else 'Включить безлимит' }}
1153
- </button>
1154
- </form>
1155
- {% with messages = get_flashed_messages(with_categories=true) %}{% if messages %}{% for category, message in messages %}<div class="flash {{ category }}">{{ message }}</div>{% endfor %}{% endif %}{% endwith %}
1156
- <div style="display: grid; grid-template-columns: repeat(auto-fill, minmax(220px, 1fr)); gap: 20px;">
1157
- {% for file_item in files %}
1158
- <div class="file-item"><div>
1159
- {% if file_item.file_type == 'image' %} <img class="file-preview" src="{{ hf_file_url_jinja(file_item.path) }}" loading="lazy" onclick="openModalAdmin('{{ hf_file_url_jinja(file_item.path) }}', '{{ file_item.file_type }}', '{{ file_item.id }}')" style="cursor: pointer;">
1160
- {% elif file_item.file_type == 'video' %} <video class="file-preview" preload="metadata" muted onclick="openModalAdmin('{{ hf_file_url_jinja(file_item.path) }}', '{{ file_item.file_type }}', '{{ file_item.id }}')" style="cursor: pointer;"><source src="{{ hf_file_url_jinja(file_item.path, True) }}#t=0.5"></video>
1161
- {% elif file_item.file_type == 'pdf' %} <div class="file-preview" style="font-size: 40px; line-height: 100px; text-align: center; color: var(--accent); cursor: pointer;" onclick="openModalAdmin('{{ hf_file_url_jinja(file_item.path, True) }}', '{{ file_item.file_type }}', '{{ file_item.id }}')">📄</div>
1162
- {% elif file_item.file_type == 'text' %} <div class="file-preview" style="font-size: 40px; line-height: 100px; text-align: center; color: var(--secondary); cursor: pointer;" onclick="openModalAdmin('{{ url_for('get_text_content_tma', file_id=file_item.id) }}', '{{ file_item.file_type }}', '{{ file_item.id }}')">📝</div>
1163
- {% else %} <div class="file-preview" style="font-size: 40px; line-height: 100px; text-align: center; color: #aaa;">❓</div> {% endif %}
1164
- <p title="{{ file_item.original_filename }}"><b>{{ file_item.original_filename | truncate(30) }}</b></p>
1165
- <p style="font-size: 0.8em; color: #888;">В папке: {{ file_item.parent_path_str }}</p>
1166
- <p style="font-size: 0.8em; color: #888;">Загружен: {{ file_item.upload_date }}</p>
1167
- <p style="font-size: 0.8em; color: #888;">Размер: {{ file_item.size_formatted }}</p>
1168
- <p style="font-size: 0.7em; color: #ccc;">ID: {{ file_item.id }}</p>
1169
- <p style="font-size: 0.7em; color: #ccc; word-break: break-all;">Path: {{ file_item.path }}</p>
1170
- </div><div class="admin-file-actions">
1171
- <a href="{{ url_for('download_tma', file_id=file_item.id) }}" class="btn download-btn" download="{{ file_item.original_filename }}">Скачать</a>
1172
- {% set previewable = file_item.file_type in ['image', 'video', 'pdf', 'text'] %}
1173
- {% if previewable %}<button type="button" class="btn" style="background: var(--accent);" onclick="openModalAdmin('{{ hf_file_url_jinja(file_item.path) if file_item.file_type != 'text' else url_for('get_text_content_tma', file_id=file_item.id) }}', '{{ file_item.file_type }}', '{{ file_item.id }}')">Просмотр</button>{% endif %}
1174
- <form method="POST" action="{{ url_for('admin_delete_file', tma_user_id_str_form=tma_user_id_str_admin_view, file_id=file_item.id) }}" style="display: inline-block;" onsubmit="return confirm('Удалить файл {{ file_item.original_filename }}?');">
1175
- <button type="submit" class="btn delete-btn">Удалить</button></form>
1176
- </div></div>{% else %} <p>У пользователя нет файлов.</p> {% endfor %}</div></div>
1177
- <div class="modal" id="mediaModalAdmin" onclick="closeModalAdminEv(event)"><div class="modal-content" id="modalContentContainerAdmin">
1178
- <span onclick="closeModalAdminManual()" class="modal-close-btn">×</span><div id="modalContentAdmin"></div></div></div>
1179
- <script>
1180
- const repoIdJs = "{{ repo_id_js_admin }}";
1181
- function hfFileUrlAdmin(path, download = false) { let url = `https://huggingface.co/datasets/${repoIdJs}/resolve/main/${path}`; if (download) url += '?download=true'; return url; }
1182
- async function openModalAdmin(srcOrUrl, type, itemId) {
1183
- const modal = document.getElementById('mediaModalAdmin'); const modalContent = document.getElementById('modalContentAdmin');
1184
- modalContent.innerHTML = '<p>Загрузка...</p>'; modal.style.display = 'flex';
1185
- try {
1186
- if (type === 'image') modalContent.innerHTML = `<img src="${srcOrUrl}" alt="Просмотр изображения">`;
1187
- else if (type === 'video') modalContent.innerHTML = `<video controls autoplay style='max-width: 95%; max-height: 85vh;'><source src="${srcOrUrl}" type="video/mp4"></video>`;
1188
- else if (type === 'pdf') modalContent.innerHTML = `<iframe src="${srcOrUrl}" title="Просмотр PDF"></iframe>`;
1189
- else if (type === 'text') { const response = await fetch(srcOrUrl); if (!response.ok) throw new Error('Network response was not ok for text file.'); const text = await response.text(); const esc = text.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">"); modalContent.innerHTML = `<pre>${esc}</pre>`;}
1190
- else modalContent.innerHTML = '<p>Предпросмотр не поддерживается.</p>';
1191
- } catch (error) { modalContent.innerHTML = `<p>Не удалось загрузить содержимое для предпросмотра. ${error.message}</p>`;}
1192
- }
1193
- function closeModalAdminEv(event) { if (event.target === document.getElementById('mediaModalAdmin')) closeModalAdminManual(); }
1194
- function closeModalAdminManual() {
1195
- const modal = document.getElementById('mediaModalAdmin'); modal.style.display = 'none';
1196
- const video = modal.querySelector('video'); if (video) video.pause();
1197
- const iframe = modal.querySelector('iframe'); if (iframe) iframe.src = 'about:blank';
1198
- document.getElementById('modalContentAdmin').innerHTML = '';
1199
- }
1200
- </script></body></html>'''
1201
-
1202
  @app.route('/admhosto/user/<tma_user_id_str>')
1203
  @admin_browser_login_required
1204
  def admin_user_files(tma_user_id_str):
@@ -1206,26 +1228,26 @@ def admin_user_files(tma_user_id_str):
1206
  user_data = data.get('users', {}).get(tma_user_id_str)
1207
  if not user_data:
1208
  flash(f'Пользователь ID {tma_user_id_str} не найден.', 'error'); return redirect(url_for('admin_panel'))
1209
-
1210
  all_files = []
1211
  def collect_files_admin(folder, current_path_id='root'):
1212
  parent_path_str = get_node_path_string(user_data['filesystem'], current_path_id)
1213
  for item in folder.get('children', []):
1214
- if item.get('type') == 'file':
1215
  item['parent_path_str'] = parent_path_str
1216
  item['size_formatted'] = format_bytes(item.get('size_bytes'))
1217
  all_files.append(item)
1218
  elif item.get('type') == 'folder': collect_files_admin(item, item.get('id'))
1219
-
1220
  collect_files_admin(user_data.get('filesystem', {}))
1221
  all_files.sort(key=lambda x: x.get('upload_date', ''), reverse=True)
1222
-
1223
  display_name_admin_view = user_data.get('first_name', user_data.get('telegram_username', f"User {tma_user_id_str}"))
1224
  storage_used_formatted_admin_view = format_bytes(user_data['storage_used_bytes'])
1225
 
1226
- return render_template_string(ADMIN_USER_FILES_HTML_TEMPLATE,
1227
- tma_user_id_str_admin_view=tma_user_id_str, display_name_admin_view=display_name_admin_view, files=all_files,
1228
- repo_id_js_admin=REPO_ID,
1229
  hf_file_url_jinja=lambda path, download=False: f"https://huggingface.co/datasets/{REPO_ID}/resolve/main/{path}{'?download=true' if download else ''}",
1230
  user_data_admin_view=user_data, storage_used_formatted_admin_view=storage_used_formatted_admin_view)
1231
 
@@ -1238,7 +1260,7 @@ def admin_toggle_unlimited_storage(tma_user_id_str):
1238
  if not user_data:
1239
  flash(f'Пользователь {tma_user_id_str} не найден.', 'error')
1240
  return redirect(url_for('admin_panel'))
1241
-
1242
  user_data['unlimited_storage'] = not user_data.get('unlimited_storage', False)
1243
  try:
1244
  save_data(data)
@@ -1246,59 +1268,9 @@ def admin_toggle_unlimited_storage(tma_user_id_str):
1246
  flash(f'Безлимитное хранилище для пользователя {tma_user_id_str} {status}.', 'success')
1247
  except Exception as e:
1248
  flash(f'Ошибка при изменении статуса безлимитного хранилища: {e}', 'error')
1249
-
1250
  return redirect(url_for('admin_user_files', tma_user_id_str=tma_user_id_str))
1251
 
1252
-
1253
- @app.route('/admhosto/create_promo', methods=['POST'])
1254
- @admin_browser_login_required
1255
- def admin_create_promo():
1256
- promo_code = request.form.get('promo_code', '').strip()
1257
- try:
1258
- activations = int(request.form.get('activations', 0))
1259
- except (ValueError, TypeError):
1260
- flash('Количество активаций должно быть числом.', 'error')
1261
- return redirect(url_for('admin_panel'))
1262
-
1263
- if not promo_code or activations <= 0:
1264
- flash('Промокод и количество активаций (больше 0) обязательны.', 'error')
1265
- return redirect(url_for('admin_panel'))
1266
-
1267
- data = load_data()
1268
- if promo_code in data.get('promocodes', {}):
1269
- flash(f'Промокод "{promo_code}" уже существует.', 'error')
1270
- return redirect(url_for('admin_panel'))
1271
-
1272
- data['promocodes'][promo_code] = {
1273
- 'code': promo_code,
1274
- 'total_activations': activations,
1275
- 'remaining_activations': activations,
1276
- 'activated_by': []
1277
- }
1278
- try:
1279
- save_data(data)
1280
- flash(f'Промокод "{promo_code}" успешно создан.', 'success')
1281
- except Exception as e:
1282
- flash(f'Ошибка сохранения промокода: {e}', 'error')
1283
- return redirect(url_for('admin_panel'))
1284
-
1285
-
1286
- @app.route('/admhosto/delete_promo/<code>', methods=['POST'])
1287
- @admin_browser_login_required
1288
- def admin_delete_promo(code):
1289
- data = load_data()
1290
- if code in data.get('promocodes', {}):
1291
- del data['promocodes'][code]
1292
- try:
1293
- save_data(data)
1294
- flash(f'Промокод "{code}" удален.', 'success')
1295
- except Exception as e:
1296
- flash(f'Ошибка удаления промокода: {e}', 'error')
1297
- else:
1298
- flash(f'Промокод "{code}" не найден.', 'error')
1299
- return redirect(url_for('admin_panel'))
1300
-
1301
-
1302
  @app.route('/admhosto/delete_user/<tma_user_id_str>', methods=['POST'])
1303
  @admin_browser_login_required
1304
  def admin_delete_user(tma_user_id_str):
@@ -1312,12 +1284,12 @@ def admin_delete_user(tma_user_id_str):
1312
  user_folder_path_on_hf = f"cloud_files/{tma_user_id_str}"
1313
  api.delete_folder(folder_path=user_folder_path_on_hf, repo_id=REPO_ID, repo_type="dataset", token=HF_TOKEN_WRITE, ignore_patterns=[".keep"])
1314
  except hf_utils.HfHubHTTPError as e:
1315
- if e.response.status_code != 404:
1316
  flash(f'Ошибка удаления файлов пользователя {tma_user_id_str} с сервера: {e}. Пользователь из базы не удален.', 'error'); return redirect(url_for('admin_panel'))
1317
  logging.info(f"Folder {user_folder_path_on_hf} not found on HF Hub for user {tma_user_id_str} or was already empty, proceeding with DB deletion.")
1318
  except Exception as e:
1319
  flash(f'Ошибка удаления файлов пользователя {tma_user_id_str} с сервера: {e}. Пользователь из базы не удален.', 'error'); return redirect(url_for('admin_panel'))
1320
-
1321
  try:
1322
  del data['users'][tma_user_id_str]
1323
  save_data(data)
@@ -1336,11 +1308,11 @@ def admin_delete_file(tma_user_id_str_form, file_id):
1336
  user_data = data.get('users', {}).get(tma_user_id_str_form)
1337
  if not user_data:
1338
  flash(f'Пользователь {tma_user_id_str_form} не найден.', 'error'); return redirect(url_for('admin_panel'))
1339
-
1340
  file_node, _ = find_node_by_id(user_data['filesystem'], file_id)
1341
  if not file_node or file_node.get('type') != 'file':
1342
  flash('Файл не найден в базе данных этого пользователя.', 'error'); return redirect(url_for('admin_user_files', tma_user_id_str=tma_user_id_str_form))
1343
-
1344
  hf_path = file_node.get('path')
1345
  original_filename = file_node.get('original_filename', 'файл')
1346
  file_size_to_deduct = file_node.get('size_bytes', 0)
@@ -1351,7 +1323,7 @@ def admin_delete_file(tma_user_id_str_form, file_id):
1351
  try: save_data(data); flash(f'Метаданные файла {original_filename} удалены из базы (путь к файлу на сервере отсутствовал).')
1352
  except Exception as e: flash('Ошибка сохранения данных после удаления метаданных (путь отсутствовал).', 'error')
1353
  return redirect(url_for('admin_user_files', tma_user_id_str=tma_user_id_str_form))
1354
-
1355
  try:
1356
  api = HfApi()
1357
  api.delete_file(path_in_repo=hf_path, repo_id=REPO_ID, repo_type="dataset", token=HF_TOKEN_WRITE)
@@ -1371,6 +1343,58 @@ def admin_delete_file(tma_user_id_str_form, file_id):
1371
  flash(f'Ошибка при удалении файла {original_filename}: {e}', 'error')
1372
  return redirect(url_for('admin_user_files', tma_user_id_str=tma_user_id_str_form))
1373
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1374
 
1375
  if __name__ == '__main__':
1376
  if not HF_TOKEN_WRITE: logging.warning("HF_TOKEN (write access) is not set. Uploads/deletions/backups will fail.")
@@ -1379,7 +1403,6 @@ if __name__ == '__main__':
1379
  if ADMIN_USERNAME == "admin" and ADMIN_PASSWORD == "zeusadminpass":
1380
  logging.warning("Using default admin username/password for browser admin panel. Please change ADMIN_USERNAME and ADMIN_PASSWORD environment variables.")
1381
 
1382
-
1383
  if HF_TOKEN_WRITE:
1384
  download_db_from_hf()
1385
  threading.Thread(target=periodic_backup, daemon=True).start()
 
13
  from io import BytesIO
14
  import uuid
15
  from functools import wraps
 
16
 
17
  app = Flask(__name__)
18
  app.secret_key = os.getenv("FLASK_SECRET_KEY", "supersecretkey_folders_unique_tma")
 
174
  total_size = 0
175
  if not filesystem_node:
176
  return 0
177
+
178
  if filesystem_node.get('type') == 'file':
179
  return filesystem_node.get('size_bytes', 0)
180
+
181
  if filesystem_node.get('type') == 'folder' and 'children' in filesystem_node:
182
  for child in filesystem_node['children']:
183
  total_size += calculate_current_storage_usage(child)
 
188
  user_data['filesystem'] = {
189
  "type": "folder", "id": "root", "name": "root", "children": []
190
  }
191
+
192
  user_data.setdefault('storage_limit_gb', DEFAULT_STORAGE_LIMIT_GB)
193
  user_data.setdefault('unlimited_storage', False)
194
+ user_data.setdefault('activated_promocode', None)
195
  user_data.setdefault('storage_used_bytes', 0)
196
 
197
  if 'files' in user_data and isinstance(user_data['files'], list):
 
202
  name_part, ext_part = os.path.splitext(original_filename)
203
  unique_suffix = uuid.uuid4().hex[:8]
204
  unique_filename = f"{name_part}_{unique_suffix}{ext_part}"
205
+
206
+ estimated_size = 0
207
+
208
+ existing_path = old_file.get('path')
209
  if not existing_path:
210
  existing_path = f"cloud_files/{tma_user_id_str}/root/{unique_filename}"
211
 
 
231
  data = {'users': {}, 'promocodes': {}}
232
  data.setdefault('users', {})
233
  data.setdefault('promocodes', {})
234
+
235
  for tma_user_id_str, user_data_item in data['users'].items():
 
 
236
  initialize_user_filesystem_tma(user_data_item, tma_user_id_str)
237
  user_data_item['storage_used_bytes'] = calculate_current_storage_usage(user_data_item['filesystem'])
238
 
 
355
  </script></body></html>
356
  '''
357
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
358
  TMA_DASHBOARD_HTML_TEMPLATE = '''
359
  <!DOCTYPE html><html lang="ru"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0">
360
  <title>Zeus Cloud</title><link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600;800&display=swap" rel="stylesheet">
 
363
  <h1>Zeus Cloud</h1><p>Пользователь: {{ display_name }}</p>
364
  <p>
365
  {% if user_data.unlimited_storage %}
366
+ Память: Безлимитно (Использовано: {{ storage_used_formatted }})<br>
367
+ <small style="color: #ccc;">Доступ активирован {% if user_data.activated_promocode %}промокодом: {{ user_data.activated_promocode }}{% else %}администратором{% endif %}.</small>
368
  {% else %}
369
  Память: {{ storage_used_formatted }} из {{ user_data.storage_limit_gb }} ГБ
370
  {% endif %}
371
  </p>
372
  {% if not user_data.unlimited_storage %}
373
+ <a href="https://t.me/morshenkhan?text=здравствуйте%2C%20хочу%20приобрести%20полный%20доступ%20на%20zeuscloud" target="_blank" class="btn" style="background: var(--secondary); margin-left: 0; margin-bottom: 10px;">Приобрести доступ к безлимитной памяти</a>
374
+ <form method="POST" action="{{ url_for('activate_promocode_tma') }}" style="margin-top: 15px; display: flex; gap: 10px; align-items: center; flex-wrap: wrap;">
375
+ <input type="text" name="promocode" placeholder="Введите промокод" required style="margin: 0; flex-grow: 1; min-width: 150px;">
376
+ <button type="submit" class="btn" style="margin: 0; flex-shrink: 0;">Активировать</button>
377
+ </form>
 
 
378
  {% endif %}
379
+
380
  {% with messages = get_flashed_messages(with_categories=true) %}{% if messages %}
381
  {% for category, message in messages %}<div class="flash {{ category }}">{{ message }}</div>{% endfor %}
382
  {% endif %}{% endwith %}
 
516
  </script></body></html>
517
  '''
518
 
519
+ ADMIN_LOGIN_HTML_TEMPLATE = '''
520
+ <!DOCTYPE html><html lang="ru"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0">
521
+ <title>Admin Login</title><link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600;800&display=swap" rel="stylesheet">
522
+ <style>
523
+ {{ admin_base_style_css }}
524
+ body { display: flex; justify-content: center; align-items: center; height: 100vh; background: var(--background-dark); }
525
+ .login-container { text-align: center; padding: 40px; background: var(--card-bg-dark); border-radius: 20px; box-shadow: var(--shadow); width: 100%; max-width: 400px; }
526
+ h1 { color: var(--primary); margin-bottom: 20px; }
527
+ input[type="text"], input[type="password"] { background: rgba(255,255,255,0.1); color: var(--text-dark); margin-bottom: 20px; }
528
+ .btn { background: var(--accent); width: 100%; }
529
+ </style>
530
+ </head><body class="dark">
531
+ <div class="login-container">
532
+ <h1>Admin Login</h1>
533
+ {% with messages = get_flashed_messages(with_categories=true) %}
534
+ {% if messages %}
535
+ {% for category, message in messages %}
536
+ <div class="flash {{ category }}">{{ message }}</div>
537
+ {% endfor %}
538
+ {% endif %}
539
+ {% endwith %}
540
+ <form method="POST" action="{{ url_for('admin_login') }}">
541
+ <input type="hidden" name="next" value="{{ request.args.get('next', '') }}">
542
+ <input type="text" name="username" placeholder="Username" required>
543
+ <input type="password" name="password" placeholder="Password" required>
544
+ <button type="submit" class="btn">Login</button>
545
+ </form>
546
+ </div>
547
+ </body></html>
548
+ '''
549
+
550
+ ADMIN_PANEL_HTML_TEMPLATE = '''
551
+ <!DOCTYPE html><html lang="ru"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0">
552
+ <title>Админ-панель</title><link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600;800&display=swap" rel="stylesheet">
553
+ <style>''' + BASE_STYLE + '''</style></head><body class="dark"><div class="container"><h1>Админ-панель</h1>
554
+ <a href="{{ url_for('admin_logout') }}" class="btn" style="margin-bottom:20px; background-color: var(--accent);">Выйти из админ-панели</a>
555
+ <a href="{{ url_for('tma_dashboard') }}" class="btn" style="margin-bottom:20px;">В приложение (если TMA сессия есть)</a>
556
+ <a href="{{ url_for('admin_promocodes') }}" class="btn" style="margin-bottom:20px; background-color: #ffc107;">Управление промокодами</a>
557
+ {% with messages = get_flashed_messages(with_categories=true) %}{% if messages %}{% for category, message in messages %}<div class="flash {{ category }}">{{ message }}</div>{% endfor %}{% endif %}{% endwith %}
558
+ <h2>Пользователи</h2><div class="user-list">
559
+ {% for user in user_details %}
560
+ <div class="user-item">
561
+ <a href="{{ url_for('admin_user_files', tma_user_id_str=user.id_key) }}">{{ user.display_name }} (ID: {{user.id_key}})</a>
562
+ <p>Зарегистрирован: {{ user.created_at }}</p><p>Файлов: {{ user.file_count }}</p>
563
+ <p>Память: {% if user.unlimited_storage %}Безлимитно ({{ user.storage_used_formatted }}){% else %}{{ user.storage_used_formatted }} из {{ user.storage_limit_gb }} ГБ{% endif %}</p>
564
+ {% if user.activated_promocode %}<p>Активирован промокод: {{ user.activated_promocode }}</p>{% endif %}
565
+ <form method="POST" action="{{ url_for('admin_delete_user', tma_user_id_str=user.id_key) }}" style="display: inline; margin-left: 10px;" onsubmit="return confirm('УДАЛИТЬ пользователя {{ user.display_name }} и ВСЕ его файлы? НЕОБРАТИМО!');">
566
+ <button type="submit" class="btn delete-btn" style="padding: 5px 10px; font-size: 0.9em;">Удалить</button>
567
+ </form>
568
+ </div>
569
+ {% else %}<p>Пользователей нет.</p>{% endfor %}</div></div></body></html>'''
570
+
571
+ ADMIN_USER_FILES_HTML_TEMPLATE = '''
572
+ <!DOCTYPE html><html lang="ru"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0">
573
+ <title>Файлы {{ display_name_admin_view }}</title><link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600;800&display=swap" rel="stylesheet">
574
+ <style>''' + BASE_STYLE + '''
575
+ .file-item { background: var(--card-bg-dark); padding: 15px; border-radius: 16px; box-shadow: var(--shadow); transition: var(--transition); display: flex; flex-direction: column; justify-content: space-between; }
576
+ .file-preview { max-width: 100%; height: 100px; object-fit: contain; border-radius: 10px; margin-bottom: 10px; display: block; margin-left: auto; margin-right: auto; }
577
+ .admin-file-actions { margin-top: 10px; display: flex; flex-wrap: wrap; gap: 5px; justify-content: center; }
578
+ .admin-file-actions .btn { font-size: 0.8em; padding: 4px 8px; margin: 0; }
579
+ </style></head><body class="dark"><div class="container"><h1>Файлы пользователя: {{ display_name_admin_view }} (ID: {{ tma_user_id_str_admin_view }})</h1>
580
+ <a href="{{ url_for('admin_panel') }}" class="btn" style="margin-bottom: 20px;">Назад к пользователям</a>
581
+ <p>Лимит памяти:
582
+ {% if user_data_admin_view.unlimited_storage %}Безлимитно (Использовано: {{ storage_used_formatted_admin_view }})
583
+ {% else %}{{ storage_used_formatted_admin_view }} из {{ user_data_admin_view.storage_limit_gb }} ГБ
584
+ {% endif %}
585
+ </p>
586
+ <form method="POST" action="{{ url_for('admin_toggle_unlimited_storage', tma_user_id_str=tma_user_id_str_admin_view) }}" style="display: inline-block;">
587
+ <button type="submit" class="btn" style="background: var(--accent);">
588
+ {{ 'Отключить безлимит' if user_data_admin_view.unlimited_storage else 'Включить безлимит' }}
589
+ </button>
590
+ </form>
591
+ {% with messages = get_flashed_messages(with_categories=true) %}{% if messages %}{% for category, message in messages %}<div class="flash {{ category }}">{{ message }}</div>{% endfor %}{% endif %}{% endwith %}
592
+ <div style="display: grid; grid-template-columns: repeat(auto-fill, minmax(220px, 1fr)); gap: 20px;">
593
+ {% for file_item in files %}
594
+ <div class="file-item"><div>
595
+ {% if file_item.file_type == 'image' %} <img class="file-preview" src="{{ hf_file_url_jinja(file_item.path) }}" loading="lazy" onclick="openModalAdmin('{{ hf_file_url_jinja(file_item.path) }}', '{{ file_item.file_type }}', '{{ file_item.id }}')" style="cursor: pointer;">
596
+ {% elif file_item.file_type == 'video' %} <video class="file-preview" preload="metadata" muted onclick="openModalAdmin('{{ hf_file_url_jinja(file_item.path) }}', '{{ file_item.file_type }}', '{{ file_item.id }}')" style="cursor: pointer;"><source src="{{ hf_file_url_jinja(file_item.path, True) }}#t=0.5"></video>
597
+ {% elif file_item.file_type == 'pdf' %} <div class="file-preview" style="font-size: 40px; line-height: 100px; text-align: center; color: var(--accent); cursor: pointer;" onclick="openModalAdmin('{{ hf_file_url_jinja(file_item.path, True) }}', '{{ file_item.file_type }}', '{{ file_item.id }}')">📄</div>
598
+ {% elif file_item.file_type == 'text' %} <div class="file-preview" style="font-size: 40px; line-height: 100px; text-align: center; color: var(--secondary); cursor: pointer;" onclick="openModalAdmin('{{ url_for('get_text_content_tma', file_id=file_item.id) }}', '{{ file_item.file_type }}', '{{ file_item.id }}')">📝</div>
599
+ {% else %} <div class="file-preview" style="font-size: 40px; line-height: 100px; text-align: center; color: #aaa;">❓</div> {% endif %}
600
+ <p title="{{ file_item.original_filename }}"><b>{{ file_item.original_filename | truncate(30) }}</b></p>
601
+ <p style="font-size: 0.8em; color: #888;">В папке: {{ file_item.parent_path_str }}</p>
602
+ <p style="font-size: 0.8em; color: #888;">Загружен: {{ file_item.upload_date }}</p>
603
+ <p style="font-size: 0.8em; color: #888;">Размер: {{ file_item.size_formatted }}</p>
604
+ <p style="font-size: 0.7em; color: #ccc;">ID: {{ file_item.id }}</p>
605
+ <p style="font-size: 0.7em; color: #ccc; word-break: break-all;">Path: {{ file_item.path }}</p>
606
+ </div><div class="admin-file-actions">
607
+ <a href="{{ url_for('download_tma', file_id=file_item.id) }}" class="btn download-btn" download="{{ file_item.original_filename }}">Скачать</a>
608
+ {% set previewable = file_item.file_type in ['image', 'video', 'pdf', 'text'] %}
609
+ {% if previewable %}<button type="button" class="btn" style="background: var(--accent);" onclick="openModalAdmin('{{ hf_file_url_jinja(file_item.path) if file_item.file_type != 'text' else url_for('get_text_content_tma', file_id=file_item.id) }}', '{{ file_item.file_type }}', '{{ file_item.id }}')">Просмотр</button>{% endif %}
610
+ <form method="POST" action="{{ url_for('admin_delete_file', tma_user_id_str_form=tma_user_id_str_admin_view, file_id=file_item.id) }}" style="display: inline-block;" onsubmit="return confirm('Удалить файл {{ file_item.original_filename }}?');">
611
+ <button type="submit" class="btn delete-btn">Удалить</button></form>
612
+ </div></div>{% else %} <p>У пользователя нет файлов.</p> {% endfor %}</div></div>
613
+ <div class="modal" id="mediaModalAdmin" onclick="closeModalAdminEv(event)"><div class="modal-content" id="modalContentContainerAdmin">
614
+ <span onclick="closeModalAdminManual()" class="modal-close-btn">×</span><div id="modalContentAdmin"></div></div></div>
615
+ <script>
616
+ const repoIdJs = "{{ repo_id_js_admin }}";
617
+ function hfFileUrlAdmin(path, download = false) { let url = `https://huggingface.co/datasets/${repoIdJs}/resolve/main/${path}`; if (download) url += '?download=true'; return url; }
618
+ async function openModalAdmin(srcOrUrl, type, itemId) {
619
+ const modal = document.getElementById('mediaModalAdmin'); const modalContent = document.getElementById('modalContentAdmin');
620
+ modalContent.innerHTML = '<p>Загрузка...</p>'; modal.style.display = 'flex';
621
+ try {
622
+ if (type === 'image') modalContent.innerHTML = `<img src="${srcOrUrl}" alt="Просмотр изображения">`;
623
+ else if (type === 'video') modalContent.innerHTML = `<video controls autoplay style='max-width: 95%; max-height: 85vh;'><source src="${srcOrUrl}" type="video/mp4"></video>`;
624
+ else if (type === 'pdf') modalContent.innerHTML = `<iframe src="${srcOrUrl}" title="Просмотр PDF"></iframe>`;
625
+ else if (type === 'text') { const response = await fetch(srcOrUrl); if (!response.ok) throw new Error('Network response was not ok for text file.'); const text = await response.text(); const esc = text.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">"); modalContent.innerHTML = `<pre>${esc}</pre>`;}
626
+ else modalContent.innerHTML = '<p>Предпросмотр не поддерживается.</p>';
627
+ } catch (error) { modalContent.innerHTML = `<p>Не удалось загрузить содержимое для предпросмотра. ${error.message}</p>`;}
628
+ }
629
+ function closeModalAdminEv(event) { if (event.target === document.getElementById('mediaModalAdmin')) closeModalAdminManual(); }
630
+ function closeModalAdminManual() {
631
+ const modal = document.getElementById('mediaModalAdmin'); modal.style.display = 'none';
632
+ const video = modal.querySelector('video'); if (video) video.pause();
633
+ const iframe = modal.querySelector('iframe'); if (iframe) iframe.src = 'about:blank';
634
+ document.getElementById('modalContentAdmin').innerHTML = '';
635
+ }
636
+ </script></body></html>'''
637
+
638
+ ADMIN_PROMOCODES_HTML_TEMPLATE = '''
639
+ <!DOCTYPE html><html lang="ru"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0">
640
+ <title>Управление промокодами</title><link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600;800&display=swap" rel="stylesheet">
641
+ <style>''' + BASE_STYLE + '''
642
+ .promocode-item { margin-bottom: 20px; padding: 15px; border-radius: 12px; }
643
+ .promocode-item h3 { color: var(--primary); font-size: 1.4em; }
644
+ .activated-user { background: rgba(255,255,255,0.05); padding: 8px; border-radius: 8px; margin-top: 8px; font-size: 0.9em; }
645
+ .activated-user a { font-weight: normal; }
646
+ </style></head><body class="dark"><div class="container">
647
+ <h1>Управление промокодами</h1>
648
+ <a href="{{ url_for('admin_panel') }}" class="btn" style="margin-bottom: 20px;">Назад к пользователям</a>
649
+ {% with messages = get_flashed_messages(with_categories=true) %}{% if messages %}{% for category, message in messages %}<div class="flash {{ category }}">{{ message }}</div>{% endfor %}{% endif %}{% endwith %}
650
+
651
+ <h2>Создать новый промокод</h2>
652
+ <form method="POST" action="{{ url_for('admin_promocodes') }}" class="folder-actions" style="background: var(--card-bg-dark); padding: 20px; border-radius: 16px; margin-bottom: 30px;">
653
+ <input type="text" name="code" placeholder="Код (оставьте пустым для генерации)">
654
+ <input type="number" name="activations" placeholder="Кол-во активаций" value="1" min="1" required style="max-width: 200px;">
655
+ <button type="submit" class="btn">Создать</button>
656
+ </form>
657
+
658
+ <h2>Существующие промокоды</h2>
659
+ <div class="user-list">
660
+ {% for promo in promocodes %}
661
+ <div class="user-item promocode-item">
662
+ <h3>{{ promo.code }}</h3>
663
+ <p>Создан: {{ promo.created_at }}</p>
664
+ <p>Активации: {{ promo.total_activations - promo.activations_left }} / {{ promo.total_activations }} (осталось {{ promo.activations_left }})</p>
665
+ {% if promo.activated_by %}
666
+ <h4>Активировали:</h4>
667
+ {% for act in promo.activated_by %}
668
+ <div class="activated-user">
669
+ <a href="{{ url_for('admin_user_files', tma_user_id_str=act.user_id) }}">{{ act.username or 'Без имени' }} (ID: {{ act.user_id }})</a> - {{ act.activation_date }}
670
+ </div>
671
+ {% endfor %}
672
+ {% else %}
673
+ <p>Еще никто не активировал.</p>
674
+ {% endif %}
675
+ <form method="POST" action="{{ url_for('admin_delete_promocode', code=promo.code) }}" style="display: inline-block; margin-top: 15px;" onsubmit="return confirm('Удалить промокод {{ promo.code }}?');">
676
+ <button type="submit" class="btn delete-btn">Удалить</button>
677
+ </form>
678
+ </div>
679
+ {% else %}
680
+ <p>Промокодов еще нет.</p>
681
+ {% endfor %}
682
+ </div>
683
+
684
+ </div></body></html>
685
+ '''
686
+
687
+ @app.route('/tma')
688
+ def tma_entry_page():
689
+ return render_template_string(TMA_ENTRY_HTML)
690
+
691
+ @app.route('/')
692
+ def root_redirect():
693
+ return redirect(url_for('tma_entry_page'))
694
+
695
+
696
+ @app.route('/auth_via_telegram', methods=['POST'])
697
+ def auth_via_telegram():
698
+ try:
699
+ payload = request.json
700
+ tg_user_data = payload.get('user')
701
+
702
+ if not tg_user_data or not tg_user_data.get('id'):
703
+ return jsonify({'status': 'error', 'message': 'Отсутствуют данные пользователя Telegram.'}), 400
704
+
705
+ tma_user_id_str = str(tg_user_data['id'])
706
+ data = load_data()
707
+
708
+ if tma_user_id_str not in data['users']:
709
+ data['users'][tma_user_id_str] = {
710
+ 'telegram_id': tg_user_data['id'],
711
+ 'telegram_username': tg_user_data.get('username'),
712
+ 'first_name': tg_user_data.get('first_name'),
713
+ 'last_name': tg_user_data.get('last_name'),
714
+ 'created_at': datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
715
+ 'filesystem': {"type": "folder", "id": "root", "name": "root", "children": []}
716
+ }
717
+ initialize_user_filesystem_tma(data['users'][tma_user_id_str], tma_user_id_str)
718
+ try:
719
+ save_data(data)
720
+ except Exception as e:
721
+ logging.error(f"Save data error for new TMA user {tma_user_id_str}: {e}")
722
+ return jsonify({'status': 'error', 'message': 'Ошибка сохранения данных нового пользователя.'}), 500
723
+
724
+ session['telegram_user_id'] = tma_user_id_str
725
+ display_name = tg_user_data.get('first_name') or tg_user_data.get('username') or f"User {tma_user_id_str}"
726
+ session['telegram_display_name'] = display_name
727
+
728
+ return jsonify({'status': 'success', 'redirect_url': url_for('tma_dashboard')})
729
+
730
+ except Exception as e:
731
+ logging.error(f"Error in auth_via_telegram: {e}")
732
+ return jsonify({'status': 'error', 'message': 'Внутренняя ошибка сервера при авторизации.'}), 500
733
+
734
  @app.route('/tma_dashboard', methods=['GET', 'POST'])
735
  def tma_dashboard():
736
  if 'telegram_user_id' not in session:
 
760
  flash('Критическая ошибка: корневая папка не найдена.', 'error')
761
  session.clear()
762
  return redirect(url_for('tma_entry_page'))
763
+
764
  items_in_folder = sorted(current_folder.get('children', []), key=lambda x: (x['type'] != 'folder', x.get('name', x.get('original_filename', '')).lower()))
765
 
766
  if request.method == 'POST':
 
789
  file_obj.seek(0, os.SEEK_END)
790
  total_new_files_size += file_obj.tell()
791
  file_obj.seek(0)
792
+
793
  if user_data['storage_used_bytes'] + total_new_files_size > user_data['storage_limit_gb'] * BYTES_IN_GB:
794
  flash(f'Недостаточно места! Ваш лимит {user_data["storage_limit_gb"]} ГБ, использовано {format_bytes(user_data["storage_used_bytes"])}. '
795
  f'Эти файлы слишком большие ({format_bytes(total_new_files_size)}).', 'error')
 
807
  file_id = uuid.uuid4().hex
808
  hf_path = f"cloud_files/{tma_user_id}/{target_folder_id}/{unique_filename}"
809
  temp_path = os.path.join(UPLOAD_FOLDER, f"{file_id}_{unique_filename}")
810
+
811
  file_obj.save(temp_path)
812
  file_size = os.path.getsize(temp_path)
813
 
 
866
  is_tma_user_admin_flag=is_admin_tma(),
867
  user_data=user_data, storage_used_formatted=storage_used_formatted)
868
 
869
+ @app.route('/activate_promocode_tma', methods=['POST'])
870
+ def activate_promocode_tma():
 
871
  if 'telegram_user_id' not in session:
872
  flash('Пожалуйста, авторизуйтесь.', 'error')
873
  return redirect(url_for('tma_entry_page'))
874
 
875
  tma_user_id = session['telegram_user_id']
876
+ promocode = request.form.get('promocode', '').strip()
877
 
878
+ if not promocode:
879
+ flash('Поле промокода не может быть пустым.', 'error')
880
  return redirect(url_for('tma_dashboard'))
881
 
882
  data = load_data()
 
889
  return redirect(url_for('tma_entry_page'))
890
 
891
  if user_data.get('unlimited_storage'):
892
+ flash('У вас уже есть безлимитный доступ.', 'info')
893
+ return redirect(url_for('tma_dashboard'))
894
+
895
+ if user_data.get('activated_promocode'):
896
+ flash('Вы уже активировали промокод.', 'error')
897
  return redirect(url_for('tma_dashboard'))
898
 
899
+ code_data = promocodes.get(promocode)
900
+
901
+ if not code_data:
902
+ flash('Промокод не найден или недействителен.', 'error')
903
  return redirect(url_for('tma_dashboard'))
904
 
905
+ if code_data.get('activations_left', 0) <= 0:
906
+ flash('К сожалению, лимит активаций для этого промокода исчерпан.', 'error')
907
  return redirect(url_for('tma_dashboard'))
908
 
909
+ code_data['activations_left'] -= 1
910
+ code_data.setdefault('activated_by', [])
911
+ code_data['activated_by'].append({
 
 
912
  'user_id': tma_user_id,
913
+ 'username': user_data.get('telegram_username'),
914
  'activation_date': datetime.now().strftime('%Y-%m-%d %H:%M:%S')
915
  })
916
+
917
+ user_data['unlimited_storage'] = True
918
+ user_data['activated_promocode'] = promocode
919
 
920
  try:
921
  save_data(data)
922
+ flash('Промокод успешно активирован! Вам предоставлен безлимитный доступ.', 'success')
923
  except Exception as e:
924
+ flash(f'Произошла ошибка при сохранении данных: {e}', 'error')
925
+
926
  return redirect(url_for('tma_dashboard'))
927
 
 
928
  @app.route('/create_folder_tma', methods=['POST'])
929
  def create_folder_tma():
930
  if 'telegram_user_id' not in session:
 
933
  tma_user_id = session['telegram_user_id']
934
  data = load_data()
935
  user_data = data['users'].get(tma_user_id)
936
+ if not user_data:
937
  flash('Пользователь не найден', 'error')
938
  return redirect(url_for('tma_entry_page'))
939
 
 
958
  def download_tma(file_id):
959
  current_tma_user_id = session.get('telegram_user_id')
960
  is_browser_admin_session = session.get('admin_browser_logged_in', False)
961
+
962
  data = load_data()
963
  file_node = None
964
+
965
  if is_browser_admin_session:
966
  for uid_str_iter, udata_iter in data.get('users', {}).items():
967
  node, _ = find_node_by_id(udata_iter.get('filesystem', {}), file_id)
 
986
  else:
987
  return Response("Unauthorized", status=401, mimetype='text/plain')
988
 
989
+
990
  redirect_url_fallback = url_for('tma_dashboard')
991
  if is_browser_admin_session:
992
  redirect_url_fallback = url_for('admin_panel')
993
+
994
  redirect_url = request.referrer or redirect_url_fallback
995
 
996
 
 
1008
  try:
1009
  req_headers = {}
1010
  if HF_TOKEN_READ: req_headers["authorization"] = f"Bearer {HF_TOKEN_READ}"
1011
+
1012
  r = requests.get(file_url, headers=req_headers, stream=True)
1013
  r.raise_for_status()
1014
 
1015
  def generate_chunks():
1016
  for chunk in r.iter_content(chunk_size=8192):
1017
  yield chunk
1018
+
1019
  mimetype = 'application/octet-stream'
1020
  if '.' in original_filename:
1021
  ext = original_filename.rsplit('.', 1)[1].lower()
 
1048
  if 'telegram_user_id' not in session:
1049
  flash('Пожалуйста, авторизуйтесь.', 'error')
1050
  return redirect(url_for('tma_entry_page'))
1051
+
1052
  file_id = request.view_args.get('file_id')
1053
 
1054
  tma_user_id = session['telegram_user_id']
 
1124
  def get_text_content_tma(file_id):
1125
  current_tma_user_id = session.get('telegram_user_id')
1126
  is_browser_admin_session = session.get('admin_browser_logged_in', False)
1127
+
1128
  data = load_data()
1129
  file_node = None
1130
 
 
1145
  file_node = node; break
1146
  else:
1147
  return Response("Не авторизован", status=401)
1148
+
1149
  if not file_node or file_node.get('type') != 'file' or file_node.get('file_type') != 'text':
1150
  return Response("Текстовый файл не найден", status=404)
1151
  hf_path = file_node.get('path')
1152
  if not hf_path: return Response("Ошибка: путь к файлу отсутствует", status=500)
1153
  file_url = f"https://huggingface.co/datasets/{REPO_ID}/resolve/main/{hf_path}?download=true"
1154
  try:
1155
+ req_headers = {};
1156
  if HF_TOKEN_READ: req_headers["authorization"] = f"Bearer {HF_TOKEN_READ}"
1157
  response = requests.get(file_url, headers=req_headers)
1158
  response.raise_for_status()
 
1169
  flash('Вы вышли из сессии приложения.')
1170
  return redirect(url_for('tma_entry_page'))
1171
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1172
  @app.route('/admin/login', methods=['GET', 'POST'])
1173
  def admin_login():
1174
  if request.method == 'POST':
 
1192
  flash('Вы вышли из админ-панели.', 'success')
1193
  return redirect(url_for('admin_login'))
1194
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1195
  @app.route('/admhosto')
1196
  @admin_browser_login_required
1197
  def admin_panel():
1198
  data = load_data()
1199
  users = data.get('users', {})
 
1200
  user_details = []
1201
  for tma_id_str, udata in users.items():
1202
  user_details.append({
1203
  'id_key': tma_id_str,
1204
  'display_name': udata.get('first_name', udata.get('telegram_username', f"User {tma_id_str}")),
1205
+ 'created_at': udata.get('created_at', 'N/A'),
1206
  'file_count': sum(1 for _, node in get_all_nodes(udata.get('filesystem', {})) if node.get('type') == 'file'),
1207
  'storage_limit_gb': udata.get('storage_limit_gb', DEFAULT_STORAGE_LIMIT_GB),
1208
  'storage_used_formatted': format_bytes(udata.get('storage_used_bytes', 0)),
1209
+ 'unlimited_storage': udata.get('unlimited_storage', False),
1210
+ 'activated_promocode': udata.get('activated_promocode')
1211
  })
1212
  user_details.sort(key=lambda x: x.get('created_at', ''), reverse=True)
1213
+ return render_template_string(ADMIN_PANEL_HTML_TEMPLATE, user_details=user_details)
1214
 
1215
  def get_all_nodes(filesystem):
1216
  queue = [filesystem]
 
1221
  for child in current_node['children']:
1222
  queue.append(child)
1223
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1224
  @app.route('/admhosto/user/<tma_user_id_str>')
1225
  @admin_browser_login_required
1226
  def admin_user_files(tma_user_id_str):
 
1228
  user_data = data.get('users', {}).get(tma_user_id_str)
1229
  if not user_data:
1230
  flash(f'Пользователь ID {tma_user_id_str} не найден.', 'error'); return redirect(url_for('admin_panel'))
1231
+
1232
  all_files = []
1233
  def collect_files_admin(folder, current_path_id='root'):
1234
  parent_path_str = get_node_path_string(user_data['filesystem'], current_path_id)
1235
  for item in folder.get('children', []):
1236
+ if item.get('type') == 'file':
1237
  item['parent_path_str'] = parent_path_str
1238
  item['size_formatted'] = format_bytes(item.get('size_bytes'))
1239
  all_files.append(item)
1240
  elif item.get('type') == 'folder': collect_files_admin(item, item.get('id'))
1241
+
1242
  collect_files_admin(user_data.get('filesystem', {}))
1243
  all_files.sort(key=lambda x: x.get('upload_date', ''), reverse=True)
1244
+
1245
  display_name_admin_view = user_data.get('first_name', user_data.get('telegram_username', f"User {tma_user_id_str}"))
1246
  storage_used_formatted_admin_view = format_bytes(user_data['storage_used_bytes'])
1247
 
1248
+ return render_template_string(ADMIN_USER_FILES_HTML_TEMPLATE,
1249
+ tma_user_id_str_admin_view=tma_user_id_str, display_name_admin_view=display_name_admin_view, files=all_files,
1250
+ repo_id_js_admin=REPO_ID,
1251
  hf_file_url_jinja=lambda path, download=False: f"https://huggingface.co/datasets/{REPO_ID}/resolve/main/{path}{'?download=true' if download else ''}",
1252
  user_data_admin_view=user_data, storage_used_formatted_admin_view=storage_used_formatted_admin_view)
1253
 
 
1260
  if not user_data:
1261
  flash(f'Пользователь {tma_user_id_str} не найден.', 'error')
1262
  return redirect(url_for('admin_panel'))
1263
+
1264
  user_data['unlimited_storage'] = not user_data.get('unlimited_storage', False)
1265
  try:
1266
  save_data(data)
 
1268
  flash(f'Безлимитное хранилище для пользователя {tma_user_id_str} {status}.', 'success')
1269
  except Exception as e:
1270
  flash(f'Ошибка при изменении статуса безлимитного хранилища: {e}', 'error')
1271
+
1272
  return redirect(url_for('admin_user_files', tma_user_id_str=tma_user_id_str))
1273
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1274
  @app.route('/admhosto/delete_user/<tma_user_id_str>', methods=['POST'])
1275
  @admin_browser_login_required
1276
  def admin_delete_user(tma_user_id_str):
 
1284
  user_folder_path_on_hf = f"cloud_files/{tma_user_id_str}"
1285
  api.delete_folder(folder_path=user_folder_path_on_hf, repo_id=REPO_ID, repo_type="dataset", token=HF_TOKEN_WRITE, ignore_patterns=[".keep"])
1286
  except hf_utils.HfHubHTTPError as e:
1287
+ if e.response.status_code != 404:
1288
  flash(f'Ошибка удаления файлов пользователя {tma_user_id_str} с сервера: {e}. Пользователь из базы не удален.', 'error'); return redirect(url_for('admin_panel'))
1289
  logging.info(f"Folder {user_folder_path_on_hf} not found on HF Hub for user {tma_user_id_str} or was already empty, proceeding with DB deletion.")
1290
  except Exception as e:
1291
  flash(f'Ошибка удаления файлов пользователя {tma_user_id_str} с сервера: {e}. Пользователь из базы не удален.', 'error'); return redirect(url_for('admin_panel'))
1292
+
1293
  try:
1294
  del data['users'][tma_user_id_str]
1295
  save_data(data)
 
1308
  user_data = data.get('users', {}).get(tma_user_id_str_form)
1309
  if not user_data:
1310
  flash(f'Пользователь {tma_user_id_str_form} не найден.', 'error'); return redirect(url_for('admin_panel'))
1311
+
1312
  file_node, _ = find_node_by_id(user_data['filesystem'], file_id)
1313
  if not file_node or file_node.get('type') != 'file':
1314
  flash('Файл не найден в базе данных этого пользователя.', 'error'); return redirect(url_for('admin_user_files', tma_user_id_str=tma_user_id_str_form))
1315
+
1316
  hf_path = file_node.get('path')
1317
  original_filename = file_node.get('original_filename', 'файл')
1318
  file_size_to_deduct = file_node.get('size_bytes', 0)
 
1323
  try: save_data(data); flash(f'Метаданные файла {original_filename} удалены из базы (путь к файлу на сервере отсутствовал).')
1324
  except Exception as e: flash('Ошибка сохранения данных после удаления метаданных (путь отсутствовал).', 'error')
1325
  return redirect(url_for('admin_user_files', tma_user_id_str=tma_user_id_str_form))
1326
+
1327
  try:
1328
  api = HfApi()
1329
  api.delete_file(path_in_repo=hf_path, repo_id=REPO_ID, repo_type="dataset", token=HF_TOKEN_WRITE)
 
1343
  flash(f'Ошибка при удалении файла {original_filename}: {e}', 'error')
1344
  return redirect(url_for('admin_user_files', tma_user_id_str=tma_user_id_str_form))
1345
 
1346
+ @app.route('/admhosto/promocodes', methods=['GET', 'POST'])
1347
+ @admin_browser_login_required
1348
+ def admin_promocodes():
1349
+ data = load_data()
1350
+ if request.method == 'POST':
1351
+ code_str = request.form.get('code', '').strip()
1352
+ activations = request.form.get('activations', '1').strip()
1353
+
1354
+ if not code_str:
1355
+ code_str = uuid.uuid4().hex[:10].upper()
1356
+
1357
+ if not activations.isdigit() or int(activations) < 1:
1358
+ flash('Количество активаций должно быть положительным числом.', 'error')
1359
+ return redirect(url_for('admin_promocodes'))
1360
+
1361
+ if code_str in data.get('promocodes', {}):
1362
+ flash(f'Промокод "{code_str}" уже существует.', 'error')
1363
+ return redirect(url_for('admin_promocodes'))
1364
+
1365
+ data.setdefault('promocodes', {})[code_str] = {
1366
+ 'code': code_str,
1367
+ 'total_activations': int(activations),
1368
+ 'activations_left': int(activations),
1369
+ 'created_at': datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
1370
+ 'activated_by': []
1371
+ }
1372
+ try:
1373
+ save_data(data)
1374
+ flash(f'Промокод "{code_str}" успешно создан.', 'success')
1375
+ except Exception as e:
1376
+ flash(f'Ошибка сохранения промокода: {e}', 'error')
1377
+
1378
+ return redirect(url_for('admin_promocodes'))
1379
+
1380
+ promocodes_list = sorted(data.get('promocodes', {}).values(), key=lambda x: x['created_at'], reverse=True)
1381
+ return render_template_string(ADMIN_PROMOCODES_HTML_TEMPLATE, promocodes=promocodes_list)
1382
+
1383
+ @app.route('/admhosto/promocodes/delete/<code>', methods=['POST'])
1384
+ @admin_browser_login_required
1385
+ def admin_delete_promocode(code):
1386
+ data = load_data()
1387
+ if code in data.get('promocodes', {}):
1388
+ del data['promocodes'][code]
1389
+ try:
1390
+ save_data(data)
1391
+ flash(f'Промокод "{code}" удален.', 'success')
1392
+ except Exception as e:
1393
+ flash(f'Ошибка удаления промокода: {e}', 'error')
1394
+ else:
1395
+ flash(f'Промокод "{code}" не найден.', 'error')
1396
+
1397
+ return redirect(url_for('admin_promocodes'))
1398
 
1399
  if __name__ == '__main__':
1400
  if not HF_TOKEN_WRITE: logging.warning("HF_TOKEN (write access) is not set. Uploads/deletions/backups will fail.")
 
1403
  if ADMIN_USERNAME == "admin" and ADMIN_PASSWORD == "zeusadminpass":
1404
  logging.warning("Using default admin username/password for browser admin panel. Please change ADMIN_USERNAME and ADMIN_PASSWORD environment variables.")
1405
 
 
1406
  if HF_TOKEN_WRITE:
1407
  download_db_from_hf()
1408
  threading.Thread(target=periodic_backup, daemon=True).start()