Update app.py
Browse files363 unmodified lines36436536636736836937065 unmodified lines4364374384394404414424434445 unmodified lines4504514524534544554564577 unmodified lines4654664674684694704716 unmodified lines47847948048148248348448548648748848979 unmodified lines569570571572573574575576174 unmodified lines751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786415 unmodified lines12021203120412051206120712081209121012111212121312145 unmodified lines1220122112221223122412251226363 unmodified lines<div id="progress-container"><div id="progress-bar"></div></div><div class="file-grid" id="file-container">{% for item in items %}<div class="item {{ item.type }}" data-id="{{ item.id }}" data-type="{{ item.type }}" {% 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.Telegram.WebApp.HapticFeedback.impactOccurred('light'); window.location.href='{{ url_for('tma_dashboard', folder_id=item.id) }}'"{% endif %}><div class="item-preview-wrapper">{% if item.type == 'folder' %}<div class="item-preview"><i class="fa-solid fa-folder"></i></div>65 unmodified lines<script>window.Telegram.WebApp.ready();window.Telegram.WebApp.expand();const haptic = window.Telegram.WebApp.HapticFeedback;async function openModal(srcOrUrl, type, itemId) {if (!srcOrUrl) return;haptic.impactOccurred('light');5 unmodified linesmodal.style.display = 'flex';if (type !== 'folder' && itemId) {const downloadUrl = `{{ url_for('download_tma', file_id='__FILE_ID__') }}`.replace('__FILE_ID__', itemId);downloadBtn.onclick = () => { tmaDownloadFile(downloadUrl); };downloadBtn.style.display = 'inline-block';} else {downloadBtn.style.display = 'none';7 unmodified linesconst response = await fetch(srcOrUrl); if (!response.ok) throw new Error(`Ошибка: ${response.statusText}`);const text = await response.text();modalContent.innerHTML = `<pre>${text.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}</pre>`;} else tmaDownloadFile(srcOrUrl);} catch (error) { modalContent.innerHTML = `<p>Ошибка предпросмотра: ${error.message}</p>`; }}6 unmodified linesdocument.getElementById('modal-download-btn').style.display = 'none';}function tmaDownloadFile(downloadUrl) {haptic.impactOccurred('medium');if (window.Telegram && window.Telegram.WebApp && Telegram.WebApp.openLink) { Telegram.WebApp.openLink(downloadUrl, {try_instant_view: false}); }else { window.open(downloadUrl, '_blank'); }}document.getElementById('upload-form')?.addEventListener('submit', function(e) {e.preventDefault(); const files = document.getElementById('file-input').files;if (files.length === 0) { Telegram.WebApp.showAlert('Выберите файлы.'); return; }79 unmodified linesfunction downloadSingleSelected() {if (selectedItems.size !== 1) return;const fileId = selectedItems.values().next().value;const url = `{{ url_for("download_tma", file_id='__FILE_ID__') }}`.replace('__FILE_ID__', fileId);tmaDownloadFile(url);toggleSelectionMode(false);}174 unmodified linesreturn nodereturn None@app.route('/download_tma/<file_id>')def download_tma(file_id):file_node = get_file_node_for_user(file_id)if not file_node:return Response("Файл не найден или доступ запрещен!", status=404)hf_path = file_node.get('path')original_filename = file_node.get('original_filename', 'downloaded_file')if not hf_path:return Response("Ошибка: Путь к файлу не найден.", status=500)try:local_file_path = hf_hub_download(repo_id=REPO_ID,filename=hf_path,repo_type="dataset",token=HF_TOKEN_READ,cache_dir=os.path.join(UPLOAD_FOLDER, 'hf_download_cache'))return send_file(local_file_path,as_attachment=True,download_name=original_filename)except hf_utils.EntryNotFoundError:logging.error(f"File not found on Hugging Face: {hf_path}")return Response("Файл не найден на удаленном хранилище.", status=404)except Exception as e:logging.error(f"Error downloading {file_id} from HF via hf_hub_download: {e}")return Response(f'Ошибка скачивания файла: {e}', status=502)@app.route('/batch_download_tma')def batch_download_tma():415 unmodified linesall_users = data.get('users', {})search_query = request.args.get('q', '').lower()# Calculate file counts and prepare user dataprocessed_users = {}for user_id, user_data in all_users.items():user_data['file_count'] = count_files_recursive(user_data.get('filesystem'))processed_users[user_id] = user_data# Filter users if a search query is providedif search_query:filtered_users = {}for user_id, user_data in processed_users.items():5 unmodified lineselse:users_to_display = processed_users# Sort users by creation date (newest first)sorted_users = sorted(users_to_display.items(),key=lambda item: item[1].get('created_at', '0000-00-00 00:00:00'),363 unmodified lines36436536636736836937037137237337437537637737865 unmodified lines4444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764775 unmodified lines4834844854864874884897 unmodified lines4974984995005015025036 unmodified lines51051151251351451579 unmodified lines595596597598599600601174 unmodified lines776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830415 unmodified lines124612471248124912501251125212531254125512565 unmodified lines126212631264126512661267363 unmodified lines<div id="progress-container"><div id="progress-bar"></div></div><div class="file-grid" id="file-container">{% for item in items %}<div class="item {{ item.type }}" data-id="{{ item.id }}" data-type="{{ item.type }}"{% if item.type == 'folder' %}onclick="window.Telegram.WebApp.HapticFeedback.impactOccurred('light'); window.location.href='{{ url_for('tma_dashboard', folder_id=item.id) }}'"{% elif item.file_type in ['image', 'video', 'pdf', 'text'] %}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="tmaDownloadFile('{{ item.id }}')"{% endif %}><div class="item-preview-wrapper">{% if item.type == 'folder' %}<div class="item-preview"><i class="fa-solid fa-folder"></i></div>65 unmodified lines<script>window.Telegram.WebApp.ready();window.Telegram.WebApp.expand();const haptic = window.Telegram.WebApp.HapticFeedback;async function tmaDownloadFile(fileId) {if(!fileId) return;haptic.impactOccurred('medium');try {const tokenUrl = `{{ url_for('generate_download_token_tma', file_id='__FILE_ID__') }}`.replace('__FILE_ID__', fileId);const response = await fetch(tokenUrl);if (!response.ok) throw new Error(`Server error: ${response.status}`);const data = await response.json();if (data.status === 'success' && data.token) {const downloadUrl = `{{ url_for('download_with_token_tma', token='__TOKEN__') }}`.replace('__TOKEN__', data.token);if (window.Telegram && window.Telegram.WebApp && Telegram.WebApp.openLink) {Telegram.WebApp.openLink(downloadUrl, {try_instant_view: false});} else {window.open(downloadUrl, '_blank');}} else {Telegram.WebApp.showAlert(data.message || 'Не удалось получить ссылку на скачивание.');haptic.notificationOccurred('error');}} catch (error) {Telegram.WebApp.showAlert('Сетевая ошибка при подготовке файла к скачиванию: ' + error.message);haptic.notificationOccurred('error');}}async function openModal(srcOrUrl, type, itemId) {if (!srcOrUrl) return;haptic.impactOccurred('light');5 unmodified linesmodal.style.display = 'flex';if (type !== 'folder' && itemId) {downloadBtn.onclick = () => { tmaDownloadFile(itemId); };downloadBtn.style.display = 'inline-block';} else {downloadBtn.style.display = 'none';7 unmodified linesconst response = await fetch(srcOrUrl); if (!response.ok) throw new Error(`Ошибка: ${response.statusText}`);const text = await response.text();modalContent.innerHTML = `<pre>${text.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}</pre>`;}} catch (error) { modalContent.innerHTML = `<p>Ошибка предпросмотра: ${error.message}</p>`; }}6 unmodified linesdocument.getElementById('modal-download-btn').style.display = 'none';}document.getElementById('upload-form')?.addEventListener('submit', function(e) {e.preventDefault(); const files = document.getElementById('file-input').files;if (files.length === 0) { Telegram.WebApp.showAlert('Выберите файлы.'); return; }79 unmodified linesfunction downloadSingleSelected() {if (selectedItems.size !== 1) return;const fileId = selectedItems.values().next().value;tmaDownloadFile(fileId);toggleSelectionMode(false);}174 unmodified linesreturn nodereturn None@app.route('/generate_download_token_tma/<file_id>')def generate_download_token_tma(file_id):if 'telegram_user_id' not in session:return jsonify({'status': 'error', 'message': 'Authentication required'}), 401tma_user_id = session['telegram_user_id']data = load_data()user_data = data['users'].get(tma_user_id)if not user_data:return jsonify({'status': 'error', 'message': 'User not found'}), 404file_node, _ = find_node_by_id(user_data.get('filesystem', {}), file_id)if not file_node or file_node.get('type') != 'file':return jsonify({'status': 'error', 'message': 'File not found or access denied'}), 404token = str(uuid.uuid4())cache.set(f"download_token_{token}", {'file_id': file_id, 'user_id': tma_user_id}, timeout=60)return jsonify({'status': 'success', 'token': token})@app.route('/download_with_token_tma/<token>')def download_with_token_tma(token):token_data = cache.get(f"download_token_{token}")if not token_data:return Response("Download link is invalid or has expired.", status=403)cache.delete(f"download_token_{token}")file_id = token_data.get('file_id')user_id = token_data.get('user_id')if not file_id or not user_id:return Response("Invalid token data.", status=500)data = load_data()user_data = data['users'].get(user_id)if not user_data:return Response("User associated with this download not found.", status=404)file_node, _ = find_node_by_id(user_data.get('filesystem', {}), file_id)if not file_node or file_node.get('type') != 'file':return Response("File not found or has been moved.", status=404)hf_path = file_node.get('path')original_filename = file_node.get('original_filename', 'downloaded_file')if not hf_path:return Response("Error: File path not found in metadata.", status=500)try:local_file_path = hf_hub_download(repo_id=REPO_ID, filename=hf_path, repo_type="dataset", token=HF_TOKEN_READ,cache_dir=os.path.join(UPLOAD_FOLDER, 'hf_download_cache'))return send_file(local_file_path, as_attachment=True, download_name=original_filename)except hf_utils.EntryNotFoundError:logging.error(f"File not found on Hugging Face: {hf_path}")return Response("File not found in remote storage.", status=404)except Exception as e:logging.error(f"Error downloading {file_id} from HF via hf_hub_download: {e}")return Response(f'Error downloading file: {e}', status=502)@app.route('/batch_download_tma')def batch_download_tma():415 unmodified linesall_users = data.get('users', {})search_query = request.args.get('q', '').lower()processed_users = {}for user_id, user_data in all_users.items():user_data['file_count'] = count_files_recursive(user_data.get('filesystem'))processed_users[user_id] = user_dataif search_query:filtered_users = {}for user_id, user_data in processed_users.items():5 unmodified lineselse:users_to_display = processed_userssorted_users = sorted(users_to_display.items(),key=lambda item: item[1].get('created_at', '0000-00-00 00:00:00'),
app.py+76-35