Eluza133 commited on
Commit
87c919f
·
verified ·
1 Parent(s): 8d6304c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +498 -392
app.py CHANGED
@@ -1,5 +1,5 @@
1
  import flask
2
- from flask import Flask, render_template_string, request, redirect, url_for, session, flash, jsonify, Response, stream_with_context
3
  from flask_caching import Cache
4
  import json
5
  import os
@@ -10,11 +10,12 @@ from datetime import datetime
10
  from huggingface_hub import HfApi, hf_hub_download, utils as hf_utils
11
  from werkzeug.utils import secure_filename
12
  import requests
 
13
  import uuid
14
  from functools import wraps
15
  from urllib.parse import quote
16
- import io
17
  import zipfile
 
18
 
19
  app = Flask(__name__)
20
  app.secret_key = os.getenv("FLASK_SECRET_KEY", "supersecretkey_folders_unique_tma")
@@ -24,139 +25,94 @@ HF_TOKEN_WRITE = os.getenv("HF_TOKEN")
24
  HF_TOKEN_READ = os.getenv("HF_TOKEN_READ") or HF_TOKEN_WRITE
25
  TELEGRAM_BOT_TOKEN = os.getenv("TELEGRAM_BOT_TOKEN", "6750208873:AAE2hvPlJ99dBdhGa_Brre0IIpUdOvXxHt4")
26
  ADMIN_TELEGRAM_ID = os.getenv("ADMIN_TELEGRAM_ID", "YOUR_ADMIN_TELEGRAM_USER_ID_HERE")
27
-
28
  ADMIN_USERNAME = os.getenv("ADMIN_USERNAME", "admin")
29
  ADMIN_PASSWORD = os.getenv("ADMIN_PASSWORD", "zeusadminpass")
30
-
31
  UPLOAD_FOLDER = 'uploads_tma'
32
  os.makedirs(UPLOAD_FOLDER, exist_ok=True)
33
-
34
  cache = Cache(app, config={'CACHE_TYPE': 'simple'})
35
  logging.basicConfig(level=logging.INFO)
36
 
37
  BASE_STYLE = '''
38
  :root {
39
- --primary: #007AFF; --primary-light: #5856d6; --secondary: #34c759; --accent: #ff9500;
40
- --background-dark: #000000; --card-bg-dark: #1C1C1E; --text-dark: #FFFFFF;
41
- --text-secondary-dark: rgba(235, 235, 245, 0.6); --separator-dark: rgba(84, 84, 88, 0.65);
42
- --shadow: 0 8px 24px rgba(0, 0, 0, 0.3); --transition: all 0.3s cubic-bezier(0.25, 0.8, 0.25, 1);
43
- --delete-color: #ff3b30; --folder-color: #ffc107; --selection-color: rgba(0, 122, 255, 0.2);
44
  }
45
  * { margin: 0; padding: 0; box-sizing: border-box; }
46
  html { scroll-behavior: smooth; }
47
- body {
48
- font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Helvetica Neue', Arial, sans-serif;
49
- background: var(--background-dark); color: var(--text-dark); line-height: 1.5; -webkit-font-smoothing: antialiased;
50
- overscroll-behavior-y: none;
51
- }
52
- .container {
53
- margin: 0 auto; max-width: 1200px; padding: 15px; padding-bottom: 120px;
54
- background: transparent;
55
- }
56
- h1 { font-size: 2.2em; font-weight: 700; text-align: left; margin: 10px 0 5px; color: var(--text-dark); }
57
- h2 { font-size: 1.5em; margin: 25px 0 15px; color: var(--text-dark); border-bottom: 1px solid var(--separator-dark); padding-bottom: 10px; }
58
- input, textarea, select {
59
- width: 100%; padding: 14px; margin: 8px 0; border: 1px solid var(--separator-dark);
60
- border-radius: 10px; background: #2C2C2E; color: var(--text-dark);
61
- font-size: 1em; appearance: none; -webkit-appearance: none;
62
- }
63
- input:focus, textarea:focus, select:focus { outline: none; border-color: var(--primary); box-shadow: 0 0 0 3px rgba(0, 122, 255, 0.3); }
64
- .btn {
65
- padding: 12px 20px; background: var(--primary); color: white; border: none;
66
- border-radius: 10px; cursor: pointer; font-size: 1em; font-weight: 600;
67
- transition: var(--transition); display: inline-flex; align-items: center; justify-content: center;
68
- gap: 8px; text-decoration: none;
69
- }
70
- .btn:hover { background: var(--primary-light); transform: translateY(-2px); }
71
- .btn:active { transform: translateY(0); }
72
- .download-btn { background: var(--secondary); } .download-btn:hover { background: #30b152; }
73
- .delete-btn { background: var(--delete-color); } .delete-btn:hover { background: #e03228; }
74
- .folder-btn { background: var(--accent); } .folder-btn:hover { background: #f08d00; }
75
- .flash { text-align: center; margin-bottom: 15px; padding: 12px; border-radius: 10px; font-weight: 500; }
76
- .flash.success { color: #30d158; background: rgba(48, 209, 88, 0.1); }
77
- .flash.error { color: var(--delete-color); background: rgba(255, 59, 48, 0.1); }
78
- .file-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(150px, 1fr)); gap: 15px; margin-top: 20px; }
79
- .item {
80
- background: var(--card-bg-dark); border-radius: 14px; text-align: center;
81
- transition: var(--transition); display: flex; flex-direction: column; position: relative;
82
- border: 2px solid transparent; user-select: none; padding: 10px;
83
- }
84
- .item.selected { border-color: var(--primary); background: var(--selection-color); }
85
- .item:hover { transform: translateY(-4px); box-shadow: 0 4px 12px rgba(0,0,0,0.4); }
86
- .item-preview {
87
- width: 100%; height: 100px; object-fit: cover; border-radius: 8px; margin-bottom: 10px; cursor: pointer;
88
- background: #2C2C2E; display: flex; align-items: center; justify-content: center;
89
- }
90
- .item.folder .item-preview { font-size: 50px; color: var(--folder-color); }
91
- .item-name { font-size: 0.9em; font-weight: 500; margin: 5px 0; word-break: break-all; color: var(--text-dark); }
92
- .item-info { font-size: 0.75em; color: var(--text-secondary-dark); }
93
- .item-actions { margin-top: auto; padding-top: 10px; display: flex; gap: 5px; justify-content: center; opacity: 1; transition: opacity 0.2s; }
94
- .selection-mode .item-actions { opacity: 0; pointer-events: none; }
95
  .file-grid.list-view { display: flex; flex-direction: column; gap: 8px; }
96
- .file-grid.list-view .item { flex-direction: row; align-items: center; text-align: left; padding: 10px; }
97
- .file-grid.list-view .item:hover { background: #2C2C2E; }
98
- .file-grid.list-view .item-preview { width: 40px; height: 40px; margin: 0 12px 0 0; flex-shrink: 0; }
99
- .file-grid.list-view .item.folder .item-preview { font-size: 24px; }
100
- .file-grid.list-view .item-name-info { flex-grow: 1; overflow: hidden; }
101
- .file-grid.list-view .item-name { margin: 0; white-space: nowrap; text-overflow: ellipsis; overflow: hidden; }
102
- .file-grid.list-view .item-actions { margin-left: auto; flex-shrink: 0; }
103
- .file-grid.list-view .item-actions .btn { display: none; } /* Hide buttons in list view for cleanliness */
104
- .modal { display: none; position: fixed; inset: 0; background: rgba(0,0,0,0.8); backdrop-filter: blur(10px); z-index: 2000; justify-content: center; align-items: center; }
105
- .modal-content { max-width: 95vw; max-height: 95vh; background: transparent; position: relative; }
106
- .modal img, .modal video, .modal iframe, .modal pre { max-width: 100%; max-height: 90vh; display: block; margin: auto; border-radius: 12px; border: 1px solid var(--separator-dark); }
107
- .modal iframe { width: 90vw; height: 90vh; background: #fff; }
108
- .modal pre { background: var(--card-bg-dark); color: var(--text-dark); padding: 15px; text-align: left; max-height: 90vh; overflow-y: auto;}
109
- .modal-close-btn { position: absolute; top: -40px; right: 0; font-size: 20px; color: var(--text-secondary-dark); cursor: pointer; background: var(--card-bg-dark); border-radius: 50%; width: 30px; height: 30px; line-height: 30px; text-align: center; }
110
- #progress-container { width: 100%; background: #2C2C2E; border-radius: 8px; margin: 15px 0; display: none; height: 8px; }
111
- #progress-bar { width: 0%; height: 100%; background: var(--primary); border-radius: 8px; transition: width 0.3s ease; }
112
- .navigation-controls { display: flex; align-items: center; gap: 10px; margin: 10px 0 20px; }
113
- .back-btn { font-size: 1.5em; color: var(--primary); text-decoration: none; transition: var(--transition); line-height: 1; }
114
- .back-btn:hover { color: var(--primary-light); }
115
- .breadcrumbs { font-size: 1em; color: var(--text-secondary-dark); }
116
- .breadcrumbs a { color: var(--primary); text-decoration: none; }
117
- .top-actions { margin: 15px 0; display: flex; gap: 10px; align-items: center; flex-wrap: wrap; }
118
- .top-actions input[type=text] { width: auto; flex-grow: 1; margin: 0; min-width: 150px; }
119
- .top-actions .btn { margin: 0; flex-shrink: 0; padding: 12px 16px; }
120
- .view-toggle button { background: var(--card-bg-dark); color: var(--text-secondary-dark); border: none; padding: 8px 12px; border-radius: 8px; cursor: pointer; }
121
- .view-toggle button.active { color: var(--primary); background: rgba(0, 122, 255, 0.15); }
122
- #selection-bar {
123
- position: fixed; bottom: -120px; left: 10px; right: 10px;
124
- background: rgba(28, 28, 30, 0.8); backdrop-filter: blur(15px);
125
- padding: 10px; border-radius: 16px; box-shadow: var(--shadow); z-index: 1000;
126
- display: flex; justify-content: space-around; align-items: center;
127
- transition: bottom 0.4s cubic-bezier(0.2, 0.8, 0.2, 1);
128
- }
129
  #selection-bar.visible { bottom: 10px; }
130
  #selection-bar .btn { margin: 0 5px; padding: 10px 15px; font-size: 0.9em; flex-grow: 1; }
131
- #selection-count { color: var(--text-secondary-dark); margin: 0 10px; }
132
- #move-modal .modal-content { padding: 20px; background: var(--card-bg-dark); border-radius: 14px; }
133
- .user-info { color: var(--text-secondary-dark); margin-bottom: 20px; }
134
- @media (max-width: 480px) {
135
- h1 { font-size: 1.8em; }
136
- .file-grid { grid-template-columns: repeat(2, 1fr); gap: 12px; }
137
- .item-preview { height: 80px; }
138
- .item.folder .item-preview { font-size: 40px; }
139
- #selection-bar { flex-wrap: wrap; gap: 8px; }
140
- #selection-bar .btn { flex-basis: 45%; }
141
- }
142
  '''
143
 
144
  def find_node_by_id(filesystem, node_id):
145
  if not filesystem: return None, None
146
- if filesystem.get('id') == node_id: return filesystem, None
 
147
  queue = [(filesystem, None)]
148
  while queue:
149
  current_node, parent = queue.pop(0)
150
  if current_node.get('type') == 'folder' and 'children' in current_node:
151
- for child in current_node['children']:
152
- if child.get('id') == node_id: return child, current_node
153
- if child.get('type') == 'folder': queue.append((child, current_node))
 
 
154
  return None, None
155
 
156
  def add_node(filesystem, parent_id, node_data):
157
  parent_node, _ = find_node_by_id(filesystem, parent_id)
158
  if parent_node and parent_node.get('type') == 'folder':
159
- if 'children' not in parent_node: parent_node['children'] = []
 
160
  parent_node['children'].append(node_data)
161
  return True
162
  return False
@@ -174,21 +130,26 @@ def get_node_path_string(filesystem, node_id):
174
  while current_id:
175
  node, parent = find_node_by_id(filesystem, current_id)
176
  if not node: break
177
- if node.get('id') != 'root': path_list.append(node.get('name', node.get('original_filename', '')))
 
178
  if not parent: break
179
  current_id = parent.get('id') if parent else None
180
  return " / ".join(reversed(path_list)) or "Root"
181
 
182
  def get_all_folders(filesystem, exclude_ids=None):
183
- if exclude_ids is None: exclude_ids = set()
 
184
  folders = []
 
185
  def traverse(node, path_prefix):
186
  if node.get('type') == 'folder':
187
  if node.get('id') not in exclude_ids:
188
  folder_name = f"{path_prefix}{node.get('name', 'Unnamed')}" if path_prefix else (node.get('name') if node.get('id') != 'root' else 'Главная (Root)')
189
  folders.append({'id': node.get('id'), 'name': folder_name})
190
  new_prefix = f"{path_prefix}{node.get('name', '')}/" if node.get('id') != 'root' else ""
191
- for child in node.get('children', []): traverse(child, new_prefix)
 
 
192
  traverse(filesystem, "")
193
  return sorted(folders, key=lambda x: x['name'].lower())
194
 
@@ -228,7 +189,8 @@ def load_data():
228
 
229
  def save_data(data):
230
  try:
231
- with open(DATA_FILE, 'w', encoding='utf-8') as file: json.dump(data, file, ensure_ascii=False, indent=4)
 
232
  upload_db_to_hf()
233
  cache.clear()
234
  except Exception as e:
@@ -239,11 +201,9 @@ def upload_db_to_hf():
239
  if not HF_TOKEN_WRITE: return
240
  try:
241
  api = HfApi()
242
- api.upload_file(
243
- path_or_fileobj=DATA_FILE, path_in_repo=DATA_FILE, repo_id=REPO_ID, repo_type="dataset",
244
- token=HF_TOKEN_WRITE, commit_message=f"Backup {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}"
245
- )
246
- except Exception as e: logging.error(f"Error uploading database: {e}")
247
 
248
  def download_db_from_hf():
249
  if not HF_TOKEN_READ:
@@ -270,30 +230,53 @@ def get_file_type(filename):
270
  if filename_lower.endswith(('.mp4', '.mov', '.avi', '.webm', '.mkv')): return 'video'
271
  elif filename_lower.endswith(('.jpg', '.jpeg', '.png', '.gif', '.bmp', '.webp', '.svg')): return 'image'
272
  elif filename_lower.endswith('.pdf'): return 'pdf'
273
- elif filename_lower.endswith(('.txt', '.py', '.js', '.html', '.css', '.md')): return 'text'
274
  return 'other'
275
 
276
  def is_admin_tma():
277
- if not ADMIN_TELEGRAM_ID or ADMIN_TELEGRAM_ID == "YOUR_ADMIN_TELEGRAM_USER_ID_HERE": return False
 
278
  return 'telegram_user_id' in session and str(session['telegram_user_id']) == str(ADMIN_TELEGRAM_ID)
279
 
280
  def admin_browser_login_required(f):
281
  @wraps(f)
282
  def decorated_function(*args, **kwargs):
283
- if not session.get('admin_browser_logged_in'): return redirect(url_for('admin_login', next=request.url))
 
284
  return f(*args, **kwargs)
285
  return decorated_function
286
 
287
- TMA_ENTRY_HTML = '''<!DOCTYPE html><html lang="ru"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Zeus Cloud</title><script src="https://telegram.org/js/telegram-web-app.js"></script><style>body{font-family:-apple-system,BlinkMacSystemFont,sans-serif;display:flex;justify-content:center;align-items:center;height:100vh;margin:0;background-color:#000;color:#fff;}.loading{font-size:1.2em;}</style></head><body><div class="loading">Подключение...</div><script>
288
- window.Telegram.WebApp.ready(); window.Telegram.WebApp.expand(); const initDataUnsafe=window.Telegram.WebApp.initDataUnsafe;
289
- if(initDataUnsafe && initDataUnsafe.user){fetch("{{url_for('auth_via_telegram')}}",{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({user:initDataUnsafe.user,initData:window.Telegram.WebApp.initData})}).then(res=>res.json()).then(data=>{if(data.status==='success'){window.location.href=data.redirect_url}else{document.body.innerHTML=`<div class="loading">Ошибка: ${data.message}</div>`;Telegram.WebApp.showAlert(data.message||"Ошибка авторизации")}}).catch(err=>{document.body.innerHTML=`<div class="loading">Сетевая ошибка: ${err}</div>`;Telegram.WebApp.showAlert("Сетевая ошибка при авторизации.")})}else{document.body.innerHTML='<div class="loading">Не удалось получить данные Telegram.</div>';Telegram.WebApp.showAlert("Не удалось получить данные пользователя Telegram.")}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
290
  </script></body></html>'''
291
 
292
  @app.route('/tma')
293
- def tma_entry_page(): return render_template_string(TMA_ENTRY_HTML)
 
294
 
295
  @app.route('/')
296
- def root_redirect(): return redirect(url_for('tma_entry_page'))
 
297
 
298
  @app.route('/auth_via_telegram', methods=['POST'])
299
  def auth_via_telegram():
@@ -301,7 +284,7 @@ def auth_via_telegram():
301
  payload = request.json
302
  tg_user_data = payload.get('user')
303
  if not tg_user_data or not tg_user_data.get('id'):
304
- return jsonify({'status': 'error', 'message': 'Отсутствуют данные пользователя.'}), 400
305
  tma_user_id_str = str(tg_user_data['id'])
306
  data = load_data()
307
  if tma_user_id_str not in data['users']:
@@ -315,248 +298,318 @@ def auth_via_telegram():
315
  try: save_data(data)
316
  except Exception as e:
317
  logging.error(f"Save data error for new TMA user {tma_user_id_str}: {e}")
318
- return jsonify({'status': 'error', 'message': 'Ошибка сохранения данных.'}), 500
319
  session['telegram_user_id'] = tma_user_id_str
320
- session['telegram_display_name'] = tg_user_data.get('first_name') or tg_user_data.get('username') or f"User {tma_user_id_str}"
 
321
  return jsonify({'status': 'success', 'redirect_url': url_for('tma_dashboard')})
322
  except Exception as e:
323
  logging.error(f"Error in auth_via_telegram: {e}")
324
- return jsonify({'status': 'error', 'message': 'Внутренняя ошибка сервера.'}), 500
325
 
326
  TMA_DASHBOARD_HTML_TEMPLATE = '''
327
- <!DOCTYPE html><html lang="ru"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover"><title>Zeus Cloud</title><link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.2/css/all.min.css"><script src="https://telegram.org/js/telegram-web-app.js"></script><style>''' + BASE_STYLE + '''</style></head><body><div class="container" id="main-container">
328
- <h1>{{ current_folder.name if current_folder_id != 'root' else 'Главная' }}</h1><p class="user-info">Пользователь: {{ display_name }}</p>
329
- {% with messages = get_flashed_messages(with_categories=true) %}{% if messages %}{% for category, message in messages %}<div class="flash {{ category }}">{{ message }}</div>{% endfor %}{% endif %}{% endwith %}
330
- <div class="navigation-controls">
331
- {% if parent_folder_id %}<a href="{{ url_for('tma_dashboard', folder_id=parent_folder_id) }}" class="back-btn" title="Назад"><i class="fa-solid fa-arrow-left"></i></a>{% endif %}
332
- <div class="breadcrumbs">{% for crumb in breadcrumbs %}{% if crumb.is_link %}<a href="{{ url_for('tma_dashboard', folder_id=crumb.id) }}">{{ crumb.name if crumb.id != 'root' else 'Главная' }}</a>{% else %}<span>{{ crumb.name if crumb.id != 'root' else 'Главная' }}</span>{% endif %}{% if not loop.last %} / {% endif %}{% endfor %}</div>
 
 
 
 
 
 
 
333
  </div>
334
- <div class="top-actions">
335
- <form method="POST" action="{{ url_for('create_folder_tma') }}" style="display: contents; flex-grow: 1;">
336
- <input type="hidden" name="parent_folder_id" value="{{ current_folder_id }}"><input type="text" name="folder_name" placeholder="Имя новой папки" required><button type="submit" class="btn folder-btn"><i class="fa-solid fa-folder-plus"></i></button>
337
- </form>
338
- <div class="view-toggle" style="margin-left: auto;"><button id="grid-view-btn" title="Сетка"><i class="fa fa-th-large"></i></button><button id="list-view-btn" title="Список"><i class="fa fa-bars"></i></button></div>
 
 
 
 
 
339
  </div>
340
- <form id="upload-form" method="POST" enctype="multipart/form-data" action="{{ url_for('tma_dashboard') }}"><input type="hidden" name="current_folder_id" value="{{ current_folder_id }}"><input type="file" name="files" id="file-input" multiple required><button type="submit" class="btn" id="upload-btn"><i class="fa-solid fa-upload"></i> Загрузить сюда</button></form>
341
  <div id="progress-container"><div id="progress-bar"></div></div>
342
  <div class="file-grid" id="file-container">
343
  {% for item in items %}
344
  <div class="item {{ item.type }}" data-id="{{ item.id }}" data-type="{{ item.type }}">
 
345
  {% if item.type == 'folder' %}
346
- <a href="{{ url_for('tma_dashboard', folder_id=item.id) }}" class="item-preview"><i class="fa-solid fa-folder"></i></a>
347
- <div class="item-name-info"><p class="item-name">{{ item.name }}</p></div>
348
- <div class="item-actions"><a href="{{ url_for('tma_dashboard', folder_id=item.id) }}" class="btn folder-btn">Открыть</a></div>
349
  {% elif item.type == 'file' %}
350
- {% set previewable = item.file_type in ['image', 'video', 'pdf', 'text'] %}
351
- <div class="item-preview" {% if previewable %}onclick="openModal('{{ hf_file_url_jinja(item.path) if item.file_type not in ['text', 'pdf'] else (url_for('get_text_content_tma', file_id=item.id) if item.file_type == 'text' else hf_file_url_jinja(item.path, True)) }}', '{{ item.file_type }}')"{% endif %}>
352
- {% if item.file_type == 'image' %}<img src="{{ hf_file_url_jinja(item.path) }}" loading="lazy">
353
- {% elif item.file_type == 'video' %}<i class="fa-solid fa-film" style="font-size: 2em;"></i>
354
- {% elif item.file_type == 'pdf' %}<i class="fa-solid fa-file-pdf" style="font-size: 2em; color:var(--accent);"></i>
355
- {% elif item.file_type == 'text' %}<i class="fa-solid fa-file-lines" style="font-size: 2em; color:var(--secondary);"></i>
356
- {% else %}<i class="fa-solid fa-file" style="font-size: 2em; color: var(--text-secondary-dark);"></i>{% endif %}
357
- </div>
358
- <div class="item-name-info"><p class="item-name" title="{{ item.original_filename }}">{{ item.original_filename | truncate(25, True) }}</p><p class="item-info">{{ item.upload_date.split(' ')[0] }}</p></div>
359
- <div class="item-actions"><button type="button" class="btn download-btn" onclick="tmaDownloadFile('{{ url_for('download_tma', file_id=item.id, _external=True) }}')">Скачать</button></div>
360
  {% endif %}
 
 
 
 
 
361
  </div>
362
  {% endfor %}
363
- {% if not items %} <p style="color: var(--text-secondary-dark); margin-top: 20px;">Папка пуста.</p> {% endif %}
364
  </div>
365
- <div style="text-align: center; margin-top: 30px;">
366
- <a href="{{ url_for('tma_logout') }}" class="btn" style="background: #3A3A3C;" id="logout-btn">Выйти</a>
367
- {% if is_tma_user_admin_flag %}<a href="{{ url_for('admin_panel') }}" class="btn" style="background-color: var(--accent);">Админ</a>{% endif %}
368
- </div></div>
369
- <div class="modal" id="mediaModal" onclick="closeModal(event)"><span onclick="closeModalManual()" class="modal-close-btn">&times;</span><div class="modal-content" id="modalContent"></div></div>
370
- <div id="selection-bar"><span id="selection-count">Выбрано: 0</span>
371
- <button class="btn download-btn" id="selection-download-btn"><i class="fa-solid fa-download"></i> Скачать</button>
372
- <button class="btn" onclick="showMoveModal()"><i class="fa-solid fa-arrow-right-to-bracket"></i> Переместить</button>
373
- <button class="btn delete-btn" onclick="deleteSelected()"><i class="fa-solid fa-trash-can"></i> Удалить</button>
374
- <button class="btn" onclick="toggleSelectionMode(false)" style="background: #505054;">Отмена</button>
375
  </div>
376
- <div class="modal" id="move-modal"><div class="modal-content"><h4>Переместить в:</h4><select id="folder-destination-select">{% for folder in all_folders_for_move %}<option value="{{ folder.id }}">{{ folder.name }}</option>{% endfor %}</select><button class="btn" onclick="moveSelected()">Переместить</button><button class="btn" onclick="closeMoveModal()" style="background: #505054;">Отмена</button></div></div>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
377
  <script>
378
  window.Telegram.WebApp.ready();
379
  window.Telegram.WebApp.expand();
380
-
381
  async function openModal(srcOrUrl, type) {
382
- const modal = document.getElementById('mediaModal'), modalContent = document.getElementById('modalContent');
 
383
  modalContent.innerHTML = '<p>Загрузка...</p>'; modal.style.display = 'flex';
384
  try {
385
  if (type === 'image') modalContent.innerHTML = `<img src="${srcOrUrl}">`;
386
- else if (type === 'video') modalContent.innerHTML = `<video controls autoplay src="${srcOrUrl}"></video>`;
387
  else if (type === 'pdf') modalContent.innerHTML = `<iframe src="${srcOrUrl}"></iframe>`;
388
  else if (type === 'text') {
389
- const res = await fetch(srcOrUrl); if (!res.ok) throw new Error(`${res.statusText}`);
390
- const text = await res.text();
391
- modalContent.innerHTML = `<pre>${text.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;")}</pre>`;
392
- } else modalContent.innerHTML = '<p>Предпросмотр недоступен.</p>';
393
- } catch (error) { modalContent.innerHTML = `<p>Ошибка загрузки: ${error.message}</p>`; }
394
  }
395
- function closeModal(event) { if (event.target === document.getElementById('mediaModal')) closeModalManual(); }
396
  function closeModalManual() {
397
  const modal = document.getElementById('mediaModal'); modal.style.display = 'none';
398
- const media = modal.querySelector('video, iframe'); if (media) media.src = 'about:blank';
399
  document.getElementById('modalContent').innerHTML = '';
400
  }
401
- function tmaDownloadFile(url) {
402
- if (window.Telegram && Telegram.WebApp.openLink) Telegram.WebApp.openLink(url); else window.open(url, '_blank');
 
403
  }
404
- const form = document.getElementById('upload-form');
405
- if(form) form.addEventListener('submit', function(e) {
406
- e.preventDefault(); if (form.files.files.length === 0) return;
407
- const progressBar = document.getElementById('progress-bar'), progressContainer = document.getElementById('progress-container'), uploadBtn = document.getElementById('upload-btn');
408
- progressContainer.style.display = 'block'; uploadBtn.disabled = true; uploadBtn.innerHTML = 'Загрузка...';
409
- const formData = new FormData(form), xhr = new XMLHttpRequest();
410
- xhr.upload.addEventListener('progress', e => { if (e.lengthComputable) progressBar.style.width = (e.loaded / e.total * 100) + '%'; });
411
- xhr.onload = () => window.location.reload();
412
- xhr.onerror = () => { Telegram.WebApp.showAlert('Ошибка загрузки.'); uploadBtn.disabled = false; uploadBtn.innerHTML = '<i class="fa-solid fa-upload"></i> Загрузить сюда';};
413
- xhr.open('POST', form.action, true); xhr.send(formData);
 
 
 
 
 
414
  });
415
 
416
  let selectionMode = false; const selectedItems = new Set(); let longPressTimer;
417
- const mainContainer = document.getElementById('main-container'), selectionBar = document.getElementById('selection-bar');
418
- const selectionCount = document.getElementById('selection-count'), allItems = document.querySelectorAll('.item');
419
- const downloadBtn = document.getElementById('selection-download-btn');
 
420
 
421
  function toggleSelectionMode(enable) {
422
- selectionMode = enable; mainContainer.classList.toggle('selection-mode', enable);
423
  selectionBar.classList.toggle('visible', enable);
424
- if (!enable) { selectedItems.clear(); allItems.forEach(i => i.classList.remove('selected')); }
425
- updateSelectionState();
426
- }
427
- function updateSelectionState() {
428
- selectionCount.textContent = `Выбрано: ${selectedItems.size}`;
429
- const hasFiles = Array.from(selectedItems).some(id => document.querySelector(`.item[data-id='${id}']`).dataset.type === 'file');
430
- downloadBtn.style.display = hasFiles ? 'inline-flex' : 'none';
431
  }
 
 
432
  allItems.forEach(item => {
433
- let pressTimer;
434
- item.addEventListener('pointerdown', () => pressTimer = setTimeout(() => {
435
- if (!selectionMode) toggleSelectionMode(true);
436
- item.classList.toggle('selected');
437
- if (item.classList.contains('selected')) selectedItems.add(item.dataset.id); else selectedItems.delete(item.dataset.id);
438
- updateSelectionState();
439
- }, 500));
440
- item.addEventListener('pointerup', () => clearTimeout(pressTimer));
 
 
 
441
  item.addEventListener('click', e => {
442
  if (selectionMode) {
443
- e.preventDefault(); item.classList.toggle('selected');
444
- if (item.classList.contains('selected')) selectedItems.add(item.dataset.id); else selectedItems.delete(item.dataset.id);
 
 
445
  if (selectedItems.size === 0) toggleSelectionMode(false);
446
- updateSelectionState();
447
  }
448
  }, true);
449
  });
450
 
451
- function showMoveModal() { if (selectedItems.size > 0) document.getElementById('move-modal').style.display = 'flex'; }
452
- function closeMoveModal() { document.getElementById('move-modal').style.display = 'none'; }
453
- async function performBatchAction(url, body, successMsg) {
454
  try {
455
- const res = await fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) });
456
- const result = await res.json();
457
- if (result.status === 'success') { window.location.reload(); }
458
- else { Telegram.WebApp.showAlert(result.message || 'Произошла ошибка.'); }
 
 
459
  } catch (error) { Telegram.WebApp.showAlert('Сетевая ошибка.'); }
460
  finally { toggleSelectionMode(false); }
461
  }
462
- function moveSelected() { performBatchAction('{{ url_for("batch_move_tma") }}', { item_ids: Array.from(selectedItems), destination_id: document.getElementById('folder-destination-select').value }); }
463
- function deleteSelected() { if (selectedItems.size > 0) Telegram.WebApp.showConfirm(`Удалить ${selectedItems.size} элемент(ов)?`, ok => { if (ok) performBatchAction('{{ url_for("batch_delete_tma") }}', { item_ids: Array.from(selectedItems) }); }); }
464
-
465
- downloadBtn.addEventListener('click', async () => {
466
- const fileIds = Array.from(selectedItems).filter(id => document.querySelector(`.item[data-id='${id}']`).dataset.type === 'file');
467
- if (fileIds.length === 0) return Telegram.WebApp.showAlert('Папки нельзя скачать. Выберите файлы.');
468
- downloadBtn.disabled = true; downloadBtn.innerHTML = 'Архивация...';
469
- try {
470
- const res = await fetch('{{ url_for("batch_download_tma") }}', { method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify({ item_ids: fileIds }) });
471
- if (!res.ok) throw new Error(`Server error: ${res.statusText}`);
472
- const blob = await res.blob();
473
- const link = document.createElement('a');
474
- link.href = URL.createObjectURL(blob);
475
- link.download = 'Zeus_Cloud_Archive.zip';
476
- document.body.appendChild(link);
477
- link.click();
478
- document.body.removeChild(link);
479
- URL.revokeObjectURL(link.href);
480
- } catch(e) { Telegram.WebApp.showAlert(`Ошибка скачивания: ${e.message}`); }
481
- finally { downloadBtn.disabled = false; downloadBtn.innerHTML = '<i class="fa-solid fa-download"></i> Скачать'; toggleSelectionMode(false); }
482
- });
 
 
483
 
 
 
 
484
  function setView(view) {
485
- const fileContainer = document.getElementById('file-container');
486
- document.getElementById('grid-view-btn').classList.toggle('active', view === 'grid');
487
- document.getElementById('list-view-btn').classList.toggle('active', view === 'list');
488
  fileContainer.classList.toggle('list-view', view === 'list');
 
 
489
  localStorage.setItem('viewMode', view);
490
  }
 
 
491
  document.addEventListener('DOMContentLoaded', () => setView(localStorage.getItem('viewMode') || 'grid'));
492
- document.getElementById('grid-view-btn').addEventListener('click', () => setView('grid'));
493
- document.getElementById('list-view-btn').addEventListener('click', () => setView('list'));
494
- </script></body></html>'''
 
 
 
 
 
495
 
496
  @app.route('/tma_dashboard', methods=['GET', 'POST'])
497
  def tma_dashboard():
498
- if 'telegram_user_id' not in session: return redirect(url_for('tma_entry_page'))
499
- tma_user_id, display_name = session['telegram_user_id'], session.get('telegram_display_name', 'User')
 
 
 
500
  data = load_data()
501
  if tma_user_id not in data['users']:
502
  session.clear()
 
503
  return redirect(url_for('tma_entry_page'))
504
  user_data = data['users'][tma_user_id]
505
  initialize_user_filesystem_tma(user_data, tma_user_id)
506
  current_folder_id = request.args.get('folder_id', 'root')
507
  current_folder, parent_folder = find_node_by_id(user_data['filesystem'], current_folder_id)
508
  if not current_folder or current_folder.get('type') != 'folder':
 
509
  current_folder_id = 'root'
510
- current_folder, parent_folder = find_node_by_id(user_data['filesystem'], current_folder_id)
 
511
  if request.method == 'POST':
512
  if not HF_TOKEN_WRITE:
513
- flash('Загрузка невозможна.', 'error')
514
  return redirect(url_for('tma_dashboard', folder_id=current_folder_id))
515
  files = request.files.getlist('files')
516
  if not files or all(not f.filename for f in files):
517
- flash('Файлы не выбраны.', 'error')
518
  return redirect(url_for('tma_dashboard', folder_id=current_folder_id))
519
  target_folder_id = request.form.get('current_folder_id', 'root')
 
 
520
  api = HfApi()
521
  for file_obj in files:
522
  if file_obj and file_obj.filename:
523
  original_filename = secure_filename(file_obj.filename)
524
  name_part, ext_part = os.path.splitext(original_filename)
525
- unique_filename = f"{name_part}_{uuid.uuid4().hex[:8]}{ext_part}"
 
526
  file_id = uuid.uuid4().hex
527
  hf_path = f"cloud_files/{tma_user_id}/{target_folder_id}/{unique_filename}"
528
  temp_path = os.path.join(UPLOAD_FOLDER, f"{file_id}_{unique_filename}")
529
  try:
530
  file_obj.save(temp_path)
531
  api.upload_file(path_or_fileobj=temp_path, path_in_repo=hf_path, repo_id=REPO_ID, repo_type="dataset", token=HF_TOKEN_WRITE)
532
- file_info = {
533
- 'type': 'file', 'id': file_id, 'original_filename': original_filename,
534
- 'unique_filename': unique_filename, 'path': hf_path,
535
- 'file_type': get_file_type(original_filename),
536
- 'upload_date': datetime.now().strftime('%Y-%m-%d %H:%M:%S')
537
- }
538
- add_node(user_data['filesystem'], target_folder_id, file_info)
539
- except Exception as e: logging.error(f"Upload error for {original_filename}: {e}")
540
  finally:
541
  if os.path.exists(temp_path): os.remove(temp_path)
542
- save_data(data)
 
 
 
 
543
  return redirect(url_for('tma_dashboard', folder_id=target_folder_id))
544
- parent_folder_id = parent_folder.get('id') if parent_folder else None
545
- items_in_folder = sorted(current_folder.get('children', []), key=lambda x: (x['type'] != 'folder', x.get('name', x.get('original_filename', '')).lower()))
546
  breadcrumbs = []
547
  temp_id = current_folder_id
548
  while temp_id:
549
  node, parent_node_bc = find_node_by_id(user_data['filesystem'], temp_id)
550
  if not node: break
551
- breadcrumbs.append({'id': node['id'], 'name': node.get('name', 'Root'), 'is_link': (node['id'] != current_folder_id)})
552
- temp_id = parent_node_bc.get('id') if parent_node_bc else None
 
 
553
  breadcrumbs.reverse()
 
554
  all_folders_for_move = get_all_folders(user_data['filesystem'])
555
- return render_template_string(TMA_DASHBOARD_HTML_TEMPLATE,
556
- display_name=display_name, items=items_in_folder, current_folder_id=current_folder_id,
557
- current_folder=current_folder, parent_folder_id=parent_folder_id, breadcrumbs=breadcrumbs,
558
- hf_file_url_jinja=lambda path, download=False: f"https://huggingface.co/datasets/{REPO_ID}/resolve/main/{path}{'?download=true' if download else ''}",
559
- is_tma_user_admin_flag=is_admin_tma(), all_folders_for_move=all_folders_for_move)
560
 
561
  @app.route('/create_folder_tma', methods=['POST'])
562
  def create_folder_tma():
@@ -565,74 +618,96 @@ def create_folder_tma():
565
  data = load_data()
566
  user_data = data['users'].get(tma_user_id)
567
  if not user_data: return redirect(url_for('tma_entry_page'))
 
568
  parent_folder_id = request.form.get('parent_folder_id', 'root')
569
  folder_name = request.form.get('folder_name', '').strip()
570
  if not folder_name:
571
  flash('Имя папки не может быть пустым!', 'error')
572
- return redirect(url_for('tma_dashboard', folder_id=parent_folder_id))
573
- folder_data = {'type': 'folder', 'id': uuid.uuid4().hex, 'name': folder_name, 'children': []}
574
- if add_node(user_data['filesystem'], parent_folder_id, folder_data):
575
- save_data(data)
 
 
 
576
  return redirect(url_for('tma_dashboard', folder_id=parent_folder_id))
577
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
578
  @app.route('/download_tma/<file_id>')
579
  def download_tma(file_id):
580
- current_tma_user_id = session.get('telegram_user_id')
581
- is_browser_admin_session = session.get('admin_browser_logged_in', False)
582
- data, file_node = load_data(), None
583
- if is_browser_admin_session:
584
- for udata_iter in data.get('users', {}).values():
585
- node, _ = find_node_by_id(udata_iter.get('filesystem', {}), file_id)
586
- if node and node.get('type') == 'file': file_node = node; break
587
- elif current_tma_user_id:
588
- user_data = data['users'].get(current_tma_user_id)
589
- if user_data: file_node, _ = find_node_by_id(user_data['filesystem'], file_id)
590
- if not file_node and is_admin_tma():
591
- for udata_iter in data.get('users', {}).values():
592
- node, _ = find_node_by_id(udata_iter.get('filesystem', {}), file_id)
593
- if node and node.get('type') == 'file': file_node = node; break
594
- if not file_node: return Response("File Not Found or Access Denied", status=404)
595
  hf_path = file_node.get('path')
596
  original_filename = file_node.get('original_filename', 'downloaded_file')
597
- if not hf_path: return Response("File path missing in database", status=500)
 
 
 
598
  file_url = f"https://huggingface.co/datasets/{REPO_ID}/resolve/main/{hf_path}?download=true"
599
  try:
600
- headers = {"authorization": f"Bearer {HF_TOKEN_READ}"} if HF_TOKEN_READ else {}
601
- r = requests.get(file_url, headers=headers, stream=True)
 
602
  r.raise_for_status()
603
- resp = Response(stream_with_context(r.iter_content(chunk_size=8192)), content_type=r.headers.get('content-type', 'application/octet-stream'))
 
604
  encoded_filename = quote(original_filename)
605
- resp.headers['Content-Disposition'] = f"attachment; filename=\"{original_filename}\"; filename*=UTF-8''{encoded_filename}"
606
  return resp
607
  except Exception as e:
608
- logging.error(f"Download error for {file_id}: {e}")
609
- return Response(f"Error downloading file: {e}", status=502)
 
610
 
611
- @app.route('/batch_download_tma', methods=['POST'])
612
  def batch_download_tma():
613
- if 'telegram_user_id' not in session: return jsonify({'status': 'error', 'message': 'Unauthorized'}), 401
614
- tma_user_id, data = session['telegram_user_id'], load_data()
615
- user_data = data['users'].get(tma_user_id)
616
- if not user_data: return jsonify({'status': 'error', 'message': 'User not found'}), 404
617
- item_ids = request.json.get('item_ids', [])
618
- if not item_ids: return jsonify({'status': 'error', 'message': 'No files selected'}), 400
619
 
620
- memory_file = io.BytesIO()
621
- headers = {"authorization": f"Bearer {HF_TOKEN_READ}"} if HF_TOKEN_READ else {}
622
 
623
- with zipfile.ZipFile(memory_file, 'w', zipfile.ZIP_DEFLATED) as zf:
624
- for item_id in item_ids:
625
- node, _ = find_node_by_id(user_data['filesystem'], item_id)
626
- if node and node.get('type') == 'file' and node.get('path'):
627
- try:
628
- r = requests.get(f"https://huggingface.co/datasets/{REPO_ID}/resolve/main/{node['path']}?download=true", headers=headers)
629
- r.raise_for_status()
630
- zf.writestr(node.get('original_filename', item_id), r.content)
631
- except Exception as e:
632
- logging.error(f"Failed to fetch {node['path']} for zipping: {e}")
633
-
634
- memory_file.seek(0)
635
- return send_file(memory_file, download_name='Zeus_Cloud_Archive.zip', as_attachment=True, mimetype='application/zip')
 
 
 
 
 
 
 
 
 
 
 
636
 
637
  @app.route('/delete_file_tma/<file_id>', methods=['POST'])
638
  def delete_file_tma(file_id):
@@ -643,114 +718,147 @@ def delete_file_tma(file_id):
643
  if not user_data: return redirect(url_for('tma_entry_page'))
644
  file_node, _ = find_node_by_id(user_data['filesystem'], file_id)
645
  current_view_folder_id = request.form.get('current_view_folder_id', 'root')
646
- if file_node and file_node.get('type') == 'file':
 
 
647
  hf_path = file_node.get('path')
648
- if hf_path and HF_TOKEN_WRITE:
 
 
649
  try:
650
  api = HfApi()
651
- api.delete_file(path_in_repo=hf_path, repo_id=REPO_ID, repo_type="dataset", token=HF_TOKEN_WRITE)
 
 
 
 
652
  except hf_utils.EntryNotFoundError:
653
- logging.warning(f"File not found on HF for deletion: {hf_path}")
 
 
 
654
  except Exception as e:
655
- flash(f"Ошибка удаления файла с сервера: {e}", 'error')
656
- return redirect(url_for('tma_dashboard', folder_id=current_view_folder_id))
657
- removed, _ = remove_node(user_data['filesystem'], file_id)
658
- if removed: save_data(data)
659
  return redirect(url_for('tma_dashboard', folder_id=current_view_folder_id))
660
 
661
  @app.route('/delete_folder_tma/<folder_id>', methods=['POST'])
662
  def delete_folder_tma(folder_id):
663
- if 'telegram_user_id' not in session or folder_id == 'root': return redirect(url_for('tma_entry_page'))
664
- tma_user_id, data = session['telegram_user_id'], load_data()
 
 
 
665
  user_data = data['users'].get(tma_user_id)
666
  if not user_data: return redirect(url_for('tma_entry_page'))
 
667
  folder_node, parent_node = find_node_by_id(user_data['filesystem'], folder_id)
668
- current_view_folder_id = request.form.get('current_view_folder_id', 'root')
669
  if not folder_node or folder_node.get('type') != 'folder' or not parent_node:
670
- return redirect(url_for('tma_dashboard', folder_id=current_view_folder_id))
671
- if folder_node.get('children'):
672
  flash('Папку можно удалить только если она пуста.', 'error')
673
- return redirect(url_for('tma_dashboard', folder_id=current_view_folder_id))
674
- removed, _ = remove_node(user_data['filesystem'], folder_id)
675
- if removed: save_data(data)
 
 
 
676
  return redirect(url_for('tma_dashboard', folder_id=parent_node.get('id', 'root')))
677
 
678
- def process_batch_delete(user_data, item_ids):
679
- api, success_count, errors = HfApi(), 0, []
 
 
 
 
 
 
 
 
 
 
680
  for item_id in item_ids:
681
  node, _ = find_node_by_id(user_data['filesystem'], item_id)
682
- if not node: continue
 
 
683
  if node.get('type') == 'folder':
684
- if node.get('children'): errors.append(f'Папка "{node.get("name")}" не пуста.')
685
- else: success_count += 1 if remove_node(user_data['filesystem'], item_id)[0] else 0
 
686
  elif node.get('type') == 'file':
687
  try:
688
  if node.get('path') and HF_TOKEN_WRITE: api.delete_file(path_in_repo=node['path'], repo_id=REPO_ID, repo_type="dataset", token=HF_TOKEN_WRITE)
689
  except hf_utils.EntryNotFoundError: pass
690
- except Exception as e: errors.append(f'Ошибка удаления "{node.get("original_filename")}": {e}'); continue
691
- success_count += 1 if remove_node(user_data['filesystem'], item_id)[0] else 0
692
- return success_count, errors
693
-
694
- @app.route('/batch_delete_tma', methods=['POST'])
695
- def batch_delete_tma():
696
- if 'telegram_user_id' not in session: return jsonify({'status': 'error', 'message': 'Unauthorized'}), 401
697
- tma_user_id, data = session['telegram_user_id'], load_data()
698
- user_data = data['users'].get(tma_user_id)
699
- if not user_data: return jsonify({'status': 'error', 'message': 'User not found'}), 404
700
- item_ids = request.json.get('item_ids', [])
701
- success_count, errors = process_batch_delete(user_data, item_ids)
702
- if success_count > 0: save_data(data)
703
  if errors: return jsonify({'status': 'error', 'message': f'Удалено {success_count}. Ошибки: ' + "; ".join(errors)})
704
- return jsonify({'status': 'success', 'message': f'У��пешно удалено {success_count} элемент(ов).'})
705
 
706
  @app.route('/batch_move_tma', methods=['POST'])
707
  def batch_move_tma():
708
- if 'telegram_user_id' not in session: return jsonify({'status': 'error', 'message': 'Unauthorized'}), 401
709
- tma_user_id, data = session['telegram_user_id'], load_data()
 
710
  user_data = data['users'].get(tma_user_id)
711
- if not user_data: return jsonify({'status': 'error', 'message': 'User not found'}), 404
712
- item_ids, destination_id = request.json.get('item_ids', []), request.json.get('destination_id')
 
 
713
  destination_node, _ = find_node_by_id(user_data['filesystem'], destination_id)
714
- if not destination_node or destination_node.get('type') != 'folder':
715
- return jsonify({'status': 'error', 'message': 'Папка назначения не найдена.'}), 404
716
- moved_count = 0
 
 
 
 
 
 
 
 
 
 
 
717
  for item_id in item_ids:
718
  if item_id == destination_id: continue
719
  removed, node_to_move = remove_node(user_data['filesystem'], item_id)
720
  if removed and node_to_move:
721
  if add_node(user_data['filesystem'], destination_id, node_to_move): moved_count += 1
722
- if moved_count > 0: save_data(data)
723
- return jsonify({'status': 'success', 'message': f'Успешно перемещено {moved_count} элемент(ов).'})
 
 
 
 
 
 
724
 
725
  @app.route('/get_text_content_tma/<file_id>')
726
  def get_text_content_tma(file_id):
727
- current_tma_user_id = session.get('telegram_user_id')
728
- is_browser_admin_session = session.get('admin_browser_logged_in', False)
729
- data, file_node = load_data(), None
730
- if is_browser_admin_session:
731
- for udata_iter in data.get('users', {}).values():
732
- node, _ = find_node_by_id(udata_iter.get('filesystem', {}), file_id)
733
- if node and node.get('file_type') == 'text': file_node = node; break
734
- elif current_tma_user_id:
735
- user_data = data['users'].get(current_tma_user_id)
736
- if user_data: file_node, _ = find_node_by_id(user_data['filesystem'], file_id)
737
- if not file_node and is_admin_tma():
738
- for udata_iter in data.get('users', {}).values():
739
- node, _ = find_node_by_id(udata_iter.get('filesystem', {}), file_id)
740
- if node and node.get('file_type') == 'text': file_node = node; break
741
- if not file_node or file_node.get('file_type') != 'text': return Response("Text file not found", status=404)
742
  hf_path = file_node.get('path')
743
- if not hf_path: return Response("File path missing", status=500)
 
744
  try:
745
- headers = {"authorization": f"Bearer {HF_TOKEN_READ}"} if HF_TOKEN_READ else {}
746
- response = requests.get(f"https://huggingface.co/datasets/{REPO_ID}/resolve/main/{hf_path}?download=true", headers=headers)
 
747
  response.raise_for_status()
748
- return Response(response.text, mimetype='text/plain')
749
- except Exception as e: return Response(f"Download error: {e}", status=502)
 
 
 
750
 
751
  @app.route('/tma_logout')
752
  def tma_logout():
753
  session.clear()
 
754
  return redirect(url_for('tma_entry_page'))
755
 
756
  @app.route('/admin/login', methods=['GET', 'POST'])
@@ -759,9 +867,8 @@ def admin_login():
759
  if request.form.get('username') == ADMIN_USERNAME and request.form.get('password') == ADMIN_PASSWORD:
760
  session['admin_browser_logged_in'] = True
761
  return redirect(request.form.get('next') or url_for('admin_panel'))
762
- else:
763
- flash('Неверные данные.', 'error')
764
- return render_template_string("Admin Login Page") # Simplified for brevity
765
 
766
  @app.route('/admin/logout')
767
  def admin_logout():
@@ -771,29 +878,29 @@ def admin_logout():
771
  @app.route('/admhosto')
772
  @admin_browser_login_required
773
  def admin_panel():
774
- return render_template_string("Admin Panel") # Simplified for brevity
775
 
776
  @app.route('/admhosto/user/<tma_user_id_str>')
777
  @admin_browser_login_required
778
  def admin_user_files(tma_user_id_str):
779
- return render_template_string("Admin User Files Page") # Simplified for brevity
780
 
781
  @app.route('/admhosto/delete_user/<tma_user_id_str>', methods=['POST'])
782
  @admin_browser_login_required
783
  def admin_delete_user(tma_user_id_str):
784
- return redirect(url_for('admin_panel')) # Simplified for brevity
785
 
786
  @app.route('/admhosto/delete_file/<tma_user_id_str_form>/<file_id>', methods=['POST'])
787
  @admin_browser_login_required
788
  def admin_delete_file(tma_user_id_str_form, file_id):
789
- return redirect(url_for('admin_user_files', tma_user_id_str=tma_user_id_str_form)) # Simplified for brevity
790
 
791
  if __name__ == '__main__':
792
- if not HF_TOKEN_WRITE: logging.warning("HF_TOKEN (write access) is not set. Uploads/deletions/backups will fail.")
793
- if not HF_TOKEN_READ: logging.warning("HF_TOKEN_READ is not set. Using HF_TOKEN for reads.")
794
- if os.getenv("FLASK_SECRET_KEY") == "supersecretkey_folders_unique_tma":
795
- logging.warning("Using default FLASK_SECRET_KEY. Please change this in production.")
796
-
797
  if HF_TOKEN_WRITE:
798
  download_db_from_hf()
799
  threading.Thread(target=periodic_backup, daemon=True).start()
@@ -802,5 +909,4 @@ if __name__ == '__main__':
802
  else:
803
  if not os.path.exists(DATA_FILE):
804
  with open(DATA_FILE, 'w', encoding='utf-8') as f: json.dump({'users': {}}, f)
805
-
806
  app.run(debug=False, host='0.0.0.0', port=7860)
 
1
  import flask
2
+ from flask import Flask, render_template_string, request, redirect, url_for, session, flash, send_file, jsonify, Response
3
  from flask_caching import Cache
4
  import json
5
  import os
 
10
  from huggingface_hub import HfApi, hf_hub_download, utils as hf_utils
11
  from werkzeug.utils import secure_filename
12
  import requests
13
+ from io import BytesIO
14
  import uuid
15
  from functools import wraps
16
  from urllib.parse import quote
 
17
  import zipfile
18
+ import tempfile
19
 
20
  app = Flask(__name__)
21
  app.secret_key = os.getenv("FLASK_SECRET_KEY", "supersecretkey_folders_unique_tma")
 
25
  HF_TOKEN_READ = os.getenv("HF_TOKEN_READ") or HF_TOKEN_WRITE
26
  TELEGRAM_BOT_TOKEN = os.getenv("TELEGRAM_BOT_TOKEN", "6750208873:AAE2hvPlJ99dBdhGa_Brre0IIpUdOvXxHt4")
27
  ADMIN_TELEGRAM_ID = os.getenv("ADMIN_TELEGRAM_ID", "YOUR_ADMIN_TELEGRAM_USER_ID_HERE")
 
28
  ADMIN_USERNAME = os.getenv("ADMIN_USERNAME", "admin")
29
  ADMIN_PASSWORD = os.getenv("ADMIN_PASSWORD", "zeusadminpass")
 
30
  UPLOAD_FOLDER = 'uploads_tma'
31
  os.makedirs(UPLOAD_FOLDER, exist_ok=True)
 
32
  cache = Cache(app, config={'CACHE_TYPE': 'simple'})
33
  logging.basicConfig(level=logging.INFO)
34
 
35
  BASE_STYLE = '''
36
  :root {
37
+ --primary: #ff4d6d; --secondary: #00ddeb; --accent: #8b5cf6;
38
+ --background-dark: #121212; --card-bg-dark: #1e1e1e;
39
+ --text-dark: #e0e0e0; --text-muted: #888; --shadow: 0 10px 30px rgba(0, 0, 0, 0.2);
40
+ --glass-bg: rgba(30, 30, 30, 0.7); --transition: all 0.3s cubic-bezier(0.25, 0.8, 0.25, 1);
41
+ --delete-color: #ff4444; --folder-color: #ffc107; --selection-color: rgba(139, 92, 246, 0.3);
42
  }
43
  * { margin: 0; padding: 0; box-sizing: border-box; }
44
  html { scroll-behavior: smooth; }
45
+ body { font-family: 'Inter', -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif; background: var(--background-dark); color: var(--text-dark); line-height: 1.6; -webkit-tap-highlight-color: transparent; }
46
+ .container { margin: 0 auto; max-width: 1200px; padding: 75px 15px 15px 15px; }
47
+ .app-header { position: fixed; top: 0; left: 0; right: 0; background: var(--glass-bg); backdrop-filter: blur(10px); -webkit-backdrop-filter: blur(10px); border-bottom: 1px solid rgba(255,255,255,0.1); z-index: 1000; padding: 10px 20px; display: flex; justify-content: space-between; align-items: center; }
48
+ .user-info { font-weight: 600; }
49
+ .view-toggle button { background: none; border: none; color: var(--text-muted); font-size: 1.2em; padding: 5px; cursor: pointer; transition: var(--transition); }
50
+ .view-toggle button:hover, .view-toggle button.active { color: var(--primary); }
51
+ h2 { font-size: 1.3em; margin-bottom: 15px; margin-top: 15px; color: var(--text-dark); }
52
+ .breadcrumbs { font-size: 1em; margin-bottom: 20px; white-space: nowrap; overflow-x: auto; -webkit-overflow-scrolling: touch; }
53
+ .breadcrumbs a { color: var(--accent); text-decoration: none; }
54
+ .breadcrumbs span { margin: 0 5px; color: var(--text-muted); }
55
+ input, select { width: 100%; padding: 14px; margin: 8px 0; border: 1px solid #333; border-radius: 12px; background: #2a2a2a; color: var(--text-dark); font-size: 1em; }
56
+ .btn { padding: 12px 24px; background: var(--primary); color: white; border: none; border-radius: 12px; cursor: pointer; font-size: 1em; font-weight: 600; transition: var(--transition); text-decoration: none; display: inline-block; text-align: center; }
57
+ .btn:hover { filter: brightness(1.2); }
58
+ .btn:active { transform: scale(0.98); }
59
+ .download-btn { background: var(--secondary); }
60
+ .delete-btn { background: var(--delete-color); }
61
+ .folder-btn { background: var(--folder-color); }
62
+ .flash { text-align: center; margin-bottom: 15px; padding: 12px; border-radius: 10px; background: rgba(0, 221, 235, 0.1); color: var(--secondary); }
63
+ .flash.error { background: rgba(255, 68, 68, 0.1); color: var(--delete-color); }
64
+ .file-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(150px, 1fr)); gap: 15px; }
65
+ .item { background: var(--card-bg-dark); border-radius: 16px; text-align: center; transition: var(--transition); position: relative; border: 2px solid transparent; user-select: none; padding: 10px; display: flex; flex-direction: column; }
66
+ .item:active { transform: scale(0.97); }
67
+ .item.selected { border-color: var(--accent); background-color: var(--selection-color); }
68
+ .item-preview-wrapper { position: relative; width: 100%; padding-top: 75%; border-radius: 10px; overflow: hidden; margin-bottom: 10px; cursor: pointer; background: #2a2a2a; }
69
+ .item-preview { position: absolute; top: 0; left: 0; width: 100%; height: 100%; object-fit: cover; }
70
+ .item.folder .item-preview { object-fit: contain; font-size: 3.5em; color: var(--folder-color); }
71
+ .item-name { font-size: 0.9em; font-weight: 500; word-break: break-all; margin: 5px 0; flex-grow: 1; }
72
+ .item-info { font-size: 0.75em; color: var(--text-muted); }
73
+ .item-actions { display: none; }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
74
  .file-grid.list-view { display: flex; flex-direction: column; gap: 8px; }
75
+ .file-grid.list-view .item { flex-direction: row; align-items: center; text-align: left; padding: 8px; }
76
+ .file-grid.list-view .item-preview-wrapper { width: 45px; height: 45px; padding-top: 0; margin-bottom: 0; margin-right: 15px; flex-shrink: 0; }
77
+ .file-grid.list-view .item.folder .item-preview { font-size: 1.8em; }
78
+ .file-grid.list-view .item-name-info { flex-grow: 1; }
79
+ .modal { display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0, 0, 0, 0.85); z-index: 2000; justify-content: center; align-items: center; }
80
+ .modal-content { max-width: 95%; max-height: 95%; background: var(--card-bg-dark); padding: 10px; border-radius: 15px; overflow: auto; position: relative; }
81
+ .modal img, .modal video, .modal iframe, .modal pre { max-width: 100%; max-height: 85vh; display: block; margin: auto; border-radius: 10px; }
82
+ .modal iframe { width: 80vw; height: 85vh; border: none; }
83
+ .modal pre { background: #121212; padding: 15px; border-radius: 8px; white-space: pre-wrap; word-wrap: break-word; max-height: 85vh; overflow-y: auto;}
84
+ .modal-close-btn { position: absolute; top: 15px; right: 25px; font-size: 30px; color: #aaa; cursor: pointer; background: rgba(0,0,0,0.5); border-radius: 50%; width: 30px; height: 30px; line-height: 30px; text-align: center; }
85
+ #progress-container { width: 100%; background: #333; border-radius: 10px; margin: 15px 0; display: none; height: 10px; }
86
+ #progress-bar { width: 0%; height: 100%; background: var(--primary); border-radius: 10px; transition: width 0.3s ease; }
87
+ #selection-bar { position: fixed; bottom: -120px; left: 10px; right: 10px; background: var(--glass-bg); backdrop-filter: blur(10px); padding: 10px; border-radius: 15px; box-shadow: var(--shadow); z-index: 1000; display: flex; justify-content: space-around; align-items: center; transition: bottom 0.4s cubic-bezier(0.25, 0.8, 0.25, 1); }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
88
  #selection-bar.visible { bottom: 10px; }
89
  #selection-bar .btn { margin: 0 5px; padding: 10px 15px; font-size: 0.9em; flex-grow: 1; }
90
+ #move-modal .modal-content, #fab-modal .modal-content { padding: 20px; max-width: 400px; }
91
+ .fab-container { position: fixed; bottom: 20px; right: 20px; z-index: 1050; }
92
+ .fab { width: 56px; height: 56px; background: var(--accent); border-radius: 50%; border: none; box-shadow: var(--shadow); color: white; font-size: 24px; display: flex; justify-content: center; align-items: center; cursor: pointer; transition: transform 0.3s; }
93
+ .fab:active { transform: scale(0.9); }
 
 
 
 
 
 
 
94
  '''
95
 
96
  def find_node_by_id(filesystem, node_id):
97
  if not filesystem: return None, None
98
+ if filesystem.get('id') == node_id:
99
+ return filesystem, None
100
  queue = [(filesystem, None)]
101
  while queue:
102
  current_node, parent = queue.pop(0)
103
  if current_node.get('type') == 'folder' and 'children' in current_node:
104
+ for i, child in enumerate(current_node['children']):
105
+ if child.get('id') == node_id:
106
+ return child, current_node
107
+ if child.get('type') == 'folder':
108
+ queue.append((child, current_node))
109
  return None, None
110
 
111
  def add_node(filesystem, parent_id, node_data):
112
  parent_node, _ = find_node_by_id(filesystem, parent_id)
113
  if parent_node and parent_node.get('type') == 'folder':
114
+ if 'children' not in parent_node:
115
+ parent_node['children'] = []
116
  parent_node['children'].append(node_data)
117
  return True
118
  return False
 
130
  while current_id:
131
  node, parent = find_node_by_id(filesystem, current_id)
132
  if not node: break
133
+ if node.get('id') != 'root':
134
+ path_list.append(node.get('name', node.get('original_filename', '')))
135
  if not parent: break
136
  current_id = parent.get('id') if parent else None
137
  return " / ".join(reversed(path_list)) or "Root"
138
 
139
  def get_all_folders(filesystem, exclude_ids=None):
140
+ if exclude_ids is None:
141
+ exclude_ids = set()
142
  folders = []
143
+
144
  def traverse(node, path_prefix):
145
  if node.get('type') == 'folder':
146
  if node.get('id') not in exclude_ids:
147
  folder_name = f"{path_prefix}{node.get('name', 'Unnamed')}" if path_prefix else (node.get('name') if node.get('id') != 'root' else 'Главная (Root)')
148
  folders.append({'id': node.get('id'), 'name': folder_name})
149
  new_prefix = f"{path_prefix}{node.get('name', '')}/" if node.get('id') != 'root' else ""
150
+ for child in node.get('children', []):
151
+ traverse(child, new_prefix)
152
+
153
  traverse(filesystem, "")
154
  return sorted(folders, key=lambda x: x['name'].lower())
155
 
 
189
 
190
  def save_data(data):
191
  try:
192
+ with open(DATA_FILE, 'w', encoding='utf-8') as file:
193
+ json.dump(data, file, ensure_ascii=False, indent=4)
194
  upload_db_to_hf()
195
  cache.clear()
196
  except Exception as e:
 
201
  if not HF_TOKEN_WRITE: return
202
  try:
203
  api = HfApi()
204
+ api.upload_file(path_or_fileobj=DATA_FILE, path_in_repo=DATA_FILE, repo_id=REPO_ID, repo_type="dataset", token=HF_TOKEN_WRITE, commit_message=f"Backup {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
205
+ except Exception as e:
206
+ logging.error(f"Error uploading database: {e}")
 
 
207
 
208
  def download_db_from_hf():
209
  if not HF_TOKEN_READ:
 
230
  if filename_lower.endswith(('.mp4', '.mov', '.avi', '.webm', '.mkv')): return 'video'
231
  elif filename_lower.endswith(('.jpg', '.jpeg', '.png', '.gif', '.bmp', '.webp', '.svg')): return 'image'
232
  elif filename_lower.endswith('.pdf'): return 'pdf'
233
+ elif filename_lower.endswith('.txt'): return 'text'
234
  return 'other'
235
 
236
  def is_admin_tma():
237
+ if not ADMIN_TELEGRAM_ID or ADMIN_TELEGRAM_ID == "YOUR_ADMIN_TELEGRAM_USER_ID_HERE":
238
+ return False
239
  return 'telegram_user_id' in session and str(session['telegram_user_id']) == str(ADMIN_TELEGRAM_ID)
240
 
241
  def admin_browser_login_required(f):
242
  @wraps(f)
243
  def decorated_function(*args, **kwargs):
244
+ if not session.get('admin_browser_logged_in'):
245
+ return redirect(url_for('admin_login', next=request.url))
246
  return f(*args, **kwargs)
247
  return decorated_function
248
 
249
+ TMA_ENTRY_HTML = '''
250
+ <!DOCTYPE html><html lang="ru"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0">
251
+ <title>Zeus Cloud TMA</title><script src="https://telegram.org/js/telegram-web-app.js"></script>
252
+ <style>body { font-family: sans-serif; display: flex; justify-content: center; align-items: center; height: 100vh; margin: 0; background-color: #121212; color: #e0e0e0; } .loading { font-size: 1.5em; }</style>
253
+ </head><body><div class="loading">Загрузка приложения...</div>
254
+ <script>
255
+ window.Telegram.WebApp.ready();
256
+ const initData = window.Telegram.WebApp.initData;
257
+ const initDataUnsafe = window.Telegram.WebApp.initDataUnsafe;
258
+ if (initDataUnsafe && initDataUnsafe.user) {
259
+ fetch("{{ url_for('auth_via_telegram') }}", {
260
+ method: 'POST',
261
+ headers: { 'Content-Type': 'application/json' },
262
+ body: JSON.stringify({ user: initDataUnsafe.user, initData: initData })
263
+ }).then(response => response.json()).then(data => {
264
+ if (data.status === 'success') { window.location.href = data.redirect_url; }
265
+ else { document.body.innerHTML = `<div class="loading">Ошибка авторизации: ${data.message}</div>`; Telegram.WebApp.showAlert(data.message || "Ошибка авторизации"); }
266
+ }).catch(error => { document.body.innerHTML = `<div class="loading">Ошибка сети: ${error}</div>`; Telegram.WebApp.showAlert("Ошибка сети при авторизации."); });
267
+ } else {
268
+ document.body.innerHTML = '<div class="loading">Не удалось получить данные. Попробуйте перезапустить приложение.</div>';
269
+ Telegram.WebApp.showAlert("Не удалось получить данные пользователя Telegram.");
270
+ }
271
  </script></body></html>'''
272
 
273
  @app.route('/tma')
274
+ def tma_entry_page():
275
+ return render_template_string(TMA_ENTRY_HTML)
276
 
277
  @app.route('/')
278
+ def root_redirect():
279
+ return redirect(url_for('tma_entry_page'))
280
 
281
  @app.route('/auth_via_telegram', methods=['POST'])
282
  def auth_via_telegram():
 
284
  payload = request.json
285
  tg_user_data = payload.get('user')
286
  if not tg_user_data or not tg_user_data.get('id'):
287
+ return jsonify({'status': 'error', 'message': 'Отсутствуют данные пользователя Telegram.'}), 400
288
  tma_user_id_str = str(tg_user_data['id'])
289
  data = load_data()
290
  if tma_user_id_str not in data['users']:
 
298
  try: save_data(data)
299
  except Exception as e:
300
  logging.error(f"Save data error for new TMA user {tma_user_id_str}: {e}")
301
+ return jsonify({'status': 'error', 'message': 'Ошибка сохранения данных нового пользователя.'}), 500
302
  session['telegram_user_id'] = tma_user_id_str
303
+ display_name = tg_user_data.get('first_name') or tg_user_data.get('username') or f"User {tma_user_id_str}"
304
+ session['telegram_display_name'] = display_name
305
  return jsonify({'status': 'success', 'redirect_url': url_for('tma_dashboard')})
306
  except Exception as e:
307
  logging.error(f"Error in auth_via_telegram: {e}")
308
+ return jsonify({'status': 'error', 'message': 'Внутренняя ошибка сервера при авторизации.'}), 500
309
 
310
  TMA_DASHBOARD_HTML_TEMPLATE = '''
311
+ <!DOCTYPE html><html lang="ru"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
312
+ <title>Zeus Cloud</title>
313
+ <link rel="preconnect" href="https://fonts.googleapis.com"><link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
314
+ <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;800&display=swap" rel="stylesheet">
315
+ <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.2/css/all.min.css">
316
+ <script src="https://telegram.org/js/telegram-web-app.js"></script>
317
+ <style>''' + BASE_STYLE + '''</style></head><body>
318
+ <div class="app-header">
319
+ <div class="user-info">{{ display_name }}</div>
320
+ <div class="view-toggle">
321
+ <button id="grid-view-btn" title="Сетка"><i class="fa fa-th-large"></i></button>
322
+ <button id="list-view-btn" title="Список"><i class="fa fa-bars"></i></button>
323
+ </div>
324
  </div>
325
+ <div class="container" id="main-container">
326
+ {% with messages = get_flashed_messages(with_categories=true) %}{% if messages %}
327
+ {% for category, message in messages %}<div class="flash {{ category }}">{{ message }}</div>{% endfor %}
328
+ {% endif %}{% endwith %}
329
+ <div class="breadcrumbs">
330
+ {% for crumb in breadcrumbs %}
331
+ {% if crumb.is_link %}<a href="{{ url_for('tma_dashboard', folder_id=crumb.id) }}">{{ crumb.name if crumb.id != 'root' else 'Главная' }}</a>
332
+ {% else %}<span>{{ crumb.name if crumb.id != 'root' else 'Главная' }}</span>{% endif %}
333
+ {% if not loop.last %}<span>/</span>{% endif %}
334
+ {% endfor %}
335
  </div>
336
+ <h2>{{ current_folder.name if current_folder_id != 'root' else 'Главная' }}</h2>
337
  <div id="progress-container"><div id="progress-bar"></div></div>
338
  <div class="file-grid" id="file-container">
339
  {% for item in items %}
340
  <div class="item {{ item.type }}" data-id="{{ item.id }}" data-type="{{ item.type }}">
341
+ <div class="item-preview-wrapper" {% if item.type != 'folder' %}onclick="openModal('{{ hf_file_url_jinja(item.path) if item.file_type not in ['text', 'pdf'] else (url_for('get_text_content_tma', file_id=item.id) if item.file_type == 'text' else hf_file_url_jinja(item.path, True)) }}', '{{ item.file_type }}', '{{ item.id }}')"{% else %}onclick="window.location.href='{{ url_for('tma_dashboard', folder_id=item.id) }}'"{% endif %}>
342
  {% if item.type == 'folder' %}
343
+ <div class="item-preview"><i class="fa-solid fa-folder"></i></div>
 
 
344
  {% elif item.type == 'file' %}
345
+ {% if item.file_type == 'image' %}<img class="item-preview" src="{{ hf_file_url_jinja(item.path) }}" loading="lazy">
346
+ {% elif item.file_type == 'video' %}<video class="item-preview" preload="metadata" muted loading="lazy"><source src="{{ hf_file_url_jinja(item.path, True) }}#t=0.5"></video>
347
+ {% elif item.file_type == 'pdf' %}<div class="item-preview" style="font-size: 2.5em; display: flex; align-items: center; justify-content: center; color: var(--accent);"><i class="fa-solid fa-file-pdf"></i></div>
348
+ {% elif item.file_type == 'text' %}<div class="item-preview" style="font-size: 2.5em; display: flex; align-items: center; justify-content: center; color: var(--secondary);"><i class="fa-solid fa-file-lines"></i></div>
349
+ {% else %}<div class="item-preview" style="font-size: 2.5em; display: flex; align-items: center; justify-content: center; color: var(--text-muted);"><i class="fa-solid fa-file-circle-question"></i></div>
350
+ {% endif %}
 
 
 
 
351
  {% endif %}
352
+ </div>
353
+ <div class="item-name-info">
354
+ <p class="item-name">{{ item.name if item.type == 'folder' else item.original_filename | truncate(30, True) }}</p>
355
+ {% if item.type == 'file' %}<p class="item-info">{{ item.upload_date }}</p>{% endif %}
356
+ </div>
357
  </div>
358
  {% endfor %}
359
+ {% if not items %} <p>Эта папка пуста.</p> {% endif %}
360
  </div>
 
 
 
 
 
 
 
 
 
 
361
  </div>
362
+ <div class="modal" id="mediaModal" onclick="closeModal(event)"><div class="modal-content" id="modalContentContainer">
363
+ <span onclick="closeModalManual()" class="modal-close-btn">&times;</span><div id="modalContent"></div></div></div>
364
+
365
+ <div id="selection-bar">
366
+ <span id="selection-count"></span>
367
+ <button class="btn download-btn" onclick="downloadSelected()"><i class="fa-solid fa-download"></i> Скачать</button>
368
+ <button class="btn" style="background: var(--accent);" onclick="showMoveModal()"><i class="fa-solid fa-arrow-right-to-bracket"></i></button>
369
+ <button class="btn delete-btn" onclick="deleteSelected()"><i class="fa-solid fa-trash-can"></i></button>
370
+ <button class="btn" style="background: #555;" onclick="toggleSelectionMode(false)">Отмена</button>
371
+ </div>
372
+
373
+ <div class="modal" id="move-modal"><div class="modal-content">
374
+ <h4>Переместить в:</h4>
375
+ <select id="folder-destination-select">
376
+ {% for folder in all_folders_for_move %}<option value="{{ folder.id }}">{{ folder.name }}</option>{% endfor %}
377
+ </select>
378
+ <button class="btn" style="background: var(--accent); width: 100%; margin-top: 10px;" onclick="moveSelected()">Переместить</button>
379
+ <button class="btn" style="background: #555; width: 100%;" onclick="closeMoveModal()">Отмена</button>
380
+ </div></div>
381
+
382
+ <div class="modal" id="fab-modal"><div class="modal-content">
383
+ <h4>Действия</h4>
384
+ <form id="upload-form" method="POST" enctype="multipart/form-data" action="{{ url_for('tma_dashboard') }}">
385
+ <input type="hidden" name="current_folder_id" value="{{ current_folder_id }}">
386
+ <input type="file" name="files" id="file-input" multiple required onchange="document.getElementById('upload-btn-modal').click()">
387
+ <label for="file-input" class="btn" style="width:100%; margin-bottom: 10px; background: var(--secondary);"><i class="fa-solid fa-upload"></i> Загрузить файлы</label>
388
+ <button type="submit" id="upload-btn-modal" style="display:none;"></button>
389
+ </form>
390
+ <form method="POST" action="{{ url_for('create_folder_tma') }}">
391
+ <input type="hidden" name="parent_folder_id" value="{{ current_folder_id }}">
392
+ <input type="text" name="folder_name" placeholder="Имя новой папки" required>
393
+ <button type="submit" class="btn folder-btn" style="width:100%"><i class="fa-solid fa-folder-plus"></i> Создать папку</button>
394
+ </form>
395
+ <button class="btn" style="background: #555; width: 100%; margin-top: 10px;" onclick="closeFabModal()">Отмена</button>
396
+ </div></div>
397
+
398
+ <div class="fab-container"><button id="fab" class="fab"><i class="fa-solid fa-plus"></i></button></div>
399
+
400
  <script>
401
  window.Telegram.WebApp.ready();
402
  window.Telegram.WebApp.expand();
 
403
  async function openModal(srcOrUrl, type) {
404
+ if (!srcOrUrl) return;
405
+ const modal = document.getElementById('mediaModal'); const modalContent = document.getElementById('modalContent');
406
  modalContent.innerHTML = '<p>Загрузка...</p>'; modal.style.display = 'flex';
407
  try {
408
  if (type === 'image') modalContent.innerHTML = `<img src="${srcOrUrl}">`;
409
+ else if (type === 'video') modalContent.innerHTML = `<video controls autoplay><source src="${srcOrUrl}"></video>`;
410
  else if (type === 'pdf') modalContent.innerHTML = `<iframe src="${srcOrUrl}"></iframe>`;
411
  else if (type === 'text') {
412
+ const response = await fetch(srcOrUrl); if (!response.ok) throw new Error(`Ошибка: ${response.statusText}`);
413
+ const text = await response.text();
414
+ modalContent.innerHTML = `<pre>${text.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}</pre>`;
415
+ } else tmaDownloadFile(srcOrUrl);
416
+ } catch (error) { modalContent.innerHTML = `<p>Ошибка предпросмотра: ${error.message}</p>`; }
417
  }
418
+ function closeModal(event) { if (event.target.id === 'mediaModal') closeModalManual(); }
419
  function closeModalManual() {
420
  const modal = document.getElementById('mediaModal'); modal.style.display = 'none';
421
+ const video = modal.querySelector('video'); if (video) video.pause();
422
  document.getElementById('modalContent').innerHTML = '';
423
  }
424
+ function tmaDownloadFile(downloadUrl, filename = 'download') {
425
+ if (window.Telegram && window.Telegram.WebApp && Telegram.WebApp.openLink) { Telegram.WebApp.openLink(downloadUrl); }
426
+ else { window.open(downloadUrl, '_blank'); }
427
  }
428
+ document.getElementById('upload-form')?.addEventListener('submit', function(e) {
429
+ e.preventDefault(); const files = document.getElementById('file-input').files;
430
+ if (files.length === 0) { Telegram.WebApp.showAlert('Выберите файлы.'); return; }
431
+ if (files.length > 20) { Telegram.WebApp.showAlert('Максимум 20 файлов за раз!'); return; }
432
+ closeFabModal();
433
+ const progressContainer = document.getElementById('progress-container');
434
+ const progressBar = document.getElementById('progress-bar');
435
+ progressContainer.style.display = 'block'; progressBar.style.width = '0%';
436
+ const formData = new FormData(this); const xhr = new XMLHttpRequest();
437
+ xhr.upload.addEventListener('progress', e => {
438
+ if (e.lengthComputable) progressBar.style.width = Math.round((e.loaded / e.total) * 100) + '%';
439
+ });
440
+ xhr.addEventListener('load', () => window.location.reload());
441
+ xhr.addEventListener('error', () => Telegram.WebApp.showAlert('Ошибка загрузки.'));
442
+ xhr.open('POST', this.action, true); xhr.send(formData);
443
  });
444
 
445
  let selectionMode = false; const selectedItems = new Set(); let longPressTimer;
446
+ const mainContainer = document.getElementById('main-container');
447
+ const selectionBar = document.getElementById('selection-bar');
448
+ const selectionCount = document.getElementById('selection-count');
449
+ const allItems = document.querySelectorAll('.item');
450
 
451
  function toggleSelectionMode(enable) {
452
+ selectionMode = enable;
453
  selectionBar.classList.toggle('visible', enable);
454
+ if (!enable) {
455
+ selectedItems.clear();
456
+ allItems.forEach(item => item.classList.remove('selected'));
457
+ }
 
 
 
458
  }
459
+ function updateSelectionUI() { selectionCount.textContent = `Выбрано: ${selectedItems.size}`; }
460
+
461
  allItems.forEach(item => {
462
+ item.addEventListener('pointerdown', e => {
463
+ if (e.pointerType === 'mouse' && e.button !== 0) return;
464
+ longPressTimer = setTimeout(() => {
465
+ if (!selectionMode) toggleSelectionMode(true);
466
+ item.classList.toggle('selected');
467
+ if (selectedItems.has(item.dataset.id)) selectedItems.delete(item.dataset.id); else selectedItems.add(item.dataset.id);
468
+ updateSelectionUI();
469
+ }, 500);
470
+ });
471
+ item.addEventListener('pointerup', () => clearTimeout(longPressTimer));
472
+ item.addEventListener('pointerleave', () => clearTimeout(longPressTimer));
473
  item.addEventListener('click', e => {
474
  if (selectionMode) {
475
+ e.preventDefault(); e.stopPropagation();
476
+ item.classList.toggle('selected');
477
+ if (selectedItems.has(item.dataset.id)) selectedItems.delete(item.dataset.id); else selectedItems.add(item.dataset.id);
478
+ updateSelectionUI();
479
  if (selectedItems.size === 0) toggleSelectionMode(false);
 
480
  }
481
  }, true);
482
  });
483
 
484
+ async function performBatchAction(url, body) {
 
 
485
  try {
486
+ const response = await fetch(url, {
487
+ method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body)
488
+ });
489
+ const result = await response.json();
490
+ if (result.status === 'success') window.location.reload();
491
+ else Telegram.WebApp.showAlert(result.message || 'Произошла ошибка.');
492
  } catch (error) { Telegram.WebApp.showAlert('Сетевая ошибка.'); }
493
  finally { toggleSelectionMode(false); }
494
  }
495
+ function downloadSelected() {
496
+ const fileIds = Array.from(selectedItems).filter(id => {
497
+ const item = document.querySelector(`.item[data-id='${id}']`);
498
+ return item && item.dataset.type === 'file';
499
+ });
500
+ if (fileIds.length === 0) { Telegram.WebApp.showAlert('Папки нельзя скачать. Выберите файлы.'); return; }
501
+ const url = `{{ url_for("batch_download_tma") }}?file_ids=${fileIds.join(',')}`;
502
+ tmaDownloadFile(url, 'archive.zip');
503
+ toggleSelectionMode(false);
504
+ }
505
+ function showMoveModal() { if (selectedItems.size > 0) document.getElementById('move-modal').style.display = 'flex'; }
506
+ function closeMoveModal() { document.getElementById('move-modal').style.display = 'none'; }
507
+ function moveSelected() {
508
+ const destinationId = document.getElementById('folder-destination-select').value;
509
+ performBatchAction('{{ url_for("batch_move_tma") }}', { item_ids: Array.from(selectedItems), destination_id: destinationId });
510
+ closeMoveModal();
511
+ }
512
+ function deleteSelected() {
513
+ if (selectedItems.size === 0) return;
514
+ Telegram.WebApp.showConfirm(`Удалить ${selectedItems.size} элемент(ов)?`, ok => {
515
+ if (ok) performBatchAction('{{ url_for("batch_delete_tma") }}', { item_ids: Array.from(selectedItems) });
516
+ });
517
+ }
518
 
519
+ const gridViewBtn = document.getElementById('grid-view-btn');
520
+ const listViewBtn = document.getElementById('list-view-btn');
521
+ const fileContainer = document.getElementById('file-container');
522
  function setView(view) {
 
 
 
523
  fileContainer.classList.toggle('list-view', view === 'list');
524
+ listViewBtn.classList.toggle('active', view === 'list');
525
+ gridViewBtn.classList.toggle('active', view !== 'list');
526
  localStorage.setItem('viewMode', view);
527
  }
528
+ gridViewBtn.addEventListener('click', () => setView('grid'));
529
+ listViewBtn.addEventListener('click', () => setView('list'));
530
  document.addEventListener('DOMContentLoaded', () => setView(localStorage.getItem('viewMode') || 'grid'));
531
+
532
+ const fab = document.getElementById('fab');
533
+ const fabModal = document.getElementById('fab-modal');
534
+ fab.addEventListener('click', () => { fabModal.style.display = 'flex'; });
535
+ function closeFabModal() { fabModal.style.display = 'none'; }
536
+ fabModal.addEventListener('click', e => { if (e.target.id === 'fab-modal') closeFabModal(); });
537
+ </script></body></html>
538
+ '''
539
 
540
  @app.route('/tma_dashboard', methods=['GET', 'POST'])
541
  def tma_dashboard():
542
+ if 'telegram_user_id' not in session:
543
+ flash('Пожалуйста, авторизуйтесь через Telegram.', 'error')
544
+ return redirect(url_for('tma_entry_page'))
545
+ tma_user_id = session['telegram_user_id']
546
+ display_name = session.get('telegram_display_name', 'Пользователь')
547
  data = load_data()
548
  if tma_user_id not in data['users']:
549
  session.clear()
550
+ flash('Пользователь не найден. Пожалуйста, перезапустите приложение.', 'error')
551
  return redirect(url_for('tma_entry_page'))
552
  user_data = data['users'][tma_user_id]
553
  initialize_user_filesystem_tma(user_data, tma_user_id)
554
  current_folder_id = request.args.get('folder_id', 'root')
555
  current_folder, parent_folder = find_node_by_id(user_data['filesystem'], current_folder_id)
556
  if not current_folder or current_folder.get('type') != 'folder':
557
+ flash('Папка не найдена!', 'error')
558
  current_folder_id = 'root'
559
+ current_folder, parent_folder = find_node_by_id(user_data['filesystem'], 'root')
560
+ items_in_folder = sorted(current_folder.get('children', []), key=lambda x: (x['type'] != 'folder', x.get('name', x.get('original_filename', '')).lower()))
561
  if request.method == 'POST':
562
  if not HF_TOKEN_WRITE:
563
+ flash('Загрузка невозможна: токен для записи не настроен.', 'error')
564
  return redirect(url_for('tma_dashboard', folder_id=current_folder_id))
565
  files = request.files.getlist('files')
566
  if not files or all(not f.filename for f in files):
567
+ flash('Файлы для загрузки не выбраны.', 'error')
568
  return redirect(url_for('tma_dashboard', folder_id=current_folder_id))
569
  target_folder_id = request.form.get('current_folder_id', 'root')
570
+ uploaded_count = 0
571
+ errors_list = []
572
  api = HfApi()
573
  for file_obj in files:
574
  if file_obj and file_obj.filename:
575
  original_filename = secure_filename(file_obj.filename)
576
  name_part, ext_part = os.path.splitext(original_filename)
577
+ unique_suffix = uuid.uuid4().hex[:8]
578
+ unique_filename = f"{name_part}_{unique_suffix}{ext_part}"
579
  file_id = uuid.uuid4().hex
580
  hf_path = f"cloud_files/{tma_user_id}/{target_folder_id}/{unique_filename}"
581
  temp_path = os.path.join(UPLOAD_FOLDER, f"{file_id}_{unique_filename}")
582
  try:
583
  file_obj.save(temp_path)
584
  api.upload_file(path_or_fileobj=temp_path, path_in_repo=hf_path, repo_id=REPO_ID, repo_type="dataset", token=HF_TOKEN_WRITE)
585
+ file_info = {'type': 'file', 'id': file_id, 'original_filename': original_filename, 'unique_filename': unique_filename, 'path': hf_path, 'file_type': get_file_type(original_filename), 'upload_date': datetime.now().strftime('%Y-%m-%d')}
586
+ if add_node(user_data['filesystem'], target_folder_id, file_info):
587
+ uploaded_count += 1
588
+ except Exception as e:
589
+ errors_list.append(f"Ошибка загрузки {original_filename}: {e}")
 
 
 
590
  finally:
591
  if os.path.exists(temp_path): os.remove(temp_path)
592
+ if uploaded_count > 0:
593
+ try: save_data(data); flash(f'{uploaded_count} файл(ов) успешно загружено!')
594
+ except Exception: flash('Файлы загружены, но ошибка сохранения метаданных.', 'error')
595
+ if errors_list:
596
+ for error_msg in errors_list: flash(error_msg, 'error')
597
  return redirect(url_for('tma_dashboard', folder_id=target_folder_id))
598
+
 
599
  breadcrumbs = []
600
  temp_id = current_folder_id
601
  while temp_id:
602
  node, parent_node_bc = find_node_by_id(user_data['filesystem'], temp_id)
603
  if not node: break
604
+ is_link = (node['id'] != current_folder_id)
605
+ breadcrumbs.append({'id': node['id'], 'name': node.get('name', 'Root'), 'is_link': is_link})
606
+ if not parent_node_bc: break
607
+ temp_id = parent_node_bc.get('id')
608
  breadcrumbs.reverse()
609
+
610
  all_folders_for_move = get_all_folders(user_data['filesystem'])
611
+
612
+ return render_template_string(TMA_DASHBOARD_HTML_TEMPLATE, display_name=display_name, items=items_in_folder, current_folder_id=current_folder_id, current_folder=current_folder, breadcrumbs=breadcrumbs, hf_file_url_jinja=lambda path, download=False: f"https://huggingface.co/datasets/{REPO_ID}/resolve/main/{path}{'?download=true' if download else ''}", is_tma_user_admin_flag=is_admin_tma(), all_folders_for_move=all_folders_for_move)
 
 
 
613
 
614
  @app.route('/create_folder_tma', methods=['POST'])
615
  def create_folder_tma():
 
618
  data = load_data()
619
  user_data = data['users'].get(tma_user_id)
620
  if not user_data: return redirect(url_for('tma_entry_page'))
621
+
622
  parent_folder_id = request.form.get('parent_folder_id', 'root')
623
  folder_name = request.form.get('folder_name', '').strip()
624
  if not folder_name:
625
  flash('Имя папки не может быть пустым!', 'error')
626
+ else:
627
+ folder_id = uuid.uuid4().hex
628
+ folder_data = {'type': 'folder', 'id': folder_id, 'name': folder_name, 'children': []}
629
+ if add_node(user_data['filesystem'], parent_folder_id, folder_data):
630
+ try: save_data(data); flash(f'Папка "{folder_name}" создана.')
631
+ except Exception: flash('Ошибка сохранения данных.', 'error')
632
+ else: flash('Не удалось найти родительскую папку.', 'error')
633
  return redirect(url_for('tma_dashboard', folder_id=parent_folder_id))
634
 
635
+ def get_file_node_for_user(file_id):
636
+ if not (session.get('telegram_user_id') or session.get('admin_browser_logged_in')):
637
+ return None
638
+ data = load_data()
639
+ if session.get('admin_browser_logged_in'):
640
+ for uid, udata in data.get('users', {}).items():
641
+ node, _ = find_node_by_id(udata.get('filesystem', {}), file_id)
642
+ if node and node.get('type') == 'file': return node
643
+ else: # TMA user
644
+ user_data = data['users'].get(session['telegram_user_id'])
645
+ if user_data:
646
+ node, _ = find_node_by_id(user_data.get('filesystem', {}), file_id)
647
+ if node and node.get('type') == 'file': return node
648
+ return None
649
+
650
  @app.route('/download_tma/<file_id>')
651
  def download_tma(file_id):
652
+ file_node = get_file_node_for_user(file_id)
653
+ if not file_node:
654
+ flash('Файл не найден или доступ запрещен!', 'error')
655
+ return redirect(request.referrer or url_for('tma_dashboard'))
656
+
 
 
 
 
 
 
 
 
 
 
657
  hf_path = file_node.get('path')
658
  original_filename = file_node.get('original_filename', 'downloaded_file')
659
+ if not hf_path:
660
+ flash('Ошибка: Путь к файлу не найден.', 'error')
661
+ return redirect(request.referrer or url_for('tma_dashboard'))
662
+
663
  file_url = f"https://huggingface.co/datasets/{REPO_ID}/resolve/main/{hf_path}?download=true"
664
  try:
665
+ req_headers = {}
666
+ if HF_TOKEN_READ: req_headers["authorization"] = f"Bearer {HF_TOKEN_READ}"
667
+ r = requests.get(file_url, headers=req_headers, stream=True)
668
  r.raise_for_status()
669
+
670
+ resp = Response(r.iter_content(chunk_size=8192), mimetype='application/octet-stream')
671
  encoded_filename = quote(original_filename)
672
+ resp.headers['Content-Disposition'] = f"attachment; filename=\"{encoded_filename}\"; filename*=UTF-8''{encoded_filename}"
673
  return resp
674
  except Exception as e:
675
+ logging.error(f"Error downloading {file_id} from HF: {e}")
676
+ flash(f'Ошибка скачивания файла: {e}', 'error')
677
+ return redirect(request.referrer or url_for('tma_dashboard'))
678
 
679
+ @app.route('/batch_download_tma')
680
  def batch_download_tma():
681
+ if 'telegram_user_id' not in session: return Response("Unauthorized", 401)
682
+ file_ids_str = request.args.get('file_ids')
683
+ if not file_ids_str: return Response("No file IDs provided", 400)
 
 
 
684
 
685
+ file_ids = file_ids_str.split(',')
 
686
 
687
+ temp_zip_file = tempfile.NamedTemporaryFile(delete=False, suffix=".zip")
688
+ req_headers = {}
689
+ if HF_TOKEN_READ: req_headers["authorization"] = f"Bearer {HF_TOKEN_READ}"
690
+
691
+ try:
692
+ with zipfile.ZipFile(temp_zip_file, 'w', zipfile.ZIP_DEFLATED) as zf:
693
+ for file_id in file_ids:
694
+ file_node = get_file_node_for_user(file_id)
695
+ if file_node and file_node.get('path'):
696
+ hf_path = file_node['path']
697
+ original_filename = file_node.get('original_filename', file_id)
698
+ file_url = f"https://huggingface.co/datasets/{REPO_ID}/resolve/main/{hf_path}?download=true"
699
+ try:
700
+ r = requests.get(file_url, headers=req_headers, stream=True)
701
+ r.raise_for_status()
702
+ zf.writestr(original_filename, r.content)
703
+ except Exception as e:
704
+ logging.error(f"Failed to download and add {original_filename} to zip: {e}")
705
+
706
+ temp_zip_file.close()
707
+ return send_file(temp_zip_file.name, as_attachment=True, download_name='archive.zip', mimetype='application/zip')
708
+ finally:
709
+ if os.path.exists(temp_zip_file.name):
710
+ os.unlink(temp_zip_file.name)
711
 
712
  @app.route('/delete_file_tma/<file_id>', methods=['POST'])
713
  def delete_file_tma(file_id):
 
718
  if not user_data: return redirect(url_for('tma_entry_page'))
719
  file_node, _ = find_node_by_id(user_data['filesystem'], file_id)
720
  current_view_folder_id = request.form.get('current_view_folder_id', 'root')
721
+ if not file_node or file_node.get('type') != 'file':
722
+ flash('Файл не найден.', 'error')
723
+ else:
724
  hf_path = file_node.get('path')
725
+ if not HF_TOKEN_WRITE:
726
+ flash('Удаление невозможно: токен для записи не настроен.', 'error')
727
+ else:
728
  try:
729
  api = HfApi()
730
+ if hf_path: api.delete_file(path_in_repo=hf_path, repo_id=REPO_ID, repo_type="dataset", token=HF_TOKEN_WRITE)
731
+ removed, _ = remove_node(user_data['filesystem'], file_id)
732
+ if removed:
733
+ try: save_data(data); flash('Файл удален.')
734
+ except Exception: flash('Файл удален с сервера, но ошибка обновления базы.', 'error')
735
  except hf_utils.EntryNotFoundError:
736
+ removed, _ = remove_node(user_data['filesystem'], file_id)
737
+ if removed:
738
+ try: save_data(data); flash('Файл не найден на сервере, удален из базы.')
739
+ except Exception: flash('Ошибка сохранения (файл не на сервере).', 'error')
740
  except Exception as e:
741
+ flash(f'Ошибка удаления: {e}', 'error')
 
 
 
742
  return redirect(url_for('tma_dashboard', folder_id=current_view_folder_id))
743
 
744
  @app.route('/delete_folder_tma/<folder_id>', methods=['POST'])
745
  def delete_folder_tma(folder_id):
746
+ if 'telegram_user_id' not in session: return redirect(url_for('tma_entry_page'))
747
+ if folder_id == 'root':
748
+ flash('Нельзя удалить корневую папку!', 'error'); return redirect(url_for('tma_dashboard'))
749
+ tma_user_id = session['telegram_user_id']
750
+ data = load_data()
751
  user_data = data['users'].get(tma_user_id)
752
  if not user_data: return redirect(url_for('tma_entry_page'))
753
+
754
  folder_node, parent_node = find_node_by_id(user_data['filesystem'], folder_id)
 
755
  if not folder_node or folder_node.get('type') != 'folder' or not parent_node:
756
+ flash('Папка не найдена.', 'error')
757
+ elif folder_node.get('children'):
758
  flash('Папку можно удалить только если она пуста.', 'error')
759
+ else:
760
+ removed, _ = remove_node(user_data['filesystem'], folder_id)
761
+ if removed:
762
+ try: save_data(data); flash(f'Папка "{folder_node.get("name")}" удалена.')
763
+ except Exception: flash('Ошибка сохранения после удаления папки.', 'error')
764
+ else: flash('Не удалось удалить папку.', 'error')
765
  return redirect(url_for('tma_dashboard', folder_id=parent_node.get('id', 'root')))
766
 
767
+ @app.route('/batch_delete_tma', methods=['POST'])
768
+ def batch_delete_tma():
769
+ if 'telegram_user_id' not in session: return jsonify({'status': 'error', 'message': 'Не авторизован.'}), 401
770
+ tma_user_id = session['telegram_user_id']
771
+ data = load_data()
772
+ user_data = data['users'].get(tma_user_id)
773
+ if not user_data: return jsonify({'status': 'error', 'message': 'Пользователь не найден.'}), 404
774
+ item_ids = request.json.get('item_ids', [])
775
+ if not item_ids: return jsonify({'status': 'error', 'message': 'Не выбраны элементы.'}), 400
776
+
777
+ api = HfApi()
778
+ success_count = 0; errors = []
779
  for item_id in item_ids:
780
  node, _ = find_node_by_id(user_data['filesystem'], item_id)
781
+ if not node:
782
+ errors.append(f"Элемент {item_id} не найден.")
783
+ continue
784
  if node.get('type') == 'folder':
785
+ if node.get('children'): errors.append(f'Папка "{node.get("name")}" не пуста.'); continue
786
+ if remove_node(user_data['filesystem'], item_id)[0]: success_count += 1
787
+ else: errors.append(f'Ошибка удаления папки "{node.get("name")}".')
788
  elif node.get('type') == 'file':
789
  try:
790
  if node.get('path') and HF_TOKEN_WRITE: api.delete_file(path_in_repo=node['path'], repo_id=REPO_ID, repo_type="dataset", token=HF_TOKEN_WRITE)
791
  except hf_utils.EntryNotFoundError: pass
792
+ except Exception as e: errors.append(f'Ошибка удаления "{node.get("original_filename")}" с сервера: {e}'); continue
793
+ if remove_node(user_data['filesystem'], item_id)[0]: success_count += 1
794
+ else: errors.append(f'Ошибка удаления "{node.get("original_filename")}" из базы.')
795
+ if success_count > 0:
796
+ try: save_data(data)
797
+ except Exception as e: return jsonify({'status': 'error', 'message': f'Ошибка сохранения: {e}'})
 
 
 
 
 
 
 
798
  if errors: return jsonify({'status': 'error', 'message': f'Удалено {success_count}. Ошибки: ' + "; ".join(errors)})
799
+ return jsonify({'status': 'success', 'message': f'Удалено {success_count} элемент(ов).'})
800
 
801
  @app.route('/batch_move_tma', methods=['POST'])
802
  def batch_move_tma():
803
+ if 'telegram_user_id' not in session: return jsonify({'status': 'error', 'message': 'Не авторизован.'}), 401
804
+ tma_user_id = session['telegram_user_id']
805
+ data = load_data()
806
  user_data = data['users'].get(tma_user_id)
807
+ if not user_data: return jsonify({'status': 'error', 'message': 'Пользователь не найден.'}), 404
808
+ item_ids = request.json.get('item_ids', [])
809
+ destination_id = request.json.get('destination_id')
810
+ if not item_ids or not destination_id: return jsonify({'status': 'error', 'message': 'Не указаны файлы или папка.'}), 400
811
  destination_node, _ = find_node_by_id(user_data['filesystem'], destination_id)
812
+ if not destination_node or destination_node.get('type') != 'folder': return jsonify({'status': 'error', 'message': 'Папка назначения не найдена.'}), 404
813
+
814
+ descendant_ids = set()
815
+ for item_id in item_ids:
816
+ node, _ = find_node_by_id(user_data['filesystem'], item_id)
817
+ if node and node.get('type') == 'folder':
818
+ queue = [node]
819
+ while queue:
820
+ curr = queue.pop(0)
821
+ descendant_ids.add(curr.get('id'))
822
+ if 'children' in curr: queue.extend(curr['children'])
823
+ if destination_id in descendant_ids: return jsonify({'status': 'error', 'message': 'Нельзя переместить папку в саму себя.'})
824
+
825
+ moved_count = 0; errors = []
826
  for item_id in item_ids:
827
  if item_id == destination_id: continue
828
  removed, node_to_move = remove_node(user_data['filesystem'], item_id)
829
  if removed and node_to_move:
830
  if add_node(user_data['filesystem'], destination_id, node_to_move): moved_count += 1
831
+ else: errors.append(f'Ошибка добавления {item_id} в новую папку.')
832
+ else: errors.append(f'Не удалось извлечь {item_id}.')
833
+
834
+ if moved_count > 0:
835
+ try: save_data(data)
836
+ except Exception as e: return jsonify({'status': 'error', 'message': f'Ошибка сохранения: {e}'})
837
+ if errors: return jsonify({'status': 'error', 'message': f'Перемещено {moved_count}. Ошибки: ' + "; ".join(errors)})
838
+ return jsonify({'status': 'success', 'message': f'Перемещено {moved_count} элемент(ов).'})
839
 
840
  @app.route('/get_text_content_tma/<file_id>')
841
  def get_text_content_tma(file_id):
842
+ file_node = get_file_node_for_user(file_id)
843
+ if not file_node or file_node.get('file_type') != 'text': return Response("Текстовый файл не найден", 404)
 
 
 
 
 
 
 
 
 
 
 
 
 
844
  hf_path = file_node.get('path')
845
+ if not hf_path: return Response("Ошибка: путь к файлу отсутствует", 500)
846
+ file_url = f"https://huggingface.co/datasets/{REPO_ID}/resolve/main/{hf_path}?download=true"
847
  try:
848
+ req_headers = {};
849
+ if HF_TOKEN_READ: req_headers["authorization"] = f"Bearer {HF_TOKEN_READ}"
850
+ response = requests.get(file_url, headers=req_headers)
851
  response.raise_for_status()
852
+ if len(response.content) > 1 * 1024 * 1024: return Response("Файл слишком большой для предпросмотра.", 413)
853
+ try: text_content = response.content.decode('utf-8')
854
+ except UnicodeDecodeError: text_content = response.content.decode('latin-1', errors='ignore')
855
+ return Response(text_content, mimetype='text/plain')
856
+ except Exception as e: return Response(f"Ошибка загрузки: {e}", 502)
857
 
858
  @app.route('/tma_logout')
859
  def tma_logout():
860
  session.clear()
861
+ flash('Вы вышли из сессии приложения.')
862
  return redirect(url_for('tma_entry_page'))
863
 
864
  @app.route('/admin/login', methods=['GET', 'POST'])
 
867
  if request.form.get('username') == ADMIN_USERNAME and request.form.get('password') == ADMIN_PASSWORD:
868
  session['admin_browser_logged_in'] = True
869
  return redirect(request.form.get('next') or url_for('admin_panel'))
870
+ else: flash('Неверные данные.', 'error')
871
+ return render_template_string("Admin Login Page")
 
872
 
873
  @app.route('/admin/logout')
874
  def admin_logout():
 
878
  @app.route('/admhosto')
879
  @admin_browser_login_required
880
  def admin_panel():
881
+ return "Admin Panel"
882
 
883
  @app.route('/admhosto/user/<tma_user_id_str>')
884
  @admin_browser_login_required
885
  def admin_user_files(tma_user_id_str):
886
+ return f"Files for user {tma_user_id_str}"
887
 
888
  @app.route('/admhosto/delete_user/<tma_user_id_str>', methods=['POST'])
889
  @admin_browser_login_required
890
  def admin_delete_user(tma_user_id_str):
891
+ return "User deleted"
892
 
893
  @app.route('/admhosto/delete_file/<tma_user_id_str_form>/<file_id>', methods=['POST'])
894
  @admin_browser_login_required
895
  def admin_delete_file(tma_user_id_str_form, file_id):
896
+ return "File deleted"
897
 
898
  if __name__ == '__main__':
899
+ if not HF_TOKEN_WRITE: logging.warning("HF_TOKEN (write) is not set. Uploads/deletions will fail.")
900
+ if not HF_TOKEN_READ: logging.warning("HF_TOKEN_READ is not set. Downloads/previews might fail.")
901
+ if ADMIN_TELEGRAM_ID == "YOUR_ADMIN_TELEGRAM_USER_ID_HERE": logging.warning("ADMIN_TELEGRAM_ID is not set.")
902
+ if ADMIN_USERNAME == "admin" and ADMIN_PASSWORD == "zeusadminpass":
903
+ logging.warning("Using default admin credentials. Please change them.")
904
  if HF_TOKEN_WRITE:
905
  download_db_from_hf()
906
  threading.Thread(target=periodic_backup, daemon=True).start()
 
909
  else:
910
  if not os.path.exists(DATA_FILE):
911
  with open(DATA_FILE, 'w', encoding='utf-8') as f: json.dump({'users': {}}, f)
 
912
  app.run(debug=False, host='0.0.0.0', port=7860)