Update app.py
Browse files
app.py
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
|
|
|
|
|
| 1 |
import flask
|
| 2 |
from flask import Flask, render_template_string, request, redirect, url_for, session, flash, send_file, jsonify, Response
|
| 3 |
from flask_caching import Cache
|
|
@@ -14,7 +16,7 @@ from io import BytesIO
|
|
| 14 |
import uuid
|
| 15 |
from functools import wraps
|
| 16 |
|
| 17 |
-
app = Flask(
|
| 18 |
app.secret_key = os.getenv("FLASK_SECRET_KEY", "supersecretkey_folders_unique_tma")
|
| 19 |
DATA_FILE = 'cloudeng_data_tma.json'
|
| 20 |
REPO_ID = "Eluza133/Z1e1u"
|
|
@@ -191,7 +193,6 @@ def initialize_user_filesystem_tma(user_data, tma_user_id_str):
|
|
| 191 |
|
| 192 |
user_data.setdefault('storage_limit_gb', DEFAULT_STORAGE_LIMIT_GB)
|
| 193 |
user_data.setdefault('unlimited_storage', False)
|
| 194 |
-
user_data.setdefault('activated_promocode', None)
|
| 195 |
user_data.setdefault('storage_used_bytes', 0)
|
| 196 |
|
| 197 |
if 'files' in user_data and isinstance(user_data['files'], list):
|
|
@@ -228,18 +229,20 @@ def load_data():
|
|
| 228 |
with open(DATA_FILE, 'r', encoding='utf-8') as file:
|
| 229 |
data = json.load(file)
|
| 230 |
if not isinstance(data, dict):
|
| 231 |
-
data = {'users': {}, '
|
| 232 |
data.setdefault('users', {})
|
| 233 |
-
data.setdefault('
|
| 234 |
-
|
| 235 |
for tma_user_id_str, user_data_item in data['users'].items():
|
|
|
|
|
|
|
| 236 |
initialize_user_filesystem_tma(user_data_item, tma_user_id_str)
|
| 237 |
user_data_item['storage_used_bytes'] = calculate_current_storage_usage(user_data_item['filesystem'])
|
| 238 |
|
| 239 |
return data
|
| 240 |
except Exception as e:
|
| 241 |
logging.error(f"Error loading data: {e}")
|
| 242 |
-
return {'users': {}, '
|
| 243 |
|
| 244 |
def save_data(data):
|
| 245 |
try:
|
|
@@ -266,7 +269,7 @@ def upload_db_to_hf():
|
|
| 266 |
def download_db_from_hf():
|
| 267 |
if not HF_TOKEN_READ:
|
| 268 |
if not os.path.exists(DATA_FILE):
|
| 269 |
-
with open(DATA_FILE, 'w', encoding='utf-8') as f: json.dump({'users': {}, '
|
| 270 |
return
|
| 271 |
try:
|
| 272 |
hf_hub_download(
|
|
@@ -275,11 +278,11 @@ def download_db_from_hf():
|
|
| 275 |
)
|
| 276 |
except (hf_utils.RepositoryNotFoundError, hf_utils.EntryNotFoundError):
|
| 277 |
if not os.path.exists(DATA_FILE):
|
| 278 |
-
with open(DATA_FILE, 'w', encoding='utf-8') as f: json.dump({'users': {}, '
|
| 279 |
except Exception as e:
|
| 280 |
logging.error(f"Error downloading database: {e}")
|
| 281 |
if not os.path.exists(DATA_FILE):
|
| 282 |
-
with open(DATA_FILE, 'w', encoding='utf-8') as f: json.dump({'users': {}, '
|
| 283 |
|
| 284 |
def periodic_backup():
|
| 285 |
while True:
|
|
@@ -355,6 +358,53 @@ TMA_ENTRY_HTML = '''
|
|
| 355 |
</script></body></html>
|
| 356 |
'''
|
| 357 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 358 |
TMA_DASHBOARD_HTML_TEMPLATE = '''
|
| 359 |
<!DOCTYPE html><html lang="ru"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0">
|
| 360 |
<title>Zeus Cloud</title><link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600;800&display=swap" rel="stylesheet">
|
|
@@ -363,20 +413,22 @@ TMA_DASHBOARD_HTML_TEMPLATE = '''
|
|
| 363 |
<h1>Zeus Cloud</h1><p>Пользователь: {{ display_name }}</p>
|
| 364 |
<p>
|
| 365 |
{% if user_data.unlimited_storage %}
|
| 366 |
-
Память: Безлимитно (Использовано: {{ storage_used_formatted }})
|
| 367 |
-
<small style="color: #ccc;">Доступ активирован {% if user_data.activated_promocode %}промокодом: {{ user_data.activated_promocode }}{% else %}администратором{% endif %}.</small>
|
| 368 |
{% else %}
|
| 369 |
Память: {{ storage_used_formatted }} из {{ user_data.storage_limit_gb }} ГБ
|
| 370 |
{% endif %}
|
| 371 |
</p>
|
| 372 |
{% if not user_data.unlimited_storage %}
|
| 373 |
-
<
|
| 374 |
-
|
| 375 |
-
|
| 376 |
-
<
|
| 377 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 378 |
{% endif %}
|
| 379 |
-
|
| 380 |
{% with messages = get_flashed_messages(with_categories=true) %}{% if messages %}
|
| 381 |
{% for category, message in messages %}<div class="flash {{ category }}">{{ message }}</div>{% endfor %}
|
| 382 |
{% endif %}{% endwith %}
|
|
@@ -513,224 +565,20 @@ TMA_DASHBOARD_HTML_TEMPLATE = '''
|
|
| 513 |
});
|
| 514 |
}
|
| 515 |
document.getElementById('logout-btn').addEventListener('click', function(e) { e.preventDefault(); window.location.href = "{{ url_for('tma_logout') }}"; });
|
| 516 |
-
</script></body></html>
|
| 517 |
-
'''
|
| 518 |
|
| 519 |
-
|
| 520 |
-
|
| 521 |
-
|
| 522 |
-
|
| 523 |
-
|
| 524 |
-
|
| 525 |
-
|
| 526 |
-
|
| 527 |
-
|
| 528 |
-
|
| 529 |
-
</
|
| 530 |
-
</head><body class="dark">
|
| 531 |
-
<div class="login-container">
|
| 532 |
-
<h1>Admin Login</h1>
|
| 533 |
-
{% with messages = get_flashed_messages(with_categories=true) %}
|
| 534 |
-
{% if messages %}
|
| 535 |
-
{% for category, message in messages %}
|
| 536 |
-
<div class="flash {{ category }}">{{ message }}</div>
|
| 537 |
-
{% endfor %}
|
| 538 |
-
{% endif %}
|
| 539 |
-
{% endwith %}
|
| 540 |
-
<form method="POST" action="{{ url_for('admin_login') }}">
|
| 541 |
-
<input type="hidden" name="next" value="{{ request.args.get('next', '') }}">
|
| 542 |
-
<input type="text" name="username" placeholder="Username" required>
|
| 543 |
-
<input type="password" name="password" placeholder="Password" required>
|
| 544 |
-
<button type="submit" class="btn">Login</button>
|
| 545 |
-
</form>
|
| 546 |
-
</div>
|
| 547 |
-
</body></html>
|
| 548 |
-
'''
|
| 549 |
-
|
| 550 |
-
ADMIN_PANEL_HTML_TEMPLATE = '''
|
| 551 |
-
<!DOCTYPE html><html lang="ru"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0">
|
| 552 |
-
<title>Админ-панель</title><link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600;800&display=swap" rel="stylesheet">
|
| 553 |
-
<style>''' + BASE_STYLE + '''</style></head><body class="dark"><div class="container"><h1>Админ-панель</h1>
|
| 554 |
-
<a href="{{ url_for('admin_logout') }}" class="btn" style="margin-bottom:20px; background-color: var(--accent);">Выйти из админ-панели</a>
|
| 555 |
-
<a href="{{ url_for('tma_dashboard') }}" class="btn" style="margin-bottom:20px;">В приложение (если TMA сессия есть)</a>
|
| 556 |
-
<a href="{{ url_for('admin_promocodes') }}" class="btn" style="margin-bottom:20px; background-color: #ffc107;">Управление промокодами</a>
|
| 557 |
-
{% with messages = get_flashed_messages(with_categories=true) %}{% if messages %}{% for category, message in messages %}<div class="flash {{ category }}">{{ message }}</div>{% endfor %}{% endif %}{% endwith %}
|
| 558 |
-
<h2>Пользователи</h2><div class="user-list">
|
| 559 |
-
{% for user in user_details %}
|
| 560 |
-
<div class="user-item">
|
| 561 |
-
<a href="{{ url_for('admin_user_files', tma_user_id_str=user.id_key) }}">{{ user.display_name }} (ID: {{user.id_key}})</a>
|
| 562 |
-
<p>Зарегистрирован: {{ user.created_at }}</p><p>Файлов: {{ user.file_count }}</p>
|
| 563 |
-
<p>Память: {% if user.unlimited_storage %}Безлимитно ({{ user.storage_used_formatted }}){% else %}{{ user.storage_used_formatted }} из {{ user.storage_limit_gb }} ГБ{% endif %}</p>
|
| 564 |
-
{% if user.activated_promocode %}<p>Активирован промокод: {{ user.activated_promocode }}</p>{% endif %}
|
| 565 |
-
<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 }} и ВСЕ его файлы? НЕОБРАТИМО!');">
|
| 566 |
-
<button type="submit" class="btn delete-btn" style="padding: 5px 10px; font-size: 0.9em;">Удалить</button>
|
| 567 |
-
</form>
|
| 568 |
-
</div>
|
| 569 |
-
{% else %}<p>Пользователей нет.</p>{% endfor %}</div></div></body></html>'''
|
| 570 |
-
|
| 571 |
-
ADMIN_USER_FILES_HTML_TEMPLATE = '''
|
| 572 |
-
<!DOCTYPE html><html lang="ru"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0">
|
| 573 |
-
<title>Файлы {{ display_name_admin_view }}</title><link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600;800&display=swap" rel="stylesheet">
|
| 574 |
-
<style>''' + BASE_STYLE + '''
|
| 575 |
-
.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; }
|
| 576 |
-
.file-preview { max-width: 100%; height: 100px; object-fit: contain; border-radius: 10px; margin-bottom: 10px; display: block; margin-left: auto; margin-right: auto; }
|
| 577 |
-
.admin-file-actions { margin-top: 10px; display: flex; flex-wrap: wrap; gap: 5px; justify-content: center; }
|
| 578 |
-
.admin-file-actions .btn { font-size: 0.8em; padding: 4px 8px; margin: 0; }
|
| 579 |
-
</style></head><body class="dark"><div class="container"><h1>Файлы пользователя: {{ display_name_admin_view }} (ID: {{ tma_user_id_str_admin_view }})</h1>
|
| 580 |
-
<a href="{{ url_for('admin_panel') }}" class="btn" style="margin-bottom: 20px;">Назад к пользователям</a>
|
| 581 |
-
<p>Лимит памяти:
|
| 582 |
-
{% if user_data_admin_view.unlimited_storage %}Безлимитно (Использовано: {{ storage_used_formatted_admin_view }})
|
| 583 |
-
{% else %}{{ storage_used_formatted_admin_view }} из {{ user_data_admin_view.storage_limit_gb }} ГБ
|
| 584 |
-
{% endif %}
|
| 585 |
-
</p>
|
| 586 |
-
<form method="POST" action="{{ url_for('admin_toggle_unlimited_storage', tma_user_id_str=tma_user_id_str_admin_view) }}" style="display: inline-block;">
|
| 587 |
-
<button type="submit" class="btn" style="background: var(--accent);">
|
| 588 |
-
{{ 'Отключить безлимит' if user_data_admin_view.unlimited_storage else 'Включить безлимит' }}
|
| 589 |
-
</button>
|
| 590 |
-
</form>
|
| 591 |
-
{% with messages = get_flashed_messages(with_categories=true) %}{% if messages %}{% for category, message in messages %}<div class="flash {{ category }}">{{ message }}</div>{% endfor %}{% endif %}{% endwith %}
|
| 592 |
-
<div style="display: grid; grid-template-columns: repeat(auto-fill, minmax(220px, 1fr)); gap: 20px;">
|
| 593 |
-
{% for file_item in files %}
|
| 594 |
-
<div class="file-item"><div>
|
| 595 |
-
{% 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;">
|
| 596 |
-
{% 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>
|
| 597 |
-
{% 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>
|
| 598 |
-
{% 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>
|
| 599 |
-
{% else %} <div class="file-preview" style="font-size: 40px; line-height: 100px; text-align: center; color: #aaa;">❓</div> {% endif %}
|
| 600 |
-
<p title="{{ file_item.original_filename }}"><b>{{ file_item.original_filename | truncate(30) }}</b></p>
|
| 601 |
-
<p style="font-size: 0.8em; color: #888;">В папке: {{ file_item.parent_path_str }}</p>
|
| 602 |
-
<p style="font-size: 0.8em; color: #888;">Загружен: {{ file_item.upload_date }}</p>
|
| 603 |
-
<p style="font-size: 0.8em; color: #888;">Размер: {{ file_item.size_formatted }}</p>
|
| 604 |
-
<p style="font-size: 0.7em; color: #ccc;">ID: {{ file_item.id }}</p>
|
| 605 |
-
<p style="font-size: 0.7em; color: #ccc; word-break: break-all;">Path: {{ file_item.path }}</p>
|
| 606 |
-
</div><div class="admin-file-actions">
|
| 607 |
-
<a href="{{ url_for('download_tma', file_id=file_item.id) }}" class="btn download-btn" download="{{ file_item.original_filename }}">Скачать</a>
|
| 608 |
-
{% set previewable = file_item.file_type in ['image', 'video', 'pdf', 'text'] %}
|
| 609 |
-
{% 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 %}
|
| 610 |
-
<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 }}?');">
|
| 611 |
-
<button type="submit" class="btn delete-btn">Удалить</button></form>
|
| 612 |
-
</div></div>{% else %} <p>У пользователя нет файлов.</p> {% endfor %}</div></div>
|
| 613 |
-
<div class="modal" id="mediaModalAdmin" onclick="closeModalAdminEv(event)"><div class="modal-content" id="modalContentContainerAdmin">
|
| 614 |
-
<span onclick="closeModalAdminManual()" class="modal-close-btn">×</span><div id="modalContentAdmin"></div></div></div>
|
| 615 |
-
<script>
|
| 616 |
-
const repoIdJs = "{{ repo_id_js_admin }}";
|
| 617 |
-
function hfFileUrlAdmin(path, download = false) { let url = `https://huggingface.co/datasets/${repoIdJs}/resolve/main/${path}`; if (download) url += '?download=true'; return url; }
|
| 618 |
-
async function openModalAdmin(srcOrUrl, type, itemId) {
|
| 619 |
-
const modal = document.getElementById('mediaModalAdmin'); const modalContent = document.getElementById('modalContentAdmin');
|
| 620 |
-
modalContent.innerHTML = '<p>Загрузка...</p>'; modal.style.display = 'flex';
|
| 621 |
-
try {
|
| 622 |
-
if (type === 'image') modalContent.innerHTML = `<img src="${srcOrUrl}" alt="Просмотр изображения">`;
|
| 623 |
-
else if (type === 'video') modalContent.innerHTML = `<video controls autoplay style='max-width: 95%; max-height: 85vh;'><source src="${srcOrUrl}" type="video/mp4"></video>`;
|
| 624 |
-
else if (type === 'pdf') modalContent.innerHTML = `<iframe src="${srcOrUrl}" title="Просмотр PDF"></iframe>`;
|
| 625 |
-
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>`;}
|
| 626 |
-
else modalContent.innerHTML = '<p>Предпросмотр не поддерживается.</p>';
|
| 627 |
-
} catch (error) { modalContent.innerHTML = `<p>Не удалось загрузить содержимое для предпросмотра. ${error.message}</p>`;}
|
| 628 |
-
}
|
| 629 |
-
function closeModalAdminEv(event) { if (event.target === document.getElementById('mediaModalAdmin')) closeModalAdminManual(); }
|
| 630 |
-
function closeModalAdminManual() {
|
| 631 |
-
const modal = document.getElementById('mediaModalAdmin'); modal.style.display = 'none';
|
| 632 |
-
const video = modal.querySelector('video'); if (video) video.pause();
|
| 633 |
-
const iframe = modal.querySelector('iframe'); if (iframe) iframe.src = 'about:blank';
|
| 634 |
-
document.getElementById('modalContentAdmin').innerHTML = '';
|
| 635 |
-
}
|
| 636 |
-
</script></body></html>'''
|
| 637 |
-
|
| 638 |
-
ADMIN_PROMOCODES_HTML_TEMPLATE = '''
|
| 639 |
-
<!DOCTYPE html><html lang="ru"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0">
|
| 640 |
-
<title>Управление промокодами</title><link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600;800&display=swap" rel="stylesheet">
|
| 641 |
-
<style>''' + BASE_STYLE + '''
|
| 642 |
-
.promocode-item { margin-bottom: 20px; padding: 15px; border-radius: 12px; }
|
| 643 |
-
.promocode-item h3 { color: var(--primary); font-size: 1.4em; }
|
| 644 |
-
.activated-user { background: rgba(255,255,255,0.05); padding: 8px; border-radius: 8px; margin-top: 8px; font-size: 0.9em; }
|
| 645 |
-
.activated-user a { font-weight: normal; }
|
| 646 |
-
</style></head><body class="dark"><div class="container">
|
| 647 |
-
<h1>Управление промокодами</h1>
|
| 648 |
-
<a href="{{ url_for('admin_panel') }}" class="btn" style="margin-bottom: 20px;">Назад к пользователям</a>
|
| 649 |
-
{% with messages = get_flashed_messages(with_categories=true) %}{% if messages %}{% for category, message in messages %}<div class="flash {{ category }}">{{ message }}</div>{% endfor %}{% endif %}{% endwith %}
|
| 650 |
-
|
| 651 |
-
<h2>Создать новый промокод</h2>
|
| 652 |
-
<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;">
|
| 653 |
-
<input type="text" name="code" placeholder="Код (оставьте пустым для генерации)">
|
| 654 |
-
<input type="number" name="activations" placeholder="Кол-во активаций" value="1" min="1" required style="max-width: 200px;">
|
| 655 |
-
<button type="submit" class="btn">Создать</button>
|
| 656 |
-
</form>
|
| 657 |
-
|
| 658 |
-
<h2>Существующие промокоды</h2>
|
| 659 |
-
<div class="user-list">
|
| 660 |
-
{% for promo in promocodes %}
|
| 661 |
-
<div class="user-item promocode-item">
|
| 662 |
-
<h3>{{ promo.code }}</h3>
|
| 663 |
-
<p>Создан: {{ promo.created_at }}</p>
|
| 664 |
-
<p>Активации: {{ promo.total_activations - promo.activations_left }} / {{ promo.total_activations }} (осталось {{ promo.activations_left }})</p>
|
| 665 |
-
{% if promo.activated_by %}
|
| 666 |
-
<h4>Активировали:</h4>
|
| 667 |
-
{% for act in promo.activated_by %}
|
| 668 |
-
<div class="activated-user">
|
| 669 |
-
<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 }}
|
| 670 |
-
</div>
|
| 671 |
-
{% endfor %}
|
| 672 |
-
{% else %}
|
| 673 |
-
<p>Еще никто не активировал.</p>
|
| 674 |
-
{% endif %}
|
| 675 |
-
<form method="POST" action="{{ url_for('admin_delete_promocode', code=promo.code) }}" style="display: inline-block; margin-top: 15px;" onsubmit="return confirm('Удалить промокод {{ promo.code }}?');">
|
| 676 |
-
<button type="submit" class="btn delete-btn">Удалить</button>
|
| 677 |
-
</form>
|
| 678 |
-
</div>
|
| 679 |
-
{% else %}
|
| 680 |
-
<p>Промокодов еще нет.</p>
|
| 681 |
-
{% endfor %}
|
| 682 |
-
</div>
|
| 683 |
-
|
| 684 |
-
</div></body></html>
|
| 685 |
'''
|
| 686 |
|
| 687 |
-
@app.route('/tma')
|
| 688 |
-
def tma_entry_page():
|
| 689 |
-
return render_template_string(TMA_ENTRY_HTML)
|
| 690 |
-
|
| 691 |
-
@app.route('/')
|
| 692 |
-
def root_redirect():
|
| 693 |
-
return redirect(url_for('tma_entry_page'))
|
| 694 |
-
|
| 695 |
-
|
| 696 |
-
@app.route('/auth_via_telegram', methods=['POST'])
|
| 697 |
-
def auth_via_telegram():
|
| 698 |
-
try:
|
| 699 |
-
payload = request.json
|
| 700 |
-
tg_user_data = payload.get('user')
|
| 701 |
-
|
| 702 |
-
if not tg_user_data or not tg_user_data.get('id'):
|
| 703 |
-
return jsonify({'status': 'error', 'message': 'Отсутствуют данные пользователя Telegram.'}), 400
|
| 704 |
-
|
| 705 |
-
tma_user_id_str = str(tg_user_data['id'])
|
| 706 |
-
data = load_data()
|
| 707 |
-
|
| 708 |
-
if tma_user_id_str not in data['users']:
|
| 709 |
-
data['users'][tma_user_id_str] = {
|
| 710 |
-
'telegram_id': tg_user_data['id'],
|
| 711 |
-
'telegram_username': tg_user_data.get('username'),
|
| 712 |
-
'first_name': tg_user_data.get('first_name'),
|
| 713 |
-
'last_name': tg_user_data.get('last_name'),
|
| 714 |
-
'created_at': datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
|
| 715 |
-
'filesystem': {"type": "folder", "id": "root", "name": "root", "children": []}
|
| 716 |
-
}
|
| 717 |
-
initialize_user_filesystem_tma(data['users'][tma_user_id_str], tma_user_id_str)
|
| 718 |
-
try:
|
| 719 |
-
save_data(data)
|
| 720 |
-
except Exception as e:
|
| 721 |
-
logging.error(f"Save data error for new TMA user {tma_user_id_str}: {e}")
|
| 722 |
-
return jsonify({'status': 'error', 'message': 'Ошибка сохранения данных нового пользователя.'}), 500
|
| 723 |
-
|
| 724 |
-
session['telegram_user_id'] = tma_user_id_str
|
| 725 |
-
display_name = tg_user_data.get('first_name') or tg_user_data.get('username') or f"User {tma_user_id_str}"
|
| 726 |
-
session['telegram_display_name'] = display_name
|
| 727 |
-
|
| 728 |
-
return jsonify({'status': 'success', 'redirect_url': url_for('tma_dashboard')})
|
| 729 |
-
|
| 730 |
-
except Exception as e:
|
| 731 |
-
logging.error(f"Error in auth_via_telegram: {e}")
|
| 732 |
-
return jsonify({'status': 'error', 'message': 'Внутренняя ошибка сервера при авторизации.'}), 500
|
| 733 |
-
|
| 734 |
@app.route('/tma_dashboard', methods=['GET', 'POST'])
|
| 735 |
def tma_dashboard():
|
| 736 |
if 'telegram_user_id' not in session:
|
|
@@ -866,22 +714,19 @@ def tma_dashboard():
|
|
| 866 |
is_tma_user_admin_flag=is_admin_tma(),
|
| 867 |
user_data=user_data, storage_used_formatted=storage_used_formatted)
|
| 868 |
|
| 869 |
-
|
| 870 |
-
|
|
|
|
| 871 |
if 'telegram_user_id' not in session:
|
| 872 |
flash('Пожалуйста, авторизуйтесь.', 'error')
|
| 873 |
return redirect(url_for('tma_entry_page'))
|
| 874 |
|
| 875 |
tma_user_id = session['telegram_user_id']
|
| 876 |
-
|
| 877 |
-
|
| 878 |
-
if not promocode:
|
| 879 |
-
flash('Поле промокода не может быть пустым.', 'error')
|
| 880 |
-
return redirect(url_for('tma_dashboard'))
|
| 881 |
|
| 882 |
data = load_data()
|
| 883 |
user_data = data['users'].get(tma_user_id)
|
| 884 |
-
|
| 885 |
|
| 886 |
if not user_data:
|
| 887 |
session.clear()
|
|
@@ -889,42 +734,37 @@ def activate_promocode_tma():
|
|
| 889 |
return redirect(url_for('tma_entry_page'))
|
| 890 |
|
| 891 |
if user_data.get('unlimited_storage'):
|
| 892 |
-
flash('У вас уже
|
| 893 |
-
return redirect(url_for('tma_dashboard'))
|
| 894 |
-
|
| 895 |
-
if user_data.get('activated_promocode'):
|
| 896 |
-
flash('Вы уже активировали промокод.', 'error')
|
| 897 |
return redirect(url_for('tma_dashboard'))
|
| 898 |
|
| 899 |
-
|
| 900 |
|
| 901 |
-
if not
|
| 902 |
-
flash('
|
| 903 |
return redirect(url_for('tma_dashboard'))
|
| 904 |
|
| 905 |
-
if
|
| 906 |
-
flash('
|
|
|
|
|
|
|
|
|
|
|
|
|
| 907 |
return redirect(url_for('tma_dashboard'))
|
| 908 |
|
| 909 |
-
code_data['activations_left'] -= 1
|
| 910 |
-
code_data.setdefault('activated_by', [])
|
| 911 |
-
code_data['activated_by'].append({
|
| 912 |
-
'user_id': tma_user_id,
|
| 913 |
-
'username': user_data.get('telegram_username'),
|
| 914 |
-
'activation_date': datetime.now().strftime('%Y-%m-%d %H:%M:%S')
|
| 915 |
-
})
|
| 916 |
-
|
| 917 |
user_data['unlimited_storage'] = True
|
| 918 |
-
|
|
|
|
|
|
|
| 919 |
|
| 920 |
try:
|
| 921 |
save_data(data)
|
| 922 |
-
flash('
|
| 923 |
except Exception as e:
|
| 924 |
-
flash(f'
|
| 925 |
-
|
| 926 |
return redirect(url_for('tma_dashboard'))
|
| 927 |
|
|
|
|
| 928 |
@app.route('/create_folder_tma', methods=['POST'])
|
| 929 |
def create_folder_tma():
|
| 930 |
if 'telegram_user_id' not in session:
|
|
@@ -1169,6 +1009,38 @@ def tma_logout():
|
|
| 1169 |
flash('Вы вышли из сессии приложения.')
|
| 1170 |
return redirect(url_for('tma_entry_page'))
|
| 1171 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1172 |
@app.route('/admin/login', methods=['GET', 'POST'])
|
| 1173 |
def admin_login():
|
| 1174 |
if request.method == 'POST':
|
|
@@ -1192,6 +1064,26 @@ def admin_logout():
|
|
| 1192 |
flash('Вы вышли из админ-панели.', 'success')
|
| 1193 |
return redirect(url_for('admin_login'))
|
| 1194 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1195 |
@app.route('/admhosto')
|
| 1196 |
@admin_browser_login_required
|
| 1197 |
def admin_panel():
|
|
@@ -1206,8 +1098,7 @@ def admin_panel():
|
|
| 1206 |
'file_count': sum(1 for _, node in get_all_nodes(udata.get('filesystem', {})) if node.get('type') == 'file'),
|
| 1207 |
'storage_limit_gb': udata.get('storage_limit_gb', DEFAULT_STORAGE_LIMIT_GB),
|
| 1208 |
'storage_used_formatted': format_bytes(udata.get('storage_used_bytes', 0)),
|
| 1209 |
-
'unlimited_storage': udata.get('unlimited_storage', False)
|
| 1210 |
-
'activated_promocode': udata.get('activated_promocode')
|
| 1211 |
})
|
| 1212 |
user_details.sort(key=lambda x: x.get('created_at', ''), reverse=True)
|
| 1213 |
return render_template_string(ADMIN_PANEL_HTML_TEMPLATE, user_details=user_details)
|
|
@@ -1221,6 +1112,73 @@ def get_all_nodes(filesystem):
|
|
| 1221 |
for child in current_node['children']:
|
| 1222 |
queue.append(child)
|
| 1223 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1224 |
@app.route('/admhosto/user/<tma_user_id_str>')
|
| 1225 |
@admin_browser_login_required
|
| 1226 |
def admin_user_files(tma_user_id_str):
|
|
@@ -1343,58 +1301,129 @@ def admin_delete_file(tma_user_id_str_form, file_id):
|
|
| 1343 |
flash(f'Ошибка при удалении файла {original_filename}: {e}', 'error')
|
| 1344 |
return redirect(url_for('admin_user_files', tma_user_id_str=tma_user_id_str_form))
|
| 1345 |
|
| 1346 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1347 |
@admin_browser_login_required
|
| 1348 |
-
def
|
| 1349 |
data = load_data()
|
| 1350 |
-
|
| 1351 |
-
|
| 1352 |
-
activations = request.form.get('activations', '1').strip()
|
| 1353 |
-
|
| 1354 |
-
if not code_str:
|
| 1355 |
-
code_str = uuid.uuid4().hex[:10].upper()
|
| 1356 |
|
| 1357 |
-
|
| 1358 |
-
|
| 1359 |
-
|
| 1360 |
-
|
| 1361 |
-
|
| 1362 |
-
|
| 1363 |
-
|
| 1364 |
-
|
| 1365 |
-
|
| 1366 |
-
|
| 1367 |
-
|
| 1368 |
-
|
| 1369 |
-
|
| 1370 |
-
|
| 1371 |
-
|
| 1372 |
-
|
| 1373 |
-
|
| 1374 |
-
|
| 1375 |
-
|
| 1376 |
-
|
| 1377 |
-
|
| 1378 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1379 |
|
| 1380 |
-
|
| 1381 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1382 |
|
| 1383 |
-
@app.route('/admhosto/
|
| 1384 |
@admin_browser_login_required
|
| 1385 |
-
def
|
| 1386 |
data = load_data()
|
| 1387 |
-
|
| 1388 |
-
|
| 1389 |
-
|
| 1390 |
-
|
| 1391 |
-
|
| 1392 |
-
|
| 1393 |
-
|
| 1394 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1395 |
flash(f'Промокод "{code}" не найден.', 'error')
|
|
|
|
| 1396 |
|
| 1397 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1398 |
|
| 1399 |
if __name__ == '__main__':
|
| 1400 |
if not HF_TOKEN_WRITE: logging.warning("HF_TOKEN (write access) is not set. Uploads/deletions/backups will fail.")
|
|
@@ -1403,6 +1432,7 @@ if __name__ == '__main__':
|
|
| 1403 |
if ADMIN_USERNAME == "admin" and ADMIN_PASSWORD == "zeusadminpass":
|
| 1404 |
logging.warning("Using default admin username/password for browser admin panel. Please change ADMIN_USERNAME and ADMIN_PASSWORD environment variables.")
|
| 1405 |
|
|
|
|
| 1406 |
if HF_TOKEN_WRITE:
|
| 1407 |
download_db_from_hf()
|
| 1408 |
threading.Thread(target=periodic_backup, daemon=True).start()
|
|
@@ -1410,6 +1440,6 @@ if __name__ == '__main__':
|
|
| 1410 |
download_db_from_hf()
|
| 1411 |
else:
|
| 1412 |
if not os.path.exists(DATA_FILE):
|
| 1413 |
-
with open(DATA_FILE, 'w', encoding='utf-8') as f: json.dump({'users': {}, '
|
| 1414 |
|
| 1415 |
app.run(debug=False, host='0.0.0.0', port=7860)
|
|
|
|
| 1 |
+
--- START OF FILE app (36).py ---
|
| 2 |
+
|
| 3 |
import flask
|
| 4 |
from flask import Flask, render_template_string, request, redirect, url_for, session, flash, send_file, jsonify, Response
|
| 5 |
from flask_caching import Cache
|
|
|
|
| 16 |
import uuid
|
| 17 |
from functools import wraps
|
| 18 |
|
| 19 |
+
app = Flask(__init__)
|
| 20 |
app.secret_key = os.getenv("FLASK_SECRET_KEY", "supersecretkey_folders_unique_tma")
|
| 21 |
DATA_FILE = 'cloudeng_data_tma.json'
|
| 22 |
REPO_ID = "Eluza133/Z1e1u"
|
|
|
|
| 193 |
|
| 194 |
user_data.setdefault('storage_limit_gb', DEFAULT_STORAGE_LIMIT_GB)
|
| 195 |
user_data.setdefault('unlimited_storage', False)
|
|
|
|
| 196 |
user_data.setdefault('storage_used_bytes', 0)
|
| 197 |
|
| 198 |
if 'files' in user_data and isinstance(user_data['files'], list):
|
|
|
|
| 229 |
with open(DATA_FILE, 'r', encoding='utf-8') as file:
|
| 230 |
data = json.load(file)
|
| 231 |
if not isinstance(data, dict):
|
| 232 |
+
data = {'users': {}, 'promo_codes': {}}
|
| 233 |
data.setdefault('users', {})
|
| 234 |
+
data.setdefault('promo_codes', {}) # Initialize promo_codes
|
| 235 |
+
|
| 236 |
for tma_user_id_str, user_data_item in data['users'].items():
|
| 237 |
+
user_data_item.setdefault('storage_limit_gb', DEFAULT_STORAGE_LIMIT_GB)
|
| 238 |
+
user_data_item.setdefault('unlimited_storage', False)
|
| 239 |
initialize_user_filesystem_tma(user_data_item, tma_user_id_str)
|
| 240 |
user_data_item['storage_used_bytes'] = calculate_current_storage_usage(user_data_item['filesystem'])
|
| 241 |
|
| 242 |
return data
|
| 243 |
except Exception as e:
|
| 244 |
logging.error(f"Error loading data: {e}")
|
| 245 |
+
return {'users': {}, 'promo_codes': {}} # Ensure promo_codes is initialized even on error
|
| 246 |
|
| 247 |
def save_data(data):
|
| 248 |
try:
|
|
|
|
| 269 |
def download_db_from_hf():
|
| 270 |
if not HF_TOKEN_READ:
|
| 271 |
if not os.path.exists(DATA_FILE):
|
| 272 |
+
with open(DATA_FILE, 'w', encoding='utf-8') as f: json.dump({'users': {}, 'promo_codes': {}}, f)
|
| 273 |
return
|
| 274 |
try:
|
| 275 |
hf_hub_download(
|
|
|
|
| 278 |
)
|
| 279 |
except (hf_utils.RepositoryNotFoundError, hf_utils.EntryNotFoundError):
|
| 280 |
if not os.path.exists(DATA_FILE):
|
| 281 |
+
with open(DATA_FILE, 'w', encoding='utf-8') as f: json.dump({'users': {}, 'promo_codes': {}}, f)
|
| 282 |
except Exception as e:
|
| 283 |
logging.error(f"Error downloading database: {e}")
|
| 284 |
if not os.path.exists(DATA_FILE):
|
| 285 |
+
with open(DATA_FILE, 'w', encoding='utf-8') as f: json.dump({'users': {}, 'promo_codes': {}}, f)
|
| 286 |
|
| 287 |
def periodic_backup():
|
| 288 |
while True:
|
|
|
|
| 358 |
</script></body></html>
|
| 359 |
'''
|
| 360 |
|
| 361 |
+
@app.route('/tma')
|
| 362 |
+
def tma_entry_page():
|
| 363 |
+
return render_template_string(TMA_ENTRY_HTML)
|
| 364 |
+
|
| 365 |
+
@app.route('/')
|
| 366 |
+
def root_redirect():
|
| 367 |
+
return redirect(url_for('tma_entry_page'))
|
| 368 |
+
|
| 369 |
+
|
| 370 |
+
@app.route('/auth_via_telegram', methods=['POST'])
|
| 371 |
+
def auth_via_telegram():
|
| 372 |
+
try:
|
| 373 |
+
payload = request.json
|
| 374 |
+
tg_user_data = payload.get('user')
|
| 375 |
+
|
| 376 |
+
if not tg_user_data or not tg_user_data.get('id'):
|
| 377 |
+
return jsonify({'status': 'error', 'message': 'Отсутствуют данные пользователя Telegram.'}), 400
|
| 378 |
+
|
| 379 |
+
tma_user_id_str = str(tg_user_data['id'])
|
| 380 |
+
data = load_data()
|
| 381 |
+
|
| 382 |
+
if tma_user_id_str not in data['users']:
|
| 383 |
+
data['users'][tma_user_id_str] = {
|
| 384 |
+
'telegram_id': tg_user_data['id'],
|
| 385 |
+
'telegram_username': tg_user_data.get('username'),
|
| 386 |
+
'first_name': tg_user_data.get('first_name'),
|
| 387 |
+
'last_name': tg_user_data.get('last_name'),
|
| 388 |
+
'created_at': datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
|
| 389 |
+
'filesystem': {"type": "folder", "id": "root", "name": "root", "children": []}
|
| 390 |
+
}
|
| 391 |
+
initialize_user_filesystem_tma(data['users'][tma_user_id_str], tma_user_id_str)
|
| 392 |
+
try:
|
| 393 |
+
save_data(data)
|
| 394 |
+
except Exception as e:
|
| 395 |
+
logging.error(f"Save data error for new TMA user {tma_user_id_str}: {e}")
|
| 396 |
+
return jsonify({'status': 'error', 'message': 'Ошибка сохранения данных нового пользователя.'}), 500
|
| 397 |
+
|
| 398 |
+
session['telegram_user_id'] = tma_user_id_str
|
| 399 |
+
display_name = tg_user_data.get('first_name') or tg_user_data.get('username') or f"User {tma_user_id_str}"
|
| 400 |
+
session['telegram_display_name'] = display_name
|
| 401 |
+
|
| 402 |
+
return jsonify({'status': 'success', 'redirect_url': url_for('tma_dashboard')})
|
| 403 |
+
|
| 404 |
+
except Exception as e:
|
| 405 |
+
logging.error(f"Error in auth_via_telegram: {e}")
|
| 406 |
+
return jsonify({'status': 'error', 'message': 'Внутренняя ошибка сервера при авторизации.'}), 500
|
| 407 |
+
|
| 408 |
TMA_DASHBOARD_HTML_TEMPLATE = '''
|
| 409 |
<!DOCTYPE html><html lang="ru"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0">
|
| 410 |
<title>Zeus Cloud</title><link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600;800&display=swap" rel="stylesheet">
|
|
|
|
| 413 |
<h1>Zeus Cloud</h1><p>Пользователь: {{ display_name }}</p>
|
| 414 |
<p>
|
| 415 |
{% if user_data.unlimited_storage %}
|
| 416 |
+
Память: Безлимитно (Использовано: {{ storage_used_formatted }})
|
|
|
|
| 417 |
{% else %}
|
| 418 |
Память: {{ storage_used_formatted }} из {{ user_data.storage_limit_gb }} ГБ
|
| 419 |
{% endif %}
|
| 420 |
</p>
|
| 421 |
{% if not user_data.unlimited_storage %}
|
| 422 |
+
<button type="button" class="btn" style="background: var(--secondary); margin-left: 0; margin-bottom: 10px;"
|
| 423 |
+
onclick="openTelegramPaymentLink()">Приобрести доступ к безлимитной памяти за 20$</button>
|
| 424 |
+
<div style="margin-top: 15px; display: flex; align-items: center; flex-wrap: wrap; gap: 10px;">
|
| 425 |
+
<h4>Активировать промокод:</h4>
|
| 426 |
+
<form method="POST" action="{{ url_for('tma_activate_promo') }}" style="display: contents;">
|
| 427 |
+
<input type="text" name="promo_code" placeholder="Введите промокод" required style="width: auto; flex-grow: 1; margin: 0; min-width: 150px;">
|
| 428 |
+
<button type="submit" class="btn" style="background: var(--accent); margin-top: 0; margin-bottom: 0;">Активировать</button>
|
| 429 |
+
</form>
|
| 430 |
+
</div>
|
| 431 |
{% endif %}
|
|
|
|
| 432 |
{% with messages = get_flashed_messages(with_categories=true) %}{% if messages %}
|
| 433 |
{% for category, message in messages %}<div class="flash {{ category }}">{{ message }}</div>{% endfor %}
|
| 434 |
{% endif %}{% endwith %}
|
|
|
|
| 565 |
});
|
| 566 |
}
|
| 567 |
document.getElementById('logout-btn').addEventListener('click', function(e) { e.preventDefault(); window.location.href = "{{ url_for('tma_logout') }}"; });
|
|
|
|
|
|
|
| 568 |
|
| 569 |
+
function openTelegramPaymentLink() {
|
| 570 |
+
const adminUsername = "morshenkhan";
|
| 571 |
+
const message = "Здравствуйте, хочу приобрести полный доступ на Zeus Cloud";
|
| 572 |
+
const telegramLink = `https://t.me/${adminUsername}?startgroup=${encodeURIComponent(message)}`;
|
| 573 |
+
if (window.Telegram && window.Telegram.WebApp && Telegram.WebApp.openTelegramLink) {
|
| 574 |
+
Telegram.WebApp.openTelegramLink(telegramLink);
|
| 575 |
+
} else {
|
| 576 |
+
window.open(telegramLink, '_blank');
|
| 577 |
+
}
|
| 578 |
+
}
|
| 579 |
+
</script></body></html>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 580 |
'''
|
| 581 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 582 |
@app.route('/tma_dashboard', methods=['GET', 'POST'])
|
| 583 |
def tma_dashboard():
|
| 584 |
if 'telegram_user_id' not in session:
|
|
|
|
| 714 |
is_tma_user_admin_flag=is_admin_tma(),
|
| 715 |
user_data=user_data, storage_used_formatted=storage_used_formatted)
|
| 716 |
|
| 717 |
+
|
| 718 |
+
@app.route('/tma_activate_promo', methods=['POST'])
|
| 719 |
+
def tma_activate_promo():
|
| 720 |
if 'telegram_user_id' not in session:
|
| 721 |
flash('Пожалуйста, авторизуйтесь.', 'error')
|
| 722 |
return redirect(url_for('tma_entry_page'))
|
| 723 |
|
| 724 |
tma_user_id = session['telegram_user_id']
|
| 725 |
+
promo_code_str = request.form.get('promo_code', '').strip().upper()
|
|
|
|
|
|
|
|
|
|
|
|
|
| 726 |
|
| 727 |
data = load_data()
|
| 728 |
user_data = data['users'].get(tma_user_id)
|
| 729 |
+
promo_codes = data.get('promo_codes', {})
|
| 730 |
|
| 731 |
if not user_data:
|
| 732 |
session.clear()
|
|
|
|
| 734 |
return redirect(url_for('tma_entry_page'))
|
| 735 |
|
| 736 |
if user_data.get('unlimited_storage'):
|
| 737 |
+
flash('У вас уже активирован безлимитный доступ.', 'info')
|
|
|
|
|
|
|
|
|
|
|
|
|
| 738 |
return redirect(url_for('tma_dashboard'))
|
| 739 |
|
| 740 |
+
promo = promo_codes.get(promo_code_str)
|
| 741 |
|
| 742 |
+
if not promo:
|
| 743 |
+
flash('Неверный промокод.', 'error')
|
| 744 |
return redirect(url_for('tma_dashboard'))
|
| 745 |
|
| 746 |
+
if promo['current_activations'] >= promo['max_activations']:
|
| 747 |
+
flash('Этот промокод исчерпал лимит активаций.', 'error')
|
| 748 |
+
return redirect(url_for('tma_dashboard'))
|
| 749 |
+
|
| 750 |
+
if tma_user_id in promo['activated_by']:
|
| 751 |
+
flash('Вы уже использовали этот промокод.', 'info')
|
| 752 |
return redirect(url_for('tma_dashboard'))
|
| 753 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 754 |
user_data['unlimited_storage'] = True
|
| 755 |
+
|
| 756 |
+
promo['current_activations'] += 1
|
| 757 |
+
promo['activated_by'].append(tma_user_id)
|
| 758 |
|
| 759 |
try:
|
| 760 |
save_data(data)
|
| 761 |
+
flash('Безлимитный доступ успешно активирован!', 'success')
|
| 762 |
except Exception as e:
|
| 763 |
+
flash(f'Ошибка сохранения данных после активации промокода: {e}', 'error')
|
| 764 |
+
|
| 765 |
return redirect(url_for('tma_dashboard'))
|
| 766 |
|
| 767 |
+
|
| 768 |
@app.route('/create_folder_tma', methods=['POST'])
|
| 769 |
def create_folder_tma():
|
| 770 |
if 'telegram_user_id' not in session:
|
|
|
|
| 1009 |
flash('Вы вышли из сессии приложения.')
|
| 1010 |
return redirect(url_for('tma_entry_page'))
|
| 1011 |
|
| 1012 |
+
|
| 1013 |
+
ADMIN_LOGIN_HTML_TEMPLATE = '''
|
| 1014 |
+
<!DOCTYPE html><html lang="ru"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0">
|
| 1015 |
+
<title>Admin Login</title><link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600;800&display=swap" rel="stylesheet">
|
| 1016 |
+
<style>
|
| 1017 |
+
{{ admin_base_style_css }}
|
| 1018 |
+
body { display: flex; justify-content: center; align-items: center; height: 100vh; background: var(--background-dark); }
|
| 1019 |
+
.login-container { text-align: center; padding: 40px; background: var(--card-bg-dark); border-radius: 20px; box-shadow: var(--shadow); width: 100%; max-width: 400px; }
|
| 1020 |
+
h1 { color: var(--primary); margin-bottom: 20px; }
|
| 1021 |
+
input[type="text"], input[type="password"] { background: rgba(255,255,255,0.1); color: var(--text-dark); margin-bottom: 20px; }
|
| 1022 |
+
.btn { background: var(--accent); width: 100%; }
|
| 1023 |
+
</style>
|
| 1024 |
+
</head><body class="dark">
|
| 1025 |
+
<div class="login-container">
|
| 1026 |
+
<h1>Admin Login</h1>
|
| 1027 |
+
{% with messages = get_flashed_messages(with_categories=true) %}
|
| 1028 |
+
{% if messages %}
|
| 1029 |
+
{% for category, message in messages %}
|
| 1030 |
+
<div class="flash {{ category }}">{{ message }}</div>
|
| 1031 |
+
{% endfor %}
|
| 1032 |
+
{% endif %}
|
| 1033 |
+
{% endwith %}
|
| 1034 |
+
<form method="POST" action="{{ url_for('admin_login') }}">
|
| 1035 |
+
<input type="hidden" name="next" value="{{ request.args.get('next', '') }}">
|
| 1036 |
+
<input type="text" name="username" placeholder="Username" required>
|
| 1037 |
+
<input type="password" name="password" placeholder="Password" required>
|
| 1038 |
+
<button type="submit" class="btn">Login</button>
|
| 1039 |
+
</form>
|
| 1040 |
+
</div>
|
| 1041 |
+
</body></html>
|
| 1042 |
+
'''
|
| 1043 |
+
|
| 1044 |
@app.route('/admin/login', methods=['GET', 'POST'])
|
| 1045 |
def admin_login():
|
| 1046 |
if request.method == 'POST':
|
|
|
|
| 1064 |
flash('Вы вышли из админ-панели.', 'success')
|
| 1065 |
return redirect(url_for('admin_login'))
|
| 1066 |
|
| 1067 |
+
ADMIN_PANEL_HTML_TEMPLATE = '''
|
| 1068 |
+
<!DOCTYPE html><html lang="ru"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0">
|
| 1069 |
+
<title>Админ-панель</title><link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600;800&display=swap" rel="stylesheet">
|
| 1070 |
+
<style>''' + BASE_STYLE + '''</style></head><body class="dark"><div class="container"><h1>Админ-панель</h1>
|
| 1071 |
+
<a href="{{ url_for('admin_logout') }}" class="btn" style="margin-bottom:20px; background-color: var(--accent);">Выйти из админ-панели</a>
|
| 1072 |
+
<a href="{{ url_for('tma_dashboard') }}" class="btn" style="margin-bottom:20px;">В приложение (если TMA сессия есть)</a>
|
| 1073 |
+
<a href="{{ url_for('admin_manage_promos') }}" class="btn" style="margin-bottom:20px; background-color: var(--folder-color);">Управление промокодами</a>
|
| 1074 |
+
{% with messages = get_flashed_messages(with_categories=true) %}{% if messages %}{% for category, message in messages %}<div class="flash {{ category }}">{{ message }}</div>{% endfor %}{% endif %}{% endwith %}
|
| 1075 |
+
<h2>Пользователи</h2><div class="user-list">
|
| 1076 |
+
{% for user in user_details %}
|
| 1077 |
+
<div class="user-item">
|
| 1078 |
+
<a href="{{ url_for('admin_user_files', tma_user_id_str=user.id_key) }}">{{ user.display_name }} (ID: {{user.id_key}})</a>
|
| 1079 |
+
<p>Зарегистрирован: {{ user.created_at }}</p><p>Файлов: {{ user.file_count }}</p>
|
| 1080 |
+
<p>Память: {% if user.unlimited_storage %}Безлимитно ({{ user.storage_used_formatted }}){% else %}{{ user.storage_used_formatted }} из {{ user.storage_limit_gb }} ГБ{% endif %}</p>
|
| 1081 |
+
<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 }} и ВСЕ его файлы? НЕОБРАТИМО!');">
|
| 1082 |
+
<button type="submit" class="btn delete-btn" style="padding: 5px 10px; font-size: 0.9em;">Удалить</button>
|
| 1083 |
+
</form>
|
| 1084 |
+
</div>
|
| 1085 |
+
{% else %}<p>Пользователей нет.</p>{% endfor %}</div></div></body></html>'''
|
| 1086 |
+
|
| 1087 |
@app.route('/admhosto')
|
| 1088 |
@admin_browser_login_required
|
| 1089 |
def admin_panel():
|
|
|
|
| 1098 |
'file_count': sum(1 for _, node in get_all_nodes(udata.get('filesystem', {})) if node.get('type') == 'file'),
|
| 1099 |
'storage_limit_gb': udata.get('storage_limit_gb', DEFAULT_STORAGE_LIMIT_GB),
|
| 1100 |
'storage_used_formatted': format_bytes(udata.get('storage_used_bytes', 0)),
|
| 1101 |
+
'unlimited_storage': udata.get('unlimited_storage', False)
|
|
|
|
| 1102 |
})
|
| 1103 |
user_details.sort(key=lambda x: x.get('created_at', ''), reverse=True)
|
| 1104 |
return render_template_string(ADMIN_PANEL_HTML_TEMPLATE, user_details=user_details)
|
|
|
|
| 1112 |
for child in current_node['children']:
|
| 1113 |
queue.append(child)
|
| 1114 |
|
| 1115 |
+
ADMIN_USER_FILES_HTML_TEMPLATE = '''
|
| 1116 |
+
<!DOCTYPE html><html lang="ru"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0">
|
| 1117 |
+
<title>Файлы {{ display_name_admin_view }}</title><link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600;800&display=swap" rel="stylesheet">
|
| 1118 |
+
<style>''' + BASE_STYLE + '''
|
| 1119 |
+
.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; }
|
| 1120 |
+
.file-preview { max-width: 100%; height: 100px; object-fit: contain; border-radius: 10px; margin-bottom: 10px; display: block; margin-left: auto; margin-right: auto; }
|
| 1121 |
+
.admin-file-actions { margin-top: 10px; display: flex; flex-wrap: wrap; gap: 5px; justify-content: center; }
|
| 1122 |
+
.admin-file-actions .btn { font-size: 0.8em; padding: 4px 8px; margin: 0; }
|
| 1123 |
+
</style></head><body class="dark"><div class="container"><h1>Файлы пользователя: {{ display_name_admin_view }} (ID: {{ tma_user_id_str_admin_view }})</h1>
|
| 1124 |
+
<a href="{{ url_for('admin_panel') }}" class="btn" style="margin-bottom: 20px;">Назад к пользователям</a>
|
| 1125 |
+
<p>Лимит памяти:
|
| 1126 |
+
{% if user_data_admin_view.unlimited_storage %}Безлимитно (Использовано: {{ storage_used_formatted_admin_view }})
|
| 1127 |
+
{% else %}{{ storage_used_formatted_admin_view }} из {{ user_data_admin_view.storage_limit_gb }} ГБ
|
| 1128 |
+
{% endif %}
|
| 1129 |
+
</p>
|
| 1130 |
+
<form method="POST" action="{{ url_for('admin_toggle_unlimited_storage', tma_user_id_str=tma_user_id_str_admin_view) }}" style="display: inline-block;">
|
| 1131 |
+
<button type="submit" class="btn" style="background: var(--accent);">
|
| 1132 |
+
{{ 'Отключить безлимит' if user_data_admin_view.unlimited_storage else 'Включить безлимит' }}
|
| 1133 |
+
</button>
|
| 1134 |
+
</form>
|
| 1135 |
+
{% with messages = get_flashed_messages(with_categories=true) %}{% if messages %}{% for category, message in messages %}<div class="flash {{ category }}">{{ message }}</div>{% endfor %}{% endif %}{% endwith %}
|
| 1136 |
+
<div style="display: grid; grid-template-columns: repeat(auto-fill, minmax(220px, 1fr)); gap: 20px;">
|
| 1137 |
+
{% for file_item in files %}
|
| 1138 |
+
<div class="file-item"><div>
|
| 1139 |
+
{% 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;">
|
| 1140 |
+
{% 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>
|
| 1141 |
+
{% 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>
|
| 1142 |
+
{% 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>
|
| 1143 |
+
{% else %} <div class="file-preview" style="font-size: 40px; line-height: 100px; text-align: center; color: #aaa;">❓</div> {% endif %}
|
| 1144 |
+
<p title="{{ file_item.original_filename }}"><b>{{ file_item.original_filename | truncate(30) }}</b></p>
|
| 1145 |
+
<p style="font-size: 0.8em; color: #888;">В папке: {{ file_item.parent_path_str }}</p>
|
| 1146 |
+
<p style="font-size: 0.8em; color: #888;">Загружен: {{ file_item.upload_date }}</p>
|
| 1147 |
+
<p style="font-size: 0.8em; color: #888;">Размер: {{ file_item.size_formatted }}</p>
|
| 1148 |
+
<p style="font-size: 0.7em; color: #ccc;">ID: {{ file_item.id }}</p>
|
| 1149 |
+
<p style="font-size: 0.7em; color: #ccc; word-break: break-all;">Path: {{ file_item.path }}</p>
|
| 1150 |
+
</div><div class="admin-file-actions">
|
| 1151 |
+
<a href="{{ url_for('download_tma', file_id=file_item.id) }}" class="btn download-btn" download="{{ file_item.original_filename }}">Скачать</a>
|
| 1152 |
+
{% set previewable = file_item.file_type in ['image', 'video', 'pdf', 'text'] %}
|
| 1153 |
+
{% 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 %}
|
| 1154 |
+
<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 }}?');">
|
| 1155 |
+
<button type="submit" class="btn delete-btn">Удалить</button></form>
|
| 1156 |
+
</div></div>{% else %} <p>У пользователя нет файлов.</p> {% endfor %}</div></div>
|
| 1157 |
+
<div class="modal" id="mediaModalAdmin" onclick="closeModalAdminEv(event)"><div class="modal-content" id="modalContentContainerAdmin">
|
| 1158 |
+
<span onclick="closeModalAdminManual()" class="modal-close-btn">×</span><div id="modalContentAdmin"></div></div></div>
|
| 1159 |
+
<script>
|
| 1160 |
+
const repoIdJs = "{{ repo_id_js_admin }}";
|
| 1161 |
+
function hfFileUrlAdmin(path, download = false) { let url = `https://huggingface.co/datasets/${repoIdJs}/resolve/main/${path}`; if (download) url += '?download=true'; return url; }
|
| 1162 |
+
async function openModalAdmin(srcOrUrl, type, itemId) {
|
| 1163 |
+
const modal = document.getElementById('mediaModalAdmin'); const modalContent = document.getElementById('modalContentAdmin');
|
| 1164 |
+
modalContent.innerHTML = '<p>Загрузка...</p>'; modal.style.display = 'flex';
|
| 1165 |
+
try {
|
| 1166 |
+
if (type === 'image') modalContent.innerHTML = `<img src="${srcOrUrl}" alt="Просмотр изображения">`;
|
| 1167 |
+
else if (type === 'video') modalContent.innerHTML = `<video controls autoplay style='max-width: 95%; max-height: 85vh;'><source src="${srcOrUrl}" type="video/mp4"></video>`;
|
| 1168 |
+
else if (type === 'pdf') modalContent.innerHTML = `<iframe src="${srcOrUrl}" title="Просмотр PDF"></iframe>`;
|
| 1169 |
+
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>`;}
|
| 1170 |
+
else modalContent.innerHTML = '<p>Предпросмотр не поддерживается.</p>';
|
| 1171 |
+
} catch (error) { modalContent.innerHTML = `<p>Не удалось загрузить содержимое для предпросмотра. ${error.message}</p>`;}
|
| 1172 |
+
}
|
| 1173 |
+
function closeModalAdminEv(event) { if (event.target === document.getElementById('mediaModalAdmin')) closeModalAdminManual(); }
|
| 1174 |
+
function closeModalAdminManual() {
|
| 1175 |
+
const modal = document.getElementById('mediaModalAdmin'); modal.style.display = 'none';
|
| 1176 |
+
const video = modal.querySelector('video'); if (video) video.pause();
|
| 1177 |
+
const iframe = modal.querySelector('iframe'); if (iframe) iframe.src = 'about:blank';
|
| 1178 |
+
document.getElementById('modalContentAdmin').innerHTML = '';
|
| 1179 |
+
}
|
| 1180 |
+
</script></body></html>'''
|
| 1181 |
+
|
| 1182 |
@app.route('/admhosto/user/<tma_user_id_str>')
|
| 1183 |
@admin_browser_login_required
|
| 1184 |
def admin_user_files(tma_user_id_str):
|
|
|
|
| 1301 |
flash(f'Ошибка при удалении файла {original_filename}: {e}', 'error')
|
| 1302 |
return redirect(url_for('admin_user_files', tma_user_id_str=tma_user_id_str_form))
|
| 1303 |
|
| 1304 |
+
|
| 1305 |
+
ADMIN_PROMO_CODES_HTML_TEMPLATE = '''
|
| 1306 |
+
<!DOCTYPE html><html lang="ru"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0">
|
| 1307 |
+
<title>Управление Промокодами</title><link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600;800&display=swap" rel="stylesheet">
|
| 1308 |
+
<style>''' + BASE_STYLE + '''</style></head><body class="dark"><div class="container">
|
| 1309 |
+
<h1>Управление Промокодами</h1>
|
| 1310 |
+
<a href="{{ url_for('admin_panel') }}" class="btn" style="margin-bottom: 20px;">Назад к админ-панели</a>
|
| 1311 |
+
{% with messages = get_flashed_messages(with_categories=true) %}{% if messages %}{% for category, message in messages %}<div class="flash {{ category }}">{{ message }}</div>{% endfor %}{% endif %}{% endwith %}
|
| 1312 |
+
|
| 1313 |
+
<h2>Создать новый промокод</h2>
|
| 1314 |
+
<form method="POST" action="{{ url_for('admin_create_promo') }}" style="margin-bottom: 30px;">
|
| 1315 |
+
<input type="text" name="code" placeholder="Промокод (например, SUMMER2024)" required>
|
| 1316 |
+
<input type="number" name="max_activations" placeholder="Максимум активаций (0 для неактивного)" min="0" value="1" required>
|
| 1317 |
+
<button type="submit" class="btn">Создать промокод</button>
|
| 1318 |
+
</form>
|
| 1319 |
+
|
| 1320 |
+
<h2>Существующие промокоды</h2>
|
| 1321 |
+
{% if promo_codes %}
|
| 1322 |
+
<div class="user-list"> {# Reusing user-list style, it's generic enough #}
|
| 1323 |
+
{% for code, promo in promo_codes.items() %}
|
| 1324 |
+
<div class="user-item">
|
| 1325 |
+
<p><b>Код:</b> {{ promo.code }}</p>
|
| 1326 |
+
<p><b>Макс. активаций:</b> {{ promo.max_activations }}</p>
|
| 1327 |
+
<p><b>Текущих активаций:</b> {{ promo.current_activations }}</p>
|
| 1328 |
+
<p><b>Активирован пользователями:</b> {{ promo.activated_by | join(', ') if promo.activated_by else 'Нет' }}</p>
|
| 1329 |
+
<form method="POST" action="{{ url_for('admin_delete_promo', code=promo.code) }}" style="display: inline; margin-right: 10px;" onsubmit="return confirm('Удалить промокод {{ promo.code }}?');">
|
| 1330 |
+
<button type="submit" class="btn delete-btn" style="padding: 5px 10px; font-size: 0.9em;">Удалить</button>
|
| 1331 |
+
</form>
|
| 1332 |
+
<form method="POST" action="{{ url_for('admin_reset_promo', code=promo.code) }}" style="display: inline;" onsubmit="return confirm('Сбросить активации для промокода {{ promo.code }}?');">
|
| 1333 |
+
<button type="submit" class="btn folder-btn" style="padding: 5px 10px; font-size: 0.9em;">Сбросить активации</button>
|
| 1334 |
+
</form>
|
| 1335 |
+
</div>
|
| 1336 |
+
{% endfor %}
|
| 1337 |
+
</div>
|
| 1338 |
+
{% else %}
|
| 1339 |
+
<p>Промокоды отсутствуют.</p>
|
| 1340 |
+
{% endif %}
|
| 1341 |
+
</div></body></html>
|
| 1342 |
+
'''
|
| 1343 |
+
|
| 1344 |
+
@app.route('/admhosto/promos')
|
| 1345 |
@admin_browser_login_required
|
| 1346 |
+
def admin_manage_promos():
|
| 1347 |
data = load_data()
|
| 1348 |
+
promo_codes = data.get('promo_codes', {})
|
| 1349 |
+
return render_template_string(ADMIN_PROMO_CODES_HTML_TEMPLATE, promo_codes=promo_codes)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1350 |
|
| 1351 |
+
@app.route('/admhosto/promos/create', methods=['POST'])
|
| 1352 |
+
@admin_browser_login_required
|
| 1353 |
+
def admin_create_promo():
|
| 1354 |
+
code = request.form.get('code', '').strip().upper()
|
| 1355 |
+
try:
|
| 1356 |
+
max_activations = int(request.form.get('max_activations'))
|
| 1357 |
+
if max_activations < 0: raise ValueError("Max activations must be non-negative.")
|
| 1358 |
+
except (ValueError, TypeError):
|
| 1359 |
+
flash('Неверное значение для максимального количества активаций.', 'error')
|
| 1360 |
+
return redirect(url_for('admin_manage_promos'))
|
| 1361 |
+
|
| 1362 |
+
if not code:
|
| 1363 |
+
flash('Код промокода не может быть пустым.', 'error')
|
| 1364 |
+
return redirect(url_for('admin_manage_promos'))
|
| 1365 |
+
|
| 1366 |
+
data = load_data()
|
| 1367 |
+
promo_codes = data.get('promo_codes', {})
|
| 1368 |
+
|
| 1369 |
+
if code in promo_codes:
|
| 1370 |
+
flash(f'Промокод "{code}" уже существует.', 'error')
|
| 1371 |
+
return redirect(url_for('admin_manage_promos'))
|
| 1372 |
+
|
| 1373 |
+
promo_codes[code] = {
|
| 1374 |
+
'code': code,
|
| 1375 |
+
'max_activations': max_activations,
|
| 1376 |
+
'current_activations': 0,
|
| 1377 |
+
'activated_by': []
|
| 1378 |
+
}
|
| 1379 |
+
data['promo_codes'] = promo_codes
|
| 1380 |
|
| 1381 |
+
try:
|
| 1382 |
+
save_data(data)
|
| 1383 |
+
flash(f'Промокод "{code}" успешно создан.', 'success')
|
| 1384 |
+
except Exception as e:
|
| 1385 |
+
flash(f'Ошибка сохранения данных при создании промокода: {e}', 'error')
|
| 1386 |
+
return redirect(url_for('admin_manage_promos'))
|
| 1387 |
|
| 1388 |
+
@app.route('/admhosto/promos/delete/<string:code>', methods=['POST'])
|
| 1389 |
@admin_browser_login_required
|
| 1390 |
+
def admin_delete_promo(code):
|
| 1391 |
data = load_data()
|
| 1392 |
+
promo_codes = data.get('promo_codes', {})
|
| 1393 |
+
|
| 1394 |
+
if code not in promo_codes:
|
| 1395 |
+
flash(f'Промокод "{code}" не найден.', 'error')
|
| 1396 |
+
return redirect(url_for('admin_manage_promos'))
|
| 1397 |
+
|
| 1398 |
+
del promo_codes[code]
|
| 1399 |
+
|
| 1400 |
+
try:
|
| 1401 |
+
save_data(data)
|
| 1402 |
+
flash(f'Промокод "{code}" успешно удален.', 'success')
|
| 1403 |
+
except Exception as e:
|
| 1404 |
+
flash(f'Ошибка сохранения данных при удалении промокода: {e}', 'error')
|
| 1405 |
+
return redirect(url_for('admin_manage_promos'))
|
| 1406 |
+
|
| 1407 |
+
@app.route('/admhosto/promos/reset/<string:code>', methods=['POST'])
|
| 1408 |
+
@admin_browser_login_required
|
| 1409 |
+
def admin_reset_promo(code):
|
| 1410 |
+
data = load_data()
|
| 1411 |
+
promo_codes = data.get('promo_codes', {})
|
| 1412 |
+
|
| 1413 |
+
promo = promo_codes.get(code)
|
| 1414 |
+
if not promo:
|
| 1415 |
flash(f'Промокод "{code}" не найден.', 'error')
|
| 1416 |
+
return redirect(url_for('admin_manage_promos'))
|
| 1417 |
|
| 1418 |
+
promo['current_activations'] = 0
|
| 1419 |
+
promo['activated_by'] = []
|
| 1420 |
+
|
| 1421 |
+
try:
|
| 1422 |
+
save_data(data)
|
| 1423 |
+
flash(f'Активации для промокода "{code}" сброшены.', 'success')
|
| 1424 |
+
except Exception as e:
|
| 1425 |
+
flash(f'Ошибка сохранения данных при сбросе активаций: {e}', 'error')
|
| 1426 |
+
return redirect(url_for('admin_manage_promos'))
|
| 1427 |
|
| 1428 |
if __name__ == '__main__':
|
| 1429 |
if not HF_TOKEN_WRITE: logging.warning("HF_TOKEN (write access) is not set. Uploads/deletions/backups will fail.")
|
|
|
|
| 1432 |
if ADMIN_USERNAME == "admin" and ADMIN_PASSWORD == "zeusadminpass":
|
| 1433 |
logging.warning("Using default admin username/password for browser admin panel. Please change ADMIN_USERNAME and ADMIN_PASSWORD environment variables.")
|
| 1434 |
|
| 1435 |
+
|
| 1436 |
if HF_TOKEN_WRITE:
|
| 1437 |
download_db_from_hf()
|
| 1438 |
threading.Thread(target=periodic_backup, daemon=True).start()
|
|
|
|
| 1440 |
download_db_from_hf()
|
| 1441 |
else:
|
| 1442 |
if not os.path.exists(DATA_FILE):
|
| 1443 |
+
with open(DATA_FILE, 'w', encoding='utf-8') as f: json.dump({'users': {}, 'promo_codes': {}}, f)
|
| 1444 |
|
| 1445 |
app.run(debug=False, host='0.0.0.0', port=7860)
|