Eluza133 commited on
Commit
1719631
·
verified ·
1 Parent(s): 0adee97

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +81 -55
app.py CHANGED
@@ -13,7 +13,7 @@ import requests
13
  from io import BytesIO
14
  import uuid
15
  from functools import wraps
16
- from urllib.parse import quote # V2 CHANGE: Added for iOS download fix
17
 
18
  app = Flask(__name__)
19
  app.secret_key = os.getenv("FLASK_SECRET_KEY", "supersecretkey_folders_unique_tma")
@@ -27,14 +27,12 @@ ADMIN_TELEGRAM_ID = os.getenv("ADMIN_TELEGRAM_ID", "YOUR_ADMIN_TELEGRAM_USER_ID_
27
  ADMIN_USERNAME = os.getenv("ADMIN_USERNAME", "admin")
28
  ADMIN_PASSWORD = os.getenv("ADMIN_PASSWORD", "zeusadminpass")
29
 
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
- # V2 CHANGE START: Improved Base Style for better UX
38
  BASE_STYLE = '''
39
  :root {
40
  --primary: #ff4d6d; --secondary: #00ddeb; --accent: #8b5cf6;
@@ -64,7 +62,7 @@ input:focus, textarea:focus, select:focus { outline: none; box-shadow: 0 0 0 4px
64
  .folder-btn:hover { background: #e6a000; }
65
  .flash { color: var(--secondary); text-align: center; margin-bottom: 15px; padding: 10px; background: rgba(0, 221, 235, 0.1); border-radius: 10px; }
66
  .flash.error { color: var(--delete-color); background: rgba(255, 68, 68, 0.1); }
67
- .file-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(180px, 1fr)); gap: 20px; margin-top: 20px; }
68
  .item { background: var(--card-bg-dark); padding: 15px; border-radius: 16px; box-shadow: var(--shadow); text-align: center; transition: var(--transition); display: flex; flex-direction: column; justify-content: space-between; position: relative; border: 2px solid transparent; user-select: none; }
69
  .item.selected { border-color: var(--accent); background-color: var(--selection-color); transform: scale(1.02); }
70
  .item:hover { transform: translateY(-5px); }
@@ -76,6 +74,15 @@ input:focus, textarea:focus, select:focus { outline: none; box-shadow: 0 0 0 4px
76
  .item a:hover { color: var(--accent); }
77
  .item-actions { margin-top: 10px; display: flex; flex-wrap: wrap; gap: 5px; justify-content: center; opacity: 1; transition: var(--transition); }
78
  .selection-mode .item-actions { opacity: 0; pointer-events: none; }
 
 
 
 
 
 
 
 
 
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; }
@@ -85,21 +92,27 @@ input:focus, textarea:focus, select:focus { outline: none; box-shadow: 0 0 0 4px
85
  #progress-container { width: 100%; background: var(--glass-bg); border-radius: 10px; margin: 15px 0; display: none; position: relative; height: 20px; }
86
  #progress-bar { width: 0%; height: 100%; background: var(--primary); border-radius: 10px; transition: width 0.3s ease; }
87
  #progress-text { position: absolute; width: 100%; text-align: center; line-height: 20px; color: white; font-size: 0.9em; font-weight: bold; text-shadow: 1px 1px 1px rgba(0,0,0,0.5); }
88
- .breadcrumbs { margin-bottom: 20px; font-size: 1.1em; }
 
 
 
89
  .breadcrumbs a { color: var(--accent); text-decoration: none; }
90
  .breadcrumbs a:hover { text-decoration: underline; }
91
  .breadcrumbs span { margin: 0 5px; color: #aaa; }
92
  .folder-actions { margin-top: 20px; margin-bottom: 10px; display: flex; gap: 10px; align-items: center; flex-wrap: wrap; }
93
  .folder-actions input[type=text] { width: auto; flex-grow: 1; margin: 0; min-width: 150px; }
94
  .folder-actions .btn { margin: 0; flex-shrink: 0;}
 
 
95
  #selection-bar { position: fixed; bottom: -100px; left: 10px; right: 10px; background: var(--card-bg-dark); padding: 10px; border-radius: 15px; box-shadow: var(--shadow); z-index: 1000; display: flex; justify-content: space-around; align-items: center; transition: bottom 0.3s ease-in-out; }
96
  #selection-bar.visible { bottom: 10px; }
97
  #selection-bar .btn { margin: 0 5px; padding: 10px 15px; font-size: 0.9em; }
98
  #move-modal .modal-content { padding: 20px; }
99
  @media (max-width: 768px) {
100
- .file-grid { grid-template-columns: repeat(auto-fill, minmax(150px, 1fr)); }
101
  .item-preview { height: 100px; }
102
  .item.folder .item-preview { font-size: 50px; line-height: 100px; }
 
103
  }
104
  @media (max-width: 480px) {
105
  .container { padding: 15px; }
@@ -110,7 +123,6 @@ input:focus, textarea:focus, select:focus { outline: none; box-shadow: 0 0 0 4px
110
  #selection-bar .btn { width: 100%; }
111
  }
112
  '''
113
- # V2 CHANGE END
114
 
115
  def find_node_by_id(filesystem, node_id):
116
  if not filesystem: return None, None
@@ -140,8 +152,8 @@ def remove_node(filesystem, node_id):
140
  node_to_remove, parent_node = find_node_by_id(filesystem, node_id)
141
  if node_to_remove and parent_node and 'children' in parent_node:
142
  parent_node['children'] = [child for child in parent_node['children'] if child.get('id') != node_id]
143
- return True, node_to_remove # V2 CHANGE: Return the removed node
144
- return False, None # V2 CHANGE: Return None
145
 
146
  def get_node_path_string(filesystem, node_id):
147
  path_list = []
@@ -155,7 +167,6 @@ def get_node_path_string(filesystem, node_id):
155
  current_id = parent.get('id') if parent else None
156
  return " / ".join(reversed(path_list)) or "Root"
157
 
158
- # V2 CHANGE START: Function to get all folders for the 'move' modal
159
  def get_all_folders(filesystem, exclude_ids=None):
160
  if exclude_ids is None:
161
  exclude_ids = set()
@@ -163,7 +174,6 @@ def get_all_folders(filesystem, exclude_ids=None):
163
 
164
  def traverse(node, path_prefix):
165
  if node.get('type') == 'folder':
166
- # Don't allow moving into self or children
167
  if node.get('id') not in exclude_ids:
168
  folder_name = f"{path_prefix}{node.get('name', 'Unnamed')}" if path_prefix else (node.get('name') if node.get('id') != 'root' else 'Главная (Root)')
169
  folders.append({'id': node.get('id'), 'name': folder_name})
@@ -174,7 +184,6 @@ def get_all_folders(filesystem, exclude_ids=None):
174
 
175
  traverse(filesystem, "")
176
  return sorted(folders, key=lambda x: x['name'].lower())
177
- # V2 CHANGE END
178
 
179
  def initialize_user_filesystem_tma(user_data, tma_user_id_str):
180
  if 'filesystem' not in user_data:
@@ -364,7 +373,6 @@ def auth_via_telegram():
364
  logging.error(f"Error in auth_via_telegram: {e}")
365
  return jsonify({'status': 'error', 'message': 'Внутренняя ошибка сервера при авторизации.'}), 500
366
 
367
- # V2 CHANGE START: Heavily modified template for new UI and features
368
  TMA_DASHBOARD_HTML_TEMPLATE = '''
369
  <!DOCTYPE html><html lang="ru"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0">
370
  <title>Zeus Cloud</title>
@@ -376,12 +384,19 @@ TMA_DASHBOARD_HTML_TEMPLATE = '''
376
  {% with messages = get_flashed_messages(with_categories=true) %}{% if messages %}
377
  {% for category, message in messages %}<div class="flash {{ category }}">{{ message }}</div>{% endfor %}
378
  {% endif %}{% endwith %}
379
- <div class="breadcrumbs">
380
- {% for crumb in breadcrumbs %}
381
- {% if crumb.is_link %}<a href="{{ url_for('tma_dashboard', folder_id=crumb.id) }}">{{ crumb.name if crumb.id != 'root' else 'Главная' }}</a>
382
- {% else %}<span>{{ crumb.name if crumb.id != 'root' else 'Главная' }}</span>{% endif %}
383
- {% if not loop.last %}<span>/</span>{% endif %}
384
- {% endfor %}
 
 
 
 
 
 
 
385
  </div>
386
  <div class="folder-actions">
387
  <form method="POST" action="{{ url_for('create_folder_tma') }}" style="display: contents;">
@@ -389,6 +404,10 @@ TMA_DASHBOARD_HTML_TEMPLATE = '''
389
  <input type="text" name="folder_name" placeholder="Имя новой папки" required>
390
  <button type="submit" class="btn folder-btn"><i class="fa-solid fa-folder-plus"></i> Создать</button>
391
  </form>
 
 
 
 
392
  </div>
393
  <form id="upload-form" method="POST" enctype="multipart/form-data" action="{{ url_for('tma_dashboard') }}">
394
  <input type="hidden" name="current_folder_id" value="{{ current_folder_id }}">
@@ -397,12 +416,14 @@ TMA_DASHBOARD_HTML_TEMPLATE = '''
397
  </form>
398
  <div id="progress-container"><div id="progress-bar"></div><div id="progress-text">0%</div></div>
399
  <h2>Содержимое папки: {{ current_folder.name if current_folder_id != 'root' else 'Главная' }}</h2>
400
- <div class="file-grid">
401
  {% for item in items %}
402
  <div class="item {{ item.type }}" data-id="{{ item.id }}" data-type="{{ item.type }}">
403
  {% if item.type == 'folder' %}
404
  <a href="{{ url_for('tma_dashboard', folder_id=item.id) }}" class="item-preview" title="Перейти в папку {{ item.name }}"><i class="fa-solid fa-folder"></i></a>
405
- <p class="item-name">{{ item.name }}</p>
 
 
406
  <div class="item-actions">
407
  <a href="{{ url_for('tma_dashboard', folder_id=item.id) }}" class="btn folder-btn">Открыть</a>
408
  <form method="POST" action="{{ url_for('delete_folder_tma', folder_id=item.id) }}" style="display: inline;" onsubmit="return confirm('Удалить папку {{ item.name }}? Папку можно удалить только если она пуста.');">
@@ -417,8 +438,10 @@ TMA_DASHBOARD_HTML_TEMPLATE = '''
417
  {% elif item.file_type == 'pdf' %}<div class="item-preview" style="cursor: pointer;" onclick="openModal('{{ hf_file_url_jinja(item.path, True) }}', '{{ item.file_type }}', '{{ item.id }}')"><i class="fa-solid fa-file-pdf" style="font-size: 60px; line-height: 120px; color: var(--accent);"></i></div>
418
  {% elif item.file_type == 'text' %}<div class="item-preview" style="cursor: pointer;" onclick="openModal('{{ url_for('get_text_content_tma', file_id=item.id) }}', '{{ item.file_type }}', '{{ item.id }}')"><i class="fa-solid fa-file-lines" style="font-size: 60px; line-height: 120px; color: var(--secondary);"></i></div>
419
  {% else %}<div class="item-preview"><i class="fa-solid fa-file-circle-question" style="font-size: 60px; line-height: 120px; color: #aaa;"></i></div>{% endif %}
420
- <p class="item-name" title="{{ item.original_filename }}">{{ item.original_filename | truncate(25, True) }}</p>
421
- <p class="item-info">{{ item.upload_date }}</p>
 
 
422
  <div class="item-actions">
423
  <button type="button" class="btn download-btn" onclick="tmaDownloadFile('{{ url_for('download_tma', file_id=item.id, _external=True) }}', '{{ item.original_filename }}')">Скачать</button>
424
  {% if previewable %}<button type="button" class="btn" style="background: var(--accent);" onclick="openModal('{{ hf_file_url_jinja(item.path) if item.file_type != 'text' else url_for('get_text_content_tma', file_id=item.id) }}', '{{ item.file_type }}', '{{ item.id }}')">Просмотр</button>{% endif %}
@@ -492,10 +515,8 @@ TMA_DASHBOARD_HTML_TEMPLATE = '''
492
 
493
  function tmaDownloadFile(downloadUrl, filename) {
494
  if (window.Telegram && window.Telegram.WebApp && Telegram.WebApp.openLink) {
495
- console.log(`Attempting TMA download for: ${filename} via URL: ${downloadUrl}`);
496
  Telegram.WebApp.openLink(downloadUrl);
497
  } else {
498
- console.warn("Telegram.WebApp.openLink not available, or not in TMA environment. Attempting fallback download.");
499
  window.open(downloadUrl, '_blank');
500
  }
501
  }
@@ -524,7 +545,6 @@ TMA_DASHBOARD_HTML_TEMPLATE = '''
524
  });
525
  }
526
 
527
- // --- SELECTION LOGIC ---
528
  let selectionMode = false;
529
  const selectedItems = new Set();
530
  let longPressTimer;
@@ -551,7 +571,7 @@ TMA_DASHBOARD_HTML_TEMPLATE = '''
551
 
552
  allItems.forEach(item => {
553
  item.addEventListener('pointerdown', (e) => {
554
- if (e.pointerType === 'mouse' && e.button !== 0) return; // Only left click
555
  longPressTimer = setTimeout(() => {
556
  if (!selectionMode) toggleSelectionMode(true);
557
  item.classList.toggle('selected');
@@ -559,20 +579,15 @@ TMA_DASHBOARD_HTML_TEMPLATE = '''
559
  if (selectedItems.has(itemId)) selectedItems.delete(itemId);
560
  else selectedItems.add(itemId);
561
  updateSelectionCount();
562
- }, 500); // 500ms for long press
563
  });
564
 
565
- item.addEventListener('pointerup', () => {
566
- clearTimeout(longPressTimer);
567
- });
568
-
569
- item.addEventListener('pointerleave', () => {
570
- clearTimeout(longPressTimer);
571
- });
572
 
573
  item.addEventListener('click', (e) => {
574
  if (selectionMode) {
575
- e.preventDefault(); // Prevent navigation
576
  item.classList.toggle('selected');
577
  const itemId = item.dataset.id;
578
  if (selectedItems.has(itemId)) selectedItems.delete(itemId);
@@ -583,10 +598,9 @@ TMA_DASHBOARD_HTML_TEMPLATE = '''
583
  toggleSelectionMode(false);
584
  }
585
  }
586
- }, true); // Use capture to prevent link navigation in selection mode
587
  });
588
 
589
- // --- BATCH ACTIONS ---
590
  function showMoveModal() {
591
  if (selectedItems.size === 0) return;
592
  document.getElementById('move-modal').style.display = 'flex';
@@ -599,7 +613,6 @@ TMA_DASHBOARD_HTML_TEMPLATE = '''
599
  async function moveSelected() {
600
  const destinationId = document.getElementById('folder-destination-select').value;
601
  const itemIds = Array.from(selectedItems);
602
-
603
  try {
604
  const response = await fetch('{{ url_for("batch_move_tma") }}', {
605
  method: 'POST',
@@ -622,7 +635,6 @@ TMA_DASHBOARD_HTML_TEMPLATE = '''
622
 
623
  async function deleteSelected() {
624
  if (selectedItems.size === 0) return;
625
-
626
  Telegram.WebApp.showConfirm(`Вы уверены, что хотите удалить ${selectedItems.size} элемент(ов)?`, async (ok) => {
627
  if (ok) {
628
  try {
@@ -646,10 +658,34 @@ TMA_DASHBOARD_HTML_TEMPLATE = '''
646
  });
647
  }
648
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
649
  document.getElementById('logout-btn').addEventListener('click', function(e) { e.preventDefault(); window.location.href = "{{ url_for('tma_logout') }}"; });
650
  </script></body></html>
651
  '''
652
- # V2 CHANGE END
653
 
654
  @app.route('/tma_dashboard', methods=['GET', 'POST'])
655
  def tma_dashboard():
@@ -670,17 +706,18 @@ def tma_dashboard():
670
  initialize_user_filesystem_tma(user_data, tma_user_id)
671
 
672
  current_folder_id = request.args.get('folder_id', 'root')
673
- current_folder, _ = find_node_by_id(user_data['filesystem'], current_folder_id)
674
 
675
  if not current_folder or current_folder.get('type') != 'folder':
676
  flash('Папка не найдена!', 'error')
677
  current_folder_id = 'root'
678
- current_folder, _ = find_node_by_id(user_data['filesystem'], current_folder_id)
679
  if not current_folder:
680
  flash('Критическая ошибка: корневая папка не найдена.', 'error')
681
  session.clear()
682
  return redirect(url_for('tma_entry_page'))
683
 
 
684
  items_in_folder = sorted(current_folder.get('children', []), key=lambda x: (x['type'] != 'folder', x.get('name', x.get('original_filename', '')).lower()))
685
 
686
  if request.method == 'POST':
@@ -758,12 +795,12 @@ def tma_dashboard():
758
  temp_id = parent_node_bc.get('id')
759
  breadcrumbs.reverse()
760
 
761
- # V2 CHANGE: Get all folders for the move modal
762
  all_folders_for_move = get_all_folders(user_data['filesystem'])
763
 
764
  return render_template_string(TMA_DASHBOARD_HTML_TEMPLATE,
765
  display_name=display_name, items=items_in_folder,
766
  current_folder_id=current_folder_id, current_folder=current_folder,
 
767
  breadcrumbs=breadcrumbs, repo_id_js=REPO_ID, HF_TOKEN_READ_js=HF_TOKEN_READ,
768
  hf_file_url_jinja=lambda path, download=False: f"https://huggingface.co/datasets/{REPO_ID}/resolve/main/{path}{'?download=true' if download else ''}",
769
  is_tma_user_admin_flag=is_admin_tma(), all_folders_for_move=all_folders_for_move)
@@ -873,11 +910,8 @@ def download_tma(file_id):
873
 
874
  resp = Response(generate_chunks(), mimetype=mimetype)
875
 
876
- # V2 CHANGE START: iOS Download Fix - properly encode filename
877
- # This helps iOS Webview correctly interpret filenames with spaces or non-latin characters.
878
  encoded_filename = quote(original_filename)
879
  resp.headers['Content-Disposition'] = f"attachment; filename*=UTF-8''{encoded_filename}"
880
- # V2 CHANGE END
881
 
882
  resp.headers['Cache-Control'] = 'no-cache, no-store, must-revalidate'
883
  resp.headers['Pragma'] = 'no-cache'
@@ -966,7 +1000,6 @@ def delete_folder_tma(folder_id):
966
  else: flash('Не удалось удалить папку.', 'error')
967
  return redirect(url_for('tma_dashboard', folder_id=parent_node.get('id', 'root')))
968
 
969
- # V2 CHANGE START: New endpoints for batch operations
970
  @app.route('/batch_delete_tma', methods=['POST'])
971
  def batch_delete_tma():
972
  if 'telegram_user_id' not in session:
@@ -1051,7 +1084,6 @@ def batch_move_tma():
1051
  if not destination_node or destination_node.get('type') != 'folder':
1052
  return jsonify({'status': 'error', 'message': 'Папка назначения не найдена.'}), 404
1053
 
1054
- # Prevent moving a folder into itself or its children
1055
  descendant_ids = set()
1056
  for item_id in item_ids:
1057
  node, _ = find_node_by_id(user_data['filesystem'], item_id)
@@ -1080,7 +1112,6 @@ def batch_move_tma():
1080
  moved_count += 1
1081
  else:
1082
  errors.append(f'Ошибка при добавлении элемента {item_id} в новую папку.')
1083
- # Re-add node to original parent? For simplicity, we don't.
1084
  else:
1085
  errors.append(f'Не удалось найти или извлечь элемент {item_id} для перемещения.')
1086
 
@@ -1094,7 +1125,6 @@ def batch_move_tma():
1094
  return jsonify({'status': 'error', 'message': f'Перемещено {moved_count} элемент(ов). Ошибки: ' + "; ".join(errors)})
1095
 
1096
  return jsonify({'status': 'success', 'message': f'Успешно перемещено {moved_count} элемент(ов).'})
1097
- # V2 CHANGE END
1098
 
1099
  @app.route('/get_text_content_tma/<file_id>')
1100
  def get_text_content_tma(file_id):
@@ -1145,9 +1175,6 @@ def tma_logout():
1145
  flash('Вы вышли из сессии приложения.')
1146
  return redirect(url_for('tma_entry_page'))
1147
 
1148
-
1149
- # --- Admin Panel (no changes below this line, but included for completeness) ---
1150
-
1151
  ADMIN_LOGIN_HTML_TEMPLATE = '''
1152
  <!DOCTYPE html><html lang="ru"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0">
1153
  <title>Admin Login</title><link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600;800&display=swap" rel="stylesheet">
@@ -1400,7 +1427,6 @@ if __name__ == '__main__':
1400
  if ADMIN_USERNAME == "admin" and ADMIN_PASSWORD == "zeusadminpass":
1401
  logging.warning("Using default admin username/password for browser admin panel. Please change ADMIN_USERNAME and ADMIN_PASSWORD environment variables.")
1402
 
1403
-
1404
  if HF_TOKEN_WRITE:
1405
  download_db_from_hf()
1406
  threading.Thread(target=periodic_backup, daemon=True).start()
 
13
  from io import BytesIO
14
  import uuid
15
  from functools import wraps
16
+ from urllib.parse import quote
17
 
18
  app = Flask(__name__)
19
  app.secret_key = os.getenv("FLASK_SECRET_KEY", "supersecretkey_folders_unique_tma")
 
27
  ADMIN_USERNAME = os.getenv("ADMIN_USERNAME", "admin")
28
  ADMIN_PASSWORD = os.getenv("ADMIN_PASSWORD", "zeusadminpass")
29
 
 
30
  UPLOAD_FOLDER = 'uploads_tma'
31
  os.makedirs(UPLOAD_FOLDER, exist_ok=True)
32
 
33
  cache = Cache(app, config={'CACHE_TYPE': 'simple'})
34
  logging.basicConfig(level=logging.INFO)
35
 
 
36
  BASE_STYLE = '''
37
  :root {
38
  --primary: #ff4d6d; --secondary: #00ddeb; --accent: #8b5cf6;
 
62
  .folder-btn:hover { background: #e6a000; }
63
  .flash { color: var(--secondary); text-align: center; margin-bottom: 15px; padding: 10px; background: rgba(0, 221, 235, 0.1); border-radius: 10px; }
64
  .flash.error { color: var(--delete-color); background: rgba(255, 68, 68, 0.1); }
65
+ .file-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(160px, 1fr)); gap: 20px; margin-top: 20px; }
66
  .item { background: var(--card-bg-dark); padding: 15px; border-radius: 16px; box-shadow: var(--shadow); text-align: center; transition: var(--transition); display: flex; flex-direction: column; justify-content: space-between; position: relative; border: 2px solid transparent; user-select: none; }
67
  .item.selected { border-color: var(--accent); background-color: var(--selection-color); transform: scale(1.02); }
68
  .item:hover { transform: translateY(-5px); }
 
74
  .item a:hover { color: var(--accent); }
75
  .item-actions { margin-top: 10px; display: flex; flex-wrap: wrap; gap: 5px; justify-content: center; opacity: 1; transition: var(--transition); }
76
  .selection-mode .item-actions { opacity: 0; pointer-events: none; }
77
+ .file-grid.list-view { display: flex; flex-direction: column; gap: 10px; }
78
+ .file-grid.list-view .item { flex-direction: row; align-items: center; text-align: left; padding: 10px; }
79
+ .file-grid.list-view .item-preview { width: 50px; height: 50px; margin-bottom: 0; margin-right: 15px; flex-shrink: 0; }
80
+ .file-grid.list-view .item.folder .item-preview { font-size: 30px; line-height: 50px; }
81
+ .file-grid.list-view .item-name-info { flex-grow: 1; }
82
+ .file-grid.list-view .item-name { margin: 0; }
83
+ .file-grid.list-view .item-info { margin-top: 2px; }
84
+ .file-grid.list-view .item-actions { margin-left: 15px; flex-shrink: 0; }
85
+ .file-grid.list-view .item-actions .btn { padding: 5px 10px; font-size: 0.9em; }
86
  .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; }
87
  .modal-content { max-width: 95%; max-height: 95%; background: var(--card-bg-dark); padding: 10px; border-radius: 15px; overflow: auto; position: relative; }
88
  .modal img, .modal video, .modal iframe, .modal pre { max-width: 100%; max-height: 85vh; display: block; margin: auto; border-radius: 10px; }
 
92
  #progress-container { width: 100%; background: var(--glass-bg); border-radius: 10px; margin: 15px 0; display: none; position: relative; height: 20px; }
93
  #progress-bar { width: 0%; height: 100%; background: var(--primary); border-radius: 10px; transition: width 0.3s ease; }
94
  #progress-text { position: absolute; width: 100%; text-align: center; line-height: 20px; color: white; font-size: 0.9em; font-weight: bold; text-shadow: 1px 1px 1px rgba(0,0,0,0.5); }
95
+ .navigation-controls { display: flex; align-items: center; gap: 15px; margin-bottom: 20px; }
96
+ .back-btn { font-size: 1.8em; color: var(--accent); text-decoration: none; transition: var(--transition); }
97
+ .back-btn:hover { transform: scale(1.2); color: var(--primary); }
98
+ .breadcrumbs { font-size: 1.1em; }
99
  .breadcrumbs a { color: var(--accent); text-decoration: none; }
100
  .breadcrumbs a:hover { text-decoration: underline; }
101
  .breadcrumbs span { margin: 0 5px; color: #aaa; }
102
  .folder-actions { margin-top: 20px; margin-bottom: 10px; display: flex; gap: 10px; align-items: center; flex-wrap: wrap; }
103
  .folder-actions input[type=text] { width: auto; flex-grow: 1; margin: 0; min-width: 150px; }
104
  .folder-actions .btn { margin: 0; flex-shrink: 0;}
105
+ .view-toggle button { background: var(--glass-bg); color: var(--text-dark); border: 2px solid var(--accent); padding: 8px 12px; border-radius: 10px; cursor: pointer; }
106
+ .view-toggle button.active { background: var(--accent); color: white; }
107
  #selection-bar { position: fixed; bottom: -100px; left: 10px; right: 10px; background: var(--card-bg-dark); padding: 10px; border-radius: 15px; box-shadow: var(--shadow); z-index: 1000; display: flex; justify-content: space-around; align-items: center; transition: bottom 0.3s ease-in-out; }
108
  #selection-bar.visible { bottom: 10px; }
109
  #selection-bar .btn { margin: 0 5px; padding: 10px 15px; font-size: 0.9em; }
110
  #move-modal .modal-content { padding: 20px; }
111
  @media (max-width: 768px) {
112
+ .file-grid { grid-template-columns: repeat(auto-fill, minmax(140px, 1fr)); }
113
  .item-preview { height: 100px; }
114
  .item.folder .item-preview { font-size: 50px; line-height: 100px; }
115
+ .file-grid.list-view .item-actions { display: none; }
116
  }
117
  @media (max-width: 480px) {
118
  .container { padding: 15px; }
 
123
  #selection-bar .btn { width: 100%; }
124
  }
125
  '''
 
126
 
127
  def find_node_by_id(filesystem, node_id):
128
  if not filesystem: return None, None
 
152
  node_to_remove, parent_node = find_node_by_id(filesystem, node_id)
153
  if node_to_remove and parent_node and 'children' in parent_node:
154
  parent_node['children'] = [child for child in parent_node['children'] if child.get('id') != node_id]
155
+ return True, node_to_remove
156
+ return False, None
157
 
158
  def get_node_path_string(filesystem, node_id):
159
  path_list = []
 
167
  current_id = parent.get('id') if parent else None
168
  return " / ".join(reversed(path_list)) or "Root"
169
 
 
170
  def get_all_folders(filesystem, exclude_ids=None):
171
  if exclude_ids is None:
172
  exclude_ids = set()
 
174
 
175
  def traverse(node, path_prefix):
176
  if node.get('type') == 'folder':
 
177
  if node.get('id') not in exclude_ids:
178
  folder_name = f"{path_prefix}{node.get('name', 'Unnamed')}" if path_prefix else (node.get('name') if node.get('id') != 'root' else 'Главная (Root)')
179
  folders.append({'id': node.get('id'), 'name': folder_name})
 
184
 
185
  traverse(filesystem, "")
186
  return sorted(folders, key=lambda x: x['name'].lower())
 
187
 
188
  def initialize_user_filesystem_tma(user_data, tma_user_id_str):
189
  if 'filesystem' not in user_data:
 
373
  logging.error(f"Error in auth_via_telegram: {e}")
374
  return jsonify({'status': 'error', 'message': 'Внутренняя ошибка сервера при авторизации.'}), 500
375
 
 
376
  TMA_DASHBOARD_HTML_TEMPLATE = '''
377
  <!DOCTYPE html><html lang="ru"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0">
378
  <title>Zeus Cloud</title>
 
384
  {% with messages = get_flashed_messages(with_categories=true) %}{% if messages %}
385
  {% for category, message in messages %}<div class="flash {{ category }}">{{ message }}</div>{% endfor %}
386
  {% endif %}{% endwith %}
387
+ <div class="navigation-controls">
388
+ {% if parent_folder_id %}
389
+ <a href="{{ url_for('tma_dashboard', folder_id=parent_folder_id) }}" class="back-btn" title="На уровень выше">
390
+ <i class="fa-solid fa-arrow-left"></i>
391
+ </a>
392
+ {% endif %}
393
+ <div class="breadcrumbs">
394
+ {% for crumb in breadcrumbs %}
395
+ {% if crumb.is_link %}<a href="{{ url_for('tma_dashboard', folder_id=crumb.id) }}">{{ crumb.name if crumb.id != 'root' else 'Главная' }}</a>
396
+ {% else %}<span>{{ crumb.name if crumb.id != 'root' else 'Главная' }}</span>{% endif %}
397
+ {% if not loop.last %}<span>/</span>{% endif %}
398
+ {% endfor %}
399
+ </div>
400
  </div>
401
  <div class="folder-actions">
402
  <form method="POST" action="{{ url_for('create_folder_tma') }}" style="display: contents;">
 
404
  <input type="text" name="folder_name" placeholder="Имя новой папки" required>
405
  <button type="submit" class="btn folder-btn"><i class="fa-solid fa-folder-plus"></i> Создать</button>
406
  </form>
407
+ <div class="view-toggle" style="margin-left: auto;">
408
+ <button id="grid-view-btn" title="Сетка"><i class="fa fa-th-large"></i></button>
409
+ <button id="list-view-btn" title="Список"><i class="fa fa-bars"></i></button>
410
+ </div>
411
  </div>
412
  <form id="upload-form" method="POST" enctype="multipart/form-data" action="{{ url_for('tma_dashboard') }}">
413
  <input type="hidden" name="current_folder_id" value="{{ current_folder_id }}">
 
416
  </form>
417
  <div id="progress-container"><div id="progress-bar"></div><div id="progress-text">0%</div></div>
418
  <h2>Содержимое папки: {{ current_folder.name if current_folder_id != 'root' else 'Главная' }}</h2>
419
+ <div class="file-grid" id="file-container">
420
  {% for item in items %}
421
  <div class="item {{ item.type }}" data-id="{{ item.id }}" data-type="{{ item.type }}">
422
  {% if item.type == 'folder' %}
423
  <a href="{{ url_for('tma_dashboard', folder_id=item.id) }}" class="item-preview" title="Перейти в папку {{ item.name }}"><i class="fa-solid fa-folder"></i></a>
424
+ <div class="item-name-info">
425
+ <p class="item-name">{{ item.name }}</p>
426
+ </div>
427
  <div class="item-actions">
428
  <a href="{{ url_for('tma_dashboard', folder_id=item.id) }}" class="btn folder-btn">Открыть</a>
429
  <form method="POST" action="{{ url_for('delete_folder_tma', folder_id=item.id) }}" style="display: inline;" onsubmit="return confirm('Удалить папку {{ item.name }}? Папку можно удалить только если она пуста.');">
 
438
  {% elif item.file_type == 'pdf' %}<div class="item-preview" style="cursor: pointer;" onclick="openModal('{{ hf_file_url_jinja(item.path, True) }}', '{{ item.file_type }}', '{{ item.id }}')"><i class="fa-solid fa-file-pdf" style="font-size: 60px; line-height: 120px; color: var(--accent);"></i></div>
439
  {% elif item.file_type == 'text' %}<div class="item-preview" style="cursor: pointer;" onclick="openModal('{{ url_for('get_text_content_tma', file_id=item.id) }}', '{{ item.file_type }}', '{{ item.id }}')"><i class="fa-solid fa-file-lines" style="font-size: 60px; line-height: 120px; color: var(--secondary);"></i></div>
440
  {% else %}<div class="item-preview"><i class="fa-solid fa-file-circle-question" style="font-size: 60px; line-height: 120px; color: #aaa;"></i></div>{% endif %}
441
+ <div class="item-name-info">
442
+ <p class="item-name" title="{{ item.original_filename }}">{{ item.original_filename | truncate(25, True) }}</p>
443
+ <p class="item-info">{{ item.upload_date }}</p>
444
+ </div>
445
  <div class="item-actions">
446
  <button type="button" class="btn download-btn" onclick="tmaDownloadFile('{{ url_for('download_tma', file_id=item.id, _external=True) }}', '{{ item.original_filename }}')">Скачать</button>
447
  {% if previewable %}<button type="button" class="btn" style="background: var(--accent);" onclick="openModal('{{ hf_file_url_jinja(item.path) if item.file_type != 'text' else url_for('get_text_content_tma', file_id=item.id) }}', '{{ item.file_type }}', '{{ item.id }}')">Просмотр</button>{% endif %}
 
515
 
516
  function tmaDownloadFile(downloadUrl, filename) {
517
  if (window.Telegram && window.Telegram.WebApp && Telegram.WebApp.openLink) {
 
518
  Telegram.WebApp.openLink(downloadUrl);
519
  } else {
 
520
  window.open(downloadUrl, '_blank');
521
  }
522
  }
 
545
  });
546
  }
547
 
 
548
  let selectionMode = false;
549
  const selectedItems = new Set();
550
  let longPressTimer;
 
571
 
572
  allItems.forEach(item => {
573
  item.addEventListener('pointerdown', (e) => {
574
+ if (e.pointerType === 'mouse' && e.button !== 0) return;
575
  longPressTimer = setTimeout(() => {
576
  if (!selectionMode) toggleSelectionMode(true);
577
  item.classList.toggle('selected');
 
579
  if (selectedItems.has(itemId)) selectedItems.delete(itemId);
580
  else selectedItems.add(itemId);
581
  updateSelectionCount();
582
+ }, 500);
583
  });
584
 
585
+ item.addEventListener('pointerup', () => { clearTimeout(longPressTimer); });
586
+ item.addEventListener('pointerleave', () => { clearTimeout(longPressTimer); });
 
 
 
 
 
587
 
588
  item.addEventListener('click', (e) => {
589
  if (selectionMode) {
590
+ e.preventDefault();
591
  item.classList.toggle('selected');
592
  const itemId = item.dataset.id;
593
  if (selectedItems.has(itemId)) selectedItems.delete(itemId);
 
598
  toggleSelectionMode(false);
599
  }
600
  }
601
+ }, true);
602
  });
603
 
 
604
  function showMoveModal() {
605
  if (selectedItems.size === 0) return;
606
  document.getElementById('move-modal').style.display = 'flex';
 
613
  async function moveSelected() {
614
  const destinationId = document.getElementById('folder-destination-select').value;
615
  const itemIds = Array.from(selectedItems);
 
616
  try {
617
  const response = await fetch('{{ url_for("batch_move_tma") }}', {
618
  method: 'POST',
 
635
 
636
  async function deleteSelected() {
637
  if (selectedItems.size === 0) return;
 
638
  Telegram.WebApp.showConfirm(`Вы уверены, что хотите удалить ${selectedItems.size} элемент(ов)?`, async (ok) => {
639
  if (ok) {
640
  try {
 
658
  });
659
  }
660
 
661
+ const gridViewBtn = document.getElementById('grid-view-btn');
662
+ const listViewBtn = document.getElementById('list-view-btn');
663
+ const fileContainer = document.getElementById('file-container');
664
+
665
+ function setView(view) {
666
+ if (view === 'list') {
667
+ fileContainer.classList.add('list-view');
668
+ listViewBtn.classList.add('active');
669
+ gridViewBtn.classList.remove('active');
670
+ } else {
671
+ fileContainer.classList.remove('list-view');
672
+ gridViewBtn.classList.add('active');
673
+ listViewBtn.classList.remove('active');
674
+ }
675
+ localStorage.setItem('viewMode', view);
676
+ }
677
+
678
+ gridViewBtn.addEventListener('click', () => setView('grid'));
679
+ listViewBtn.addEventListener('click', () => setView('list'));
680
+
681
+ document.addEventListener('DOMContentLoaded', () => {
682
+ const savedView = localStorage.getItem('viewMode') || 'grid';
683
+ setView(savedView);
684
+ });
685
+
686
  document.getElementById('logout-btn').addEventListener('click', function(e) { e.preventDefault(); window.location.href = "{{ url_for('tma_logout') }}"; });
687
  </script></body></html>
688
  '''
 
689
 
690
  @app.route('/tma_dashboard', methods=['GET', 'POST'])
691
  def tma_dashboard():
 
706
  initialize_user_filesystem_tma(user_data, tma_user_id)
707
 
708
  current_folder_id = request.args.get('folder_id', 'root')
709
+ current_folder, parent_folder = find_node_by_id(user_data['filesystem'], current_folder_id)
710
 
711
  if not current_folder or current_folder.get('type') != 'folder':
712
  flash('Папка не найдена!', 'error')
713
  current_folder_id = 'root'
714
+ current_folder, parent_folder = find_node_by_id(user_data['filesystem'], current_folder_id)
715
  if not current_folder:
716
  flash('Критическая ошибка: корневая папка не найдена.', 'error')
717
  session.clear()
718
  return redirect(url_for('tma_entry_page'))
719
 
720
+ parent_folder_id = parent_folder.get('id') if parent_folder else None
721
  items_in_folder = sorted(current_folder.get('children', []), key=lambda x: (x['type'] != 'folder', x.get('name', x.get('original_filename', '')).lower()))
722
 
723
  if request.method == 'POST':
 
795
  temp_id = parent_node_bc.get('id')
796
  breadcrumbs.reverse()
797
 
 
798
  all_folders_for_move = get_all_folders(user_data['filesystem'])
799
 
800
  return render_template_string(TMA_DASHBOARD_HTML_TEMPLATE,
801
  display_name=display_name, items=items_in_folder,
802
  current_folder_id=current_folder_id, current_folder=current_folder,
803
+ parent_folder_id=parent_folder_id,
804
  breadcrumbs=breadcrumbs, repo_id_js=REPO_ID, HF_TOKEN_READ_js=HF_TOKEN_READ,
805
  hf_file_url_jinja=lambda path, download=False: f"https://huggingface.co/datasets/{REPO_ID}/resolve/main/{path}{'?download=true' if download else ''}",
806
  is_tma_user_admin_flag=is_admin_tma(), all_folders_for_move=all_folders_for_move)
 
910
 
911
  resp = Response(generate_chunks(), mimetype=mimetype)
912
 
 
 
913
  encoded_filename = quote(original_filename)
914
  resp.headers['Content-Disposition'] = f"attachment; filename*=UTF-8''{encoded_filename}"
 
915
 
916
  resp.headers['Cache-Control'] = 'no-cache, no-store, must-revalidate'
917
  resp.headers['Pragma'] = 'no-cache'
 
1000
  else: flash('Не удалось удалить папку.', 'error')
1001
  return redirect(url_for('tma_dashboard', folder_id=parent_node.get('id', 'root')))
1002
 
 
1003
  @app.route('/batch_delete_tma', methods=['POST'])
1004
  def batch_delete_tma():
1005
  if 'telegram_user_id' not in session:
 
1084
  if not destination_node or destination_node.get('type') != 'folder':
1085
  return jsonify({'status': 'error', 'message': 'Папка назначения не найдена.'}), 404
1086
 
 
1087
  descendant_ids = set()
1088
  for item_id in item_ids:
1089
  node, _ = find_node_by_id(user_data['filesystem'], item_id)
 
1112
  moved_count += 1
1113
  else:
1114
  errors.append(f'Ошибка при добавлении элемента {item_id} в новую папку.')
 
1115
  else:
1116
  errors.append(f'Не удалось найти или извлечь элемент {item_id} для перемещения.')
1117
 
 
1125
  return jsonify({'status': 'error', 'message': f'Перемещено {moved_count} элемент(ов). Ошибки: ' + "; ".join(errors)})
1126
 
1127
  return jsonify({'status': 'success', 'message': f'Успешно перемещено {moved_count} элемент(ов).'})
 
1128
 
1129
  @app.route('/get_text_content_tma/<file_id>')
1130
  def get_text_content_tma(file_id):
 
1175
  flash('Вы вышли из сессии приложения.')
1176
  return redirect(url_for('tma_entry_page'))
1177
 
 
 
 
1178
  ADMIN_LOGIN_HTML_TEMPLATE = '''
1179
  <!DOCTYPE html><html lang="ru"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0">
1180
  <title>Admin Login</title><link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600;800&display=swap" rel="stylesheet">
 
1427
  if ADMIN_USERNAME == "admin" and ADMIN_PASSWORD == "zeusadminpass":
1428
  logging.warning("Using default admin username/password for browser admin panel. Please change ADMIN_USERNAME and ADMIN_PASSWORD environment variables.")
1429
 
 
1430
  if HF_TOKEN_WRITE:
1431
  download_db_from_hf()
1432
  threading.Thread(target=periodic_backup, daemon=True).start()