Update app.py
Browse files12 unmodified lines13141516171819155 unmodified lines1751761771781791801811821831844 unmodified lines1891901911921931941951961974 unmodified lines20220320420520620720820921021119 unmodified lines231232233234235236237238239240116 unmodified lines3573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084092 unmodified lines412413414415416417418419420421422423424425426427428429430431133 unmodified lines56556656756856957023 unmodified lines59459559659759859960022 unmodified lines62362462562662762862911 unmodified lines64164264364464564664752 unmodified lines7007017027037047057067077087097107117127137147157167176 unmodified lines7247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597602 unmodified lines76376476576676776876918 unmodified lines78878979079179279379479579679718 unmodified lines81681781881982082182282382482582611 unmodified lines83883984084184284384484584684784884985085126 unmodified lines87887988088188288388469 unmodified lines95495595695795895996014 unmodified lines97597697797897998098198298398498598698798810 unmodified lines999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103617 unmodified lines105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611274 unmodified lines11321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041 unmodified line120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012316 unmodified lines12381239124012411242124312441 unmodified line124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313047 unmodified lines13121313131413151316131713181319132013211322132312 unmodified lines133613371338133913401341134213431344134513464 unmodified lines135113521353135413551356135713 unmodified lines1371137213731374137513762 unmodified lines137913801381138213831384138512 unmodified linesfrom io import BytesIOimport uuidfrom functools import wrapsimport urllib.parseapp = Flask(__name__)app.secret_key = os.getenv("FLASK_SECRET_KEY", "supersecretkey_folders_unique_tma")155 unmodified linestotal_size = 0if not filesystem_node:return 0if filesystem_node.get('type') == 'file':return filesystem_node.get('size_bytes', 0)if filesystem_node.get('type') == 'folder' and 'children' in filesystem_node:for child in filesystem_node['children']:total_size += calculate_current_storage_usage(child)4 unmodified linesuser_data['filesystem'] = {"type": "folder", "id": "root", "name": "root", "children": []}user_data.setdefault('storage_limit_gb', DEFAULT_STORAGE_LIMIT_GB)user_data.setdefault('unlimited_storage', False)user_data.setdefault('storage_used_bytes', 0)if 'files' in user_data and isinstance(user_data['files'], list):4 unmodified linesname_part, ext_part = os.path.splitext(original_filename)unique_suffix = uuid.uuid4().hex[:8]unique_filename = f"{name_part}_{unique_suffix}{ext_part}"estimated_size = 0existing_path = old_file.get('path')if not existing_path:existing_path = f"cloud_files/{tma_user_id_str}/root/{unique_filename}"19 unmodified linesdata = {'users': {}, 'promocodes': {}}data.setdefault('users', {})data.setdefault('promocodes', {})for tma_user_id_str, user_data_item in data['users'].items():user_data_item.setdefault('storage_limit_gb', DEFAULT_STORAGE_LIMIT_GB)user_data_item.setdefault('unlimited_storage', False)initialize_user_filesystem_tma(user_data_item, tma_user_id_str)user_data_item['storage_used_bytes'] = calculate_current_storage_usage(user_data_item['filesystem'])116 unmodified lines</script></body></html>'''@app.route('/tma')def tma_entry_page():return render_template_string(TMA_ENTRY_HTML)@app.route('/')def root_redirect():return redirect(url_for('tma_entry_page'))@app.route('/auth_via_telegram', methods=['POST'])def auth_via_telegram():try:payload = request.jsontg_user_data = payload.get('user')if not tg_user_data or not tg_user_data.get('id'):return jsonify({'status': 'error', 'message': 'Отсутствуют данные пользователя Telegram.'}), 400tma_user_id_str = str(tg_user_data['id'])data = load_data()if tma_user_id_str not in data['users']:data['users'][tma_user_id_str] = {'telegram_id': tg_user_data['id'],'telegram_username': tg_user_data.get('username'),'first_name': tg_user_data.get('first_name'),'last_name': tg_user_data.get('last_name'),'created_at': datetime.now().strftime('%Y-%m-%d %H:%M:%S'),'filesystem': {"type": "folder", "id": "root", "name": "root", "children": []}}initialize_user_filesystem_tma(data['users'][tma_user_id_str], tma_user_id_str)try:save_data(data)except Exception as e:logging.error(f"Save data error for new TMA user {tma_user_id_str}: {e}")return jsonify({'status': 'error', 'message': 'Ошибка сохранения данных нового пользователя.'}), 500session['telegram_user_id'] = tma_user_id_strdisplay_name = tg_user_data.get('first_name') or tg_user_data.get('username') or f"User {tma_user_id_str}"session['telegram_display_name'] = display_namereturn jsonify({'status': 'success', 'redirect_url': url_for('tma_dashboard')})except Exception as e:logging.error(f"Error in auth_via_telegram: {e}")return jsonify({'status': 'error', 'message': 'Внутренняя ошибка сервера при авторизации.'}), 500TMA_DASHBOARD_HTML_TEMPLATE = '''<!DOCTYPE html><html lang="ru"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Zeus Cloud</title><link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600;800&display=swap" rel="stylesheet">2 unmodified lines<h1>Zeus Cloud</h1><p>Пользователь: {{ display_name }}</p><p>{% if user_data.unlimited_storage %}Память: Безлимитно (Использовано: {{ storage_used_formatted }}){% else %}Память: {{ storage_used_formatted }} из {{ user_data.storage_limit_gb }} ГБ{% endif %}</p>{% if not user_data.unlimited_storage %}<div style="margin-bottom: 20px; display: flex; flex-wrap: wrap; gap: 10px; align-items: center;"><a href="https://t.me/morshenkhan?text={{ 'здравствуйте , хочу приобрести полный доступ на zeuscloud' | urlencode }}" target="_blank" class="btn" style="background: var(--secondary); margin: 0;">Приобрести безлимит ($20)</a><form method="POST" action="{{ url_for('activate_promo_tma') }}" style="display: contents; flex-grow: 1;"><input type="text" name="promo_code" placeholder="Введите промокод" required style="margin: 0;"><button type="submit" class="btn" style="margin: 0;">Активировать</button></form></div>{% endif %}{% with messages = get_flashed_messages(with_categories=true) %}{% if messages %}{% for category, message in messages %}<div class="flash {{ category }}">{{ message }}</div>{% endfor %}{% endif %}{% endwith %}133 unmodified lines</script></body></html>'''@app.route('/tma_dashboard', methods=['GET', 'POST'])def tma_dashboard():if 'telegram_user_id' not in session:23 unmodified linesflash('Критическая ошибка: корневая папка не найдена.', 'error')session.clear()return redirect(url_for('tma_entry_page'))items_in_folder = sorted(current_folder.get('children', []), key=lambda x: (x['type'] != 'folder', x.get('name', x.get('original_filename', '')).lower()))if request.method == 'POST':22 unmodified linesfile_obj.seek(0, os.SEEK_END)total_new_files_size += file_obj.tell()file_obj.seek(0)if user_data['storage_used_bytes'] + total_new_files_size > user_data['storage_limit_gb'] * BYTES_IN_GB:flash(f'Недостаточно места! Ваш лимит {user_data["storage_limit_gb"]} ГБ, использовано {format_bytes(user_data["storage_used_bytes"])}. 'f'Эти файлы слишком большие ({format_bytes(total_new_files_size)}).', 'error')11 unmodified linesfile_id = uuid.uuid4().hexhf_path = f"cloud_files/{tma_user_id}/{target_folder_id}/{unique_filename}"temp_path = os.path.join(UPLOAD_FOLDER, f"{file_id}_{unique_filename}")file_obj.save(temp_path)file_size = os.path.getsize(temp_path)52 unmodified linesis_tma_user_admin_flag=is_admin_tma(),user_data=user_data, storage_used_formatted=storage_used_formatted)@app.route('/activate_promo_tma', methods=['POST'])def activate_promo_tma():if 'telegram_user_id' not in session:flash('Пожалуйста, авторизуйтесь.', 'error')return redirect(url_for('tma_entry_page'))tma_user_id = session['telegram_user_id']promo_code = request.form.get('promo_code', '').strip()if not promo_code:flash('Пожалуйста, введите промокод.', 'error')return redirect(url_for('tma_dashboard'))data = load_data()6 unmodified linesreturn redirect(url_for('tma_entry_page'))if user_data.get('unlimited_storage'):flash('У вас уже есть безлимитное хранилище.', 'info')return redirect(url_for('tma_dashboard'))promo_data = promocodes.get(promo_code)if not promo_data:flash('Неверный промокод.', 'error')return redirect(url_for('tma_dashboard'))if promo_data.get('remaining_activations', 0) <= 0:flash('Этот промокод больше не действителен.', 'error')return redirect(url_for('tma_dashboard'))user_data['unlimited_storage'] = Truepromo_data['remaining_activations'] -= 1if 'activated_by' not in promo_data:promo_data['activated_by'] = []promo_data['activated_by'].append({'user_id': tma_user_id,'display_name': session.get('telegram_display_name', f'User {tма_user_id}'),'activation_date': datetime.now().strftime('%Y-%m-%d %H:%M:%S')})try:save_data(data)flash('Промокод успешно активирован! Безлимитное хранилище включено.', 'success')except Exception as e:flash(f'Ошибка сохранения данных при активации промокода: {e}', 'error')return redirect(url_for('tma_dashboard'))@app.route('/create_folder_tma', methods=['POST'])def create_folder_tma():if 'telegram_user_id' not in session:2 unmodified linestma_user_id = session['telegram_user_id']data = load_data()user_data = data['users'].get(tma_user_id)if not user_data:flash('Пользователь не найден', 'error')return redirect(url_for('tma_entry_page'))18 unmodified linesdef download_tma(file_id):current_tma_user_id = session.get('telegram_user_id')is_browser_admin_session = session.get('admin_browser_logged_in', False)data = load_data()file_node = Noneif is_browser_admin_session:for uid_str_iter, udata_iter in data.get('users', {}).items():node, _ = find_node_by_id(udata_iter.get('filesystem', {}), file_id)18 unmodified lineselse:return Response("Unauthorized", status=401, mimetype='text/plain')redirect_url_fallback = url_for('tma_dashboard')if is_browser_admin_session:redirect_url_fallback = url_for('admin_panel')redirect_url = request.referrer or redirect_url_fallback11 unmodified linestry:req_headers = {}if HF_TOKEN_READ: req_headers["authorization"] = f"Bearer {HF_TOKEN_READ}"r = requests.get(file_url, headers=req_headers, stream=True)r.raise_for_status()def generate_chunks():for chunk in r.iter_content(chunk_size=8192):yield chunkmimetype = 'application/octet-stream'if '.' in original_filename:ext = original_filename.rsplit('.', 1)[1].lower()26 unmodified linesif 'telegram_user_id' not in session:flash('Пожалуйста, авторизуйтесь.', 'error')return redirect(url_for('tma_entry_page'))file_id = request.view_args.get('file_id')tma_user_id = session['telegram_user_id']69 unmodified linesdef get_text_content_tma(file_id):current_tma_user_id = session.get('telegram_user_id')is_browser_admin_session = session.get('admin_browser_logged_in', False)data = load_data()file_node = None14 unmodified linesfile_node = node; breakelse:return Response("Не авторизован", status=401)if not file_node or file_node.get('type') != 'file' or file_node.get('file_type') != 'text':return Response("Текстовый файл не найден", status=404)hf_path = file_node.get('path')if not hf_path: return Response("Ошибка: путь к файлу отсутствует", status=500)file_url = f"https://huggingface.co/datasets/{REPO_ID}/resolve/main/{hf_path}?download=true"try:req_headers = {};if HF_TOKEN_READ: req_headers["authorization"] = f"Bearer {HF_TOKEN_READ}"response = requests.get(file_url, headers=req_headers)response.raise_for_status()10 unmodified linesflash('Вы вышли из сессии приложения.')return redirect(url_for('tma_entry_page'))ADMIN_LOGIN_HTML_TEMPLATE = '''<!DOCTYPE html><html lang="ru"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Admin Login</title><link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600;800&display=swap" rel="stylesheet"><style>{{ admin_base_style_css }}body { display: flex; justify-content: center; align-items: center; height: 100vh; background: var(--background-dark); }.login-container { text-align: center; padding: 40px; background: var(--card-bg-dark); border-radius: 20px; box-shadow: var(--shadow); width: 100%; max-width: 400px; }h1 { color: var(--primary); margin-bottom: 20px; }input[type="text"], input[type="password"] { background: rgba(255,255,255,0.1); color: var(--text-dark); margin-bottom: 20px; }.btn { background: var(--accent); width: 100%; }</style></head><body class="dark"><div class="login-container"><h1>Admin Login</h1>{% with messages = get_flashed_messages(with_categories=true) %}{% if messages %}{% for category, message in messages %}<div class="flash {{ category }}">{{ message }}</div>{% endfor %}{% endif %}{% endwith %}<form method="POST" action="{{ url_for('admin_login') }}"><input type="hidden" name="next" value="{{ request.args.get('next', '') }}"><input type="text" name="username" placeholder="Username" required><input type="password" name="password" placeholder="Password" required><button type="submit" class="btn">Login</button></form></div></body></html>'''@app.route('/admin/login', methods=['GET', 'POST'])def admin_login():if request.method == 'POST':17 unmodified linesflash('Вы вышли из админ-панели.', 'success')return redirect(url_for('admin_login'))ADMIN_PANEL_HTML_TEMPLATE = '''<!DOCTYPE html><html lang="ru"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Админ-панель</title><link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600;800&display=swap" rel="stylesheet"><style>''' + BASE_STYLE + '''</style></head><body class="dark"><div class="container"><h1>Админ-панель</h1><a href="{{ url_for('admin_logout') }}" class="btn" style="margin-bottom:20px; background-color: var(--accent);">Выйти из админ-панели</a><a href="{{ url_for('tma_dashboard') }}" class="btn" style="margin-bottom:20px;">В приложение (если TMA сессия есть)</a>{% with messages = get_flashed_messages(with_categories=true) %}{% if messages %}{% for category, message in messages %}<div class="flash {{ category }}">{{ message }}</div>{% endfor %}{% endif %}{% endwith %}<h2>Управление промокодами</h2><form method="POST" action="{{ url_for('admin_create_promo') }}" style="margin-bottom: 20px;"><input type="text" name="promo_code" placeholder="Новый промокод" required><input type="number" name="activations" placeholder="Количество активаций" required min="1"><button type="submit" class="btn">Создать промокод</button></form><div class="user-list">{% for code, details in promocodes.items() %}<div class="user-item"><div style="display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap;"><p><b>Код: {{ code }}</b> (Активаций: {{ (details.total_activations or 0) - (details.remaining_activations or 0) }} / {{ details.total_activations or 'N/A' }})</p><form method="POST" action="{{ url_for('admin_delete_promo', code=code) }}" style="display:inline;" onsubmit="return confirm('Удалить промокод {{ code }}?')"><button type="submit" class="btn delete-btn" style="padding: 5px 10px; font-size: 0.9em;">Удалить</button></form></div>{% if details.activated_by %}<h4 style="margin-top:10px;">Активировали:</h4><ul style="font-size: 0.9em;">{% for activator in details.activated_by %}<li>{{ activator.display_name }} (ID: {{ activator.user_id }}) - {{ activator.activation_date }}</li>{% endfor %}</ul>{% endif %}</div>{% else %}<p>Промокодов нет.</p>{% endfor %}</div><h2>Пользователи</h2><div class="user-list">{% for user in user_details %}<div class="user-item"><a href="{{ url_for('admin_user_files', tma_user_id_str=user.id_key) }}">{{ user.display_name }} (ID: {{user.id_key}})</a><p>Зарегистрирован: {{ user.created_at }}</p><p>Файлов: {{ user.file_count }}</p><p>Память: {% if user.unlimited_storage %}Безлимитно ({{ user.storage_used_formatted }}){% else %}{{ user.storage_used_formatted }} из {{ user.storage_limit_gb }} ГБ{% endif %}</p><form method="POST" action="{{ url_for('admin_delete_user', tma_user_id_str=user.id_key) }}" style="display: inline; margin-left: 10px;" onsubmit="return confirm('УДАЛИТЬ пользователя {{ user.display_name }} и ВСЕ его файлы? НЕОБРАТИМО!');"><button type="submit" class="btn delete-btn" style="padding: 5px 10px; font-size: 0.9em;">Удалить</button></form></div>{% else %}<p>Пользователей нет.</p>{% endfor %}</div></div></body></html>'''@app.route('/admhosto')@admin_browser_login_requireddef admin_panel():data = load_data()users = data.get('users', {})promocodes = data.get('promocodes', {})user_details = []for tma_id_str, udata in users.items():user_details.append({'id_key': tma_id_str,'display_name': udata.get('first_name', udata.get('telegram_username', f"User {tma_id_str}")),'created_at': udata.get('created_at', 'N/A'),'file_count': sum(1 for _, node in get_all_nodes(udata.get('filesystem', {})) if node.get('type') == 'file'),'storage_limit_gb': udata.get('storage_limit_gb', DEFAULT_STORAGE_LIMIT_GB),'storage_used_formatted': format_bytes(udata.get('storage_used_bytes', 0)),'unlimited_storage': udata.get('unlimited_storage', False)})user_details.sort(key=lambda x: x.get('created_at', ''), reverse=True)return render_template_string(ADMIN_PANEL_HTML_TEMPLATE, user_details=user_details, promocodes=promocodes)def get_all_nodes(filesystem):queue = [filesystem]4 unmodified linesfor child in current_node['children']:queue.append(child)ADMIN_USER_FILES_HTML_TEMPLATE = '''<!DOCTYPE html><html lang="ru"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Файлы {{ display_name_admin_view }}</title><link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600;800&display=swap" rel="stylesheet"><style>''' + BASE_STYLE + '''.file-item { background: var(--card-bg-dark); padding: 15px; border-radius: 16px; box-shadow: var(--shadow); transition: var(--transition); display: flex; flex-direction: column; justify-content: space-between; }.file-preview { max-width: 100%; height: 100px; object-fit: contain; border-radius: 10px; margin-bottom: 10px; display: block; margin-left: auto; margin-right: auto; }.admin-file-actions { margin-top: 10px; display: flex; flex-wrap: wrap; gap: 5px; justify-content: center; }.admin-file-actions .btn { font-size: 0.8em; padding: 4px 8px; margin: 0; }</style></head><body class="dark"><div class="container"><h1>Файлы пользователя: {{ display_name_admin_view }} (ID: {{ tma_user_id_str_admin_view }})</h1><a href="{{ url_for('admin_panel') }}" class="btn" style="margin-bottom: 20px;">Назад к пользователям</a><p>Лимит памяти:{% if user_data_admin_view.unlimited_storage %}Безлимитно (Использовано: {{ storage_used_formatted_admin_view }}){% else %}{{ storage_used_formatted_admin_view }} из {{ user_data_admin_view.storage_limit_gb }} ГБ{% endif %}</p><form method="POST" action="{{ url_for('admin_toggle_unlimited_storage', tma_user_id_str=tma_user_id_str_admin_view) }}" style="display: inline-block;"><button type="submit" class="btn" style="background: var(--accent);">{{ 'Отключить безлимит' if user_data_admin_view.unlimited_storage else 'Включить безлимит' }}</button></form>{% with messages = get_flashed_messages(with_categories=true) %}{% if messages %}{% for category, message in messages %}<div class="flash {{ category }}">{{ message }}</div>{% endfor %}{% endif %}{% endwith %}<div style="display: grid; grid-template-columns: repeat(auto-fill, minmax(220px, 1fr)); gap: 20px;">{% for file_item in files %}<div class="file-item"><div>{% if file_item.file_type == 'image' %} <img class="file-preview" src="{{ hf_file_url_jinja(file_item.path) }}" loading="lazy" onclick="openModalAdmin('{{ hf_file_url_jinja(file_item.path) }}', '{{ file_item.file_type }}', '{{ file_item.id }}')" style="cursor: pointer;">{% elif file_item.file_type == 'video' %} <video class="file-preview" preload="metadata" muted onclick="openModalAdmin('{{ hf_file_url_jinja(file_item.path) }}', '{{ file_item.file_type }}', '{{ file_item.id }}')" style="cursor: pointer;"><source src="{{ hf_file_url_jinja(file_item.path, True) }}#t=0.5"></video>{% elif file_item.file_type == 'pdf' %} <div class="file-preview" style="font-size: 40px; line-height: 100px; text-align: center; color: var(--accent); cursor: pointer;" onclick="openModalAdmin('{{ hf_file_url_jinja(file_item.path, True) }}', '{{ file_item.file_type }}', '{{ file_item.id }}')">📄</div>{% elif file_item.file_type == 'text' %} <div class="file-preview" style="font-size: 40px; line-height: 100px; text-align: center; color: var(--secondary); cursor: pointer;" onclick="openModalAdmin('{{ url_for('get_text_content_tma', file_id=file_item.id) }}', '{{ file_item.file_type }}', '{{ file_item.id }}')">📝</div>{% else %} <div class="file-preview" style="font-size: 40px; line-height: 100px; text-align: center; color: #aaa;">❓</div> {% endif %}<p title="{{ file_item.original_filename }}"><b>{{ file_item.original_filename | truncate(30) }}</b></p><p style="font-size: 0.8em; color: #888;">В папке: {{ file_item.parent_path_str }}</p><p style="font-size: 0.8em; color: #888;">Загружен: {{ file_item.upload_date }}</p><p style="font-size: 0.8em; color: #888;">Размер: {{ file_item.size_formatted }}</p><p style="font-size: 0.7em; color: #ccc;">ID: {{ file_item.id }}</p><p style="font-size: 0.7em; color: #ccc; word-break: break-all;">Path: {{ file_item.path }}</p></div><div class="admin-file-actions"><a href="{{ url_for('download_tma', file_id=file_item.id) }}" class="btn download-btn" download="{{ file_item.original_filename }}">Скачать</a>{% set previewable = file_item.file_type in ['image', 'video', 'pdf', 'text'] %}{% if previewable %}<button type="button" class="btn" style="background: var(--accent);" onclick="openModalAdmin('{{ hf_file_url_jinja(file_item.path) if file_item.file_type != 'text' else url_for('get_text_content_tma', file_id=file_item.id) }}', '{{ file_item.file_type }}', '{{ file_item.id }}')">Просмотр</button>{% endif %}<form method="POST" action="{{ url_for('admin_delete_file', tma_user_id_str_form=tma_user_id_str_admin_view, file_id=file_item.id) }}" style="display: inline-block;" onsubmit="return confirm('Удалить файл {{ file_item.original_filename }}?');"><button type="submit" class="btn delete-btn">Удалить</button></form></div></div>{% else %} <p>У пользователя нет файлов.</p> {% endfor %}</div></div><div class="modal" id="mediaModalAdmin" onclick="closeModalAdminEv(event)"><div class="modal-content" id="modalContentContainerAdmin"><span onclick="closeModalAdminManual()" class="modal-close-btn">×</span><div id="modalContentAdmin"></div></div></div><script>const repoIdJs = "{{ repo_id_js_admin }}";function hfFileUrlAdmin(path, download = false) { let url = `https://huggingface.co/datasets/${repoIdJs}/resolve/main/${path}`; if (download) url += '?download=true'; return url; }async function openModalAdmin(srcOrUrl, type, itemId) {const modal = document.getElementById('mediaModalAdmin'); const modalContent = document.getElementById('modalContentAdmin');modalContent.innerHTML = '<p>Загрузка...</p>'; modal.style.display = 'flex';try {if (type === 'image') modalContent.innerHTML = `<img src="${srcOrUrl}" alt="Просмотр изображения">`;else if (type === 'video') modalContent.innerHTML = `<video controls autoplay style='max-width: 95%; max-height: 85vh;'><source src="${srcOrUrl}" type="video/mp4"></video>`;else if (type === 'pdf') modalContent.innerHTML = `<iframe src="${srcOrUrl}" title="Просмотр PDF"></iframe>`;else if (type === 'text') { const response = await fetch(srcOrUrl); if (!response.ok) throw new Error('Network response was not ok for text file.'); const text = await response.text(); const esc = text.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">"); modalContent.innerHTML = `<pre>${esc}</pre>`;}else modalContent.innerHTML = '<p>Предпросмотр не поддерживается.</p>';} catch (error) { modalContent.innerHTML = `<p>Не удалось загрузить содержимое для предпросмотра. ${error.message}</p>`;}}function closeModalAdminEv(event) { if (event.target === document.getElementById('mediaModalAdmin')) closeModalAdminManual(); }function closeModalAdminManual() {const modal = document.getElementById('mediaModalAdmin'); modal.style.display = 'none';const video = modal.querySelector('video'); if (video) video.pause();const iframe = modal.querySelector('iframe'); if (iframe) iframe.src = 'about:blank';document.getElementById('modalContentAdmin').innerHTML = '';}</script></body></html>'''@app.route('/admhosto/user/<tma_user_id_str>')@admin_browser_login_requireddef admin_user_files(tma_user_id_str):1 unmodified lineuser_data = data.get('users', {}).get(tma_user_id_str)if not user_data:flash(f'Пользователь ID {tma_user_id_str} не найден.', 'error'); return redirect(url_for('admin_panel'))all_files = []def collect_files_admin(folder, current_path_id='root'):parent_path_str = get_node_path_string(user_data['filesystem'], current_path_id)for item in folder.get('children', []):if item.get('type') == 'file':item['parent_path_str'] = parent_path_stritem['size_formatted'] = format_bytes(item.get('size_bytes'))all_files.append(item)elif item.get('type') == 'folder': collect_files_admin(item, item.get('id'))collect_files_admin(user_data.get('filesystem', {}))all_files.sort(key=lambda x: x.get('upload_date', ''), reverse=True)display_name_admin_view = user_data.get('first_name', user_data.get('telegram_username', f"User {tma_user_id_str}"))storage_used_formatted_admin_view = format_bytes(user_data['storage_used_bytes'])return render_template_string(ADMIN_USER_FILES_HTML_TEMPLATE,tma_user_id_str_admin_view=tma_user_id_str, display_name_admin_view=display_name_admin_view, files=all_files,repo_id_js_admin=REPO_ID,hf_file_url_jinja=lambda path, download=False: f"https://huggingface.co/datasets/{REPO_ID}/resolve/main/{path}{'?download=true' if download else ''}",user_data_admin_view=user_data, storage_used_formatted_admin_view=storage_used_formatted_admin_view)6 unmodified linesif not user_data:flash(f'Пользователь {tma_user_id_str} не найден.', 'error')return redirect(url_for('admin_panel'))user_data['unlimited_storage'] = not user_data.get('unlimited_storage', False)try:save_data(data)1 unmodified lineflash(f'Безлимитное хранилище для пользователя {tma_user_id_str} {status}.', 'success')except Exception as e:flash(f'Ошибка при изменении статуса безлимитного хранилища: {e}', 'error')return redirect(url_for('admin_user_files', tma_user_id_str=tma_user_id_str))@app.route('/admhosto/create_promo', methods=['POST'])@admin_browser_login_requireddef admin_create_promo():promo_code = request.form.get('promo_code', '').strip()try:activations = int(request.form.get('activations', 0))except (ValueError, TypeError):flash('Количество активаций должно быть числом.', 'error')return redirect(url_for('admin_panel'))if not promo_code or activations <= 0:flash('Промокод и количество активаций (больше 0) обязательны.', 'error')return redirect(url_for('admin_panel'))data = load_data()if promo_code in data.get('promocodes', {}):flash(f'Промокод "{promo_code}" уже существует.', 'error')return redirect(url_for('admin_panel'))data['promocodes'][promo_code] = {'code': promo_code,'total_activations': activations,'remaining_activations': activations,'activated_by': []}try:save_data(data)flash(f'Промокод "{promo_code}" успешно создан.', 'success')except Exception as e:flash(f'Ошибка сохранения промокода: {e}', 'error')return redirect(url_for('admin_panel'))@app.route('/admhosto/delete_promo/<code>', methods=['POST'])@admin_browser_login_requireddef admin_delete_promo(code):data = load_data()if code in data.get('promocodes', {}):del data['promocodes'][code]try:save_data(data)flash(f'Промокод "{code}" удален.', 'success')except Exception as e:flash(f'Ошибка удаления промокода: {e}', 'error')else:flash(f'Промокод "{code}" не найден.', 'error')return redirect(url_for('admin_panel'))@app.route('/admhosto/delete_user/<tma_user_id_str>', methods=['POST'])@admin_browser_login_requireddef admin_delete_user(tma_user_id_str):7 unmodified linesuser_folder_path_on_hf = f"cloud_files/{tma_user_id_str}"api.delete_folder(folder_path=user_folder_path_on_hf, repo_id=REPO_ID, repo_type="dataset", token=HF_TOKEN_WRITE, ignore_patterns=[".keep"])except hf_utils.HfHubHTTPError as e:if e.response.status_code != 404:flash(f'Ошибка удаления файлов пользователя {tma_user_id_str} с сервера: {e}. Пользователь из базы не удален.', 'error'); return redirect(url_for('admin_panel'))logging.info(f"Folder {user_folder_path_on_hf} not found on HF Hub for user {tma_user_id_str} or was already empty, proceeding with DB deletion.")except Exception as e:flash(f'Ошибка удаления файлов пользователя {tma_user_id_str} с сервера: {e}. Пользователь из базы не удален.', 'error'); return redirect(url_for('admin_panel'))try:del data['users'][tma_user_id_str]save_data(data)12 unmodified linesuser_data = data.get('users', {}).get(tma_user_id_str_form)if not user_data:flash(f'Пользователь {tma_user_id_str_form} не найден.', 'error'); return redirect(url_for('admin_panel'))file_node, _ = find_node_by_id(user_data['filesystem'], file_id)if not file_node or file_node.get('type') != 'file':flash('Файл не найден в базе данных этого пользователя.', 'error'); return redirect(url_for('admin_user_files', tma_user_id_str=tma_user_id_str_form))hf_path = file_node.get('path')original_filename = file_node.get('original_filename', 'файл')file_size_to_deduct = file_node.get('size_bytes', 0)4 unmodified linestry: save_data(data); flash(f'Метаданные файла {original_filename} удалены из базы (путь к файлу на сервере отсутствовал).')except Exception as e: flash('Ошибка сохранения данных после удаления метаданных (путь отсутствовал).', 'error')return redirect(url_for('admin_user_files', tma_user_id_str=tma_user_id_str_form))try:api = HfApi()api.delete_file(path_in_repo=hf_path, repo_id=REPO_ID, repo_type="dataset", token=HF_TOKEN_WRITE)13 unmodified linesflash(f'Ошибка при удалении файла {original_filename}: {e}', 'error')return redirect(url_for('admin_user_files', tma_user_id_str=tma_user_id_str_form))if __name__ == '__main__':if not HF_TOKEN_WRITE: logging.warning("HF_TOKEN (write access) is not set. Uploads/deletions/backups will fail.")2 unmodified linesif ADMIN_USERNAME == "admin" and ADMIN_PASSWORD == "zeusadminpass":logging.warning("Using default admin username/password for browser admin panel. Please change ADMIN_USERNAME and ADMIN_PASSWORD environment variables.")if HF_TOKEN_WRITE:download_db_from_hf()threading.Thread(target=periodic_backup, daemon=True).start()12 unmodified lines131415161718155 unmodified lines1741751761771781791801811821834 unmodified lines1881891901911921931941951961974 unmodified lines20220320420520620720820921021119 unmodified lines231232233234235236237238116 unmodified lines3553563573583593602 unmodified lines363364365366367368369370371372373374375376377378379380381382133 unmodified lines51651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573623 unmodified lines76076176276376476576622 unmodified lines78979079179279379479511 unmodified lines80780880981081181281352 unmodified lines8668678688698708718728738748758768778788798808818826 unmodified lines8898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299302 unmodified lines93393493593693793893918 unmodified lines95895996096196296396496596696718 unmodified lines98698798898999099199299399499599611 unmodified lines1008100910101011101210131014101510161017101810191020102126 unmodified lines104810491050105110521053105469 unmodified lines112411251126112711281129113014 unmodified lines1145114611471148114911501151115211531154115511561157115810 unmodified lines11691170117111721173117417 unmodified lines11921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512164 unmodified lines1221122212231224122512261 unmodified line122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212536 unmodified lines12601261126212631264126512661 unmodified line1268126912701271127212731274127512767 unmodified lines12841285128612871288128912901291129212931294129512 unmodified lines130813091310131113121313131413151316131713184 unmodified lines132313241325132613271328132913 unmodified lines13431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914002 unmodified lines14031404140514061407140812 unmodified linesfrom io import BytesIOimport uuidfrom functools import wrapsapp = Flask(__name__)app.secret_key = os.getenv("FLASK_SECRET_KEY", "supersecretkey_folders_unique_tma")155 unmodified linestotal_size = 0if not filesystem_node:return 0if filesystem_node.get('type') == 'file':return filesystem_node.get('size_bytes', 0)if filesystem_node.get('type') == 'folder' and 'children' in filesystem_node:for child in filesystem_node['children']:total_size += calculate_current_storage_usage(child)4 unmodified linesuser_data['filesystem'] = {"type": "folder", "id": "root", "name": "root", "children": []}user_data.setdefault('storage_limit_gb', DEFAULT_STORAGE_LIMIT_GB)user_data.setdefault('unlimited_storage', False)user_data.setdefault('activated_promocode', None)user_data.setdefault('storage_used_bytes', 0)if 'files' in user_data and isinstance(user_data['files'], list):4 unmodified linesname_part, ext_part = os.path.splitext(original_filename)unique_suffix = uuid.uuid4().hex[:8]unique_filename = f"{name_part}_{unique_suffix}{ext_part}"estimated_size = 0existing_path = old_file.get('path')if not existing_path:existing_path = f"cloud_files/{tma_user_id_str}/root/{unique_filename}"19 unmodified linesdata = {'users': {}, 'promocodes': {}}data.setdefault('users', {})data.setdefault('promocodes', {})for tma_user_id_str, user_data_item in data['users'].items():initialize_user_filesystem_tma(user_data_item, tma_user_id_str)user_data_item['storage_used_bytes'] = calculate_current_storage_usage(user_data_item['filesystem'])116 unmodified lines</script></body></html>'''TMA_DASHBOARD_HTML_TEMPLATE = '''<!DOCTYPE html><html lang="ru"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Zeus Cloud</title><link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600;800&display=swap" rel="stylesheet">2 unmodified lines<h1>Zeus Cloud</h1><p>Пользователь: {{ display_name }}</p><p>{% if user_data.unlimited_storage %}Память: Безлимитно (Использовано: {{ storage_used_formatted }})<br><small style="color: #ccc;">Доступ активирован {% if user_data.activated_promocode %}промокодом: {{ user_data.activated_promocode }}{% else %}администратором{% endif %}.</small>{% else %}Память: {{ storage_used_formatted }} из {{ user_data.storage_limit_gb }} ГБ{% endif %}</p>{% if not user_data.unlimited_storage %}<a href="https://t.me/morshenkhan?text=здравствуйте%2C%20хочу%20приобрести%20полный%20доступ%20на%20zeuscloud" target="_blank" class="btn" style="background: var(--secondary); margin-left: 0; margin-bottom: 10px;">Приобрести доступ к безлимитной памяти</a><form method="POST" action="{{ url_for('activate_promocode_tma') }}" style="margin-top: 15px; display: flex; gap: 10px; align-items: center; flex-wrap: wrap;"><input type="text" name="promocode" placeholder="Введите промокод" required style="margin: 0; flex-grow: 1; min-width: 150px;"><button type="submit" class="btn" style="margin: 0; flex-shrink: 0;">Активировать</button></form>{% endif %}{% with messages = get_flashed_messages(with_categories=true) %}{% if messages %}{% for category, message in messages %}<div class="flash {{ category }}">{{ message }}</div>{% endfor %}{% endif %}{% endwith %}133 unmodified lines</script></body></html>'''ADMIN_LOGIN_HTML_TEMPLATE = '''<!DOCTYPE html><html lang="ru"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Admin Login</title><link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600;800&display=swap" rel="stylesheet"><style>{{ admin_base_style_css }}body { display: flex; justify-content: center; align-items: center; height: 100vh; background: var(--background-dark); }.login-container { text-align: center; padding: 40px; background: var(--card-bg-dark); border-radius: 20px; box-shadow: var(--shadow); width: 100%; max-width: 400px; }h1 { color: var(--primary); margin-bottom: 20px; }input[type="text"], input[type="password"] { background: rgba(255,255,255,0.1); color: var(--text-dark); margin-bottom: 20px; }.btn { background: var(--accent); width: 100%; }</style></head><body class="dark"><div class="login-container"><h1>Admin Login</h1>{% with messages = get_flashed_messages(with_categories=true) %}{% if messages %}{% for category, message in messages %}<div class="flash {{ category }}">{{ message }}</div>{% endfor %}{% endif %}{% endwith %}<form method="POST" action="{{ url_for('admin_login') }}"><input type="hidden" name="next" value="{{ request.args.get('next', '') }}"><input type="text" name="username" placeholder="Username" required><input type="password" name="password" placeholder="Password" required><button type="submit" class="btn">Login</button></form></div></body></html>'''ADMIN_PANEL_HTML_TEMPLATE = '''<!DOCTYPE html><html lang="ru"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Админ-панель</title><link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600;800&display=swap" rel="stylesheet"><style>''' + BASE_STYLE + '''</style></head><body class="dark"><div class="container"><h1>Админ-панель</h1><a href="{{ url_for('admin_logout') }}" class="btn" style="margin-bottom:20px; background-color: var(--accent);">Выйти из админ-панели</a><a href="{{ url_for('tma_dashboard') }}" class="btn" style="margin-bottom:20px;">В приложение (если TMA сессия есть)</a><a href="{{ url_for('admin_promocodes') }}" class="btn" style="margin-bottom:20px; background-color: #ffc107;">Управление промокодами</a>{% with messages = get_flashed_messages(with_categories=true) %}{% if messages %}{% for category, message in messages %}<div class="flash {{ category }}">{{ message }}</div>{% endfor %}{% endif %}{% endwith %}<h2>Пользователи</h2><div class="user-list">{% for user in user_details %}<div class="user-item"><a href="{{ url_for('admin_user_files', tma_user_id_str=user.id_key) }}">{{ user.display_name }} (ID: {{user.id_key}})</a><p>Зарегистрирован: {{ user.created_at }}</p><p>Файлов: {{ user.file_count }}</p><p>Память: {% if user.unlimited_storage %}Безлимитно ({{ user.storage_used_formatted }}){% else %}{{ user.storage_used_formatted }} из {{ user.storage_limit_gb }} ГБ{% endif %}</p>{% if user.activated_promocode %}<p>Активирован промокод: {{ user.activated_promocode }}</p>{% endif %}<form method="POST" action="{{ url_for('admin_delete_user', tma_user_id_str=user.id_key) }}" style="display: inline; margin-left: 10px;" onsubmit="return confirm('УДАЛИТЬ пользователя {{ user.display_name }} и ВСЕ его файлы? НЕОБРАТИМО!');"><button type="submit" class="btn delete-btn" style="padding: 5px 10px; font-size: 0.9em;">Удалить</button></form></div>{% else %}<p>Пользователей нет.</p>{% endfor %}</div></div></body></html>'''ADMIN_USER_FILES_HTML_TEMPLATE = '''<!DOCTYPE html><html lang="ru"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Файлы {{ display_name_admin_view }}</title><link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600;800&display=swap" rel="stylesheet"><style>''' + BASE_STYLE + '''.file-item { background: var(--card-bg-dark); padding: 15px; border-radius: 16px; box-shadow: var(--shadow); transition: var(--transition); display: flex; flex-direction: column; justify-content: space-between; }.file-preview { max-width: 100%; height: 100px; object-fit: contain; border-radius: 10px; margin-bottom: 10px; display: block; margin-left: auto; margin-right: auto; }.admin-file-actions { margin-top: 10px; display: flex; flex-wrap: wrap; gap: 5px; justify-content: center; }.admin-file-actions .btn { font-size: 0.8em; padding: 4px 8px; margin: 0; }</style></head><body class="dark"><div class="container"><h1>Файлы пользователя: {{ display_name_admin_view }} (ID: {{ tma_user_id_str_admin_view }})</h1><a href="{{ url_for('admin_panel') }}" class="btn" style="margin-bottom: 20px;">Назад к пользователям</a><p>Лимит памяти:{% if user_data_admin_view.unlimited_storage %}Безлимитно (Использовано: {{ storage_used_formatted_admin_view }}){% else %}{{ storage_used_formatted_admin_view }} из {{ user_data_admin_view.storage_limit_gb }} ГБ{% endif %}</p><form method="POST" action="{{ url_for('admin_toggle_unlimited_storage', tma_user_id_str=tma_user_id_str_admin_view) }}" style="display: inline-block;"><button type="submit" class="btn" style="background: var(--accent);">{{ 'Отключить безлимит' if user_data_admin_view.unlimited_storage else 'Включить безлимит' }}</button></form>{% with messages = get_flashed_messages(with_categories=true) %}{% if messages %}{% for category, message in messages %}<div class="flash {{ category }}">{{ message }}</div>{% endfor %}{% endif %}{% endwith %}<div style="display: grid; grid-template-columns: repeat(auto-fill, minmax(220px, 1fr)); gap: 20px;">{% for file_item in files %}<div class="file-item"><div>{% if file_item.file_type == 'image' %} <img class="file-preview" src="{{ hf_file_url_jinja(file_item.path) }}" loading="lazy" onclick="openModalAdmin('{{ hf_file_url_jinja(file_item.path) }}', '{{ file_item.file_type }}', '{{ file_item.id }}')" style="cursor: pointer;">{% elif file_item.file_type == 'video' %} <video class="file-preview" preload="metadata" muted onclick="openModalAdmin('{{ hf_file_url_jinja(file_item.path) }}', '{{ file_item.file_type }}', '{{ file_item.id }}')" style="cursor: pointer;"><source src="{{ hf_file_url_jinja(file_item.path, True) }}#t=0.5"></video>{% elif file_item.file_type == 'pdf' %} <div class="file-preview" style="font-size: 40px; line-height: 100px; text-align: center; color: var(--accent); cursor: pointer;" onclick="openModalAdmin('{{ hf_file_url_jinja(file_item.path, True) }}', '{{ file_item.file_type }}', '{{ file_item.id }}')">📄</div>{% elif file_item.file_type == 'text' %} <div class="file-preview" style="font-size: 40px; line-height: 100px; text-align: center; color: var(--secondary); cursor: pointer;" onclick="openModalAdmin('{{ url_for('get_text_content_tma', file_id=file_item.id) }}', '{{ file_item.file_type }}', '{{ file_item.id }}')">📝</div>{% else %} <div class="file-preview" style="font-size: 40px; line-height: 100px; text-align: center; color: #aaa;">❓</div> {% endif %}<p title="{{ file_item.original_filename }}"><b>{{ file_item.original_filename | truncate(30) }}</b></p><p style="font-size: 0.8em; color: #888;">В папке: {{ file_item.parent_path_str }}</p><p style="font-size: 0.8em; color: #888;">Загружен: {{ file_item.upload_date }}</p><p style="font-size: 0.8em; color: #888;">Размер: {{ file_item.size_formatted }}</p><p style="font-size: 0.7em; color: #ccc;">ID: {{ file_item.id }}</p><p style="font-size: 0.7em; color: #ccc; word-break: break-all;">Path: {{ file_item.path }}</p></div><div class="admin-file-actions"><a href="{{ url_for('download_tma', file_id=file_item.id) }}" class="btn download-btn" download="{{ file_item.original_filename }}">Скачать</a>{% set previewable = file_item.file_type in ['image', 'video', 'pdf', 'text'] %}{% if previewable %}<button type="button" class="btn" style="background: var(--accent);" onclick="openModalAdmin('{{ hf_file_url_jinja(file_item.path) if file_item.file_type != 'text' else url_for('get_text_content_tma', file_id=file_item.id) }}', '{{ file_item.file_type }}', '{{ file_item.id }}')">Просмотр</button>{% endif %}<form method="POST" action="{{ url_for('admin_delete_file', tma_user_id_str_form=tma_user_id_str_admin_view, file_id=file_item.id) }}" style="display: inline-block;" onsubmit="return confirm('Удалить файл {{ file_item.original_filename }}?');"><button type="submit" class="btn delete-btn">Удалить</button></form></div></div>{% else %} <p>У пользователя нет файлов.</p> {% endfor %}</div></div><div class="modal" id="mediaModalAdmin" onclick="closeModalAdminEv(event)"><div class="modal-content" id="modalContentContainerAdmin"><span onclick="closeModalAdminManual()" class="modal-close-btn">×</span><div id="modalContentAdmin"></div></div></div><script>const repoIdJs = "{{ repo_id_js_admin }}";function hfFileUrlAdmin(path, download = false) { let url = `https://huggingface.co/datasets/${repoIdJs}/resolve/main/${path}`; if (download) url += '?download=true'; return url; }async function openModalAdmin(srcOrUrl, type, itemId) {const modal = document.getElementById('mediaModalAdmin'); const modalContent = document.getElementById('modalContentAdmin');modalContent.innerHTML = '<p>Загрузка...</p>'; modal.style.display = 'flex';try {if (type === 'image') modalContent.innerHTML = `<img src="${srcOrUrl}" alt="Просмотр изображения">`;else if (type === 'video') modalContent.innerHTML = `<video controls autoplay style='max-width: 95%; max-height: 85vh;'><source src="${srcOrUrl}" type="video/mp4"></video>`;else if (type === 'pdf') modalContent.innerHTML = `<iframe src="${srcOrUrl}" title="Просмотр PDF"></iframe>`;else if (type === 'text') { const response = await fetch(srcOrUrl); if (!response.ok) throw new Error('Network response was not ok for text file.'); const text = await response.text(); const esc = text.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">"); modalContent.innerHTML = `<pre>${esc}</pre>`;}else modalContent.innerHTML = '<p>Предпросмотр не поддерживается.</p>';} catch (error) { modalContent.innerHTML = `<p>Не удалось загрузить содержимое для предпросмотра. ${error.message}</p>`;}}function closeModalAdminEv(event) { if (event.target === document.getElementById('mediaModalAdmin')) closeModalAdminManual(); }function closeModalAdminManual() {const modal = document.getElementById('mediaModalAdmin'); modal.style.display = 'none';const video = modal.querySelector('video'); if (video) video.pause();const iframe = modal.querySelector('iframe'); if (iframe) iframe.src = 'about:blank';document.getElementById('modalContentAdmin').innerHTML = '';}</script></body></html>'''ADMIN_PROMOCODES_HTML_TEMPLATE = '''<!DOCTYPE html><html lang="ru"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Управление промокодами</title><link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600;800&display=swap" rel="stylesheet"><style>''' + BASE_STYLE + '''.promocode-item { margin-bottom: 20px; padding: 15px; border-radius: 12px; }.promocode-item h3 { color: var(--primary); font-size: 1.4em; }.activated-user { background: rgba(255,255,255,0.05); padding: 8px; border-radius: 8px; margin-top: 8px; font-size: 0.9em; }.activated-user a { font-weight: normal; }</style></head><body class="dark"><div class="container"><h1>Управление промокодами</h1><a href="{{ url_for('admin_panel') }}" class="btn" style="margin-bottom: 20px;">Назад к пользователям</a>{% with messages = get_flashed_messages(with_categories=true) %}{% if messages %}{% for category, message in messages %}<div class="flash {{ category }}">{{ message }}</div>{% endfor %}{% endif %}{% endwith %}<h2>Создать новый промокод</h2><form method="POST" action="{{ url_for('admin_promocodes') }}" class="folder-actions" style="background: var(--card-bg-dark); padding: 20px; border-radius: 16px; margin-bottom: 30px;"><input type="text" name="code" placeholder="Код (оставьте пустым для генерации)"><input type="number" name="activations" placeholder="Кол-во активаций" value="1" min="1" required style="max-width: 200px;"><button type="submit" class="btn">Создать</button></form><h2>Существующие промокоды</h2><div class="user-list">{% for promo in promocodes %}<div class="user-item promocode-item"><h3>{{ promo.code }}</h3><p>Создан: {{ promo.created_at }}</p><p>Активации: {{ promo.total_activations - promo.activations_left }} / {{ promo.total_activations }} (осталось {{ promo.activations_left }})</p>{% if promo.activated_by %}<h4>Активировали:</h4>{% for act in promo.activated_by %}<div class="activated-user"><a href="{{ url_for('admin_user_files', tma_user_id_str=act.user_id) }}">{{ act.username or 'Без имени' }} (ID: {{ act.user_id }})</a> - {{ act.activation_date }}</div>{% endfor %}{% else %}<p>Еще никто не активировал.</p>{% endif %}<form method="POST" action="{{ url_for('admin_delete_promocode', code=promo.code) }}" style="display: inline-block; margin-top: 15px;" onsubmit="return confirm('Удалить промокод {{ promo.code }}?');"><button type="submit" class="btn delete-btn">Удалить</button></form></div>{% else %}<p>Промокодов еще нет.</p>{% endfor %}</div></div></body></html>'''@app.route('/tma')def tma_entry_page():return render_template_string(TMA_ENTRY_HTML)@app.route('/')def root_redirect():return redirect(url_for('tma_entry_page'))@app.route('/auth_via_telegram', methods=['POST'])def auth_via_telegram():try:payload = request.jsontg_user_data = payload.get('user')if not tg_user_data or not tg_user_data.get('id'):return jsonify({'status': 'error', 'message': 'Отсутствуют данные пользователя Telegram.'}), 400tma_user_id_str = str(tg_user_data['id'])data = load_data()if tma_user_id_str not in data['users']:data['users'][tma_user_id_str] = {'telegram_id': tg_user_data['id'],'telegram_username': tg_user_data.get('username'),'first_name': tg_user_data.get('first_name'),'last_name': tg_user_data.get('last_name'),'created_at': datetime.now().strftime('%Y-%m-%d %H:%M:%S'),'filesystem': {"type": "folder", "id": "root", "name": "root", "children": []}}initialize_user_filesystem_tma(data['users'][tma_user_id_str], tma_user_id_str)try:save_data(data)except Exception as e:logging.error(f"Save data error for new TMA user {tma_user_id_str}: {e}")return jsonify({'status': 'error', 'message': 'Ошибка сохранения данных нового пользователя.'}), 500session['telegram_user_id'] = tma_user_id_strdisplay_name = tg_user_data.get('first_name') or tg_user_data.get('username') or f"User {tma_user_id_str}"session['telegram_display_name'] = display_namereturn jsonify({'status': 'success', 'redirect_url': url_for('tma_dashboard')})except Exception as e:logging.error(f"Error in auth_via_telegram: {e}")return jsonify({'status': 'error', 'message': 'Внутренняя ошибка сервера при авторизации.'}), 500@app.route('/tma_dashboard', methods=['GET', 'POST'])def tma_dashboard():if 'telegram_user_id' not in session:23 unmodified linesflash('Критическая ошибка: корневая папка не найдена.', 'error')session.clear()return redirect(url_for('tma_entry_page'))items_in_folder = sorted(current_folder.get('children', []), key=lambda x: (x['type'] != 'folder', x.get('name', x.get('original_filename', '')).lower()))if request.method == 'POST':22 unmodified linesfile_obj.seek(0, os.SEEK_END)total_new_files_size += file_obj.tell()file_obj.seek(0)if user_data['storage_used_bytes'] + total_new_files_size > user_data['storage_limit_gb'] * BYTES_IN_GB:flash(f'Недостаточно места! Ваш лимит {user_data["storage_limit_gb"]} ГБ, использовано {format_bytes(user_data["storage_used_bytes"])}. 'f'Эти файлы слишком большие ({format_bytes(total_new_files_size)}).', 'error')11 unmodified linesfile_id = uuid.uuid4().hexhf_path = f"cloud_files/{tma_user_id}/{target_folder_id}/{unique_filename}"temp_path = os.path.join(UPLOAD_FOLDER, f"{file_id}_{unique_filename}")file_obj.save(temp_path)file_size = os.path.getsize(temp_path)52 unmodified linesis_tma_user_admin_flag=is_admin_tma(),user_data=user_data, storage_used_formatted=storage_used_formatted)@app.route('/activate_promocode_tma', methods=['POST'])def activate_promocode_tma():if 'telegram_user_id' not in session:flash('Пожалуйста, авторизуйтесь.', 'error')return redirect(url_for('tma_entry_page'))tma_user_id = session['telegram_user_id']promocode = request.form.get('promocode', '').strip()if not promocode:flash('Поле промокода не может быть пустым.', 'error')return redirect(url_for('tma_dashboard'))data = load_data()6 unmodified linesreturn redirect(url_for('tma_entry_page'))if user_data.get('unlimited_storage'):flash('У вас уже есть безлимитный доступ.', 'info')return redirect(url_for('tma_dashboard'))if user_data.get('activated_promocode'):flash('Вы уже активировали промокод.', 'error')return redirect(url_for('tma_dashboard'))code_data = promocodes.get(promocode)if not code_data:flash('Промокод не найден или недействителен.', 'error')return redirect(url_for('tma_dashboard'))if code_data.get('activations_left', 0) <= 0:flash('К сожалению, лимит активаций для этого промокода исчерпан.', 'error')return redirect(url_for('tma_dashboard'))code_data['activations_left'] -= 1code_data.setdefault('activated_by', [])code_data['activated_by'].append({'user_id': tma_user_id,'username': user_data.get('telegram_username'),'activation_date': datetime.now().strftime('%Y-%m-%d %H:%M:%S')})user_data['unlimited_storage'] = Trueuser_data['activated_promocode'] = promocodetry:save_data(data)flash('Промокод успешно активирован! Вам предоставлен безлимитный доступ.', 'success')except Exception as e:flash(f'Произошла ошибка при сохранении данных: {e}', 'error')return redirect(url_for('tma_dashboard'))@app.route('/create_folder_tma', methods=['POST'])def create_folder_tma():if 'telegram_user_id' not in session:2 unmodified linestma_user_id = session['telegram_user_id']data = load_data()user_data = data['users'].get(tma_user_id)if not user_data:flash('Пользователь не найден', 'error')return redirect(url_for('tma_entry_page'))18 unmodified linesdef download_tma(file_id):current_tma_user_id = session.get('telegram_user_id')is_browser_admin_session = session.get('admin_browser_logged_in', False)data = load_data()file_node = Noneif is_browser_admin_session:for uid_str_iter, udata_iter in data.get('users', {}).items():node, _ = find_node_by_id(udata_iter.get('filesystem', {}), file_id)18 unmodified lineselse:return Response("Unauthorized", status=401, mimetype='text/plain')redirect_url_fallback = url_for('tma_dashboard')if is_browser_admin_session:redirect_url_fallback = url_for('admin_panel')redirect_url = request.referrer or redirect_url_fallback11 unmodified linestry:req_headers = {}if HF_TOKEN_READ: req_headers["authorization"] = f"Bearer {HF_TOKEN_READ}"r = requests.get(file_url, headers=req_headers, stream=True)r.raise_for_status()def generate_chunks():for chunk in r.iter_content(chunk_size=8192):yield chunkmimetype = 'application/octet-stream'if '.' in original_filename:ext = original_filename.rsplit('.', 1)[1].lower()26 unmodified linesif 'telegram_user_id' not in session:flash('Пожалуйста, авторизуйтесь.', 'error')return redirect(url_for('tma_entry_page'))file_id = request.view_args.get('file_id')tma_user_id = session['telegram_user_id']69 unmodified linesdef get_text_content_tma(file_id):current_tma_user_id = session.get('telegram_user_id')is_browser_admin_session = session.get('admin_browser_logged_in', False)data = load_data()file_node = None14 unmodified linesfile_node = node; breakelse:return Response("Не авторизован", status=401)if not file_node or file_node.get('type') != 'file' or file_node.get('file_type') != 'text':return Response("Текстовый файл не найден", status=404)hf_path = file_node.get('path')if not hf_path: return Response("Ошибка: путь к файлу отсутствует", status=500)file_url = f"https://huggingface.co/datasets/{REPO_ID}/resolve/main/{hf_path}?download=true"try:req_headers = {};if HF_TOKEN_READ: req_headers["authorization"] = f"Bearer {HF_TOKEN_READ}"response = requests.get(file_url, headers=req_headers)response.raise_for_status()10 unmodified linesflash('Вы вышли из сессии приложения.')return redirect(url_for('tma_entry_page'))@app.route('/admin/login', methods=['GET', 'POST'])def admin_login():if request.method == 'POST':17 unmodified linesflash('Вы вышли из админ-панели.', 'success')return redirect(url_for('admin_login'))@app.route('/admhosto')@admin_browser_login_requireddef admin_panel():data = load_data()users = data.get('users', {})user_details = []for tma_id_str, udata in users.items():user_details.append({'id_key': tma_id_str,'display_name': udata.get('first_name', udata.get('telegram_username', f"User {tma_id_str}")),'created_at': udata.get('created_at', 'N/A'),'file_count': sum(1 for _, node in get_all_nodes(udata.get('filesystem', {})) if node.get('type') == 'file'),'storage_limit_gb': udata.get('storage_limit_gb', DEFAULT_STORAGE_LIMIT_GB),'storage_used_formatted': format_bytes(udata.get('storage_used_bytes', 0)),'unlimited_storage': udata.get('unlimited_storage', False),'activated_promocode': udata.get('activated_promocode')})user_details.sort(key=lambda x: x.get('created_at', ''), reverse=True)return render_template_string(ADMIN_PANEL_HTML_TEMPLATE, user_details=user_details)def get_all_nodes(filesystem):queue = [filesystem]4 unmodified linesfor child in current_node['children']:queue.append(child)@app.route('/admhosto/user/<tma_user_id_str>')@admin_browser_login_requireddef admin_user_files(tma_user_id_str):1 unmodified lineuser_data = data.get('users', {}).get(tma_user_id_str)if not user_data:flash(f'Пользователь ID {tma_user_id_str} не найден.', 'error'); return redirect(url_for('admin_panel'))all_files = []def collect_files_admin(folder, current_path_id='root'):parent_path_str = get_node_path_string(user_data['filesystem'], current_path_id)for item in folder.get('children', []):if item.get('type') == 'file':item['parent_path_str'] = parent_path_stritem['size_formatted'] = format_bytes(item.get('size_bytes'))all_files.append(item)elif item.get('type') == 'folder': collect_files_admin(item, item.get('id'))collect_files_admin(user_data.get('filesystem', {}))all_files.sort(key=lambda x: x.get('upload_date', ''), reverse=True)display_name_admin_view = user_data.get('first_name', user_data.get('telegram_username', f"User {tma_user_id_str}"))storage_used_formatted_admin_view = format_bytes(user_data['storage_used_bytes'])return render_template_string(ADMIN_USER_FILES_HTML_TEMPLATE,tma_user_id_str_admin_view=tma_user_id_str, display_name_admin_view=display_name_admin_view, files=all_files,repo_id_js_admin=REPO_ID,hf_file_url_jinja=lambda path, download=False: f"https://huggingface.co/datasets/{REPO_ID}/resolve/main/{path}{'?download=true' if download else ''}",user_data_admin_view=user_data, storage_used_formatted_admin_view=storage_used_formatted_admin_view)6 unmodified linesif not user_data:flash(f'Пользователь {tma_user_id_str} не найден.', 'error')return redirect(url_for('admin_panel'))user_data['unlimited_storage'] = not user_data.get('unlimited_storage', False)try:save_data(data)1 unmodified lineflash(f'Безлимитное хранилище для пользователя {tma_user_id_str} {status}.', 'success')except Exception as e:flash(f'Ошибка при изменении статуса безлимитного хранилища: {e}', 'error')return redirect(url_for('admin_user_files', tma_user_id_str=tma_user_id_str))@app.route('/admhosto/delete_user/<tma_user_id_str>', methods=['POST'])@admin_browser_login_requireddef admin_delete_user(tma_user_id_str):7 unmodified linesuser_folder_path_on_hf = f"cloud_files/{tma_user_id_str}"api.delete_folder(folder_path=user_folder_path_on_hf, repo_id=REPO_ID, repo_type="dataset", token=HF_TOKEN_WRITE, ignore_patterns=[".keep"])except hf_utils.HfHubHTTPError as e:if e.response.status_code != 404:flash(f'Ошибка удаления файлов пользователя {tma_user_id_str} с сервера: {e}. Пользователь из базы не удален.', 'error'); return redirect(url_for('admin_panel'))logging.info(f"Folder {user_folder_path_on_hf} not found on HF Hub for user {tma_user_id_str} or was already empty, proceeding with DB deletion.")except Exception as e:flash(f'Ошибка удаления файлов пользователя {tma_user_id_str} с сервера: {e}. Пользователь из базы не удален.', 'error'); return redirect(url_for('admin_panel'))try:del data['users'][tma_user_id_str]save_data(data)12 unmodified linesuser_data = data.get('users', {}).get(tma_user_id_str_form)if not user_data:flash(f'Пользователь {tma_user_id_str_form} не найден.', 'error'); return redirect(url_for('admin_panel'))file_node, _ = find_node_by_id(user_data['filesystem'], file_id)if not file_node or file_node.get('type') != 'file':flash('Файл не найден в базе данных этого пользователя.', 'error'); return redirect(url_for('admin_user_files', tma_user_id_str=tma_user_id_str_form))hf_path = file_node.get('path')original_filename = file_node.get('original_filename', 'файл')file_size_to_deduct = file_node.get('size_bytes', 0)4 unmodified linestry: save_data(data); flash(f'Метаданные файла {original_filename} удалены из базы (путь к файлу на сервере отсутствовал).')except Exception as e: flash('Ошибка сохранения данных после удаления метаданных (путь отсутствовал).', 'error')return redirect(url_for('admin_user_files', tma_user_id_str=tma_user_id_str_form))try:api = HfApi()api.delete_file(path_in_repo=hf_path, repo_id=REPO_ID, repo_type="dataset", token=HF_TOKEN_WRITE)13 unmodified linesflash(f'Ошибка при удалении файла {original_filename}: {e}', 'error')return redirect(url_for('admin_user_files', tma_user_id_str=tma_user_id_str_form))@app.route('/admhosto/promocodes', methods=['GET', 'POST'])@admin_browser_login_requireddef admin_promocodes():data = load_data()if request.method == 'POST':code_str = request.form.get('code', '').strip()activations = request.form.get('activations', '1').strip()if not code_str:code_str = uuid.uuid4().hex[:10].upper()if not activations.isdigit() or int(activations) < 1:flash('Количество активаций должно быть положительным числом.', 'error')return redirect(url_for('admin_promocodes'))if code_str in data.get('promocodes', {}):flash(f'Промокод "{code_str}" уже существует.', 'error')return redirect(url_for('admin_promocodes'))data.setdefault('promocodes', {})[code_str] = {'code': code_str,'total_activations': int(activations),'activations_left': int(activations),'created_at': datetime.now().strftime('%Y-%m-%d %H:%M:%S'),'activated_by': []}try:save_data(data)flash(f'Промокод "{code_str}" успешно создан.', 'success')except Exception as e:flash(f'Ошибка сохранения промокода: {e}', 'error')return redirect(url_for('admin_promocodes'))promocodes_list = sorted(data.get('promocodes', {}).values(), key=lambda x: x['created_at'], reverse=True)return render_template_string(ADMIN_PROMOCODES_HTML_TEMPLATE, promocodes=promocodes_list)@app.route('/admhosto/promocodes/delete/<code>', methods=['POST'])@admin_browser_login_requireddef admin_delete_promocode(code):data = load_data()if code in data.get('promocodes', {}):del data['promocodes'][code]try:save_data(data)flash(f'Промокод "{code}" удален.', 'success')except Exception as e:flash(f'Ошибка удаления промокода: {e}', 'error')else:flash(f'Промокод "{code}" не найден.', 'error')return redirect(url_for('admin_promocodes'))if __name__ == '__main__':if not HF_TOKEN_WRITE: logging.warning("HF_TOKEN (write access) is not set. Uploads/deletions/backups will fail.")2 unmodified linesif ADMIN_USERNAME == "admin" and ADMIN_PASSWORD == "zeusadminpass":logging.warning("Using default admin username/password for browser admin panel. Please change ADMIN_USERNAME and ADMIN_PASSWORD environment variables.")if HF_TOKEN_WRITE:download_db_from_hf()threading.Thread(target=periodic_backup, daemon=True).start()
app.py+342-319