Eluza133 commited on
Commit
07c4473
·
verified ·
1 Parent(s): d2493c1

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +239 -111
app.py CHANGED
@@ -12,15 +12,20 @@ from werkzeug.utils import secure_filename
12
  import requests
13
  from io import BytesIO
14
  import uuid
 
15
 
16
  app = Flask(__name__)
17
  app.secret_key = os.getenv("FLASK_SECRET_KEY", "supersecretkey_folders_unique_tma")
18
  DATA_FILE = 'cloudeng_data_tma.json'
19
- REPO_ID = "Eluza133/Z1e1u" # Needs to be accessible by the tokens
20
  HF_TOKEN_WRITE = os.getenv("HF_TOKEN")
21
  HF_TOKEN_READ = os.getenv("HF_TOKEN_READ") or HF_TOKEN_WRITE
22
  TELEGRAM_BOT_TOKEN = os.getenv("TELEGRAM_BOT_TOKEN", "6750208873:AAE2hvPlJ99dBdhGa_Brre0IIpUdOvXxHt4")
23
- ADMIN_TELEGRAM_ID = os.getenv("ADMIN_TELEGRAM_ID", "YOUR_ADMIN_TELEGRAM_USER_ID_HERE") # IMPORTANT: Set this!
 
 
 
 
24
 
25
  UPLOAD_FOLDER = 'uploads_tma'
26
  os.makedirs(UPLOAD_FOLDER, exist_ok=True)
@@ -48,8 +53,8 @@ body.dark h2 { color: var(--text-dark); }
48
  h4 { font-size: 1.1em; margin-top: 15px; margin-bottom: 5px; color: var(--accent); }
49
  ol, ul { margin-left: 20px; margin-bottom: 15px; }
50
  li { margin-bottom: 5px; }
51
- input, textarea { width: 100%; padding: 14px; margin: 12px 0; border: none; border-radius: 14px; background: var(--glass-bg); color: var(--text-light); font-size: 1.1em; box-shadow: inset 0 3px 10px rgba(0, 0, 0, 0.1); }
52
- body.dark input, body.dark textarea { color: var(--text-dark); }
53
  input:focus, textarea:focus { outline: none; box-shadow: 0 0 0 4px var(--primary); }
54
  .btn { padding: 14px 28px; background: var(--primary); color: white; border: none; border-radius: 14px; cursor: pointer; font-size: 1.1em; font-weight: 600; transition: var(--transition); box-shadow: var(--shadow); display: inline-block; text-decoration: none; margin-top: 5px; margin-right: 5px; }
55
  .btn:hover { transform: scale(1.05); background: #e6415f; }
@@ -166,7 +171,7 @@ def initialize_user_filesystem_tma(user_data, tma_user_id_str):
166
  user_data['filesystem'] = {
167
  "type": "folder", "id": "root", "name": "root", "children": []
168
  }
169
- if 'files' in user_data and isinstance(user_data['files'], list): # Migration logic
170
  for old_file in user_data['files']:
171
  file_id = old_file.get('id', uuid.uuid4().hex)
172
  original_filename = old_file.get('filename', 'unknown_file')
@@ -255,7 +260,16 @@ def get_file_type(filename):
255
  def is_admin_tma():
256
  if not ADMIN_TELEGRAM_ID or ADMIN_TELEGRAM_ID == "YOUR_ADMIN_TELEGRAM_USER_ID_HERE":
257
  return False
258
- return 'telegram_user_id' in session and session['telegram_user_id'] == ADMIN_TELEGRAM_ID
 
 
 
 
 
 
 
 
 
259
 
260
  TMA_ENTRY_HTML = '''
261
  <!DOCTYPE html><html lang="ru"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0">
@@ -307,7 +321,6 @@ def auth_via_telegram():
307
  try:
308
  payload = request.json
309
  tg_user_data = payload.get('user')
310
- # init_data_str = payload.get('initData') # For future validation if needed
311
 
312
  if not tg_user_data or not tg_user_data.get('id'):
313
  return jsonify({'status': 'error', 'message': 'Отсутствуют данные пользователя Telegram.'}), 400
@@ -335,9 +348,6 @@ def auth_via_telegram():
335
  display_name = tg_user_data.get('first_name') or tg_user_data.get('username') or f"User {tma_user_id_str}"
336
  session['telegram_display_name'] = display_name
337
 
338
- if is_admin_tma():
339
- session['is_admin_flag'] = True # Optional flag
340
-
341
  return jsonify({'status': 'success', 'redirect_url': url_for('tma_dashboard')})
342
 
343
  except Exception as e:
@@ -348,7 +358,7 @@ TMA_DASHBOARD_HTML_TEMPLATE = '''
348
  <!DOCTYPE html><html lang="ru"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0">
349
  <title>Zeus Cloud</title><link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600;800&display=swap" rel="stylesheet">
350
  <script src="https://telegram.org/js/telegram-web-app.js"></script>
351
- <style>''' + BASE_STYLE + '''</style></head><body><div class="container">
352
  <h1>Zeus Cloud</h1><p>Пользователь: {{ display_name }}</p>
353
  {% with messages = get_flashed_messages(with_categories=true) %}{% if messages %}
354
  {% for category, message in messages %}<div class="flash {{ category }}">{{ message }}</div>{% endfor %}
@@ -409,14 +419,15 @@ TMA_DASHBOARD_HTML_TEMPLATE = '''
409
  {% if not items %} <p>Эта папка пуста.</p> {% endif %}
410
  </div>
411
  <a href="{{ url_for('tma_logout') }}" class="btn" style="margin-top: 20px;" id="logout-btn">Выйти (очистить сессию)</a>
412
- {% if is_admin %}
413
- <a href="{{ url_for('admin_panel_tma') }}" class="btn" style="margin-top: 20px; background-color: var(--accent);">Админ-панель</a>
414
  {% endif %}
415
  </div>
416
  <div class="modal" id="mediaModal" onclick="closeModal(event)"><div class="modal-content" id="modalContentContainer">
417
  <span onclick="closeModalManual()" class="modal-close-btn">×</span><div id="modalContent"></div></div></div>
418
  <script>
419
  window.Telegram.WebApp.ready();
 
420
  const repoId = "{{ repo_id_js }}";
421
  const hfTokenRead = "{{ HF_TOKEN_READ_js or '' }}";
422
  function hfFileUrl(path, download = false) {
@@ -487,7 +498,7 @@ def tma_dashboard():
487
  return redirect(url_for('tma_entry_page'))
488
 
489
  user_data = data['users'][tma_user_id]
490
- initialize_user_filesystem_tma(user_data, tma_user_id) # Ensure filesystem exists
491
 
492
  current_folder_id = request.args.get('folder_id', 'root')
493
  current_folder, _ = find_node_by_id(user_data['filesystem'], current_folder_id)
@@ -496,7 +507,7 @@ def tma_dashboard():
496
  flash('Папка не найдена!', 'error')
497
  current_folder_id = 'root'
498
  current_folder, _ = find_node_by_id(user_data['filesystem'], current_folder_id)
499
- if not current_folder: # Should not happen if init is correct
500
  flash('Критическая ошибка: корневая папка не найдена.', 'error')
501
  session.clear()
502
  return redirect(url_for('tma_entry_page'))
@@ -525,9 +536,9 @@ def tma_dashboard():
525
  api = HfApi()
526
  uploaded_count = 0
527
  errors_list = []
528
- for file in files:
529
- if file and file.filename:
530
- original_filename = secure_filename(file.filename)
531
  name_part, ext_part = os.path.splitext(original_filename)
532
  unique_suffix = uuid.uuid4().hex[:8]
533
  unique_filename = f"{name_part}_{unique_suffix}{ext_part}"
@@ -535,7 +546,7 @@ def tma_dashboard():
535
  hf_path = f"cloud_files/{tma_user_id}/{target_folder_id}/{unique_filename}"
536
  temp_path = os.path.join(UPLOAD_FOLDER, f"{file_id}_{unique_filename}")
537
  try:
538
- file.save(temp_path)
539
  api.upload_file(
540
  path_or_fileobj=temp_path, path_in_repo=hf_path, repo_id=REPO_ID,
541
  repo_type="dataset", token=HF_TOKEN_WRITE,
@@ -583,17 +594,20 @@ def tma_dashboard():
583
  current_folder_id=current_folder_id, current_folder=current_folder,
584
  breadcrumbs=breadcrumbs, repo_id_js=REPO_ID, HF_TOKEN_READ_js=HF_TOKEN_READ,
585
  hf_file_url_jinja=lambda path, download=False: f"https://huggingface.co/datasets/{REPO_ID}/resolve/main/{path}{'?download=true' if download else ''}",
586
- is_admin=is_admin_tma())
587
 
588
 
589
  @app.route('/create_folder_tma', methods=['POST'])
590
  def create_folder_tma():
591
  if 'telegram_user_id' not in session:
592
- return jsonify({'status': 'error', 'message': 'Не авторизован'}), 401
 
593
  tma_user_id = session['telegram_user_id']
594
  data = load_data()
595
  user_data = data['users'].get(tma_user_id)
596
- if not user_data: return jsonify({'status': 'error', 'message': 'Пользователь не найден'}), 404
 
 
597
 
598
  parent_folder_id = request.form.get('parent_folder_id', 'root')
599
  folder_name = request.form.get('folder_name', '').strip()
@@ -615,44 +629,82 @@ def create_folder_tma():
615
  @app.route('/download_tma/<file_id>')
616
  def download_tma(file_id):
617
  current_tma_user_id = session.get('telegram_user_id')
618
- if not current_tma_user_id:
619
- flash('Пожалуйста, авторизуйтесь.', 'error')
620
- return redirect(url_for('tma_entry_page'))
621
-
622
  data = load_data()
623
  file_node = None
624
 
625
- user_data = data['users'].get(current_tma_user_id)
626
- if user_data:
627
- file_node, _ = find_node_by_id(user_data['filesystem'], file_id)
628
-
629
- if not file_node and is_admin_tma():
630
- for uid_str, udata_iter in data.get('users', {}).items():
631
  node, _ = find_node_by_id(udata_iter.get('filesystem', {}), file_id)
632
  if node and node.get('type') == 'file':
633
  file_node = node
634
  break
 
 
 
 
 
 
 
 
 
 
 
 
 
 
635
 
 
 
 
 
 
 
 
636
  if not file_node or file_node.get('type') != 'file':
637
  flash('Файл не найден или доступ запрещен!', 'error')
638
- return redirect(request.referrer or url_for('tma_dashboard'))
639
 
640
  hf_path = file_node.get('path')
641
  original_filename = file_node.get('original_filename', 'downloaded_file')
642
  if not hf_path:
643
  flash('Ошибка: Путь к файлу не найден.', 'error')
644
- return redirect(request.referrer or url_for('tma_dashboard'))
645
 
646
  file_url = f"https://huggingface.co/datasets/{REPO_ID}/resolve/main/{hf_path}?download=true"
647
  try:
648
- headers = {}
649
- if HF_TOKEN_READ: headers["authorization"] = f"Bearer {HF_TOKEN_READ}"
650
- response = requests.get(file_url, headers=headers, stream=True)
651
- response.raise_for_status()
652
- return send_file(BytesIO(response.content), as_attachment=True, download_name=original_filename)
653
- except Exception as e:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
654
  flash(f'Ошибка скачивания файла: {e}', 'error')
655
- return redirect(request.referrer or url_for('tma_dashboard'))
 
 
 
656
 
657
  @app.route('/delete_file_tma/<file_id>', methods=['POST'])
658
  def delete_file_tma(file_id):
@@ -726,19 +778,28 @@ def delete_folder_tma(folder_id):
726
  @app.route('/get_text_content_tma/<file_id>')
727
  def get_text_content_tma(file_id):
728
  current_tma_user_id = session.get('telegram_user_id')
729
- if not current_tma_user_id: return Response("Не авторизован", status=401)
730
 
731
  data = load_data()
732
  file_node = None
733
- user_data = data['users'].get(current_tma_user_id)
734
- if user_data:
735
- file_node, _ = find_node_by_id(user_data['filesystem'], file_id)
736
 
737
- if not file_node and is_admin_tma():
738
  for uid_str, udata_iter in data.get('users', {}).items():
739
  node, _ = find_node_by_id(udata_iter.get('filesystem', {}), file_id)
740
  if node and node.get('type') == 'file' and node.get('file_type') == 'text':
741
  file_node = node; break
 
 
 
 
 
 
 
 
 
 
 
 
742
 
743
  if not file_node or file_node.get('type') != 'file' or file_node.get('file_type') != 'text':
744
  return Response("Текстовый файл не найден", status=404)
@@ -746,9 +807,9 @@ def get_text_content_tma(file_id):
746
  if not hf_path: return Response("Ошибка: путь к файлу отсутствует", status=500)
747
  file_url = f"https://huggingface.co/datasets/{REPO_ID}/resolve/main/{hf_path}?download=true"
748
  try:
749
- headers = {};
750
- if HF_TOKEN_READ: headers["authorization"] = f"Bearer {HF_TOKEN_READ}"
751
- response = requests.get(file_url, headers=headers)
752
  response.raise_for_status()
753
  if len(response.content) > 1 * 1024 * 1024: return Response("Файл слишком большой.", status=413)
754
  try: text_content = response.content.decode('utf-8')
@@ -758,31 +819,87 @@ def get_text_content_tma(file_id):
758
 
759
  @app.route('/tma_logout')
760
  def tma_logout():
761
- session.clear()
 
762
  flash('Вы вышли из сессии приложения.')
763
  return redirect(url_for('tma_entry_page'))
764
 
765
- ADMIN_PANEL_HTML_TMA_TEMPLATE = '''
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
766
  <!DOCTYPE html><html lang="ru"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0">
767
  <title>Админ-панель</title><link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600;800&display=swap" rel="stylesheet">
768
- <style>''' + BASE_STYLE + '''</style></head><body><div class="container"><h1>Админ-панель</h1>
769
- <a href="{{ url_for('tma_dashboard') }}" class="btn" style="margin-bottom:20px;">Назад в приложение</a>
 
770
  {% with messages = get_flashed_messages(with_categories=true) %}{% if messages %}{% for category, message in messages %}<div class="flash {{ category }}">{{ message }}</div>{% endfor %}{% endif %}{% endwith %}
771
  <h2>Пользователи</h2><div class="user-list">
772
  {% for user in user_details %}
773
  <div class="user-item">
774
- <a href="{{ url_for('admin_user_files_tma', tma_user_id_str=user.id_key) }}">{{ user.display_name }} (ID: {{user.id_key}})</a>
775
  <p>Зарегистрирован: {{ user.created_at }}</p><p>Файлов: {{ user.file_count }}</p>
776
- <form method="POST" action="{{ url_for('admin_delete_user_tma', tma_user_id_str=user.id_key) }}" style="display: inline; margin-left: 10px;" onsubmit="return confirm('УДАЛИТЬ пользователя {{ user.display_name }} и ВСЕ его файлы? НЕОБРАТИМО!');">
777
  <button type="submit" class="btn delete-btn" style="padding: 5px 10px; font-size: 0.9em;">Удалить</button>
778
  </form>
779
  </div>
780
  {% else %}<p>Пользователей нет.</p>{% endfor %}</div></div></body></html>'''
781
 
782
  @app.route('/admhosto')
783
- def admin_panel_tma():
784
- if not is_admin_tma():
785
- flash('Доступ запрещен.', 'error'); return redirect(url_for('tma_dashboard'))
786
  data = load_data()
787
  users = data.get('users', {})
788
  user_details = []
@@ -799,38 +916,38 @@ def admin_panel_tma():
799
  'display_name': udata.get('first_name', udata.get('telegram_username', f"User {tma_id_str}")),
800
  'created_at': udata.get('created_at', 'N/A'), 'file_count': file_count
801
  })
802
- return render_template_string(ADMIN_PANEL_HTML_TMA_TEMPLATE, user_details=user_details)
 
803
 
804
- ADMIN_USER_FILES_HTML_TMA_TEMPLATE = '''
805
  <!DOCTYPE html><html lang="ru"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0">
806
  <title>Файлы {{ display_name_admin_view }}</title><link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600;800&display=swap" rel="stylesheet">
807
  <style>''' + BASE_STYLE + '''
808
- .file-item { background: var(--card-bg); padding: 15px; border-radius: 16px; box-shadow: var(--shadow); transition: var(--transition); display: flex; flex-direction: column; justify-content: space-between; }
809
- body.dark .file-item { background: var(--card-bg-dark); } .file-item:hover { transform: translateY(-5px); }
810
  .file-preview { max-width: 100%; height: 100px; object-fit: contain; border-radius: 10px; margin-bottom: 10px; display: block; margin-left: auto; margin-right: auto; }
811
  .admin-file-actions { margin-top: 10px; display: flex; flex-wrap: wrap; gap: 5px; justify-content: center; }
812
  .admin-file-actions .btn { font-size: 0.8em; padding: 4px 8px; margin: 0; }
813
- </style></head><body><div class="container"><h1>Файлы пользователя: {{ display_name_admin_view }} (ID: {{ tma_user_id_str_admin_view }})</h1>
814
- <a href="{{ url_for('admin_panel_tma') }}" class="btn" style="margin-bottom: 20px;">Назад к пользователям</a>
815
  {% with messages = get_flashed_messages(with_categories=true) %}{% if messages %}{% for category, message in messages %}<div class="flash {{ category }}">{{ message }}</div>{% endfor %}{% endif %}{% endwith %}
816
  <div style="display: grid; grid-template-columns: repeat(auto-fill, minmax(220px, 1fr)); gap: 20px;">
817
- {% for file in files %}
818
  <div class="file-item"><div>
819
- {% if file.file_type == 'image' %} <img class="file-preview" src="{{ hf_file_url_jinja(file.path) }}" loading="lazy" onclick="openModalAdmin('{{ hf_file_url_jinja(file.path) }}', '{{ file.file_type }}', '{{ file.id }}')" style="cursor: pointer;">
820
- {% elif file.file_type == 'video' %} <video class="file-preview" preload="metadata" muted onclick="openModalAdmin('{{ hf_file_url_jinja(file.path) }}', '{{ file.file_type }}', '{{ file.id }}')" style="cursor: pointer;"><source src="{{ hf_file_url_jinja(file.path, True) }}#t=0.5"></video>
821
- {% elif file.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.path, True) }}', '{{ file.file_type }}', '{{ file.id }}')">📄</div>
822
- {% elif file.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.id) }}', '{{ file.file_type }}', '{{ file.id }}')">📝</div>
823
  {% else %} <div class="file-preview" style="font-size: 40px; line-height: 100px; text-align: center; color: #aaa;">❓</div> {% endif %}
824
- <p title="{{ file.original_filename }}"><b>{{ file.original_filename | truncate(30) }}</b></p>
825
- <p style="font-size: 0.8em; color: #888;">В папке: {{ file.parent_path_str }}</p>
826
- <p style="font-size: 0.8em; color: #888;">Загружен: {{ file.upload_date }}</p>
827
- <p style="font-size: 0.7em; color: #ccc;">ID: {{ file.id }}</p>
828
- <p style="font-size: 0.7em; color: #ccc; word-break: break-all;">Path: {{ file.path }}</p>
829
  </div><div class="admin-file-actions">
830
- <a href="{{ url_for('download_tma', file_id=file.id) }}" class="btn download-btn">Скачать</a>
831
- {% set previewable = file.file_type in ['image', 'video', 'pdf', 'text'] %}
832
- {% if previewable %}<button class="btn" style="background: var(--accent);" onclick="openModalAdmin('{{ hf_file_url_jinja(file.path) if file.file_type != 'text' else url_for('get_text_content_tma', file_id=file.id) }}', '{{ file.file_type }}', '{{ file.id }}')">Просмотр</button>{% endif %}
833
- <form method="POST" action="{{ url_for('admin_delete_file_tma', tma_user_id_str_form=tma_user_id_str_admin_view, file_id=file.id) }}" style="display: inline-block;" onsubmit="return confirm('Удалить файл {{ file.original_filename }}?');">
834
  <button type="submit" class="btn delete-btn">Удалить</button></form>
835
  </div></div>{% else %} <p>У пользователя нет файлов.</p> {% endfor %}</div></div>
836
  <div class="modal" id="mediaModalAdmin" onclick="closeModalAdminEv(event)"><div class="modal-content" id="modalContentContainerAdmin">
@@ -859,13 +976,12 @@ body.dark .file-item { background: var(--card-bg-dark); } .file-item:hover { tra
859
  </script></body></html>'''
860
 
861
  @app.route('/admhosto/user/<tma_user_id_str>')
862
- def admin_user_files_tma(tma_user_id_str):
863
- if not is_admin_tma():
864
- flash('Доступ запрещен.', 'error'); return redirect(url_for('tma_dashboard'))
865
  data = load_data()
866
  user_data = data.get('users', {}).get(tma_user_id_str)
867
  if not user_data:
868
- flash(f'Пользователь ID {tma_user_id_str} не найден.', 'error'); return redirect(url_for('admin_panel_tma'))
869
 
870
  all_files = []
871
  def collect_files_admin(folder, current_path_id='root'):
@@ -877,75 +993,87 @@ def admin_user_files_tma(tma_user_id_str):
877
  all_files.sort(key=lambda x: x.get('upload_date', ''), reverse=True)
878
 
879
  display_name_admin_view = user_data.get('first_name', user_data.get('telegram_username', f"User {tma_user_id_str}"))
880
- return render_template_string(ADMIN_USER_FILES_HTML_TMA_TEMPLATE,
881
  tma_user_id_str_admin_view=tma_user_id_str, display_name_admin_view=display_name_admin_view, files=all_files,
882
  repo_id_js_admin=REPO_ID,
883
  hf_file_url_jinja=lambda path, download=False: f"https://huggingface.co/datasets/{REPO_ID}/resolve/main/{path}{'?download=true' if download else ''}")
884
 
885
  @app.route('/admhosto/delete_user/<tma_user_id_str>', methods=['POST'])
886
- def admin_delete_user_tma(tma_user_id_str):
887
- if not is_admin_tma():
888
- flash('Доступ запрещен.', 'error'); return redirect(url_for('tma_dashboard'))
889
  if not HF_TOKEN_WRITE:
890
- flash('Удаление невозможно: токен для записи не настроен.', 'error'); return redirect(url_for('admin_panel_tma'))
891
  data = load_data()
892
  if tma_user_id_str not in data['users']:
893
- flash('Пользователь не найден!', 'error'); return redirect(url_for('admin_panel_tma'))
894
  try:
895
  api = HfApi()
896
  user_folder_path_on_hf = f"cloud_files/{tma_user_id_str}"
897
- api.delete_folder(folder_path=user_folder_path_on_hf, repo_id=REPO_ID, repo_type="dataset", token=HF_TOKEN_WRITE)
898
  except hf_utils.HfHubHTTPError as e:
899
- if e.response.status_code != 404:
900
- flash(f'Ошибка удаления файлов пользователя {tma_user_id_str} с сервера: {e}.', 'error'); return redirect(url_for('admin_panel_tma'))
 
901
  except Exception as e:
902
- flash(f'Ошибка удаления файлов {tma_user_id_str} с сервера: {e}.', 'error'); return redirect(url_for('admin_panel_tma'))
 
903
  try:
904
  del data['users'][tma_user_id_str]
905
  save_data(data)
906
- flash(f'Пользователь {tma_user_id_str} и его файлы удалены.')
907
  except Exception as e:
908
- flash(f'Файлы удалены, но ошибка удаления из базы: {e}', 'error')
909
- return redirect(url_for('admin_panel_tma'))
 
910
 
911
  @app.route('/admhosto/delete_file/<tma_user_id_str_form>/<file_id>', methods=['POST'])
912
- def admin_delete_file_tma(tma_user_id_str_form, file_id):
913
- if not is_admin_tma():
914
- flash('Доступ запрещен.', 'error'); return redirect(url_for('tma_dashboard'))
915
  if not HF_TOKEN_WRITE:
916
- flash('Удаление невозможно: токен не настроен.', 'error'); return redirect(url_for('admin_user_files_tma', tma_user_id_str=tma_user_id_str_form))
917
  data = load_data()
918
  user_data = data.get('users', {}).get(tma_user_id_str_form)
919
  if not user_data:
920
- flash(f'Пользователь {tma_user_id_str_form} не найден.', 'error'); return redirect(url_for('admin_panel_tma'))
 
921
  file_node, _ = find_node_by_id(user_data['filesystem'], file_id)
922
  if not file_node or file_node.get('type') != 'file':
923
- flash('Файл не найден.', 'error'); return redirect(url_for('admin_user_files_tma', tma_user_id_str=tma_user_id_str_form))
 
924
  hf_path = file_node.get('path')
925
  original_filename = file_node.get('original_filename', 'файл')
 
926
  if not hf_path:
927
  if remove_node(user_data['filesystem'], file_id):
928
- try: save_data(data); flash(f'Метаданные {original_filename} удалены (путь отсутствовал).')
929
- except Exception as e: flash('Ошибка сохранения (путь отсутствовал).', 'error')
930
- return redirect(url_for('admin_user_files_tma', tma_user_id_str=tma_user_id_str_form))
 
931
  try:
932
  api = HfApi()
933
  api.delete_file(path_in_repo=hf_path, repo_id=REPO_ID, repo_type="dataset", token=HF_TOKEN_WRITE)
934
  if remove_node(user_data['filesystem'], file_id):
935
- try: save_data(data); flash(f'Файл {original_filename} удален!')
936
- except Exception as e: flash('Файл удален с сервера, ошибка обновления базы.', 'error')
 
 
937
  except hf_utils.EntryNotFoundError:
 
938
  if remove_node(user_data['filesystem'], file_id):
939
- try: save_data(data); flash(f'Файл {original_filename} не найден на сервере, удален из базы.')
940
- except Exception as e: flash('Ошибка сохранения (файл не на сервере).', 'error')
941
  except Exception as e:
942
- flash(f'Ошибка удаления файла {original_filename}: {e}', 'error')
943
- return redirect(url_for('admin_user_files_tma', tma_user_id_str=tma_user_id_str_form))
 
944
 
945
  if __name__ == '__main__':
946
  if not HF_TOKEN_WRITE: logging.warning("HF_TOKEN (write access) is not set. Uploads/deletions/backups will fail.")
947
  if not HF_TOKEN_READ: logging.warning("HF_TOKEN_READ is not set. Using HF_TOKEN. Downloads/previews might fail for private repos if HF_TOKEN also lacks read.")
948
- if ADMIN_TELEGRAM_ID == "YOUR_ADMIN_TELEGRAM_USER_ID_HERE": logging.warning("ADMIN_TELEGRAM_ID is not set. Admin panel will not be accessible.")
 
 
 
949
 
950
  if HF_TOKEN_WRITE:
951
  download_db_from_hf()
 
12
  import requests
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")
19
  DATA_FILE = 'cloudeng_data_tma.json'
20
+ REPO_ID = "Eluza133/Z1e1u"
21
  HF_TOKEN_WRITE = os.getenv("HF_TOKEN")
22
  HF_TOKEN_READ = os.getenv("HF_TOKEN_READ") or HF_TOKEN_WRITE
23
  TELEGRAM_BOT_TOKEN = os.getenv("TELEGRAM_BOT_TOKEN", "6750208873:AAE2hvPlJ99dBdhGa_Brre0IIpUdOvXxHt4")
24
+ ADMIN_TELEGRAM_ID = os.getenv("ADMIN_TELEGRAM_ID", "YOUR_ADMIN_TELEGRAM_USER_ID_HERE")
25
+
26
+ ADMIN_USERNAME = os.getenv("ADMIN_USERNAME", "admin")
27
+ ADMIN_PASSWORD = os.getenv("ADMIN_PASSWORD", "zeusadminpass")
28
+
29
 
30
  UPLOAD_FOLDER = 'uploads_tma'
31
  os.makedirs(UPLOAD_FOLDER, exist_ok=True)
 
53
  h4 { font-size: 1.1em; margin-top: 15px; margin-bottom: 5px; color: var(--accent); }
54
  ol, ul { margin-left: 20px; margin-bottom: 15px; }
55
  li { margin-bottom: 5px; }
56
+ input, textarea, input[type="text"], input[type="password"], input[type="file"] { width: 100%; padding: 14px; margin: 12px 0; border: none; border-radius: 14px; background: var(--glass-bg); color: var(--text-light); font-size: 1.1em; box-shadow: inset 0 3px 10px rgba(0, 0, 0, 0.1); }
57
+ body.dark input, body.dark textarea, body.dark input[type="text"], body.dark input[type="password"], body.dark input[type="file"] { color: var(--text-dark); background: rgba(255,255,255,0.05); }
58
  input:focus, textarea:focus { outline: none; box-shadow: 0 0 0 4px var(--primary); }
59
  .btn { padding: 14px 28px; background: var(--primary); color: white; border: none; border-radius: 14px; cursor: pointer; font-size: 1.1em; font-weight: 600; transition: var(--transition); box-shadow: var(--shadow); display: inline-block; text-decoration: none; margin-top: 5px; margin-right: 5px; }
60
  .btn:hover { transform: scale(1.05); background: #e6415f; }
 
171
  user_data['filesystem'] = {
172
  "type": "folder", "id": "root", "name": "root", "children": []
173
  }
174
+ if 'files' in user_data and isinstance(user_data['files'], list):
175
  for old_file in user_data['files']:
176
  file_id = old_file.get('id', uuid.uuid4().hex)
177
  original_filename = old_file.get('filename', 'unknown_file')
 
260
  def is_admin_tma():
261
  if not ADMIN_TELEGRAM_ID or ADMIN_TELEGRAM_ID == "YOUR_ADMIN_TELEGRAM_USER_ID_HERE":
262
  return False
263
+ return 'telegram_user_id' in session and str(session['telegram_user_id']) == str(ADMIN_TELEGRAM_ID)
264
+
265
+
266
+ def admin_browser_login_required(f):
267
+ @wraps(f)
268
+ def decorated_function(*args, **kwargs):
269
+ if not session.get('admin_browser_logged_in'):
270
+ return redirect(url_for('admin_login', next=request.url))
271
+ return f(*args, **kwargs)
272
+ return decorated_function
273
 
274
  TMA_ENTRY_HTML = '''
275
  <!DOCTYPE html><html lang="ru"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0">
 
321
  try:
322
  payload = request.json
323
  tg_user_data = payload.get('user')
 
324
 
325
  if not tg_user_data or not tg_user_data.get('id'):
326
  return jsonify({'status': 'error', 'message': 'Отсутствуют данные пользователя Telegram.'}), 400
 
348
  display_name = tg_user_data.get('first_name') or tg_user_data.get('username') or f"User {tma_user_id_str}"
349
  session['telegram_display_name'] = display_name
350
 
 
 
 
351
  return jsonify({'status': 'success', 'redirect_url': url_for('tma_dashboard')})
352
 
353
  except Exception as e:
 
358
  <!DOCTYPE html><html lang="ru"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0">
359
  <title>Zeus Cloud</title><link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600;800&display=swap" rel="stylesheet">
360
  <script src="https://telegram.org/js/telegram-web-app.js"></script>
361
+ <style>''' + BASE_STYLE + '''</style></head><body class="dark"><div class="container">
362
  <h1>Zeus Cloud</h1><p>Пользователь: {{ display_name }}</p>
363
  {% with messages = get_flashed_messages(with_categories=true) %}{% if messages %}
364
  {% for category, message in messages %}<div class="flash {{ category }}">{{ message }}</div>{% endfor %}
 
419
  {% if not items %} <p>Эта папка пуста.</p> {% endif %}
420
  </div>
421
  <a href="{{ url_for('tma_logout') }}" class="btn" style="margin-top: 20px;" id="logout-btn">Выйти (очистить сессию)</a>
422
+ {% if is_tma_user_admin_flag %}
423
+ <a href="{{ url_for('admin_panel') }}" class="btn" style="margin-top: 20px; background-color: var(--accent);">Админ-панель</a>
424
  {% endif %}
425
  </div>
426
  <div class="modal" id="mediaModal" onclick="closeModal(event)"><div class="modal-content" id="modalContentContainer">
427
  <span onclick="closeModalManual()" class="modal-close-btn">×</span><div id="modalContent"></div></div></div>
428
  <script>
429
  window.Telegram.WebApp.ready();
430
+ document.body.classList.add('dark');
431
  const repoId = "{{ repo_id_js }}";
432
  const hfTokenRead = "{{ HF_TOKEN_READ_js or '' }}";
433
  function hfFileUrl(path, download = false) {
 
498
  return redirect(url_for('tma_entry_page'))
499
 
500
  user_data = data['users'][tma_user_id]
501
+ initialize_user_filesystem_tma(user_data, tma_user_id)
502
 
503
  current_folder_id = request.args.get('folder_id', 'root')
504
  current_folder, _ = find_node_by_id(user_data['filesystem'], current_folder_id)
 
507
  flash('Папка не найдена!', 'error')
508
  current_folder_id = 'root'
509
  current_folder, _ = find_node_by_id(user_data['filesystem'], current_folder_id)
510
+ if not current_folder:
511
  flash('Критическая ошибка: корневая папка не найдена.', 'error')
512
  session.clear()
513
  return redirect(url_for('tma_entry_page'))
 
536
  api = HfApi()
537
  uploaded_count = 0
538
  errors_list = []
539
+ for file_obj in files:
540
+ if file_obj and file_obj.filename:
541
+ original_filename = secure_filename(file_obj.filename)
542
  name_part, ext_part = os.path.splitext(original_filename)
543
  unique_suffix = uuid.uuid4().hex[:8]
544
  unique_filename = f"{name_part}_{unique_suffix}{ext_part}"
 
546
  hf_path = f"cloud_files/{tma_user_id}/{target_folder_id}/{unique_filename}"
547
  temp_path = os.path.join(UPLOAD_FOLDER, f"{file_id}_{unique_filename}")
548
  try:
549
+ file_obj.save(temp_path)
550
  api.upload_file(
551
  path_or_fileobj=temp_path, path_in_repo=hf_path, repo_id=REPO_ID,
552
  repo_type="dataset", token=HF_TOKEN_WRITE,
 
594
  current_folder_id=current_folder_id, current_folder=current_folder,
595
  breadcrumbs=breadcrumbs, repo_id_js=REPO_ID, HF_TOKEN_READ_js=HF_TOKEN_READ,
596
  hf_file_url_jinja=lambda path, download=False: f"https://huggingface.co/datasets/{REPO_ID}/resolve/main/{path}{'?download=true' if download else ''}",
597
+ is_tma_user_admin_flag=is_admin_tma())
598
 
599
 
600
  @app.route('/create_folder_tma', methods=['POST'])
601
  def create_folder_tma():
602
  if 'telegram_user_id' not in session:
603
+ flash('Не авторизован', 'error')
604
+ return redirect(url_for('tma_entry_page'))
605
  tma_user_id = session['telegram_user_id']
606
  data = load_data()
607
  user_data = data['users'].get(tma_user_id)
608
+ if not user_data:
609
+ flash('Пользователь не найден', 'error')
610
+ return redirect(url_for('tma_entry_page'))
611
 
612
  parent_folder_id = request.form.get('parent_folder_id', 'root')
613
  folder_name = request.form.get('folder_name', '').strip()
 
629
  @app.route('/download_tma/<file_id>')
630
  def download_tma(file_id):
631
  current_tma_user_id = session.get('telegram_user_id')
632
+ is_browser_admin_session = session.get('admin_browser_logged_in', False)
633
+
 
 
634
  data = load_data()
635
  file_node = None
636
 
637
+ if is_browser_admin_session:
638
+ for uid_str_iter, udata_iter in data.get('users', {}).items():
 
 
 
 
639
  node, _ = find_node_by_id(udata_iter.get('filesystem', {}), file_id)
640
  if node and node.get('type') == 'file':
641
  file_node = node
642
  break
643
+ elif current_tma_user_id:
644
+ user_data = data['users'].get(current_tma_user_id)
645
+ if user_data:
646
+ file_node, _ = find_node_by_id(user_data['filesystem'], file_id)
647
+
648
+ if not file_node and is_admin_tma():
649
+ for uid_str_iter, udata_iter in data.get('users', {}).items():
650
+ node, _ = find_node_by_id(udata_iter.get('filesystem', {}), file_id)
651
+ if node and node.get('type') == 'file':
652
+ file_node = node
653
+ break
654
+ else:
655
+ flash('Пожалуйста, авторизуйтесь.', 'error')
656
+ return redirect(url_for('tma_entry_page'))
657
 
658
+ redirect_url = request.referrer
659
+ if not redirect_url:
660
+ if is_browser_admin_session:
661
+ redirect_url = url_for('admin_panel')
662
+ else:
663
+ redirect_url = url_for('tma_dashboard')
664
+
665
  if not file_node or file_node.get('type') != 'file':
666
  flash('Файл не найден или доступ запрещен!', 'error')
667
+ return redirect(redirect_url)
668
 
669
  hf_path = file_node.get('path')
670
  original_filename = file_node.get('original_filename', 'downloaded_file')
671
  if not hf_path:
672
  flash('Ошибка: Путь к файлу не найден.', 'error')
673
+ return redirect(redirect_url)
674
 
675
  file_url = f"https://huggingface.co/datasets/{REPO_ID}/resolve/main/{hf_path}?download=true"
676
  try:
677
+ req_headers = {}
678
+ if HF_TOKEN_READ: req_headers["authorization"] = f"Bearer {HF_TOKEN_READ}"
679
+
680
+ r = requests.get(file_url, headers=req_headers, stream=True)
681
+ r.raise_for_status()
682
+
683
+ def generate_chunks():
684
+ for chunk in r.iter_content(chunk_size=8192):
685
+ yield chunk
686
+
687
+ mimetype = 'application/octet-stream'
688
+ if '.' in original_filename:
689
+ ext = original_filename.rsplit('.', 1)[1].lower()
690
+ content_types = {
691
+ 'pdf': 'application/pdf', 'jpg': 'image/jpeg', 'jpeg': 'image/jpeg',
692
+ 'png': 'image/png', 'gif': 'image/gif', 'txt': 'text/plain',
693
+ 'mp4': 'video/mp4', 'mov': 'video/quicktime', 'avi': 'video/x-msvideo',
694
+ 'zip': 'application/zip', 'rar': 'application/x-rar-compressed',
695
+ }
696
+ mimetype = content_types.get(ext, 'application/octet-stream')
697
+
698
+ resp = Response(generate_chunks(), mimetype=mimetype)
699
+ resp.headers['Content-Disposition'] = f'attachment; filename="{original_filename}"'
700
+ return resp
701
+
702
+ except requests.exceptions.RequestException as e:
703
  flash(f'Ошибка скачивания файла: {e}', 'error')
704
+ except Exception as e:
705
+ flash(f'Внутренняя ошибка при скачивании: {e}', 'error')
706
+ return redirect(redirect_url)
707
+
708
 
709
  @app.route('/delete_file_tma/<file_id>', methods=['POST'])
710
  def delete_file_tma(file_id):
 
778
  @app.route('/get_text_content_tma/<file_id>')
779
  def get_text_content_tma(file_id):
780
  current_tma_user_id = session.get('telegram_user_id')
781
+ is_browser_admin_session = session.get('admin_browser_logged_in', False)
782
 
783
  data = load_data()
784
  file_node = None
 
 
 
785
 
786
+ if is_browser_admin_session:
787
  for uid_str, udata_iter in data.get('users', {}).items():
788
  node, _ = find_node_by_id(udata_iter.get('filesystem', {}), file_id)
789
  if node and node.get('type') == 'file' and node.get('file_type') == 'text':
790
  file_node = node; break
791
+ elif current_tma_user_id:
792
+ user_data = data['users'].get(current_tma_user_id)
793
+ if user_data:
794
+ file_node, _ = find_node_by_id(user_data['filesystem'], file_id)
795
+
796
+ if not file_node and is_admin_tma():
797
+ for uid_str, udata_iter in data.get('users', {}).items():
798
+ node, _ = find_node_by_id(udata_iter.get('filesystem', {}), file_id)
799
+ if node and node.get('type') == 'file' and node.get('file_type') == 'text':
800
+ file_node = node; break
801
+ else:
802
+ return Response("Не авторизован", status=401)
803
 
804
  if not file_node or file_node.get('type') != 'file' or file_node.get('file_type') != 'text':
805
  return Response("Текстовый файл не найден", status=404)
 
807
  if not hf_path: return Response("Ошибка: путь к файлу отсутствует", status=500)
808
  file_url = f"https://huggingface.co/datasets/{REPO_ID}/resolve/main/{hf_path}?download=true"
809
  try:
810
+ req_headers = {};
811
+ if HF_TOKEN_READ: req_headers["authorization"] = f"Bearer {HF_TOKEN_READ}"
812
+ response = requests.get(file_url, headers=req_headers)
813
  response.raise_for_status()
814
  if len(response.content) > 1 * 1024 * 1024: return Response("Файл слишком большой.", status=413)
815
  try: text_content = response.content.decode('utf-8')
 
819
 
820
  @app.route('/tma_logout')
821
  def tma_logout():
822
+ session.pop('telegram_user_id', None)
823
+ session.pop('telegram_display_name', None)
824
  flash('Вы вышли из сессии приложения.')
825
  return redirect(url_for('tma_entry_page'))
826
 
827
+
828
+ ADMIN_LOGIN_HTML_TEMPLATE = '''
829
+ <!DOCTYPE html><html lang="ru"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0">
830
+ <title>Admin Login</title><link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600;800&display=swap" rel="stylesheet">
831
+ <style>
832
+ {{ admin_base_style_css }}
833
+ body { display: flex; justify-content: center; align-items: center; height: 100vh; background: var(--background-dark); }
834
+ .login-container { text-align: center; padding: 40px; background: var(--card-bg-dark); border-radius: 20px; box-shadow: var(--shadow); width: 100%; max-width: 400px; }
835
+ h1 { color: var(--primary); margin-bottom: 20px; }
836
+ input[type="text"], input[type="password"] { background: rgba(255,255,255,0.1); color: var(--text-dark); margin-bottom: 20px; }
837
+ .btn { background: var(--accent); width: 100%; }
838
+ </style>
839
+ </head><body class="dark">
840
+ <div class="login-container">
841
+ <h1>Admin Login</h1>
842
+ {% with messages = get_flashed_messages(with_categories=true) %}
843
+ {% if messages %}
844
+ {% for category, message in messages %}
845
+ <div class="flash {{ category }}">{{ message }}</div>
846
+ {% endfor %}
847
+ {% endif %}
848
+ {% endwith %}
849
+ <form method="POST" action="{{ url_for('admin_login') }}">
850
+ <input type="hidden" name="next" value="{{ request.args.get('next', '') }}">
851
+ <input type="text" name="username" placeholder="Username" required>
852
+ <input type="password" name="password" placeholder="Password" required>
853
+ <button type="submit" class="btn">Login</button>
854
+ </form>
855
+ </div>
856
+ </body></html>
857
+ '''
858
+
859
+ @app.route('/admin/login', methods=['GET', 'POST'])
860
+ def admin_login():
861
+ if request.method == 'POST':
862
+ username = request.form.get('username')
863
+ password = request.form.get('password')
864
+ next_url = request.form.get('next')
865
+
866
+ if username == ADMIN_USERNAME and password == ADMIN_PASSWORD:
867
+ session['admin_browser_logged_in'] = True
868
+ flash('Успешный вход в админ-панель.', 'success')
869
+ if next_url:
870
+ return redirect(next_url)
871
+ return redirect(url_for('admin_panel'))
872
+ else:
873
+ flash('Неверное имя пользователя или пароль.', 'error')
874
+ return render_template_string(ADMIN_LOGIN_HTML_TEMPLATE, admin_base_style_css=BASE_STYLE)
875
+
876
+ @app.route('/admin/logout')
877
+ def admin_logout():
878
+ session.pop('admin_browser_logged_in', None)
879
+ flash('Вы вышли из админ-панели.', 'success')
880
+ return redirect(url_for('admin_login'))
881
+
882
+ ADMIN_PANEL_HTML_TEMPLATE = '''
883
  <!DOCTYPE html><html lang="ru"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0">
884
  <title>Админ-панель</title><link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600;800&display=swap" rel="stylesheet">
885
+ <style>''' + BASE_STYLE + '''</style></head><body class="dark"><div class="container"><h1>Админ-панель</h1>
886
+ <a href="{{ url_for('admin_logout') }}" class="btn" style="margin-bottom:20px; background-color: var(--accent);">Выйти из админ-панели</a>
887
+ <a href="{{ url_for('tma_dashboard') }}" class="btn" style="margin-bottom:20px;">В приложение (если TMA сессия есть)</a>
888
  {% with messages = get_flashed_messages(with_categories=true) %}{% if messages %}{% for category, message in messages %}<div class="flash {{ category }}">{{ message }}</div>{% endfor %}{% endif %}{% endwith %}
889
  <h2>Пользователи</h2><div class="user-list">
890
  {% for user in user_details %}
891
  <div class="user-item">
892
+ <a href="{{ url_for('admin_user_files', tma_user_id_str=user.id_key) }}">{{ user.display_name }} (ID: {{user.id_key}})</a>
893
  <p>Зарегистрирован: {{ user.created_at }}</p><p>Файлов: {{ user.file_count }}</p>
894
+ <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 }} и ВСЕ его файлы? НЕОБРАТИМО!');">
895
  <button type="submit" class="btn delete-btn" style="padding: 5px 10px; font-size: 0.9em;">Удалить</button>
896
  </form>
897
  </div>
898
  {% else %}<p>Пользователей нет.</p>{% endfor %}</div></div></body></html>'''
899
 
900
  @app.route('/admhosto')
901
+ @admin_browser_login_required
902
+ def admin_panel():
 
903
  data = load_data()
904
  users = data.get('users', {})
905
  user_details = []
 
916
  'display_name': udata.get('first_name', udata.get('telegram_username', f"User {tma_id_str}")),
917
  'created_at': udata.get('created_at', 'N/A'), 'file_count': file_count
918
  })
919
+ user_details.sort(key=lambda x: x.get('created_at', ''), reverse=True)
920
+ return render_template_string(ADMIN_PANEL_HTML_TEMPLATE, user_details=user_details)
921
 
922
+ ADMIN_USER_FILES_HTML_TEMPLATE = '''
923
  <!DOCTYPE html><html lang="ru"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0">
924
  <title>Файлы {{ display_name_admin_view }}</title><link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600;800&display=swap" rel="stylesheet">
925
  <style>''' + BASE_STYLE + '''
926
+ .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; }
 
927
  .file-preview { max-width: 100%; height: 100px; object-fit: contain; border-radius: 10px; margin-bottom: 10px; display: block; margin-left: auto; margin-right: auto; }
928
  .admin-file-actions { margin-top: 10px; display: flex; flex-wrap: wrap; gap: 5px; justify-content: center; }
929
  .admin-file-actions .btn { font-size: 0.8em; padding: 4px 8px; margin: 0; }
930
+ </style></head><body class="dark"><div class="container"><h1>Файлы пользователя: {{ display_name_admin_view }} (ID: {{ tma_user_id_str_admin_view }})</h1>
931
+ <a href="{{ url_for('admin_panel') }}" class="btn" style="margin-bottom: 20px;">Назад к пользователям</a>
932
  {% with messages = get_flashed_messages(with_categories=true) %}{% if messages %}{% for category, message in messages %}<div class="flash {{ category }}">{{ message }}</div>{% endfor %}{% endif %}{% endwith %}
933
  <div style="display: grid; grid-template-columns: repeat(auto-fill, minmax(220px, 1fr)); gap: 20px;">
934
+ {% for file_item in files %}
935
  <div class="file-item"><div>
936
+ {% 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;">
937
+ {% 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>
938
+ {% 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>
939
+ {% 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>
940
  {% else %} <div class="file-preview" style="font-size: 40px; line-height: 100px; text-align: center; color: #aaa;">❓</div> {% endif %}
941
+ <p title="{{ file_item.original_filename }}"><b>{{ file_item.original_filename | truncate(30) }}</b></p>
942
+ <p style="font-size: 0.8em; color: #888;">В папке: {{ file_item.parent_path_str }}</p>
943
+ <p style="font-size: 0.8em; color: #888;">Загружен: {{ file_item.upload_date }}</p>
944
+ <p style="font-size: 0.7em; color: #ccc;">ID: {{ file_item.id }}</p>
945
+ <p style="font-size: 0.7em; color: #ccc; word-break: break-all;">Path: {{ file_item.path }}</p>
946
  </div><div class="admin-file-actions">
947
+ <a href="{{ url_for('download_tma', file_id=file_item.id) }}" class="btn download-btn">Скачать</a>
948
+ {% set previewable = file_item.file_type in ['image', 'video', 'pdf', 'text'] %}
949
+ {% if previewable %}<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 %}
950
+ <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 }}?');">
951
  <button type="submit" class="btn delete-btn">Удалить</button></form>
952
  </div></div>{% else %} <p>У пользователя нет файлов.</p> {% endfor %}</div></div>
953
  <div class="modal" id="mediaModalAdmin" onclick="closeModalAdminEv(event)"><div class="modal-content" id="modalContentContainerAdmin">
 
976
  </script></body></html>'''
977
 
978
  @app.route('/admhosto/user/<tma_user_id_str>')
979
+ @admin_browser_login_required
980
+ def admin_user_files(tma_user_id_str):
 
981
  data = load_data()
982
  user_data = data.get('users', {}).get(tma_user_id_str)
983
  if not user_data:
984
+ flash(f'Пользователь ID {tma_user_id_str} не найден.', 'error'); return redirect(url_for('admin_panel'))
985
 
986
  all_files = []
987
  def collect_files_admin(folder, current_path_id='root'):
 
993
  all_files.sort(key=lambda x: x.get('upload_date', ''), reverse=True)
994
 
995
  display_name_admin_view = user_data.get('first_name', user_data.get('telegram_username', f"User {tma_user_id_str}"))
996
+ return render_template_string(ADMIN_USER_FILES_HTML_TEMPLATE,
997
  tma_user_id_str_admin_view=tma_user_id_str, display_name_admin_view=display_name_admin_view, files=all_files,
998
  repo_id_js_admin=REPO_ID,
999
  hf_file_url_jinja=lambda path, download=False: f"https://huggingface.co/datasets/{REPO_ID}/resolve/main/{path}{'?download=true' if download else ''}")
1000
 
1001
  @app.route('/admhosto/delete_user/<tma_user_id_str>', methods=['POST'])
1002
+ @admin_browser_login_required
1003
+ def admin_delete_user(tma_user_id_str):
 
1004
  if not HF_TOKEN_WRITE:
1005
+ flash('Удаление невозможно: токен для записи не настроен.', 'error'); return redirect(url_for('admin_panel'))
1006
  data = load_data()
1007
  if tma_user_id_str not in data['users']:
1008
+ flash('Пользователь не найден!', 'error'); return redirect(url_for('admin_panel'))
1009
  try:
1010
  api = HfApi()
1011
  user_folder_path_on_hf = f"cloud_files/{tma_user_id_str}"
1012
+ api.delete_folder(folder_path=user_folder_path_on_hf, repo_id=REPO_ID, repo_type="dataset", token=HF_TOKEN_WRITE, ignore_patterns=[".keep"])
1013
  except hf_utils.HfHubHTTPError as e:
1014
+ if e.response.status_code != 404: # 404 means folder not found, which is fine for deletion.
1015
+ flash(f'Ошибка удаления файлов пользователя {tma_user_id_str} с сервера: {e}. Пользователь из базы не удален.', 'error'); return redirect(url_for('admin_panel'))
1016
+ 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.")
1017
  except Exception as e:
1018
+ flash(f'Ошибка удаления файлов пользователя {tma_user_id_str} с сервера: {e}. Пользователь из базы не удален.', 'error'); return redirect(url_for('admin_panel'))
1019
+
1020
  try:
1021
  del data['users'][tma_user_id_str]
1022
  save_data(data)
1023
+ flash(f'Пользователь {tma_user_id_str} и его файлы (если были) удалены.')
1024
  except Exception as e:
1025
+ flash(f'Файлы на сервере могли быть удалены, но произошла ошибка удаления пользователя из базы данных: {e}', 'error')
1026
+ return redirect(url_for('admin_panel'))
1027
+
1028
 
1029
  @app.route('/admhosto/delete_file/<tma_user_id_str_form>/<file_id>', methods=['POST'])
1030
+ @admin_browser_login_required
1031
+ def admin_delete_file(tma_user_id_str_form, file_id):
 
1032
  if not HF_TOKEN_WRITE:
1033
+ flash('Удаление невозможно: токен для записи не настроен.', 'error'); return redirect(url_for('admin_user_files', tma_user_id_str=tma_user_id_str_form))
1034
  data = load_data()
1035
  user_data = data.get('users', {}).get(tma_user_id_str_form)
1036
  if not user_data:
1037
+ flash(f'Пользователь {tma_user_id_str_form} не найден.', 'error'); return redirect(url_for('admin_panel'))
1038
+
1039
  file_node, _ = find_node_by_id(user_data['filesystem'], file_id)
1040
  if not file_node or file_node.get('type') != 'file':
1041
+ flash('Файл не найден в базе данных этого пользователя.', 'error'); return redirect(url_for('admin_user_files', tma_user_id_str=tma_user_id_str_form))
1042
+
1043
  hf_path = file_node.get('path')
1044
  original_filename = file_node.get('original_filename', 'файл')
1045
+
1046
  if not hf_path:
1047
  if remove_node(user_data['filesystem'], file_id):
1048
+ try: save_data(data); flash(f'Метаданные файла {original_filename} удалены из базы (путь к файлу на сервере отсутствовал).')
1049
+ except Exception as e: flash('Ошибка сохранения данных после удаления метаданных (путь отсутствовал).', 'error')
1050
+ return redirect(url_for('admin_user_files', tma_user_id_str=tma_user_id_str_form))
1051
+
1052
  try:
1053
  api = HfApi()
1054
  api.delete_file(path_in_repo=hf_path, repo_id=REPO_ID, repo_type="dataset", token=HF_TOKEN_WRITE)
1055
  if remove_node(user_data['filesystem'], file_id):
1056
+ try: save_data(data); flash(f'Файл {original_filename} успешно удален с сервера и из базы данных!')
1057
+ except Exception as e: flash('Файл удален с сервера, но произошла ошибка при обновлении базы данных.', 'error')
1058
+ else:
1059
+ flash(f'Файл {original_filename} удален с сервера, но не найден в структуре папок пользователя для удаления из базы.', 'error')
1060
  except hf_utils.EntryNotFoundError:
1061
+ flash(f'Файл {original_filename} не найден на сервере. Удаляем из базы данных.')
1062
  if remove_node(user_data['filesystem'], file_id):
1063
+ try: save_data(data); flash(f'Запись о файле {original_filename} удалена из базы.')
1064
+ except Exception as e: flash('Ошибка сохранения данных после удаления записи о файле (файл не на сервере).', 'error')
1065
  except Exception as e:
1066
+ flash(f'Ошибка при удалении файла {original_filename}: {e}', 'error')
1067
+ return redirect(url_for('admin_user_files', tma_user_id_str=tma_user_id_str_form))
1068
+
1069
 
1070
  if __name__ == '__main__':
1071
  if not HF_TOKEN_WRITE: logging.warning("HF_TOKEN (write access) is not set. Uploads/deletions/backups will fail.")
1072
  if not HF_TOKEN_READ: logging.warning("HF_TOKEN_READ is not set. Using HF_TOKEN. Downloads/previews might fail for private repos if HF_TOKEN also lacks read.")
1073
+ if ADMIN_TELEGRAM_ID == "YOUR_ADMIN_TELEGRAM_USER_ID_HERE": logging.warning("ADMIN_TELEGRAM_ID is not set. TMA admin features might not work as expected for specific users.")
1074
+ if ADMIN_USERNAME == "admin" and ADMIN_PASSWORD == "zeusadminpass":
1075
+ logging.warning("Using default admin username/password for browser admin panel. Please change ADMIN_USERNAME and ADMIN_PASSWORD environment variables.")
1076
+
1077
 
1078
  if HF_TOKEN_WRITE:
1079
  download_db_from_hf()