Update app.py
Browse files
app.py
CHANGED
|
@@ -13,6 +13,7 @@ import requests
|
|
| 13 |
from io import BytesIO
|
| 14 |
import uuid
|
| 15 |
from functools import wraps
|
|
|
|
| 16 |
|
| 17 |
app = Flask(__name__)
|
| 18 |
app.secret_key = os.getenv("FLASK_SECRET_KEY", "supersecretkey_folders_unique_tma")
|
|
@@ -33,29 +34,26 @@ os.makedirs(UPLOAD_FOLDER, exist_ok=True)
|
|
| 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;
|
| 39 |
--background-light: #f5f6fa; --background-dark: #1a1625;
|
| 40 |
--card-bg: rgba(255, 255, 255, 0.95); --card-bg-dark: rgba(40, 35, 60, 0.95);
|
| 41 |
-
--text-light: #2a1e5a; --text-dark: #e8e1ff; --shadow: 0 10px 30px rgba(0, 0, 0, 0.
|
| 42 |
--glass-bg: rgba(255, 255, 255, 0.15); --transition: all 0.3s ease; --delete-color: #ff4444;
|
| 43 |
-
--folder-color: #ffc107;
|
| 44 |
}
|
| 45 |
* { margin: 0; padding: 0; box-sizing: border-box; }
|
| 46 |
-
body { font-family: 'Inter', sans-serif; background: var(--background-
|
| 47 |
-
|
| 48 |
-
.container { margin: 20px auto; max-width: 1200px; padding: 25px; background: var(--card-bg); border-radius: 20px; box-shadow: var(--shadow); overflow-x: hidden; }
|
| 49 |
-
body.dark .container { background: var(--card-bg-dark); }
|
| 50 |
h1 { font-size: 2em; font-weight: 800; text-align: center; margin-bottom: 25px; background: linear-gradient(135deg, var(--primary), var(--accent)); -webkit-background-clip: text; color: transparent; }
|
| 51 |
-
h2 { font-size: 1.5em; margin-top: 30px; color: var(--text-
|
| 52 |
-
body.dark h2 { color: var(--text-dark); }
|
| 53 |
h4 { font-size: 1.1em; margin-top: 15px; margin-bottom: 5px; color: var(--accent); }
|
| 54 |
ol, ul { margin-left: 20px; margin-bottom: 15px; }
|
| 55 |
li { margin-bottom: 5px; }
|
| 56 |
-
input, textarea, input[type="text"], input[type="password"], input[type="file"] { width: 100%; padding: 14px; margin: 12px 0; border: none; border-radius: 14px; background:
|
| 57 |
-
|
| 58 |
-
input:focus, textarea:focus { outline: none; box-shadow: 0 0 0 4px var(--primary); }
|
| 59 |
.btn { padding: 14px 28px; background: var(--primary); color: white; border: none; border-radius: 14px; cursor: pointer; font-size: 1.1em; font-weight: 600; transition: var(--transition); box-shadow: var(--shadow); display: inline-block; text-decoration: none; margin-top: 5px; margin-right: 5px; }
|
| 60 |
.btn:hover { transform: scale(1.05); background: #e6415f; }
|
| 61 |
.download-btn { background: var(--secondary); }
|
|
@@ -66,32 +64,24 @@ input:focus, textarea:focus { outline: none; box-shadow: 0 0 0 4px var(--primary
|
|
| 66 |
.folder-btn:hover { background: #e6a000; }
|
| 67 |
.flash { color: var(--secondary); text-align: center; margin-bottom: 15px; padding: 10px; background: rgba(0, 221, 235, 0.1); border-radius: 10px; }
|
| 68 |
.flash.error { color: var(--delete-color); background: rgba(255, 68, 68, 0.1); }
|
| 69 |
-
.file-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(
|
| 70 |
-
.
|
| 71 |
-
.
|
| 72 |
-
body.dark .user-item { background: var(--card-bg-dark); }
|
| 73 |
-
.user-item:hover { transform: translateY(-5px); }
|
| 74 |
-
.user-item a { color: var(--primary); text-decoration: none; font-weight: 600; }
|
| 75 |
-
.user-item a:hover { color: var(--accent); }
|
| 76 |
-
.item { background: var(--card-bg); padding: 15px; border-radius: 16px; box-shadow: var(--shadow); text-align: center; transition: var(--transition); display: flex; flex-direction: column; justify-content: space-between; }
|
| 77 |
-
body.dark .item { background: var(--card-bg-dark); }
|
| 78 |
.item:hover { transform: translateY(-5px); }
|
| 79 |
-
.item-preview {
|
| 80 |
-
.item.folder .item-preview { object-fit: contain; font-size: 60px; color: var(--folder-color); line-height:
|
| 81 |
-
.item
|
|
|
|
| 82 |
.item a { color: var(--primary); text-decoration: none; }
|
| 83 |
.item a:hover { color: var(--accent); }
|
| 84 |
-
.item-actions { margin-top: 10px; display: flex; flex-wrap: wrap; gap: 5px; justify-content: center; }
|
| 85 |
-
.item-actions
|
| 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:
|
| 88 |
-
body.dark .modal-content { background: var(--card-bg-dark); }
|
| 89 |
.modal img, .modal video, .modal iframe, .modal pre { max-width: 100%; max-height: 85vh; display: block; margin: auto; border-radius: 10px; }
|
| 90 |
.modal iframe { width: 80vw; height: 85vh; border: none; }
|
| 91 |
-
.modal pre { background: #
|
| 92 |
-
body.dark .modal pre { background: #2b2a33; color: var(--text-dark); }
|
| 93 |
.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; }
|
| 94 |
-
body.dark .modal-close-btn { color: #555; background: rgba(255,255,255,0.2); }
|
| 95 |
#progress-container { width: 100%; background: var(--glass-bg); border-radius: 10px; margin: 15px 0; display: none; position: relative; height: 20px; }
|
| 96 |
#progress-bar { width: 0%; height: 100%; background: var(--primary); border-radius: 10px; transition: width 0.3s ease; }
|
| 97 |
#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); }
|
|
@@ -102,26 +92,25 @@ body.dark .modal-close-btn { color: #555; background: rgba(255,255,255,0.2); }
|
|
| 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 |
@media (max-width: 768px) {
|
| 106 |
.file-grid { grid-template-columns: repeat(auto-fill, minmax(150px, 1fr)); }
|
| 107 |
-
.folder-actions { flex-direction: column; align-items: stretch; }
|
| 108 |
-
.folder-actions input[type=text] { width: 100%; }
|
| 109 |
.item-preview { height: 100px; }
|
| 110 |
.item.folder .item-preview { font-size: 50px; line-height: 100px; }
|
| 111 |
-
h1 { font-size: 1.8em; }
|
| 112 |
-
.btn { padding: 12px 24px; font-size: 1em; }
|
| 113 |
-
.item-actions .btn { padding: 4px 8px; font-size: 0.8em;}
|
| 114 |
}
|
| 115 |
@media (max-width: 480px) {
|
| 116 |
.container { padding: 15px; }
|
| 117 |
-
.file-grid { grid-template-columns: repeat(
|
| 118 |
.item-preview { height: 80px; }
|
| 119 |
.item.folder .item-preview { font-size: 40px; line-height: 80px; }
|
| 120 |
-
|
| 121 |
-
.
|
| 122 |
-
.btn { padding: 10px 20px; }
|
| 123 |
}
|
| 124 |
'''
|
|
|
|
| 125 |
|
| 126 |
def find_node_by_id(filesystem, node_id):
|
| 127 |
if not filesystem: return None, None
|
|
@@ -151,8 +140,8 @@ def remove_node(filesystem, node_id):
|
|
| 151 |
node_to_remove, parent_node = find_node_by_id(filesystem, node_id)
|
| 152 |
if node_to_remove and parent_node and 'children' in parent_node:
|
| 153 |
parent_node['children'] = [child for child in parent_node['children'] if child.get('id') != node_id]
|
| 154 |
-
return True
|
| 155 |
-
return False
|
| 156 |
|
| 157 |
def get_node_path_string(filesystem, node_id):
|
| 158 |
path_list = []
|
|
@@ -166,6 +155,27 @@ def get_node_path_string(filesystem, node_id):
|
|
| 166 |
current_id = parent.get('id') if parent else None
|
| 167 |
return " / ".join(reversed(path_list)) or "Root"
|
| 168 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 169 |
def initialize_user_filesystem_tma(user_data, tma_user_id_str):
|
| 170 |
if 'filesystem' not in user_data:
|
| 171 |
user_data['filesystem'] = {
|
|
@@ -354,11 +364,14 @@ def auth_via_telegram():
|
|
| 354 |
logging.error(f"Error in auth_via_telegram: {e}")
|
| 355 |
return jsonify({'status': 'error', 'message': 'Внутренняя ошибка сервера при авторизации.'}), 500
|
| 356 |
|
|
|
|
| 357 |
TMA_DASHBOARD_HTML_TEMPLATE = '''
|
| 358 |
<!DOCTYPE html><html lang="ru"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0">
|
| 359 |
-
<title>Zeus Cloud</title>
|
|
|
|
|
|
|
| 360 |
<script src="https://telegram.org/js/telegram-web-app.js"></script>
|
| 361 |
-
<style>''' + BASE_STYLE + '''</style></head><body class="
|
| 362 |
<h1>Zeus Cloud</h1><p>Пользователь: {{ display_name }}</p>
|
| 363 |
{% with messages = get_flashed_messages(with_categories=true) %}{% if messages %}
|
| 364 |
{% for category, message in messages %}<div class="flash {{ category }}">{{ message }}</div>{% endfor %}
|
|
@@ -374,22 +387,22 @@ TMA_DASHBOARD_HTML_TEMPLATE = '''
|
|
| 374 |
<form method="POST" action="{{ url_for('create_folder_tma') }}" style="display: contents;">
|
| 375 |
<input type="hidden" name="parent_folder_id" value="{{ current_folder_id }}">
|
| 376 |
<input type="text" name="folder_name" placeholder="Имя новой папки" required>
|
| 377 |
-
<button type="submit" class="btn folder-btn">Создать
|
| 378 |
</form>
|
| 379 |
</div>
|
| 380 |
<form id="upload-form" method="POST" enctype="multipart/form-data" action="{{ url_for('tma_dashboard') }}">
|
| 381 |
<input type="hidden" name="current_folder_id" value="{{ current_folder_id }}">
|
| 382 |
<input type="file" name="files" id="file-input" multiple required>
|
| 383 |
-
<button type="submit" class="btn" id="upload-btn">Загрузить
|
| 384 |
</form>
|
| 385 |
<div id="progress-container"><div id="progress-bar"></div><div id="progress-text">0%</div></div>
|
| 386 |
<h2>Содержимое папки: {{ current_folder.name if current_folder_id != 'root' else 'Главная' }}</h2>
|
| 387 |
<div class="file-grid">
|
| 388 |
{% for item in items %}
|
| 389 |
-
<div class="item {{ item.type }}">
|
| 390 |
{% if item.type == 'folder' %}
|
| 391 |
-
<a href="{{ url_for('tma_dashboard', folder_id=item.id) }}" class="item-preview" title="Перейти в папку {{ item.name }}">
|
| 392 |
-
<p>
|
| 393 |
<div class="item-actions">
|
| 394 |
<a href="{{ url_for('tma_dashboard', folder_id=item.id) }}" class="btn folder-btn">Открыть</a>
|
| 395 |
<form method="POST" action="{{ url_for('delete_folder_tma', folder_id=item.id) }}" style="display: inline;" onsubmit="return confirm('Удалить папку {{ item.name }}? Папку можно удалить только если она пуста.');">
|
|
@@ -401,11 +414,11 @@ TMA_DASHBOARD_HTML_TEMPLATE = '''
|
|
| 401 |
{% set previewable = item.file_type in ['image', 'video', 'pdf', 'text'] %}
|
| 402 |
{% if item.file_type == 'image' %}<img class="item-preview" src="{{ hf_file_url_jinja(item.path) }}" alt="{{ item.original_filename }}" loading="lazy" onclick="openModal('{{ hf_file_url_jinja(item.path) }}', '{{ item.file_type }}', '{{ item.id }}')">
|
| 403 |
{% elif item.file_type == 'video' %}<video class="item-preview" preload="metadata" muted loading="lazy" onclick="openModal('{{ hf_file_url_jinja(item.path) }}', '{{ item.file_type }}', '{{ item.id }}')"><source src="{{ hf_file_url_jinja(item.path, True) }}#t=0.5" type="video/mp4"></video>
|
| 404 |
-
{% elif item.file_type == 'pdf' %}<div class="item-preview" style="
|
| 405 |
-
{% elif item.file_type == 'text' %}<div class="item-preview" style="
|
| 406 |
-
{% else %}<div class="item-preview" style="font-size: 60px; line-height:
|
| 407 |
-
<p title="{{ item.original_filename }}">{{ item.original_filename | truncate(25, True) }}</p>
|
| 408 |
-
<p
|
| 409 |
<div class="item-actions">
|
| 410 |
<button type="button" class="btn download-btn" onclick="tmaDownloadFile('{{ url_for('download_tma', file_id=item.id, _external=True) }}', '{{ item.original_filename }}')">Скачать</button>
|
| 411 |
{% 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 %}
|
|
@@ -425,9 +438,29 @@ TMA_DASHBOARD_HTML_TEMPLATE = '''
|
|
| 425 |
</div>
|
| 426 |
<div class="modal" id="mediaModal" onclick="closeModal(event)"><div class="modal-content" id="modalContentContainer">
|
| 427 |
<span onclick="closeModalManual()" class="modal-close-btn">×</span><div id="modalContent"></div></div></div>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 428 |
<script>
|
| 429 |
window.Telegram.WebApp.ready();
|
| 430 |
-
document.body.classList.add('dark');
|
| 431 |
const repoId = "{{ repo_id_js }}";
|
| 432 |
const hfTokenRead = "{{ HF_TOKEN_READ_js or '' }}";
|
| 433 |
function hfFileUrl(path, download = false) {
|
|
@@ -444,7 +477,7 @@ TMA_DASHBOARD_HTML_TEMPLATE = '''
|
|
| 444 |
else if (type === 'text') {
|
| 445 |
const response = await fetch(srcOrUrl); if (!response.ok) throw new Error(`Ошибка загрузки текста: ${response.statusText}`);
|
| 446 |
const text = await response.text();
|
| 447 |
-
const escapedText = text.replace(/&/g, "&").replace(/</g, "
|
| 448 |
modalContent.innerHTML = `<pre>${escapedText}</pre>`;
|
| 449 |
} else modalContent.innerHTML = '<p>Предпросмотр для этого типа файла не поддерживается.</p>';
|
| 450 |
} catch (error) { modalContent.innerHTML = `<p>Не удалось загрузить содержимое для предпросмотра. ${error.message}</p>`; }
|
|
@@ -463,12 +496,7 @@ TMA_DASHBOARD_HTML_TEMPLATE = '''
|
|
| 463 |
Telegram.WebApp.openLink(downloadUrl);
|
| 464 |
} else {
|
| 465 |
console.warn("Telegram.WebApp.openLink not available, or not in TMA environment. Attempting fallback download.");
|
| 466 |
-
|
| 467 |
-
link.href = downloadUrl;
|
| 468 |
-
link.setAttribute('download', filename);
|
| 469 |
-
document.body.appendChild(link);
|
| 470 |
-
link.click();
|
| 471 |
-
document.body.removeChild(link);
|
| 472 |
}
|
| 473 |
}
|
| 474 |
|
|
@@ -495,9 +523,133 @@ TMA_DASHBOARD_HTML_TEMPLATE = '''
|
|
| 495 |
xhr.open('POST', form.action, true); xhr.send(formData);
|
| 496 |
});
|
| 497 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 498 |
document.getElementById('logout-btn').addEventListener('click', function(e) { e.preventDefault(); window.location.href = "{{ url_for('tma_logout') }}"; });
|
| 499 |
</script></body></html>
|
| 500 |
'''
|
|
|
|
| 501 |
|
| 502 |
@app.route('/tma_dashboard', methods=['GET', 'POST'])
|
| 503 |
def tma_dashboard():
|
|
@@ -605,13 +757,16 @@ def tma_dashboard():
|
|
| 605 |
if not parent_node_bc: break
|
| 606 |
temp_id = parent_node_bc.get('id')
|
| 607 |
breadcrumbs.reverse()
|
|
|
|
|
|
|
|
|
|
| 608 |
|
| 609 |
return render_template_string(TMA_DASHBOARD_HTML_TEMPLATE,
|
| 610 |
display_name=display_name, items=items_in_folder,
|
| 611 |
current_folder_id=current_folder_id, current_folder=current_folder,
|
| 612 |
breadcrumbs=breadcrumbs, repo_id_js=REPO_ID, HF_TOKEN_READ_js=HF_TOKEN_READ,
|
| 613 |
hf_file_url_jinja=lambda path, download=False: f"https://huggingface.co/datasets/{REPO_ID}/resolve/main/{path}{'?download=true' if download else ''}",
|
| 614 |
-
is_tma_user_admin_flag=is_admin_tma())
|
| 615 |
|
| 616 |
|
| 617 |
@app.route('/create_folder_tma', methods=['POST'])
|
|
@@ -670,10 +825,9 @@ def download_tma(file_id):
|
|
| 670 |
break
|
| 671 |
else:
|
| 672 |
flash('Пожалуйста, авторизуйтесь.', 'error')
|
| 673 |
-
|
| 674 |
-
if request.referrer: # if accessed via a click in-app
|
| 675 |
return redirect(url_for('tma_entry_page'))
|
| 676 |
-
else:
|
| 677 |
return Response("Unauthorized", status=401, mimetype='text/plain')
|
| 678 |
|
| 679 |
|
|
@@ -718,8 +872,13 @@ def download_tma(file_id):
|
|
| 718 |
mimetype = content_types.get(ext, 'application/octet-stream')
|
| 719 |
|
| 720 |
resp = Response(generate_chunks(), mimetype=mimetype)
|
| 721 |
-
|
| 722 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 723 |
resp.headers['Cache-Control'] = 'no-cache, no-store, must-revalidate'
|
| 724 |
resp.headers['Pragma'] = 'no-cache'
|
| 725 |
resp.headers['Expires'] = '0'
|
|
@@ -754,7 +913,8 @@ def delete_file_tma(file_id):
|
|
| 754 |
hf_path = file_node.get('path')
|
| 755 |
original_filename = file_node.get('original_filename', 'файл')
|
| 756 |
if not hf_path:
|
| 757 |
-
|
|
|
|
| 758 |
try: save_data(data); flash(f'Метаданные файла {original_filename} удалены (путь отсутствовал).')
|
| 759 |
except Exception as e: flash('Ошибка сохранения данных после удаления метаданных.', 'error')
|
| 760 |
return redirect(url_for('tma_dashboard', folder_id=current_view_folder_id))
|
|
@@ -765,12 +925,14 @@ def delete_file_tma(file_id):
|
|
| 765 |
try:
|
| 766 |
api = HfApi()
|
| 767 |
api.delete_file(path_in_repo=hf_path, repo_id=REPO_ID, repo_type="dataset", token=HF_TOKEN_WRITE)
|
| 768 |
-
|
|
|
|
| 769 |
try: save_data(data); flash(f'Файл {original_filename} успешно удален!')
|
| 770 |
except Exception as e: flash('Файл удален с сервера, но ошибка обновления базы.', 'error')
|
| 771 |
else: flash('Файл удален с сервера, но не найден в базе для удаления.', 'error')
|
| 772 |
except hf_utils.EntryNotFoundError:
|
| 773 |
-
|
|
|
|
| 774 |
try: save_data(data); flash(f'Файл {original_filename} не найден на сервере, удален из базы.')
|
| 775 |
except Exception as e: flash('Ошибка сохранения (файл не на сервере).', 'error')
|
| 776 |
except Exception as e:
|
|
@@ -797,11 +959,142 @@ def delete_folder_tma(folder_id):
|
|
| 797 |
if folder_node.get('children'):
|
| 798 |
flash(f'Папку "{folder_node.get("name")}" можно удалить только если она пуста.', 'error')
|
| 799 |
return redirect(url_for('tma_dashboard', folder_id=current_view_folder_id))
|
| 800 |
-
|
|
|
|
| 801 |
try: save_data(data); flash(f'Папка "{folder_node.get("name")}" удалена.')
|
| 802 |
except Exception as e: flash('Ошибка сохранения после удаления папки.', 'error')
|
| 803 |
else: flash('Не удалось удалить папку.', 'error')
|
| 804 |
return redirect(url_for('tma_dashboard', folder_id=parent_node.get('id', 'root')))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 805 |
|
| 806 |
@app.route('/get_text_content_tma/<file_id>')
|
| 807 |
def get_text_content_tma(file_id):
|
|
@@ -853,6 +1146,8 @@ def tma_logout():
|
|
| 853 |
return redirect(url_for('tma_entry_page'))
|
| 854 |
|
| 855 |
|
|
|
|
|
|
|
| 856 |
ADMIN_LOGIN_HTML_TEMPLATE = '''
|
| 857 |
<!DOCTYPE html><html lang="ru"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0">
|
| 858 |
<title>Admin Login</title><link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600;800&display=swap" rel="stylesheet">
|
|
@@ -1072,7 +1367,8 @@ def admin_delete_file(tma_user_id_str_form, file_id):
|
|
| 1072 |
original_filename = file_node.get('original_filename', 'файл')
|
| 1073 |
|
| 1074 |
if not hf_path:
|
| 1075 |
-
|
|
|
|
| 1076 |
try: save_data(data); flash(f'Метаданные файла {original_filename} удалены из базы (путь к файлу на сервере отсутствовал).')
|
| 1077 |
except Exception as e: flash('Ошибка сохранения данных после удаления метаданных (путь отсутствовал).', 'error')
|
| 1078 |
return redirect(url_for('admin_user_files', tma_user_id_str=tma_user_id_str_form))
|
|
@@ -1080,14 +1376,16 @@ def admin_delete_file(tma_user_id_str_form, file_id):
|
|
| 1080 |
try:
|
| 1081 |
api = HfApi()
|
| 1082 |
api.delete_file(path_in_repo=hf_path, repo_id=REPO_ID, repo_type="dataset", token=HF_TOKEN_WRITE)
|
| 1083 |
-
|
|
|
|
| 1084 |
try: save_data(data); flash(f'Файл {original_filename} успешно удален с сервера и из базы данных!')
|
| 1085 |
except Exception as e: flash('Файл удален с сервера, но произошла ошибка при обновлении базы данных.', 'error')
|
| 1086 |
else:
|
| 1087 |
flash(f'Файл {original_filename} удален с сервера, но не найден в структуре папок пользователя для удаления из базы.', 'error')
|
| 1088 |
except hf_utils.EntryNotFoundError:
|
| 1089 |
flash(f'Файл {original_filename} не найден на сервере. Удаляем из базы данных.')
|
| 1090 |
-
|
|
|
|
| 1091 |
try: save_data(data); flash(f'Запись о файле {original_filename} удалена из базы.')
|
| 1092 |
except Exception as e: flash('Ошибка сохранения данных после удаления записи о файле (файл не на сервере).', 'error')
|
| 1093 |
except Exception as e:
|
|
|
|
| 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")
|
|
|
|
| 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;
|
| 41 |
--background-light: #f5f6fa; --background-dark: #1a1625;
|
| 42 |
--card-bg: rgba(255, 255, 255, 0.95); --card-bg-dark: rgba(40, 35, 60, 0.95);
|
| 43 |
+
--text-light: #2a1e5a; --text-dark: #e8e1ff; --shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
|
| 44 |
--glass-bg: rgba(255, 255, 255, 0.15); --transition: all 0.3s ease; --delete-color: #ff4444;
|
| 45 |
+
--folder-color: #ffc107; --selection-color: rgba(139, 92, 246, 0.3);
|
| 46 |
}
|
| 47 |
* { margin: 0; padding: 0; box-sizing: border-box; }
|
| 48 |
+
body { font-family: 'Inter', sans-serif; background: var(--background-dark); color: var(--text-dark); line-height: 1.6; }
|
| 49 |
+
.container { margin: 20px auto; max-width: 1200px; padding: 25px; background: var(--card-bg-dark); border-radius: 20px; box-shadow: var(--shadow); overflow-x: hidden; }
|
|
|
|
|
|
|
| 50 |
h1 { font-size: 2em; font-weight: 800; text-align: center; margin-bottom: 25px; background: linear-gradient(135deg, var(--primary), var(--accent)); -webkit-background-clip: text; color: transparent; }
|
| 51 |
+
h2 { font-size: 1.5em; margin-top: 30px; color: var(--text-dark); }
|
|
|
|
| 52 |
h4 { font-size: 1.1em; margin-top: 15px; margin-bottom: 5px; color: var(--accent); }
|
| 53 |
ol, ul { margin-left: 20px; margin-bottom: 15px; }
|
| 54 |
li { margin-bottom: 5px; }
|
| 55 |
+
input, textarea, input[type="text"], input[type="password"], input[type="file"], select { width: 100%; padding: 14px; margin: 12px 0; border: none; border-radius: 14px; background: rgba(255,255,255,0.05); color: var(--text-dark); font-size: 1.1em; box-shadow: inset 0 3px 10px rgba(0, 0, 0, 0.1); }
|
| 56 |
+
input:focus, textarea:focus, select:focus { outline: none; box-shadow: 0 0 0 4px var(--primary); }
|
|
|
|
| 57 |
.btn { padding: 14px 28px; background: var(--primary); color: white; border: none; border-radius: 14px; cursor: pointer; font-size: 1.1em; font-weight: 600; transition: var(--transition); box-shadow: var(--shadow); display: inline-block; text-decoration: none; margin-top: 5px; margin-right: 5px; }
|
| 58 |
.btn:hover { transform: scale(1.05); background: #e6415f; }
|
| 59 |
.download-btn { background: var(--secondary); }
|
|
|
|
| 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); }
|
| 71 |
+
.item-preview { width: 100%; height: 120px; object-fit: cover; border-radius: 10px; margin-bottom: 10px; cursor: pointer; display: block; }
|
| 72 |
+
.item.folder .item-preview { object-fit: contain; font-size: 60px; color: var(--folder-color); line-height: 120px; }
|
| 73 |
+
.item-name { font-size: 0.9em; font-weight: 600; margin: 5px 0; word-break: break-all; }
|
| 74 |
+
.item-info { font-size: 0.75em; color: #aaa; }
|
| 75 |
.item a { color: var(--primary); text-decoration: none; }
|
| 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; }
|
| 82 |
.modal iframe { width: 80vw; height: 85vh; border: none; }
|
| 83 |
+
.modal pre { background: #2b2a33; color: var(--text-dark); padding: 15px; border-radius: 8px; white-space: pre-wrap; word-wrap: break-word; text-align: left; 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: 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); }
|
|
|
|
| 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; }
|
| 106 |
+
.file-grid { grid-template-columns: repeat(2, 1fr); gap: 15px; }
|
| 107 |
.item-preview { height: 80px; }
|
| 108 |
.item.folder .item-preview { font-size: 40px; line-height: 80px; }
|
| 109 |
+
#selection-bar { flex-direction: column; gap: 10px; }
|
| 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 |
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 |
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()
|
| 162 |
+
folders = []
|
| 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})
|
| 170 |
+
|
| 171 |
+
new_prefix = f"{path_prefix}{node.get('name', '')}/" if node.get('id') != 'root' else ""
|
| 172 |
+
for child in node.get('children', []):
|
| 173 |
+
traverse(child, new_prefix)
|
| 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:
|
| 181 |
user_data['filesystem'] = {
|
|
|
|
| 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>
|
| 371 |
+
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600;800&display=swap" rel="stylesheet">
|
| 372 |
+
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.2/css/all.min.css">
|
| 373 |
<script src="https://telegram.org/js/telegram-web-app.js"></script>
|
| 374 |
+
<style>''' + BASE_STYLE + '''</style></head><body><div class="container" id="main-container">
|
| 375 |
<h1>Zeus Cloud</h1><p>Пользователь: {{ display_name }}</p>
|
| 376 |
{% with messages = get_flashed_messages(with_categories=true) %}{% if messages %}
|
| 377 |
{% for category, message in messages %}<div class="flash {{ category }}">{{ message }}</div>{% endfor %}
|
|
|
|
| 387 |
<form method="POST" action="{{ url_for('create_folder_tma') }}" style="display: contents;">
|
| 388 |
<input type="hidden" name="parent_folder_id" value="{{ current_folder_id }}">
|
| 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 }}">
|
| 395 |
<input type="file" name="files" id="file-input" multiple required>
|
| 396 |
+
<button type="submit" class="btn" id="upload-btn"><i class="fa-solid fa-upload"></i> Загрузить сюда</button>
|
| 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 }}? Папку можно удалить только если она пуста.');">
|
|
|
|
| 414 |
{% set previewable = item.file_type in ['image', 'video', 'pdf', 'text'] %}
|
| 415 |
{% if item.file_type == 'image' %}<img class="item-preview" src="{{ hf_file_url_jinja(item.path) }}" alt="{{ item.original_filename }}" loading="lazy" onclick="openModal('{{ hf_file_url_jinja(item.path) }}', '{{ item.file_type }}', '{{ item.id }}')">
|
| 416 |
{% elif item.file_type == 'video' %}<video class="item-preview" preload="metadata" muted loading="lazy" onclick="openModal('{{ hf_file_url_jinja(item.path) }}', '{{ item.file_type }}', '{{ item.id }}')"><source src="{{ hf_file_url_jinja(item.path, True) }}#t=0.5" type="video/mp4"></video>
|
| 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 %}
|
|
|
|
| 438 |
</div>
|
| 439 |
<div class="modal" id="mediaModal" onclick="closeModal(event)"><div class="modal-content" id="modalContentContainer">
|
| 440 |
<span onclick="closeModalManual()" class="modal-close-btn">×</span><div id="modalContent"></div></div></div>
|
| 441 |
+
|
| 442 |
+
<div id="selection-bar">
|
| 443 |
+
<span id="selection-count">Выбрано: 0</span>
|
| 444 |
+
<button class="btn" style="background: var(--accent);" onclick="showMoveModal()"><i class="fa-solid fa-arrow-right-to-bracket"></i> Переместить</button>
|
| 445 |
+
<button class="btn delete-btn" onclick="deleteSelected()"><i class="fa-solid fa-trash-can"></i> Удалить</button>
|
| 446 |
+
<button class="btn" onclick="toggleSelectionMode(false)">Отмена</button>
|
| 447 |
+
</div>
|
| 448 |
+
|
| 449 |
+
<div class="modal" id="move-modal">
|
| 450 |
+
<div class="modal-content">
|
| 451 |
+
<h4>Переместить выбранные элементы в:</h4>
|
| 452 |
+
<select id="folder-destination-select" name="destination_folder">
|
| 453 |
+
{% for folder in all_folders_for_move %}
|
| 454 |
+
<option value="{{ folder.id }}">{{ folder.name }}</option>
|
| 455 |
+
{% endfor %}
|
| 456 |
+
</select>
|
| 457 |
+
<button class="btn" style="background: var(--accent);" onclick="moveSelected()">Переместить</button>
|
| 458 |
+
<button class="btn" onclick="closeMoveModal()">Отмена</button>
|
| 459 |
+
</div>
|
| 460 |
+
</div>
|
| 461 |
+
|
| 462 |
<script>
|
| 463 |
window.Telegram.WebApp.ready();
|
|
|
|
| 464 |
const repoId = "{{ repo_id_js }}";
|
| 465 |
const hfTokenRead = "{{ HF_TOKEN_READ_js or '' }}";
|
| 466 |
function hfFileUrl(path, download = false) {
|
|
|
|
| 477 |
else if (type === 'text') {
|
| 478 |
const response = await fetch(srcOrUrl); if (!response.ok) throw new Error(`Ошибка загрузки текста: ${response.statusText}`);
|
| 479 |
const text = await response.text();
|
| 480 |
+
const escapedText = text.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
|
| 481 |
modalContent.innerHTML = `<pre>${escapedText}</pre>`;
|
| 482 |
} else modalContent.innerHTML = '<p>Предпросмотр для этого типа файла не поддерживается.</p>';
|
| 483 |
} catch (error) { modalContent.innerHTML = `<p>Не удалось загрузить содержимое для предпросмотра. ${error.message}</p>`; }
|
|
|
|
| 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 |
}
|
| 502 |
|
|
|
|
| 523 |
xhr.open('POST', form.action, true); xhr.send(formData);
|
| 524 |
});
|
| 525 |
}
|
| 526 |
+
|
| 527 |
+
// --- SELECTION LOGIC ---
|
| 528 |
+
let selectionMode = false;
|
| 529 |
+
const selectedItems = new Set();
|
| 530 |
+
let longPressTimer;
|
| 531 |
+
|
| 532 |
+
const mainContainer = document.getElementById('main-container');
|
| 533 |
+
const selectionBar = document.getElementById('selection-bar');
|
| 534 |
+
const selectionCount = document.getElementById('selection-count');
|
| 535 |
+
const allItems = document.querySelectorAll('.item');
|
| 536 |
+
|
| 537 |
+
function toggleSelectionMode(enable) {
|
| 538 |
+
selectionMode = enable;
|
| 539 |
+
mainContainer.classList.toggle('selection-mode', enable);
|
| 540 |
+
selectionBar.classList.toggle('visible', enable);
|
| 541 |
+
if (!enable) {
|
| 542 |
+
selectedItems.clear();
|
| 543 |
+
allItems.forEach(item => item.classList.remove('selected'));
|
| 544 |
+
updateSelectionCount();
|
| 545 |
+
}
|
| 546 |
+
}
|
| 547 |
+
|
| 548 |
+
function updateSelectionCount() {
|
| 549 |
+
selectionCount.textContent = `Выбрано: ${selectedItems.size}`;
|
| 550 |
+
}
|
| 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');
|
| 558 |
+
const itemId = item.dataset.id;
|
| 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);
|
| 579 |
+
else selectedItems.add(itemId);
|
| 580 |
+
updateSelectionCount();
|
| 581 |
+
|
| 582 |
+
if (selectedItems.size === 0) {
|
| 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';
|
| 593 |
+
}
|
| 594 |
+
|
| 595 |
+
function closeMoveModal() {
|
| 596 |
+
document.getElementById('move-modal').style.display = 'none';
|
| 597 |
+
}
|
| 598 |
+
|
| 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',
|
| 606 |
+
headers: { 'Content-Type': 'application/json' },
|
| 607 |
+
body: JSON.stringify({ item_ids: itemIds, destination_id: destinationId })
|
| 608 |
+
});
|
| 609 |
+
const result = await response.json();
|
| 610 |
+
if (result.status === 'success') {
|
| 611 |
+
window.location.reload();
|
| 612 |
+
} else {
|
| 613 |
+
Telegram.WebApp.showAlert(result.message || 'Ошибка при перемещении.');
|
| 614 |
+
}
|
| 615 |
+
} catch (error) {
|
| 616 |
+
Telegram.WebApp.showAlert('Сетевая ошибка при перемещении.');
|
| 617 |
+
} finally {
|
| 618 |
+
closeMoveModal();
|
| 619 |
+
toggleSelectionMode(false);
|
| 620 |
+
}
|
| 621 |
+
}
|
| 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 {
|
| 629 |
+
const response = await fetch('{{ url_for("batch_delete_tma") }}', {
|
| 630 |
+
method: 'POST',
|
| 631 |
+
headers: { 'Content-Type': 'application/json' },
|
| 632 |
+
body: JSON.stringify({ item_ids: Array.from(selectedItems) })
|
| 633 |
+
});
|
| 634 |
+
const result = await response.json();
|
| 635 |
+
if (result.status === 'success') {
|
| 636 |
+
window.location.reload();
|
| 637 |
+
} else {
|
| 638 |
+
Telegram.WebApp.showAlert(result.message || 'Ошибка при удалении.');
|
| 639 |
+
}
|
| 640 |
+
} catch (error) {
|
| 641 |
+
Telegram.WebApp.showAlert('Сетевая ошибка при удалении.');
|
| 642 |
+
} finally {
|
| 643 |
+
toggleSelectionMode(false);
|
| 644 |
+
}
|
| 645 |
+
}
|
| 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():
|
|
|
|
| 757 |
if not parent_node_bc: break
|
| 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)
|
| 770 |
|
| 771 |
|
| 772 |
@app.route('/create_folder_tma', methods=['POST'])
|
|
|
|
| 825 |
break
|
| 826 |
else:
|
| 827 |
flash('Пожалуйста, авторизуйтесь.', 'error')
|
| 828 |
+
if request.referrer:
|
|
|
|
| 829 |
return redirect(url_for('tma_entry_page'))
|
| 830 |
+
else:
|
| 831 |
return Response("Unauthorized", status=401, mimetype='text/plain')
|
| 832 |
|
| 833 |
|
|
|
|
| 872 |
mimetype = content_types.get(ext, 'application/octet-stream')
|
| 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'
|
| 884 |
resp.headers['Expires'] = '0'
|
|
|
|
| 913 |
hf_path = file_node.get('path')
|
| 914 |
original_filename = file_node.get('original_filename', 'файл')
|
| 915 |
if not hf_path:
|
| 916 |
+
removed, _ = remove_node(user_data['filesystem'], file_id)
|
| 917 |
+
if removed:
|
| 918 |
try: save_data(data); flash(f'Метаданные файла {original_filename} удалены (путь отсутствовал).')
|
| 919 |
except Exception as e: flash('Ошибка сохранения данных после удаления метаданных.', 'error')
|
| 920 |
return redirect(url_for('tma_dashboard', folder_id=current_view_folder_id))
|
|
|
|
| 925 |
try:
|
| 926 |
api = HfApi()
|
| 927 |
api.delete_file(path_in_repo=hf_path, repo_id=REPO_ID, repo_type="dataset", token=HF_TOKEN_WRITE)
|
| 928 |
+
removed, _ = remove_node(user_data['filesystem'], file_id)
|
| 929 |
+
if removed:
|
| 930 |
try: save_data(data); flash(f'Файл {original_filename} успешно удален!')
|
| 931 |
except Exception as e: flash('Файл удален с сервера, но ошибка обновления базы.', 'error')
|
| 932 |
else: flash('Файл удален с сервера, но не найден в базе для удаления.', 'error')
|
| 933 |
except hf_utils.EntryNotFoundError:
|
| 934 |
+
removed, _ = remove_node(user_data['filesystem'], file_id)
|
| 935 |
+
if removed:
|
| 936 |
try: save_data(data); flash(f'Файл {original_filename} не найден на сервере, удален из базы.')
|
| 937 |
except Exception as e: flash('Ошибка сохранения (файл не на сервере).', 'error')
|
| 938 |
except Exception as e:
|
|
|
|
| 959 |
if folder_node.get('children'):
|
| 960 |
flash(f'Папку "{folder_node.get("name")}" можно удалить только если она пуста.', 'error')
|
| 961 |
return redirect(url_for('tma_dashboard', folder_id=current_view_folder_id))
|
| 962 |
+
removed, _ = remove_node(user_data['filesystem'], folder_id)
|
| 963 |
+
if removed:
|
| 964 |
try: save_data(data); flash(f'Папка "{folder_node.get("name")}" удалена.')
|
| 965 |
except Exception as e: flash('Ошибка сохранения после удаления папки.', 'error')
|
| 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:
|
| 973 |
+
return jsonify({'status': 'error', 'message': 'Не авторизован.'}), 401
|
| 974 |
+
|
| 975 |
+
tma_user_id = session['telegram_user_id']
|
| 976 |
+
data = load_data()
|
| 977 |
+
user_data = data['users'].get(tma_user_id)
|
| 978 |
+
if not user_data:
|
| 979 |
+
return jsonify({'status': 'error', 'message': 'Пользователь не найден.'}), 404
|
| 980 |
+
|
| 981 |
+
item_ids = request.json.get('item_ids', [])
|
| 982 |
+
if not item_ids:
|
| 983 |
+
return jsonify({'status': 'error', 'message': 'Не выбраны элементы для удаления.'}), 400
|
| 984 |
+
|
| 985 |
+
api = HfApi()
|
| 986 |
+
success_count = 0
|
| 987 |
+
errors = []
|
| 988 |
+
|
| 989 |
+
for item_id in item_ids:
|
| 990 |
+
node, parent = find_node_by_id(user_data['filesystem'], item_id)
|
| 991 |
+
if not node:
|
| 992 |
+
errors.append(f"Элемент {item_id} не найден.")
|
| 993 |
+
continue
|
| 994 |
+
|
| 995 |
+
if node.get('type') == 'folder':
|
| 996 |
+
if node.get('children'):
|
| 997 |
+
errors.append(f'Папка "{node.get("name")}" не пуста и не может быть удалена.')
|
| 998 |
+
continue
|
| 999 |
+
removed, _ = remove_node(user_data['filesystem'], item_id)
|
| 1000 |
+
if removed:
|
| 1001 |
+
success_count += 1
|
| 1002 |
+
else:
|
| 1003 |
+
errors.append(f'Не удалось удалить папку "{node.get("name")}" из базы.')
|
| 1004 |
+
|
| 1005 |
+
elif node.get('type') == 'file':
|
| 1006 |
+
hf_path = node.get('path')
|
| 1007 |
+
try:
|
| 1008 |
+
if hf_path and HF_TOKEN_WRITE:
|
| 1009 |
+
api.delete_file(path_in_repo=hf_path, repo_id=REPO_ID, repo_type="dataset", token=HF_TOKEN_WRITE)
|
| 1010 |
+
except hf_utils.EntryNotFoundError:
|
| 1011 |
+
logging.warning(f"File {hf_path} not found on HF for deletion, proceeding.")
|
| 1012 |
+
except Exception as e:
|
| 1013 |
+
errors.append(f'Ошибка удаления файла "{node.get("original_filename")}" с сервера: {e}')
|
| 1014 |
+
continue
|
| 1015 |
+
|
| 1016 |
+
removed, _ = remove_node(user_data['filesystem'], item_id)
|
| 1017 |
+
if removed:
|
| 1018 |
+
success_count += 1
|
| 1019 |
+
else:
|
| 1020 |
+
errors.append(f'Не удалось удалить файл "{node.get("original_filename")}" из базы.')
|
| 1021 |
+
|
| 1022 |
+
if success_count > 0:
|
| 1023 |
+
try:
|
| 1024 |
+
save_data(data)
|
| 1025 |
+
except Exception as e:
|
| 1026 |
+
return jsonify({'status': 'error', 'message': f'Элементы удалены, но произошла ошибка сохранения: {e}'})
|
| 1027 |
+
|
| 1028 |
+
if errors:
|
| 1029 |
+
return jsonify({'status': 'error', 'message': f'Удалено {success_count} элемент(ов). Ошибки: ' + "; ".join(errors)})
|
| 1030 |
+
|
| 1031 |
+
return jsonify({'status': 'success', 'message': f'Успешно удалено {success_count} элемент(ов).'})
|
| 1032 |
+
|
| 1033 |
+
@app.route('/batch_move_tma', methods=['POST'])
|
| 1034 |
+
def batch_move_tma():
|
| 1035 |
+
if 'telegram_user_id' not in session:
|
| 1036 |
+
return jsonify({'status': 'error', 'message': 'Не авторизован.'}), 401
|
| 1037 |
+
|
| 1038 |
+
tma_user_id = session['telegram_user_id']
|
| 1039 |
+
data = load_data()
|
| 1040 |
+
user_data = data['users'].get(tma_user_id)
|
| 1041 |
+
if not user_data:
|
| 1042 |
+
return jsonify({'status': 'error', 'message': 'Пользователь не найден.'}), 404
|
| 1043 |
+
|
| 1044 |
+
item_ids = request.json.get('item_ids', [])
|
| 1045 |
+
destination_id = request.json.get('destination_id')
|
| 1046 |
+
|
| 1047 |
+
if not item_ids or not destination_id:
|
| 1048 |
+
return jsonify({'status': 'error', 'message': 'Не указаны файлы или папка назначения.'}), 400
|
| 1049 |
+
|
| 1050 |
+
destination_node, _ = find_node_by_id(user_data['filesystem'], destination_id)
|
| 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)
|
| 1058 |
+
if node and node.get('type') == 'folder':
|
| 1059 |
+
queue = [node]
|
| 1060 |
+
while queue:
|
| 1061 |
+
curr = queue.pop(0)
|
| 1062 |
+
descendant_ids.add(curr.get('id'))
|
| 1063 |
+
if 'children' in curr:
|
| 1064 |
+
queue.extend(curr['children'])
|
| 1065 |
+
|
| 1066 |
+
if destination_id in descendant_ids:
|
| 1067 |
+
return jsonify({'status': 'error', 'message': 'Нельзя переместить папку в саму себя или в свою дочернюю папку.'})
|
| 1068 |
+
|
| 1069 |
+
moved_count = 0
|
| 1070 |
+
errors = []
|
| 1071 |
+
|
| 1072 |
+
for item_id in item_ids:
|
| 1073 |
+
if item_id == destination_id:
|
| 1074 |
+
errors.append("Нельзя переместить элемент в самого себя.")
|
| 1075 |
+
continue
|
| 1076 |
+
|
| 1077 |
+
removed, node_to_move = remove_node(user_data['filesystem'], item_id)
|
| 1078 |
+
if removed and node_to_move:
|
| 1079 |
+
if add_node(user_data['filesystem'], destination_id, node_to_move):
|
| 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 |
+
|
| 1087 |
+
if moved_count > 0:
|
| 1088 |
+
try:
|
| 1089 |
+
save_data(data)
|
| 1090 |
+
except Exception as e:
|
| 1091 |
+
return jsonify({'status': 'error', 'message': f'Элементы перемещены, но произошла ошибка сохранения: {e}'})
|
| 1092 |
+
|
| 1093 |
+
if errors:
|
| 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):
|
|
|
|
| 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">
|
|
|
|
| 1367 |
original_filename = file_node.get('original_filename', 'файл')
|
| 1368 |
|
| 1369 |
if not hf_path:
|
| 1370 |
+
removed, _ = remove_node(user_data['filesystem'], file_id)
|
| 1371 |
+
if removed:
|
| 1372 |
try: save_data(data); flash(f'Метаданные файла {original_filename} удалены из базы (путь к файлу на сервере отсутствовал).')
|
| 1373 |
except Exception as e: flash('Ошибка сохранения данных после удаления метаданных (путь отсутствовал).', 'error')
|
| 1374 |
return redirect(url_for('admin_user_files', tma_user_id_str=tma_user_id_str_form))
|
|
|
|
| 1376 |
try:
|
| 1377 |
api = HfApi()
|
| 1378 |
api.delete_file(path_in_repo=hf_path, repo_id=REPO_ID, repo_type="dataset", token=HF_TOKEN_WRITE)
|
| 1379 |
+
removed, _ = remove_node(user_data['filesystem'], file_id)
|
| 1380 |
+
if removed:
|
| 1381 |
try: save_data(data); flash(f'Файл {original_filename} успешно удален с сервера и из базы данных!')
|
| 1382 |
except Exception as e: flash('Файл удален с сервера, но произошла ошибка при обновлении базы данных.', 'error')
|
| 1383 |
else:
|
| 1384 |
flash(f'Файл {original_filename} удален с сервера, но не найден в структуре папок пользователя для удаления из базы.', 'error')
|
| 1385 |
except hf_utils.EntryNotFoundError:
|
| 1386 |
flash(f'Файл {original_filename} не найден на сервере. Удаляем из базы данных.')
|
| 1387 |
+
removed, _ = remove_node(user_data['filesystem'], file_id)
|
| 1388 |
+
if removed:
|
| 1389 |
try: save_data(data); flash(f'Запись о файле {original_filename} удалена из базы.')
|
| 1390 |
except Exception as e: flash('Ошибка сохранения данных после удаления записи о файле (файл не на сервере).', 'error')
|
| 1391 |
except Exception as e:
|