Update app.py
Browse files
app.py
CHANGED
|
@@ -364,7 +364,15 @@ TMA_DASHBOARD_HTML_TEMPLATE = '''
|
|
| 364 |
<div id="progress-container"><div id="progress-bar"></div></div>
|
| 365 |
<div class="file-grid" id="file-container">
|
| 366 |
{% for item in items %}
|
| 367 |
-
<div class="item {{ item.type }}" data-id="{{ item.id }}" data-type="{{ item.type }}"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 368 |
<div class="item-preview-wrapper">
|
| 369 |
{% if item.type == 'folder' %}
|
| 370 |
<div class="item-preview"><i class="fa-solid fa-folder"></i></div>
|
|
@@ -436,9 +444,34 @@ TMA_DASHBOARD_HTML_TEMPLATE = '''
|
|
| 436 |
<script>
|
| 437 |
window.Telegram.WebApp.ready();
|
| 438 |
window.Telegram.WebApp.expand();
|
| 439 |
-
|
| 440 |
const haptic = window.Telegram.WebApp.HapticFeedback;
|
| 441 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 442 |
async function openModal(srcOrUrl, type, itemId) {
|
| 443 |
if (!srcOrUrl) return;
|
| 444 |
haptic.impactOccurred('light');
|
|
@@ -450,8 +483,7 @@ TMA_DASHBOARD_HTML_TEMPLATE = '''
|
|
| 450 |
modal.style.display = 'flex';
|
| 451 |
|
| 452 |
if (type !== 'folder' && itemId) {
|
| 453 |
-
|
| 454 |
-
downloadBtn.onclick = () => { tmaDownloadFile(downloadUrl); };
|
| 455 |
downloadBtn.style.display = 'inline-block';
|
| 456 |
} else {
|
| 457 |
downloadBtn.style.display = 'none';
|
|
@@ -465,7 +497,7 @@ TMA_DASHBOARD_HTML_TEMPLATE = '''
|
|
| 465 |
const response = await fetch(srcOrUrl); if (!response.ok) throw new Error(`Ошибка: ${response.statusText}`);
|
| 466 |
const text = await response.text();
|
| 467 |
modalContent.innerHTML = `<pre>${text.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}</pre>`;
|
| 468 |
-
}
|
| 469 |
} catch (error) { modalContent.innerHTML = `<p>Ошибка предпросмотра: ${error.message}</p>`; }
|
| 470 |
}
|
| 471 |
|
|
@@ -478,12 +510,6 @@ TMA_DASHBOARD_HTML_TEMPLATE = '''
|
|
| 478 |
document.getElementById('modal-download-btn').style.display = 'none';
|
| 479 |
}
|
| 480 |
|
| 481 |
-
function tmaDownloadFile(downloadUrl) {
|
| 482 |
-
haptic.impactOccurred('medium');
|
| 483 |
-
if (window.Telegram && window.Telegram.WebApp && Telegram.WebApp.openLink) { Telegram.WebApp.openLink(downloadUrl, {try_instant_view: false}); }
|
| 484 |
-
else { window.open(downloadUrl, '_blank'); }
|
| 485 |
-
}
|
| 486 |
-
|
| 487 |
document.getElementById('upload-form')?.addEventListener('submit', function(e) {
|
| 488 |
e.preventDefault(); const files = document.getElementById('file-input').files;
|
| 489 |
if (files.length === 0) { Telegram.WebApp.showAlert('Выберите файлы.'); return; }
|
|
@@ -569,8 +595,7 @@ TMA_DASHBOARD_HTML_TEMPLATE = '''
|
|
| 569 |
function downloadSingleSelected() {
|
| 570 |
if (selectedItems.size !== 1) return;
|
| 571 |
const fileId = selectedItems.values().next().value;
|
| 572 |
-
|
| 573 |
-
tmaDownloadFile(url);
|
| 574 |
toggleSelectionMode(false);
|
| 575 |
}
|
| 576 |
|
|
@@ -751,36 +776,55 @@ def get_file_node_for_admin(tma_user_id_str, file_id):
|
|
| 751 |
return node
|
| 752 |
return None
|
| 753 |
|
| 754 |
-
@app.route('/
|
| 755 |
-
def
|
| 756 |
-
|
| 757 |
-
|
| 758 |
-
|
| 759 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 760 |
hf_path = file_node.get('path')
|
| 761 |
original_filename = file_node.get('original_filename', 'downloaded_file')
|
| 762 |
if not hf_path:
|
| 763 |
-
return Response("
|
| 764 |
-
|
| 765 |
try:
|
| 766 |
local_file_path = hf_hub_download(
|
| 767 |
-
repo_id=REPO_ID,
|
| 768 |
-
filename=hf_path,
|
| 769 |
-
repo_type="dataset",
|
| 770 |
-
token=HF_TOKEN_READ,
|
| 771 |
cache_dir=os.path.join(UPLOAD_FOLDER, 'hf_download_cache')
|
| 772 |
)
|
| 773 |
-
return send_file(
|
| 774 |
-
local_file_path,
|
| 775 |
-
as_attachment=True,
|
| 776 |
-
download_name=original_filename
|
| 777 |
-
)
|
| 778 |
except hf_utils.EntryNotFoundError:
|
| 779 |
logging.error(f"File not found on Hugging Face: {hf_path}")
|
| 780 |
-
return Response("
|
| 781 |
except Exception as e:
|
| 782 |
logging.error(f"Error downloading {file_id} from HF via hf_hub_download: {e}")
|
| 783 |
-
return Response(f'
|
| 784 |
|
| 785 |
@app.route('/batch_download_tma')
|
| 786 |
def batch_download_tma():
|
|
@@ -1202,13 +1246,11 @@ def admin_panel():
|
|
| 1202 |
all_users = data.get('users', {})
|
| 1203 |
search_query = request.args.get('q', '').lower()
|
| 1204 |
|
| 1205 |
-
# Calculate file counts and prepare user data
|
| 1206 |
processed_users = {}
|
| 1207 |
for user_id, user_data in all_users.items():
|
| 1208 |
user_data['file_count'] = count_files_recursive(user_data.get('filesystem'))
|
| 1209 |
processed_users[user_id] = user_data
|
| 1210 |
|
| 1211 |
-
# Filter users if a search query is provided
|
| 1212 |
if search_query:
|
| 1213 |
filtered_users = {}
|
| 1214 |
for user_id, user_data in processed_users.items():
|
|
@@ -1220,7 +1262,6 @@ def admin_panel():
|
|
| 1220 |
else:
|
| 1221 |
users_to_display = processed_users
|
| 1222 |
|
| 1223 |
-
# Sort users by creation date (newest first)
|
| 1224 |
sorted_users = sorted(
|
| 1225 |
users_to_display.items(),
|
| 1226 |
key=lambda item: item[1].get('created_at', '0000-00-00 00:00:00'),
|
|
|
|
| 364 |
<div id="progress-container"><div id="progress-bar"></div></div>
|
| 365 |
<div class="file-grid" id="file-container">
|
| 366 |
{% for item in items %}
|
| 367 |
+
<div class="item {{ item.type }}" data-id="{{ item.id }}" data-type="{{ item.type }}"
|
| 368 |
+
{% if item.type == 'folder' %}
|
| 369 |
+
onclick="window.Telegram.WebApp.HapticFeedback.impactOccurred('light'); window.location.href='{{ url_for('tma_dashboard', folder_id=item.id) }}'"
|
| 370 |
+
{% elif item.file_type in ['image', 'video', 'pdf', 'text'] %}
|
| 371 |
+
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 }}')"
|
| 372 |
+
{% else %}
|
| 373 |
+
onclick="tmaDownloadFile('{{ item.id }}')"
|
| 374 |
+
{% endif %}
|
| 375 |
+
>
|
| 376 |
<div class="item-preview-wrapper">
|
| 377 |
{% if item.type == 'folder' %}
|
| 378 |
<div class="item-preview"><i class="fa-solid fa-folder"></i></div>
|
|
|
|
| 444 |
<script>
|
| 445 |
window.Telegram.WebApp.ready();
|
| 446 |
window.Telegram.WebApp.expand();
|
|
|
|
| 447 |
const haptic = window.Telegram.WebApp.HapticFeedback;
|
| 448 |
|
| 449 |
+
async function tmaDownloadFile(fileId) {
|
| 450 |
+
if(!fileId) return;
|
| 451 |
+
haptic.impactOccurred('medium');
|
| 452 |
+
try {
|
| 453 |
+
const tokenUrl = `{{ url_for('generate_download_token_tma', file_id='__FILE_ID__') }}`.replace('__FILE_ID__', fileId);
|
| 454 |
+
const response = await fetch(tokenUrl);
|
| 455 |
+
if (!response.ok) throw new Error(`Server error: ${response.status}`);
|
| 456 |
+
const data = await response.json();
|
| 457 |
+
|
| 458 |
+
if (data.status === 'success' && data.token) {
|
| 459 |
+
const downloadUrl = `{{ url_for('download_with_token_tma', token='__TOKEN__') }}`.replace('__TOKEN__', data.token);
|
| 460 |
+
if (window.Telegram && window.Telegram.WebApp && Telegram.WebApp.openLink) {
|
| 461 |
+
Telegram.WebApp.openLink(downloadUrl, {try_instant_view: false});
|
| 462 |
+
} else {
|
| 463 |
+
window.open(downloadUrl, '_blank');
|
| 464 |
+
}
|
| 465 |
+
} else {
|
| 466 |
+
Telegram.WebApp.showAlert(data.message || 'Не удалось получить ссылку на скачивание.');
|
| 467 |
+
haptic.notificationOccurred('error');
|
| 468 |
+
}
|
| 469 |
+
} catch (error) {
|
| 470 |
+
Telegram.WebApp.showAlert('Сетевая ошибка при подготовке файла к скачиванию: ' + error.message);
|
| 471 |
+
haptic.notificationOccurred('error');
|
| 472 |
+
}
|
| 473 |
+
}
|
| 474 |
+
|
| 475 |
async function openModal(srcOrUrl, type, itemId) {
|
| 476 |
if (!srcOrUrl) return;
|
| 477 |
haptic.impactOccurred('light');
|
|
|
|
| 483 |
modal.style.display = 'flex';
|
| 484 |
|
| 485 |
if (type !== 'folder' && itemId) {
|
| 486 |
+
downloadBtn.onclick = () => { tmaDownloadFile(itemId); };
|
|
|
|
| 487 |
downloadBtn.style.display = 'inline-block';
|
| 488 |
} else {
|
| 489 |
downloadBtn.style.display = 'none';
|
|
|
|
| 497 |
const response = await fetch(srcOrUrl); if (!response.ok) throw new Error(`Ошибка: ${response.statusText}`);
|
| 498 |
const text = await response.text();
|
| 499 |
modalContent.innerHTML = `<pre>${text.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}</pre>`;
|
| 500 |
+
}
|
| 501 |
} catch (error) { modalContent.innerHTML = `<p>Ошибка предпросмотра: ${error.message}</p>`; }
|
| 502 |
}
|
| 503 |
|
|
|
|
| 510 |
document.getElementById('modal-download-btn').style.display = 'none';
|
| 511 |
}
|
| 512 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 513 |
document.getElementById('upload-form')?.addEventListener('submit', function(e) {
|
| 514 |
e.preventDefault(); const files = document.getElementById('file-input').files;
|
| 515 |
if (files.length === 0) { Telegram.WebApp.showAlert('Выберите файлы.'); return; }
|
|
|
|
| 595 |
function downloadSingleSelected() {
|
| 596 |
if (selectedItems.size !== 1) return;
|
| 597 |
const fileId = selectedItems.values().next().value;
|
| 598 |
+
tmaDownloadFile(fileId);
|
|
|
|
| 599 |
toggleSelectionMode(false);
|
| 600 |
}
|
| 601 |
|
|
|
|
| 776 |
return node
|
| 777 |
return None
|
| 778 |
|
| 779 |
+
@app.route('/generate_download_token_tma/<file_id>')
|
| 780 |
+
def generate_download_token_tma(file_id):
|
| 781 |
+
if 'telegram_user_id' not in session:
|
| 782 |
+
return jsonify({'status': 'error', 'message': 'Authentication required'}), 401
|
| 783 |
+
tma_user_id = session['telegram_user_id']
|
| 784 |
+
data = load_data()
|
| 785 |
+
user_data = data['users'].get(tma_user_id)
|
| 786 |
+
if not user_data:
|
| 787 |
+
return jsonify({'status': 'error', 'message': 'User not found'}), 404
|
| 788 |
+
file_node, _ = find_node_by_id(user_data.get('filesystem', {}), file_id)
|
| 789 |
+
if not file_node or file_node.get('type') != 'file':
|
| 790 |
+
return jsonify({'status': 'error', 'message': 'File not found or access denied'}), 404
|
| 791 |
+
token = str(uuid.uuid4())
|
| 792 |
+
cache.set(f"download_token_{token}", {'file_id': file_id, 'user_id': tma_user_id}, timeout=60)
|
| 793 |
+
return jsonify({'status': 'success', 'token': token})
|
| 794 |
+
|
| 795 |
+
@app.route('/download_with_token_tma/<token>')
|
| 796 |
+
def download_with_token_tma(token):
|
| 797 |
+
token_data = cache.get(f"download_token_{token}")
|
| 798 |
+
if not token_data:
|
| 799 |
+
return Response("Download link is invalid or has expired.", status=403)
|
| 800 |
+
cache.delete(f"download_token_{token}")
|
| 801 |
+
file_id = token_data.get('file_id')
|
| 802 |
+
user_id = token_data.get('user_id')
|
| 803 |
+
if not file_id or not user_id:
|
| 804 |
+
return Response("Invalid token data.", status=500)
|
| 805 |
+
data = load_data()
|
| 806 |
+
user_data = data['users'].get(user_id)
|
| 807 |
+
if not user_data:
|
| 808 |
+
return Response("User associated with this download not found.", status=404)
|
| 809 |
+
file_node, _ = find_node_by_id(user_data.get('filesystem', {}), file_id)
|
| 810 |
+
if not file_node or file_node.get('type') != 'file':
|
| 811 |
+
return Response("File not found or has been moved.", status=404)
|
| 812 |
hf_path = file_node.get('path')
|
| 813 |
original_filename = file_node.get('original_filename', 'downloaded_file')
|
| 814 |
if not hf_path:
|
| 815 |
+
return Response("Error: File path not found in metadata.", status=500)
|
|
|
|
| 816 |
try:
|
| 817 |
local_file_path = hf_hub_download(
|
| 818 |
+
repo_id=REPO_ID, filename=hf_path, repo_type="dataset", token=HF_TOKEN_READ,
|
|
|
|
|
|
|
|
|
|
| 819 |
cache_dir=os.path.join(UPLOAD_FOLDER, 'hf_download_cache')
|
| 820 |
)
|
| 821 |
+
return send_file(local_file_path, as_attachment=True, download_name=original_filename)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 822 |
except hf_utils.EntryNotFoundError:
|
| 823 |
logging.error(f"File not found on Hugging Face: {hf_path}")
|
| 824 |
+
return Response("File not found in remote storage.", status=404)
|
| 825 |
except Exception as e:
|
| 826 |
logging.error(f"Error downloading {file_id} from HF via hf_hub_download: {e}")
|
| 827 |
+
return Response(f'Error downloading file: {e}', status=502)
|
| 828 |
|
| 829 |
@app.route('/batch_download_tma')
|
| 830 |
def batch_download_tma():
|
|
|
|
| 1246 |
all_users = data.get('users', {})
|
| 1247 |
search_query = request.args.get('q', '').lower()
|
| 1248 |
|
|
|
|
| 1249 |
processed_users = {}
|
| 1250 |
for user_id, user_data in all_users.items():
|
| 1251 |
user_data['file_count'] = count_files_recursive(user_data.get('filesystem'))
|
| 1252 |
processed_users[user_id] = user_data
|
| 1253 |
|
|
|
|
| 1254 |
if search_query:
|
| 1255 |
filtered_users = {}
|
| 1256 |
for user_id, user_data in processed_users.items():
|
|
|
|
| 1262 |
else:
|
| 1263 |
users_to_display = processed_users
|
| 1264 |
|
|
|
|
| 1265 |
sorted_users = sorted(
|
| 1266 |
users_to_display.items(),
|
| 1267 |
key=lambda item: item[1].get('created_at', '0000-00-00 00:00:00'),
|