Update app.py
Browse files
app.py
CHANGED
|
@@ -14,8 +14,6 @@ from io import BytesIO
|
|
| 14 |
import uuid
|
| 15 |
from functools import wraps
|
| 16 |
from urllib.parse import quote
|
| 17 |
-
import zipfile
|
| 18 |
-
import tempfile
|
| 19 |
|
| 20 |
app = Flask(__name__)
|
| 21 |
app.secret_key = os.getenv("FLASK_SECRET_KEY", "supersecretkey_folders_unique_tma")
|
|
@@ -63,8 +61,11 @@ input, select { width: 100%; padding: 14px; margin: 8px 0; border: 1px solid #33
|
|
| 63 |
.flash.error { background: rgba(255, 68, 68, 0.1); color: var(--delete-color); }
|
| 64 |
.file-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(150px, 1fr)); gap: 15px; }
|
| 65 |
.item { background: var(--card-bg-dark); border-radius: 16px; text-align: center; transition: var(--transition); position: relative; border: 2px solid transparent; user-select: none; padding: 10px; display: flex; flex-direction: column; }
|
|
|
|
| 66 |
.item:active { transform: scale(0.97); }
|
| 67 |
.item.selected { border-color: var(--accent); background-color: var(--selection-color); }
|
|
|
|
|
|
|
| 68 |
.item-preview-wrapper { position: relative; width: 100%; padding-top: 75%; border-radius: 10px; overflow: hidden; margin-bottom: 10px; cursor: pointer; background: #2a2a2a; }
|
| 69 |
.item-preview { position: absolute; top: 0; left: 0; width: 100%; height: 100%; object-fit: cover; }
|
| 70 |
.item.folder .item-preview { object-fit: contain; font-size: 3.5em; color: var(--folder-color); }
|
|
@@ -140,7 +141,7 @@ def get_all_folders(filesystem, exclude_ids=None):
|
|
| 140 |
if exclude_ids is None:
|
| 141 |
exclude_ids = set()
|
| 142 |
folders = []
|
| 143 |
-
|
| 144 |
def traverse(node, path_prefix):
|
| 145 |
if node.get('type') == 'folder':
|
| 146 |
if node.get('id') not in exclude_ids:
|
|
@@ -338,6 +339,7 @@ TMA_DASHBOARD_HTML_TEMPLATE = '''
|
|
| 338 |
<div class="file-grid" id="file-container">
|
| 339 |
{% for item in items %}
|
| 340 |
<div class="item {{ item.type }}" data-id="{{ item.id }}" data-type="{{ item.type }}">
|
|
|
|
| 341 |
<div class="item-preview-wrapper" {% if item.type != 'folder' %}onclick="openModal('{{ hf_file_url_jinja(item.path) if item.file_type not in ['text', 'pdf'] else (url_for('get_text_content_tma', file_id=item.id) if item.file_type == 'text' else hf_file_url_jinja(item.path, True)) }}', '{{ item.file_type }}', '{{ item.id }}')"{% else %}onclick="window.location.href='{{ url_for('tma_dashboard', folder_id=item.id) }}'"{% endif %}>
|
| 342 |
{% if item.type == 'folder' %}
|
| 343 |
<div class="item-preview"><i class="fa-solid fa-folder"></i></div>
|
|
@@ -400,6 +402,35 @@ TMA_DASHBOARD_HTML_TEMPLATE = '''
|
|
| 400 |
<script>
|
| 401 |
window.Telegram.WebApp.ready();
|
| 402 |
window.Telegram.WebApp.expand();
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 403 |
async function openModal(srcOrUrl, type) {
|
| 404 |
if (!srcOrUrl) return;
|
| 405 |
const modal = document.getElementById('mediaModal'); const modalContent = document.getElementById('modalContent');
|
|
@@ -430,6 +461,7 @@ TMA_DASHBOARD_HTML_TEMPLATE = '''
|
|
| 430 |
if (files.length === 0) { Telegram.WebApp.showAlert('Выберите файлы.'); return; }
|
| 431 |
if (files.length > 20) { Telegram.WebApp.showAlert('Максимум 20 файлов за раз!'); return; }
|
| 432 |
closeFabModal();
|
|
|
|
| 433 |
const progressContainer = document.getElementById('progress-container');
|
| 434 |
const progressBar = document.getElementById('progress-bar');
|
| 435 |
progressContainer.style.display = 'block'; progressBar.style.width = '0%';
|
|
@@ -437,8 +469,8 @@ TMA_DASHBOARD_HTML_TEMPLATE = '''
|
|
| 437 |
xhr.upload.addEventListener('progress', e => {
|
| 438 |
if (e.lengthComputable) progressBar.style.width = Math.round((e.loaded / e.total) * 100) + '%';
|
| 439 |
});
|
| 440 |
-
xhr.addEventListener('load', () => window.location.reload());
|
| 441 |
-
xhr.addEventListener('error', () => Telegram.WebApp.showAlert('Ошибка загрузки.'));
|
| 442 |
xhr.open('POST', this.action, true); xhr.send(formData);
|
| 443 |
});
|
| 444 |
|
|
@@ -462,6 +494,7 @@ TMA_DASHBOARD_HTML_TEMPLATE = '''
|
|
| 462 |
item.addEventListener('pointerdown', e => {
|
| 463 |
if (e.pointerType === 'mouse' && e.button !== 0) return;
|
| 464 |
longPressTimer = setTimeout(() => {
|
|
|
|
| 465 |
if (!selectionMode) toggleSelectionMode(true);
|
| 466 |
item.classList.toggle('selected');
|
| 467 |
if (selectedItems.has(item.dataset.id)) selectedItems.delete(item.dataset.id); else selectedItems.add(item.dataset.id);
|
|
@@ -473,6 +506,7 @@ TMA_DASHBOARD_HTML_TEMPLATE = '''
|
|
| 473 |
item.addEventListener('click', e => {
|
| 474 |
if (selectionMode) {
|
| 475 |
e.preventDefault(); e.stopPropagation();
|
|
|
|
| 476 |
item.classList.toggle('selected');
|
| 477 |
if (selectedItems.has(item.dataset.id)) selectedItems.delete(item.dataset.id); else selectedItems.add(item.dataset.id);
|
| 478 |
updateSelectionUI();
|
|
@@ -487,32 +521,65 @@ TMA_DASHBOARD_HTML_TEMPLATE = '''
|
|
| 487 |
method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body)
|
| 488 |
});
|
| 489 |
const result = await response.json();
|
| 490 |
-
if (result.status === 'success')
|
| 491 |
-
|
| 492 |
-
|
| 493 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 494 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 495 |
function downloadSelected() {
|
| 496 |
const fileIds = Array.from(selectedItems).filter(id => {
|
| 497 |
const item = document.querySelector(`.item[data-id='${id}']`);
|
| 498 |
return item && item.dataset.type === 'file';
|
| 499 |
});
|
| 500 |
-
if (fileIds.length === 0) {
|
| 501 |
-
|
| 502 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 503 |
toggleSelectionMode(false);
|
| 504 |
}
|
| 505 |
-
|
|
|
|
| 506 |
function closeMoveModal() { document.getElementById('move-modal').style.display = 'none'; }
|
| 507 |
function moveSelected() {
|
|
|
|
| 508 |
const destinationId = document.getElementById('folder-destination-select').value;
|
| 509 |
performBatchAction('{{ url_for("batch_move_tma") }}', { item_ids: Array.from(selectedItems), destination_id: destinationId });
|
| 510 |
closeMoveModal();
|
| 511 |
}
|
| 512 |
function deleteSelected() {
|
| 513 |
if (selectedItems.size === 0) return;
|
|
|
|
| 514 |
Telegram.WebApp.showConfirm(`Удалить ${selectedItems.size} элемент(ов)?`, ok => {
|
| 515 |
-
if (ok)
|
|
|
|
|
|
|
|
|
|
| 516 |
});
|
| 517 |
}
|
| 518 |
|
|
@@ -525,13 +592,13 @@ TMA_DASHBOARD_HTML_TEMPLATE = '''
|
|
| 525 |
gridViewBtn.classList.toggle('active', view !== 'list');
|
| 526 |
localStorage.setItem('viewMode', view);
|
| 527 |
}
|
| 528 |
-
gridViewBtn.addEventListener('click', () => setView('grid'));
|
| 529 |
-
listViewBtn.addEventListener('click', () => setView('list'));
|
| 530 |
document.addEventListener('DOMContentLoaded', () => setView(localStorage.getItem('viewMode') || 'grid'));
|
| 531 |
|
| 532 |
const fab = document.getElementById('fab');
|
| 533 |
const fabModal = document.getElementById('fab-modal');
|
| 534 |
-
fab.addEventListener('click', () => { fabModal.style.display = 'flex'; });
|
| 535 |
function closeFabModal() { fabModal.style.display = 'none'; }
|
| 536 |
fabModal.addEventListener('click', e => { if (e.target.id === 'fab-modal') closeFabModal(); });
|
| 537 |
</script></body></html>
|
|
@@ -608,8 +675,9 @@ def tma_dashboard():
|
|
| 608 |
breadcrumbs.reverse()
|
| 609 |
|
| 610 |
all_folders_for_move = get_all_folders(user_data['filesystem'])
|
|
|
|
| 611 |
|
| 612 |
-
return render_template_string(TMA_DASHBOARD_HTML_TEMPLATE, display_name=display_name, items=items_in_folder, current_folder_id=current_folder_id, current_folder=current_folder, breadcrumbs=breadcrumbs, hf_file_url_jinja=lambda path, download=False: f"https://huggingface.co/datasets/{REPO_ID}/resolve/main/{path}{'?download=true' if download else ''}", is_tma_user_admin_flag=is_admin_tma(), all_folders_for_move=all_folders_for_move)
|
| 613 |
|
| 614 |
@app.route('/create_folder_tma', methods=['POST'])
|
| 615 |
def create_folder_tma():
|
|
@@ -640,7 +708,7 @@ def get_file_node_for_user(file_id):
|
|
| 640 |
for uid, udata in data.get('users', {}).items():
|
| 641 |
node, _ = find_node_by_id(udata.get('filesystem', {}), file_id)
|
| 642 |
if node and node.get('type') == 'file': return node
|
| 643 |
-
else:
|
| 644 |
user_data = data['users'].get(session['telegram_user_id'])
|
| 645 |
if user_data:
|
| 646 |
node, _ = find_node_by_id(user_data.get('filesystem', {}), file_id)
|
|
@@ -653,7 +721,7 @@ def download_tma(file_id):
|
|
| 653 |
if not file_node:
|
| 654 |
flash('Файл не найден или доступ запрещен!', 'error')
|
| 655 |
return redirect(request.referrer or url_for('tma_dashboard'))
|
| 656 |
-
|
| 657 |
hf_path = file_node.get('path')
|
| 658 |
original_filename = file_node.get('original_filename', 'downloaded_file')
|
| 659 |
if not hf_path:
|
|
@@ -666,7 +734,7 @@ def download_tma(file_id):
|
|
| 666 |
if HF_TOKEN_READ: req_headers["authorization"] = f"Bearer {HF_TOKEN_READ}"
|
| 667 |
r = requests.get(file_url, headers=req_headers, stream=True)
|
| 668 |
r.raise_for_status()
|
| 669 |
-
|
| 670 |
resp = Response(r.iter_content(chunk_size=8192), mimetype='application/octet-stream')
|
| 671 |
encoded_filename = quote(original_filename)
|
| 672 |
resp.headers['Content-Disposition'] = f"attachment; filename=\"{encoded_filename}\"; filename*=UTF-8''{encoded_filename}"
|
|
@@ -676,39 +744,6 @@ def download_tma(file_id):
|
|
| 676 |
flash(f'Ошибка скачивания файла: {e}', 'error')
|
| 677 |
return redirect(request.referrer or url_for('tma_dashboard'))
|
| 678 |
|
| 679 |
-
@app.route('/batch_download_tma')
|
| 680 |
-
def batch_download_tma():
|
| 681 |
-
if 'telegram_user_id' not in session: return Response("Unauthorized", 401)
|
| 682 |
-
file_ids_str = request.args.get('file_ids')
|
| 683 |
-
if not file_ids_str: return Response("No file IDs provided", 400)
|
| 684 |
-
|
| 685 |
-
file_ids = file_ids_str.split(',')
|
| 686 |
-
|
| 687 |
-
temp_zip_file = tempfile.NamedTemporaryFile(delete=False, suffix=".zip")
|
| 688 |
-
req_headers = {}
|
| 689 |
-
if HF_TOKEN_READ: req_headers["authorization"] = f"Bearer {HF_TOKEN_READ}"
|
| 690 |
-
|
| 691 |
-
try:
|
| 692 |
-
with zipfile.ZipFile(temp_zip_file, 'w', zipfile.ZIP_DEFLATED) as zf:
|
| 693 |
-
for file_id in file_ids:
|
| 694 |
-
file_node = get_file_node_for_user(file_id)
|
| 695 |
-
if file_node and file_node.get('path'):
|
| 696 |
-
hf_path = file_node['path']
|
| 697 |
-
original_filename = file_node.get('original_filename', file_id)
|
| 698 |
-
file_url = f"https://huggingface.co/datasets/{REPO_ID}/resolve/main/{hf_path}?download=true"
|
| 699 |
-
try:
|
| 700 |
-
r = requests.get(file_url, headers=req_headers, stream=True)
|
| 701 |
-
r.raise_for_status()
|
| 702 |
-
zf.writestr(original_filename, r.content)
|
| 703 |
-
except Exception as e:
|
| 704 |
-
logging.error(f"Failed to download and add {original_filename} to zip: {e}")
|
| 705 |
-
|
| 706 |
-
temp_zip_file.close()
|
| 707 |
-
return send_file(temp_zip_file.name, as_attachment=True, download_name='archive.zip', mimetype='application/zip')
|
| 708 |
-
finally:
|
| 709 |
-
if os.path.exists(temp_zip_file.name):
|
| 710 |
-
os.unlink(temp_zip_file.name)
|
| 711 |
-
|
| 712 |
@app.route('/delete_file_tma/<file_id>', methods=['POST'])
|
| 713 |
def delete_file_tma(file_id):
|
| 714 |
if 'telegram_user_id' not in session: return redirect(url_for('tma_entry_page'))
|
|
@@ -763,7 +798,7 @@ def delete_folder_tma(folder_id):
|
|
| 763 |
except Exception: flash('Ошибка сохранения после удаления папки.', 'error')
|
| 764 |
else: flash('Не удалось удалить папку.', 'error')
|
| 765 |
return redirect(url_for('tma_dashboard', folder_id=parent_node.get('id', 'root')))
|
| 766 |
-
|
| 767 |
@app.route('/batch_delete_tma', methods=['POST'])
|
| 768 |
def batch_delete_tma():
|
| 769 |
if 'telegram_user_id' not in session: return jsonify({'status': 'error', 'message': 'Не авторизован.'}), 401
|
|
@@ -810,7 +845,7 @@ def batch_move_tma():
|
|
| 810 |
if not item_ids or not destination_id: return jsonify({'status': 'error', 'message': 'Не указаны файлы или папка.'}), 400
|
| 811 |
destination_node, _ = find_node_by_id(user_data['filesystem'], destination_id)
|
| 812 |
if not destination_node or destination_node.get('type') != 'folder': return jsonify({'status': 'error', 'message': 'Папка назначения не найдена.'}), 404
|
| 813 |
-
|
| 814 |
descendant_ids = set()
|
| 815 |
for item_id in item_ids:
|
| 816 |
node, _ = find_node_by_id(user_data['filesystem'], item_id)
|
|
@@ -845,7 +880,7 @@ def get_text_content_tma(file_id):
|
|
| 845 |
if not hf_path: return Response("Ошибка: путь к файлу отсутствует", 500)
|
| 846 |
file_url = f"https://huggingface.co/datasets/{REPO_ID}/resolve/main/{hf_path}?download=true"
|
| 847 |
try:
|
| 848 |
-
req_headers = {};
|
| 849 |
if HF_TOKEN_READ: req_headers["authorization"] = f"Bearer {HF_TOKEN_READ}"
|
| 850 |
response = requests.get(file_url, headers=req_headers)
|
| 851 |
response.raise_for_status()
|
|
|
|
| 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")
|
|
|
|
| 61 |
.flash.error { background: rgba(255, 68, 68, 0.1); color: var(--delete-color); }
|
| 62 |
.file-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(150px, 1fr)); gap: 15px; }
|
| 63 |
.item { background: var(--card-bg-dark); border-radius: 16px; text-align: center; transition: var(--transition); position: relative; border: 2px solid transparent; user-select: none; padding: 10px; display: flex; flex-direction: column; }
|
| 64 |
+
.item:hover { transform: translateY(-5px); box-shadow: 0 15px 30px rgba(0,0,0,0.3); }
|
| 65 |
.item:active { transform: scale(0.97); }
|
| 66 |
.item.selected { border-color: var(--accent); background-color: var(--selection-color); }
|
| 67 |
+
.selection-indicator { position: absolute; top: 10px; right: 10px; font-size: 1.5em; color: var(--accent); opacity: 0; transform: scale(0.5); transition: var(--transition); z-index: 5; }
|
| 68 |
+
.item.selected .selection-indicator { opacity: 1; transform: scale(1); }
|
| 69 |
.item-preview-wrapper { position: relative; width: 100%; padding-top: 75%; border-radius: 10px; overflow: hidden; margin-bottom: 10px; cursor: pointer; background: #2a2a2a; }
|
| 70 |
.item-preview { position: absolute; top: 0; left: 0; width: 100%; height: 100%; object-fit: cover; }
|
| 71 |
.item.folder .item-preview { object-fit: contain; font-size: 3.5em; color: var(--folder-color); }
|
|
|
|
| 141 |
if exclude_ids is None:
|
| 142 |
exclude_ids = set()
|
| 143 |
folders = []
|
| 144 |
+
|
| 145 |
def traverse(node, path_prefix):
|
| 146 |
if node.get('type') == 'folder':
|
| 147 |
if node.get('id') not in exclude_ids:
|
|
|
|
| 339 |
<div class="file-grid" id="file-container">
|
| 340 |
{% for item in items %}
|
| 341 |
<div class="item {{ item.type }}" data-id="{{ item.id }}" data-type="{{ item.type }}">
|
| 342 |
+
<div class="selection-indicator"><i class="fa-solid fa-check-circle"></i></div>
|
| 343 |
<div class="item-preview-wrapper" {% if item.type != 'folder' %}onclick="openModal('{{ hf_file_url_jinja(item.path) if item.file_type not in ['text', 'pdf'] else (url_for('get_text_content_tma', file_id=item.id) if item.file_type == 'text' else hf_file_url_jinja(item.path, True)) }}', '{{ item.file_type }}', '{{ item.id }}')"{% else %}onclick="window.location.href='{{ url_for('tma_dashboard', folder_id=item.id) }}'"{% endif %}>
|
| 344 |
{% if item.type == 'folder' %}
|
| 345 |
<div class="item-preview"><i class="fa-solid fa-folder"></i></div>
|
|
|
|
| 402 |
<script>
|
| 403 |
window.Telegram.WebApp.ready();
|
| 404 |
window.Telegram.WebApp.expand();
|
| 405 |
+
|
| 406 |
+
const haptic = (type) => {
|
| 407 |
+
if (!window.Telegram || !window.Telegram.WebApp || !window.Telegram.WebApp.HapticFeedback) return;
|
| 408 |
+
const hf = window.Telegram.WebApp.HapticFeedback;
|
| 409 |
+
try {
|
| 410 |
+
switch(type) {
|
| 411 |
+
case 'light': hf.impactOccurred('light'); break;
|
| 412 |
+
case 'medium': hf.impactOccurred('medium'); break;
|
| 413 |
+
case 'heavy': hf.impactOccurred('heavy'); break;
|
| 414 |
+
case 'success': hf.notificationOccurred('success'); break;
|
| 415 |
+
case 'error': hf.notificationOccurred('error'); break;
|
| 416 |
+
case 'warning': hf.notificationOccurred('warning'); break;
|
| 417 |
+
default: hf.impactOccurred('light');
|
| 418 |
+
}
|
| 419 |
+
} catch (e) { /* Haptic feedback might not be supported */ }
|
| 420 |
+
};
|
| 421 |
+
|
| 422 |
+
const parentFolderId = '{{ parent_folder_id_for_js }}';
|
| 423 |
+
if (parentFolderId) {
|
| 424 |
+
Telegram.WebApp.BackButton.show();
|
| 425 |
+
Telegram.WebApp.BackButton.onClick(() => {
|
| 426 |
+
haptic('light');
|
| 427 |
+
Telegram.WebApp.BackButton.hide();
|
| 428 |
+
window.location.href = `{{ url_for('tma_dashboard') }}?folder_id=${parentFolderId}`;
|
| 429 |
+
});
|
| 430 |
+
} else {
|
| 431 |
+
Telegram.WebApp.BackButton.hide();
|
| 432 |
+
}
|
| 433 |
+
|
| 434 |
async function openModal(srcOrUrl, type) {
|
| 435 |
if (!srcOrUrl) return;
|
| 436 |
const modal = document.getElementById('mediaModal'); const modalContent = document.getElementById('modalContent');
|
|
|
|
| 461 |
if (files.length === 0) { Telegram.WebApp.showAlert('Выберите файлы.'); return; }
|
| 462 |
if (files.length > 20) { Telegram.WebApp.showAlert('Максимум 20 файлов за раз!'); return; }
|
| 463 |
closeFabModal();
|
| 464 |
+
haptic('heavy');
|
| 465 |
const progressContainer = document.getElementById('progress-container');
|
| 466 |
const progressBar = document.getElementById('progress-bar');
|
| 467 |
progressContainer.style.display = 'block'; progressBar.style.width = '0%';
|
|
|
|
| 469 |
xhr.upload.addEventListener('progress', e => {
|
| 470 |
if (e.lengthComputable) progressBar.style.width = Math.round((e.loaded / e.total) * 100) + '%';
|
| 471 |
});
|
| 472 |
+
xhr.addEventListener('load', () => { haptic('success'); window.location.reload(); });
|
| 473 |
+
xhr.addEventListener('error', () => { haptic('error'); Telegram.WebApp.showAlert('Ошибка загрузки.'); });
|
| 474 |
xhr.open('POST', this.action, true); xhr.send(formData);
|
| 475 |
});
|
| 476 |
|
|
|
|
| 494 |
item.addEventListener('pointerdown', e => {
|
| 495 |
if (e.pointerType === 'mouse' && e.button !== 0) return;
|
| 496 |
longPressTimer = setTimeout(() => {
|
| 497 |
+
haptic('medium');
|
| 498 |
if (!selectionMode) toggleSelectionMode(true);
|
| 499 |
item.classList.toggle('selected');
|
| 500 |
if (selectedItems.has(item.dataset.id)) selectedItems.delete(item.dataset.id); else selectedItems.add(item.dataset.id);
|
|
|
|
| 506 |
item.addEventListener('click', e => {
|
| 507 |
if (selectionMode) {
|
| 508 |
e.preventDefault(); e.stopPropagation();
|
| 509 |
+
haptic('light');
|
| 510 |
item.classList.toggle('selected');
|
| 511 |
if (selectedItems.has(item.dataset.id)) selectedItems.delete(item.dataset.id); else selectedItems.add(item.dataset.id);
|
| 512 |
updateSelectionUI();
|
|
|
|
| 521 |
method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body)
|
| 522 |
});
|
| 523 |
const result = await response.json();
|
| 524 |
+
if (result.status === 'success') {
|
| 525 |
+
haptic('success');
|
| 526 |
+
window.location.reload();
|
| 527 |
+
} else {
|
| 528 |
+
haptic('error');
|
| 529 |
+
Telegram.WebApp.showAlert(result.message || 'Произошла ошибка.');
|
| 530 |
+
}
|
| 531 |
+
} catch (error) {
|
| 532 |
+
haptic('error');
|
| 533 |
+
Telegram.WebApp.showAlert('Сетевая ошибка.');
|
| 534 |
+
} finally {
|
| 535 |
+
toggleSelectionMode(false);
|
| 536 |
+
}
|
| 537 |
}
|
| 538 |
+
|
| 539 |
+
function initiateDownload(url) {
|
| 540 |
+
const a = document.createElement('a');
|
| 541 |
+
a.href = url;
|
| 542 |
+
a.style.display = 'none';
|
| 543 |
+
document.body.appendChild(a);
|
| 544 |
+
a.click();
|
| 545 |
+
document.body.removeChild(a);
|
| 546 |
+
}
|
| 547 |
+
|
| 548 |
function downloadSelected() {
|
| 549 |
const fileIds = Array.from(selectedItems).filter(id => {
|
| 550 |
const item = document.querySelector(`.item[data-id='${id}']`);
|
| 551 |
return item && item.dataset.type === 'file';
|
| 552 |
});
|
| 553 |
+
if (fileIds.length === 0) {
|
| 554 |
+
Telegram.WebApp.showAlert('Папки нельзя скачать. Выберите файлы.');
|
| 555 |
+
haptic('error');
|
| 556 |
+
return;
|
| 557 |
+
}
|
| 558 |
+
haptic('success');
|
| 559 |
+
fileIds.forEach((fileId, index) => {
|
| 560 |
+
setTimeout(() => {
|
| 561 |
+
initiateDownload(`/download_tma/${fileId}`);
|
| 562 |
+
}, index * 400);
|
| 563 |
+
});
|
| 564 |
toggleSelectionMode(false);
|
| 565 |
}
|
| 566 |
+
|
| 567 |
+
function showMoveModal() { if (selectedItems.size > 0) { document.getElementById('move-modal').style.display = 'flex'; haptic('light'); } }
|
| 568 |
function closeMoveModal() { document.getElementById('move-modal').style.display = 'none'; }
|
| 569 |
function moveSelected() {
|
| 570 |
+
haptic('medium');
|
| 571 |
const destinationId = document.getElementById('folder-destination-select').value;
|
| 572 |
performBatchAction('{{ url_for("batch_move_tma") }}', { item_ids: Array.from(selectedItems), destination_id: destinationId });
|
| 573 |
closeMoveModal();
|
| 574 |
}
|
| 575 |
function deleteSelected() {
|
| 576 |
if (selectedItems.size === 0) return;
|
| 577 |
+
haptic('warning');
|
| 578 |
Telegram.WebApp.showConfirm(`Удалить ${selectedItems.size} элемент(ов)?`, ok => {
|
| 579 |
+
if (ok) {
|
| 580 |
+
haptic('heavy');
|
| 581 |
+
performBatchAction('{{ url_for("batch_delete_tma") }}', { item_ids: Array.from(selectedItems) });
|
| 582 |
+
}
|
| 583 |
});
|
| 584 |
}
|
| 585 |
|
|
|
|
| 592 |
gridViewBtn.classList.toggle('active', view !== 'list');
|
| 593 |
localStorage.setItem('viewMode', view);
|
| 594 |
}
|
| 595 |
+
gridViewBtn.addEventListener('click', () => { setView('grid'); haptic('light'); });
|
| 596 |
+
listViewBtn.addEventListener('click', () => { setView('list'); haptic('light'); });
|
| 597 |
document.addEventListener('DOMContentLoaded', () => setView(localStorage.getItem('viewMode') || 'grid'));
|
| 598 |
|
| 599 |
const fab = document.getElementById('fab');
|
| 600 |
const fabModal = document.getElementById('fab-modal');
|
| 601 |
+
fab.addEventListener('click', () => { fabModal.style.display = 'flex'; haptic('medium'); });
|
| 602 |
function closeFabModal() { fabModal.style.display = 'none'; }
|
| 603 |
fabModal.addEventListener('click', e => { if (e.target.id === 'fab-modal') closeFabModal(); });
|
| 604 |
</script></body></html>
|
|
|
|
| 675 |
breadcrumbs.reverse()
|
| 676 |
|
| 677 |
all_folders_for_move = get_all_folders(user_data['filesystem'])
|
| 678 |
+
parent_folder_id_for_js = parent_folder.get('id') if parent_folder and current_folder_id != 'root' else ''
|
| 679 |
|
| 680 |
+
return render_template_string(TMA_DASHBOARD_HTML_TEMPLATE, display_name=display_name, items=items_in_folder, current_folder_id=current_folder_id, current_folder=current_folder, breadcrumbs=breadcrumbs, hf_file_url_jinja=lambda path, download=False: f"https://huggingface.co/datasets/{REPO_ID}/resolve/main/{path}{'?download=true' if download else ''}", is_tma_user_admin_flag=is_admin_tma(), all_folders_for_move=all_folders_for_move, parent_folder_id_for_js=parent_folder_id_for_js)
|
| 681 |
|
| 682 |
@app.route('/create_folder_tma', methods=['POST'])
|
| 683 |
def create_folder_tma():
|
|
|
|
| 708 |
for uid, udata in data.get('users', {}).items():
|
| 709 |
node, _ = find_node_by_id(udata.get('filesystem', {}), file_id)
|
| 710 |
if node and node.get('type') == 'file': return node
|
| 711 |
+
else:
|
| 712 |
user_data = data['users'].get(session['telegram_user_id'])
|
| 713 |
if user_data:
|
| 714 |
node, _ = find_node_by_id(user_data.get('filesystem', {}), file_id)
|
|
|
|
| 721 |
if not file_node:
|
| 722 |
flash('Файл не найден или доступ запрещен!', 'error')
|
| 723 |
return redirect(request.referrer or url_for('tma_dashboard'))
|
| 724 |
+
|
| 725 |
hf_path = file_node.get('path')
|
| 726 |
original_filename = file_node.get('original_filename', 'downloaded_file')
|
| 727 |
if not hf_path:
|
|
|
|
| 734 |
if HF_TOKEN_READ: req_headers["authorization"] = f"Bearer {HF_TOKEN_READ}"
|
| 735 |
r = requests.get(file_url, headers=req_headers, stream=True)
|
| 736 |
r.raise_for_status()
|
| 737 |
+
|
| 738 |
resp = Response(r.iter_content(chunk_size=8192), mimetype='application/octet-stream')
|
| 739 |
encoded_filename = quote(original_filename)
|
| 740 |
resp.headers['Content-Disposition'] = f"attachment; filename=\"{encoded_filename}\"; filename*=UTF-8''{encoded_filename}"
|
|
|
|
| 744 |
flash(f'Ошибка скачивания файла: {e}', 'error')
|
| 745 |
return redirect(request.referrer or url_for('tma_dashboard'))
|
| 746 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 747 |
@app.route('/delete_file_tma/<file_id>', methods=['POST'])
|
| 748 |
def delete_file_tma(file_id):
|
| 749 |
if 'telegram_user_id' not in session: return redirect(url_for('tma_entry_page'))
|
|
|
|
| 798 |
except Exception: flash('Ошибка сохранения после удаления папки.', 'error')
|
| 799 |
else: flash('Не удалось удалить папку.', 'error')
|
| 800 |
return redirect(url_for('tma_dashboard', folder_id=parent_node.get('id', 'root')))
|
| 801 |
+
|
| 802 |
@app.route('/batch_delete_tma', methods=['POST'])
|
| 803 |
def batch_delete_tma():
|
| 804 |
if 'telegram_user_id' not in session: return jsonify({'status': 'error', 'message': 'Не авторизован.'}), 401
|
|
|
|
| 845 |
if not item_ids or not destination_id: return jsonify({'status': 'error', 'message': 'Не указаны файлы или папка.'}), 400
|
| 846 |
destination_node, _ = find_node_by_id(user_data['filesystem'], destination_id)
|
| 847 |
if not destination_node or destination_node.get('type') != 'folder': return jsonify({'status': 'error', 'message': 'Папка назначения не найдена.'}), 404
|
| 848 |
+
|
| 849 |
descendant_ids = set()
|
| 850 |
for item_id in item_ids:
|
| 851 |
node, _ = find_node_by_id(user_data['filesystem'], item_id)
|
|
|
|
| 880 |
if not hf_path: return Response("Ошибка: путь к файлу отсутствует", 500)
|
| 881 |
file_url = f"https://huggingface.co/datasets/{REPO_ID}/resolve/main/{hf_path}?download=true"
|
| 882 |
try:
|
| 883 |
+
req_headers = {};
|
| 884 |
if HF_TOKEN_READ: req_headers["authorization"] = f"Bearer {HF_TOKEN_READ}"
|
| 885 |
response = requests.get(file_url, headers=req_headers)
|
| 886 |
response.raise_for_status()
|