"""Flask-приложение и все HTTP-маршруты /api/*, /health и /. Вынесено из bot.py без изменения поведения (шаг «каркас», пункт 2.7 роадмапа). bot.py запускается как __main__, поэтому здесь нет `import bot`; общее состояние лежит в runtime.py, сессии в session_auth.py, а отправка сообщений в Telegram идёт через хук runtime.send_message (его регистрирует бот). Маршруты, которым нужен сам бот (/api/bot_info, /webhook), остаются в bot.py и регистрируются на этом же app. """ import os import threading as _threading from datetime import datetime import requests from flask import Flask, request, jsonify from flask_cors import CORS import ai_router from text_utils import set_markdown_mode from providers.gemini_provider import UnsupportedFileError from ai_clients import check_keys_status from stats_report import get_stats_report from database import (get_user, get_user_by_username, register_user, set_ai_model, remove_subscription, has_active_sub, get_balance, get_referral_count, get_all_users, get_stats, is_maintenance, set_setting, get_setting, log_admin_grant, get_mini_app_chats, save_mini_app_chat, delete_mini_app_chat, log_session_activity, get_user_purchase_history, grant_pro, check_daily_limit, check_feature_quota, increment_feature_usage, IMAGE_GEN_FEATURE, IMAGE_GEN_DAILY_LIMIT, check_token_quota) from runtime import (OWNER_ID, BOT_USERNAME, is_privileged, GenerationInProgress, _generation_lock, resolve_model_id, is_pro_model, _finalize_usage_async, get_mime_for_extension, MAX_ATTACHMENT_BYTES, MAX_ATTACHMENTS_TOTAL_BYTES, auth_tokens as _auth_tokens, send_message as _notify) from session_auth import (_make_session_token, _require_authed_user_id, _verify_telegram_webapp_init_data, check_admin_auth as _check_admin_auth) app = Flask(__name__) CORS(app, resources={r"/api/*": {"origins": "*"}}, supports_credentials=False) # Флаги функций и конфиг клиентов: /api/app-config, /api/admin/flags, /api/admin/app_version, /api/admin/maintenance (пункт 1.1) from app_config import app_config_bp app.register_blueprint(app_config_bp) # Загрузка больших вложений частями: /api/upload/* (прокси Vercel режет тела > ~4.5 МБ) from uploads import uploads_bp, read_upload, discard_upload, UploadError app.register_blueprint(uploads_bp) # Оплата подписки: ЮKassa (виджет) и CryptoBot (динамический инвойс): /api/pay/*, /api/admin/pay/* from payments import payments_bp, start_reconciler app.register_blueprint(payments_bp) start_reconciler() # фоновая сверка зависших оплат (PAY_RECONCILE_INTERVAL, 0 — выключить) @app.before_request def _set_client_format_mode(): # Сайт, мини-апп и приложения (/api/*) рендерят markdown и блоки кода; Telegram-бот (/webhook) # отправляет обычный текст — ему остаётся plain-промпт. Ставим явно на каждый запрос. set_markdown_mode(request.path.startswith("/api/")) @app.after_request def after_request(response): response.headers.add("Access-Control-Allow-Origin", "*") response.headers.add("Access-Control-Allow-Headers", "Content-Type,Authorization,X-Admin-Secret") response.headers.add("Access-Control-Allow-Methods", "GET,POST,DELETE,OPTIONS") return response # App version / auto-update переехал на сайт: приложение теперь берёт # версию напрямую из https://elyon-ai-web.vercel.app/downloads/version.json # (статический файл, обновляется через push_release.ps1 в Elyon-AI-Web-repo), # без похода через бота вообще. См. update_service.dart. @app.route("/api/chat", methods=["POST", "OPTIONS"]) def api_chat(): if request.method == "OPTIONS": return "", 204 try: authed_uid, err = _require_authed_user_id() if err: return err data = request.json user_id = authed_uid # было: data.get("user_id") — клиентский user_id без проверки, позволял имперсонировать любого model = data.get("model", "elyon_nova") messages = data.get("messages", []) if not messages: return jsonify({"error": "Missing messages"}), 400 if is_maintenance() and not is_privileged(user_id): return jsonify({"error": "Maintenance in progress"}), 503 model_id = resolve_model_id(model) if not model_id: return jsonify({"error": "Unknown model"}), 400 model_is_pro = is_pro_model(model_id) user_is_pro = has_active_sub(user_id) if model_is_pro and not user_is_pro: return jsonify({"error": "No active subscription"}), 403 if not is_privileged(user_id): # БЫЛО: сюда передавался model_is_pro вместо user_is_pro — Pro-подписчик на бесплатной # модели (Nova) получал дневной лимит 15 вместо 30 — именно это было видно в "0/15" на сайте. allowed, current, limit = check_daily_limit(user_id, user_is_pro) if not allowed: return jsonify({"error": "daily_limit", "limit": limit}), 429 token_allowed, token_info = check_token_quota(user_id, is_pro=user_is_pro) if not token_allowed: return jsonify({"error": "token_limit", "tier": token_info["tier"]}), 429 reply = usage = None try: with _generation_lock(user_id): reply, usage = ai_router.ask(model_id, messages) except GenerationInProgress: return jsonify({"error": "already_generating"}), 429 # Счётчики в фоне ПОСЛЕ того, как готов ответ — 3-4 сетевых похода к Turso больше не задерживают ответ. _finalize_usage_async(user_id, usage, "miniapp") return jsonify({"reply": reply}) except Exception as e: return jsonify({"error": str(e)}), 500 @app.route("/api/user/", methods=["GET", "OPTIONS"]) def api_user(user_id): if request.method == "OPTIONS": return "", 204 authed_uid, err = _require_authed_user_id() if err: return err if authed_uid != user_id: return jsonify({"error": "Unauthorized"}), 403 user = get_user(user_id) if not user: return jsonify({"error": "User not found"}), 404 is_pro = has_active_sub(user_id) # один раз, дальше передаётся в check_token_quota вместо её внутреннего повторного has_active_sub token_allowed, token_info = check_token_quota(user_id, is_pro=is_pro) # Карточка "Messages today" на сайте раньше всегда показывала статичное "0 / 15" и не учитывала Pro-лимит 30 — # ответ этого endpoint вообще не содержал этих полей. _, daily_current, daily_limit = check_daily_limit(user_id, is_pro) return jsonify({ "user_id": user[0], "username": user[1], "role": user[3], "ai_model": user[4], "sub_type": user[5], "sub_until": user[6], "balance": get_balance(user_id), "referrals": get_referral_count(user_id), "has_sub": is_pro, "ref_link": f"https://t.me/{BOT_USERNAME}?start={user_id}", "purchase_history": [list(p) for p in get_user_purchase_history(user_id)], "token_usage": token_info["usage"], "token_limits": token_info["limits"], "daily_messages": daily_current, "daily_limit": daily_limit, }) @app.route("/api/chats/", methods=["GET", "OPTIONS"]) def api_get_chats(user_id): if request.method == "OPTIONS": return "", 204 authed_uid, err = _require_authed_user_id() if err: return err if authed_uid != user_id: return jsonify({"error": "Unauthorized"}), 403 return jsonify({"chats": get_mini_app_chats(user_id)}) @app.route("/api/chats/", methods=["POST", "OPTIONS"]) def api_save_chat(user_id): if request.method == "OPTIONS": return "", 204 authed_uid, err = _require_authed_user_id() if err: return err if authed_uid != user_id: return jsonify({"error": "Unauthorized"}), 403 try: data = request.json chat_id = data.get("chat_id") if not chat_id: return jsonify({"error": "Missing chat_id"}), 400 save_mini_app_chat(user_id, chat_id, data.get("title","New chat"), data.get("model","gpt"), data.get("messages",[])) return jsonify({"ok": True}) except Exception as e: return jsonify({"error": str(e)}), 500 @app.route("/api/chats//", methods=["DELETE", "OPTIONS"]) def api_delete_chat(user_id, chat_id): if request.method == "OPTIONS": return "", 204 authed_uid, err = _require_authed_user_id() if err: return err if authed_uid != user_id: return jsonify({"error": "Unauthorized"}), 403 delete_mini_app_chat(user_id, chat_id) return jsonify({"ok": True}) # Лимиты вложений в одном сообщении (сайт/мини-апп/приложение): Free — 1 файл, Pro — до 4. Проверяется на сервере # (клиенты тоже ограничивают UI по этим числам, но доверять им нельзя). MAX_ATTACHMENTS_FREE = 1 MAX_ATTACHMENTS_PRO = 4 # MAX_ATTACHMENT_BYTES (20 МБ на файл) и MAX_ATTACHMENTS_TOTAL_BYTES (30 МБ на сообщение) живут в runtime.py _FILE_MIME_MAP = { ".py":"text/x-python",".js":"text/javascript",".cpp":"text/x-c++",".c":"text/x-c",".java":"text/x-java", ".txt":"text/plain",".md":"text/plain",".csv":"text/csv",".json":"application/json",".html":"text/html", ".css":"text/css",".sql":"text/plain",".gif":"image/gif",".png":"image/png",".jpg":"image/jpeg", ".jpeg":"image/jpeg",".webp":"image/webp",".pdf":"application/pdf", ".heic":"image/heic",".heif":"image/heif", # Gemini принимает HEIC/HEIF как есть (фото с Samsung/iPhone) } _HEIF_BRANDS = {b"heic": "image/heic", b"heix": "image/heic", b"hevc": "image/heic", b"hevx": "image/heic", b"heim": "image/heic", b"heis": "image/heic", b"mif1": "image/heif", b"msf1": "image/heif"} def _sniff_image_mime(blob: bytes): """Тип изображения по первым байтам (не по имени и не по тому, что сказал клиент). None, если это не картинка из списка.""" if blob[:3] == b"\xff\xd8\xff": return "image/jpeg" if blob[:8] == b"\x89PNG\r\n\x1a\n": return "image/png" if blob[:6] in (b"GIF87a", b"GIF89a"): return "image/gif" if blob[:4] == b"RIFF" and blob[8:12] == b"WEBP": return "image/webp" if blob[4:8] == b"ftyp": return _HEIF_BRANDS.get(blob[8:12]) return None def _resolve_file_mime(file_name: str, file_type: str, blob: bytes = b"") -> str: """MIME вложения. Приоритет: то, что сказал клиент (кроме octet-stream), иначе расширение; если по первым байтам это известная картинка (JPEG/PNG/GIF/WebP/HEIC/HEIF), верим содержимому. Android-проводник часто не знает HEIC (octet-stream), сайт подставлял text/plain: файл принимали за текст и отклоняли («Формат файла не поддерживается»).""" if file_type and file_type != "application/octet-stream": mime = file_type else: ext = os.path.splitext((file_name or "").lower())[1] mime = _FILE_MIME_MAP.get(ext) or get_mime_for_extension(file_name or "") or "application/octet-stream" sniffed = _sniff_image_mime(blob) if blob else None if sniffed and mime != sniffed: return sniffed # сигнатура картинки в начале файла надёжнее имени и догадки клиента (сайт раньше считал неизвестное text/plain) return mime @app.route("/api/file_b64", methods=["POST", "OPTIONS"]) def api_file_b64(): """JSON: {model, prompt, history, lang, files:[{name,type,data(base64)}]}. Старый формат одного файла (file_name/file_type/file_data) поддержан для необновлённых клиентов.""" if request.method == "OPTIONS": return "", 204 try: authed_uid, err = _require_authed_user_id() if err: return err import base64 as b64 data = request.json or {} user_id = authed_uid model = data.get("model", "elyon_nova") prompt = data.get("prompt") or "" history = data.get("history", []) lang = "en" if str(data.get("lang", "ru")).lower().startswith("en") else "ru" raw_files = data.get("files") if not raw_files: raw_files = [{"name": data.get("file_name", "file"), "type": data.get("file_type", "application/octet-stream"), "data": data.get("file_data", "")}] if not isinstance(raw_files, list) or not raw_files: return jsonify({"error": "No files"}), 400 if is_maintenance() and not is_privileged(user_id): return jsonify({"error": "Maintenance in progress"}), 503 model_id = resolve_model_id(model) if not model_id: return jsonify({"error": "Unknown model"}), 400 user_is_pro = has_active_sub(user_id) if is_pro_model(model_id) and not user_is_pro: return jsonify({"error": "No active subscription"}), 403 is_privileged_user = is_privileged(user_id) attach_limit = MAX_ATTACHMENTS_PRO if (user_is_pro or is_privileged_user) else MAX_ATTACHMENTS_FREE if len(raw_files) > attach_limit: return jsonify({"error": f"Max {attach_limit} attachment(s) per message on your plan", "code": "too_many_attachments", "limit": attach_limit}), 400 if not is_privileged_user: # Раньше здесь проверялся только токен-лимит: сообщения с файлом увеличивали дневной # счётчик, но не упирались в дневной лимит — файлы можно было слать бесконечно. allowed, _cur, limit = check_daily_limit(user_id, user_is_pro) if not allowed: return jsonify({"error": "daily_limit", "limit": limit}), 429 token_allowed, token_info = check_token_quota(user_id, is_pro=user_is_pro) if not token_allowed: return jsonify({"error": "token_limit", "tier": token_info["tier"]}), 429 files = [] total = 0 used_uploads = [] for rf in raw_files: if not isinstance(rf, dict): return jsonify({"error": "Bad file entry"}), 400 name = str(rf.get("name") or "file") if rf.get("upload_id"): # большой файл, загруженный частями (см. uploads.py): берём байты из временного хранилища try: blob = read_upload(user_id, rf.get("upload_id")) except UploadError as ue: return jsonify({"error": ue.message, "code": ue.code}), ue.status used_uploads.append(rf.get("upload_id")) else: try: blob = b64.b64decode(rf.get("data") or "") except Exception: return jsonify({"error": f"Bad file data: {name}"}), 400 if not blob: return jsonify({"error": f"Empty file: {name}"}), 400 if len(blob) > MAX_ATTACHMENT_BYTES: return jsonify({"error": f"File too large (max 20 MB): {name}"}), 413 total += len(blob) files.append((blob, _resolve_file_mime(name, str(rf.get("type") or ""), blob), name)) if total > MAX_ATTACHMENTS_TOTAL_BYTES: return jsonify({"error": "Attachments too large (max 30 MB total)"}), 413 reply = usage = None try: with _generation_lock(user_id): reply, usage = ai_router.ask_with_files(model_id, files, prompt, history, lang) except GenerationInProgress: return jsonify({"error": "already_generating"}), 429 except UnsupportedFileError as e: return jsonify({"error": str(e), "code": "unsupported_file"}), 400 for _uid in used_uploads: # ответ получен: временные файлы больше не нужны (при ошибке остаются до TTL для повтора) discard_upload(user_id, _uid) _finalize_usage_async(user_id, usage, "miniapp") return jsonify({"reply": reply}) except Exception as e: return jsonify({"error": str(e)}), 500 @app.route("/api/voice", methods=["POST", "OPTIONS"]) def api_voice(): """Голос → текст (сайт/миниапп/десктоп). multipart/form-data: file (аудио), user_id. Не отправляет в AI самостоятельно — только возвращает транскрипт, клиент показывает его в поле ввода для подтверждения/редактирования перед отправкой — как и обычное текстовое сообщение.""" if request.method == "OPTIONS": return "", 204 try: authed_uid, err = _require_authed_user_id() if err: return err user_id = authed_uid if is_maintenance() and not is_privileged(user_id): return jsonify({"error": "Maintenance in progress"}), 503 if "file" not in request.files: return jsonify({"error": "No audio file"}), 400 f = request.files["file"] audio_bytes = f.read() filename = f.filename or "voice.webm" transcript = ai_router.transcribe_voice(audio_bytes, filename) if not transcript or not transcript.strip(): return jsonify({"error": "Не удалось распознать речь"}), 422 return jsonify({"transcript": transcript}) except Exception as e: return jsonify({"error": str(e)}), 500 @app.route("/api/generate_image", methods=["POST", "OPTIONS"]) def api_generate_image(): """Генерация картинок (сайт/миниапп/десктоп), только Pro. JSON: {user_id, prompt}. Квота 3/сутки (сброс 00:00 UTC), та же таблица feature_usage, что и у бота (общий лимит на юзера независимо от клиента). Возвращает {image: base64, mime_type}, как в data URI на клиенте.""" if request.method == "OPTIONS": return "", 204 try: authed_uid, err = _require_authed_user_id() if err: return err import base64 as b64 data = request.json or {} user_id = authed_uid prompt = (data.get("prompt") or "").strip() if not prompt: return jsonify({"error": "Missing prompt"}), 400 if is_maintenance() and not is_privileged(user_id): return jsonify({"error": "Maintenance in progress"}), 503 if not has_active_sub(user_id) and not is_privileged(user_id): return jsonify({"error": "No active subscription"}), 403 allowed, current, limit = check_feature_quota(user_id, IMAGE_GEN_FEATURE, IMAGE_GEN_DAILY_LIMIT) if not allowed and not is_privileged(user_id): return jsonify({"error": "daily_limit", "limit": limit}), 429 image_bytes = mime_type = None try: with _generation_lock(user_id): image_bytes, mime_type = ai_router.generate_image(prompt) except GenerationInProgress: return jsonify({"error": "already_generating"}), 429 # Счётчики в фоне — картинка уже готова, ждать Turso пользователю не надо. _threading.Thread(target=lambda: ( increment_feature_usage(user_id, IMAGE_GEN_FEATURE), log_session_activity(user_id, "miniapp"), ), daemon=True).start() return jsonify({"image": b64.b64encode(image_bytes).decode(), "mime_type": mime_type}) except Exception as e: return jsonify({"error": str(e)}), 500 @app.route("/api/file", methods=["POST", "OPTIONS"]) def api_file(): if request.method == "OPTIONS": return "", 204 try: authed_uid, err = _require_authed_user_id() if err: return err import json as json_lib user_id = authed_uid model = request.form.get("model", "elyon_nova") prompt = request.form.get("prompt", "Проанализируй этот файл") history = json_lib.loads(request.form.get("history","[]")) if "file" not in request.files: return jsonify({"error": "No file"}), 400 model_id = resolve_model_id(model) if not model_id: return jsonify({"error": "Unknown model"}), 400 user_is_pro = has_active_sub(user_id) if is_pro_model(model_id) and not user_is_pro: return jsonify({"error": "No active subscription"}), 403 if not is_privileged(user_id): token_allowed, token_info = check_token_quota(user_id, is_pro=user_is_pro) if not token_allowed: return jsonify({"error": "token_limit", "tier": token_info["tier"]}), 429 f = request.files["file"] file_bytes = f.read(); file_name = f.filename or "file" mime_type = f.content_type or "application/octet-stream" if mime_type == "application/octet-stream": ext = os.path.splitext(file_name.lower())[1] mime_map = {".py":"text/x-python",".js":"text/javascript",".txt":"text/plain", ".md":"text/plain",".csv":"text/csv",".json":"application/json"} mime_type = mime_map.get(ext, "application/octet-stream") reply, usage = ai_router.ask_with_file(model_id, file_bytes, mime_type, file_name, prompt, history) _finalize_usage_async(user_id, usage, "miniapp") return jsonify({"reply": reply}) except Exception as e: return jsonify({"error": str(e)}), 500 # ── Auth ────────────────────────────────────────────────────────────────── GOOGLE_CLIENT_ID = os.environ.get("GOOGLE_CLIENT_ID", "468899724697-mct44qubsrdaps8ll6m4npv34k6jeucn.apps.googleusercontent.com") def _upsert_web_user(email, first_name, last_name, avatar="", provider="email"): # Используем публичные функции database.py, а не сырой SQL через # database.cursor/database.conn — после миграции на Turso (libsql_client) # этих атрибутов больше не существует (там теперь внутренний _exec()), # из-за чего Google/email авторизация падала с AttributeError: "module 'database' # has no attribute 'cursor'". existing = get_user_by_username(email) if existing: user_id = existing[0] else: user_id = abs(hash(email + provider)) % (10**12) register_user(user_id, email) return {"user_id":user_id,"email":email,"first_name":first_name, "last_name":last_name,"avatar":avatar,"provider":provider} @app.route("/api/auth/google_profile", methods=["POST","OPTIONS"]) def auth_google_profile(): if request.method == "OPTIONS": return "", 204 try: data = request.json or {} # РАНЬШЕ клиент присылал готовый объект profile, взятый им самим из Google — сервер никак # не проверял, что этот JSON действительно пришёл от Google, а не придуман атакующим напрямую в # POST /api/auth/google_profile — можно было заявиться любым email. Теперь клиент шлёт сам access_token, # а сервер сам запрашивает им профиль у Google — только так он доказан, что токен действительно выдал Google. access_token = data.get("access_token", "") if not access_token: return jsonify({"ok":False,"error":"Missing access_token"}), 400 try: g = requests.get("https://www.googleapis.com/oauth2/v3/userinfo", headers={"Authorization": f"Bearer {access_token}"}, timeout=10) except requests.RequestException as e: return jsonify({"ok":False,"error":f"Google verification failed: {e}"}), 502 if g.status_code != 200: return jsonify({"ok":False,"error":"Invalid or expired Google token"}), 401 profile = g.json() email = profile.get("email","") if not email: return jsonify({"ok":False,"error":"No email"}), 400 user = _upsert_web_user(email, profile.get("given_name",""), profile.get("family_name",""), profile.get("picture",""), "google") return jsonify({"ok":True,"user":user,"token":_make_session_token(user["user_id"])}) except Exception as e: return jsonify({"ok":False,"error":str(e)}), 500 @app.route("/api/auth/telegram_webapp", methods=["POST","OPTIONS"]) def auth_telegram_webapp(): """Авторизация для Мини-Аппа внутри Telegram: клиент шлёт сырой подписанный Telegram.WebApp.initData целиком (не initDataUnsafe.user отдельно), сервер сам проверяет HMAC-подпись.""" if request.method == "OPTIONS": return "", 204 try: init_data = (request.json or {}).get("init_data", "") tg_user = _verify_telegram_webapp_init_data(init_data) if not tg_user or not tg_user.get("id"): return jsonify({"ok":False,"error":"Invalid Telegram initData"}), 401 user_id = int(tg_user["id"]) username = tg_user.get("username", "") register_user(user_id, username) user = get_user(user_id) sub_type = user[5] if user else "none" web_user = { "user_id": user_id, "email": f"{username}@telegram" if username else f"tg_{user_id}@telegram", "first_name": tg_user.get("first_name",""), "last_name": tg_user.get("last_name",""), "avatar": "", "provider": "telegram", "username": username, "sub_type": sub_type, } return jsonify({"ok":True,"user":web_user,"token":_make_session_token(user_id)}) except Exception as e: return jsonify({"ok":False,"error":str(e)}), 500 @app.route("/api/auth/email", methods=["POST","OPTIONS"]) def auth_email(): if request.method == "OPTIONS": return "", 204 try: import hashlib as _hl data = request.json or {} action = data.get("action","signin") email = data.get("email","").lower().strip() password = data.get("password","") if not email or not password: return jsonify({"ok":False,"error":"Missing email or password"}), 400 pw_hash = _hl.sha256(password.encode()).hexdigest() if action == "signup": if get_user_by_username(email): return jsonify({"ok":False,"error":"Email already registered"}), 409 user_id = abs(hash(email + pw_hash)) % (10**12) register_user(user_id, email) set_setting(f"pw_{email}", pw_hash) user = _upsert_web_user(email, data.get("first_name",""), data.get("last_name",""), "", "email") return jsonify({"ok":True,"verify":False,"user":user,"token":_make_session_token(user["user_id"])}) else: stored = get_setting(f"pw_{email}") if not stored or stored != pw_hash: return jsonify({"ok":False,"error":"Invalid email or password"}), 401 user = _upsert_web_user(email, "", "", "", "email") return jsonify({"ok":True,"user":user,"token":_make_session_token(user["user_id"])}) except Exception as e: return jsonify({"ok":False,"error":str(e)}), 500 @app.route("/api/auth/telegram_token", methods=["POST","OPTIONS"]) def auth_telegram_token(): if request.method == "OPTIONS": return "", 204 try: data = request.json or {} token = data.get("token","") if not token: return jsonify({"ok":False,"error":"Missing token"}), 400 info = _auth_tokens.get(token) if not info: return jsonify({"ok":False,"error":"Invalid token"}), 401 if datetime.now().timestamp() > info["expires"]: _auth_tokens.pop(token, None) return jsonify({"ok":False,"error":"Token expired"}), 401 _auth_tokens.pop(token, None) user_id = info["user_id"]; username = info["username"] register_user(user_id, username) user = get_user(user_id) sub_type = user[5] if user else "none" web_user = { "user_id": user_id, "email": f"{username}@telegram" if username else f"tg_{user_id}@telegram", "first_name": info["first_name"], "last_name": "", "avatar": "", "provider": "telegram", "username": username, "sub_type": sub_type, } return jsonify({"ok":True,"user":web_user,"token":_make_session_token(user_id)}) except Exception as e: return jsonify({"ok":False,"error":str(e)}), 500 @app.route("/api/admin/stats", methods=["GET","OPTIONS"]) def api_admin_stats(): if request.method == "OPTIONS": return "", 204 if not _check_admin_auth(): return jsonify({"ok":False,"error":"Unauthorized"}), 403 return jsonify(get_stats()) @app.route("/api/admin/stats_report", methods=["GET","OPTIONS"]) def api_admin_stats_report(): """Данные для двух баннеров админ-панели: «Сегодня (UTC)» с почасовым графиком и «За всё время» с дневным.""" if request.method == "OPTIONS": return "", 204 if not _check_admin_auth(): return jsonify({"ok":False,"error":"Unauthorized"}), 403 try: return jsonify(get_stats_report()) except Exception as e: print(f"[stats_report] {e}", flush=True) return jsonify({"ok":False,"error":str(e)}), 500 @app.route("/api/admin/users", methods=["GET","OPTIONS"]) def api_admin_users(): if request.method == "OPTIONS": return "", 204 if not _check_admin_auth(): return jsonify({"ok":False,"error":"Unauthorized"}), 403 users = get_all_users() return jsonify({"users": [{"user_id":u[0],"username":u[1] or "","role":u[3] or "default user", "sub_type":u[5] or "none","balance":u[7] if len(u)>7 else 0} for u in users]}) # ══════════════════════════════════════════════════════════════════ # Admin API — /give sub и /remove sub из веб-панели (задача 2 и 4) # ══════════════════════════════════════════════════════════════════ # _check_admin_auth() живёт в session_auth.py (check_admin_auth): её используют и маршруты из app_config.py @app.route("/api/admin/give_sub", methods=["POST","OPTIONS"]) def api_admin_give_sub(): """ Выдать Elyon Pro из веб-панели. Headers: X-Admin-Secret Body: {"target":"@username","days":30,"forever":false} """ if request.method == "OPTIONS": return "", 204 if not _check_admin_auth(): return jsonify({"ok":False,"error":"Unauthorized"}), 403 try: data = request.json or {} target = data.get("target","").strip().lstrip("@") days = int(data.get("days", 30)) forever = bool(data.get("forever", False)) user = get_user_by_username(target) if not user: return jsonify({"ok":False,"error":f"User @{target} not found"}), 404 user_id = user[0] until_str = grant_pro(user_id, days=None if forever else days, forever=forever) set_ai_model(user_id, "elyon_sol") log_admin_grant(user_id, "subscription", "pro", until_str, OWNER_ID) try: _notify(user_id, f"✅ Подписка Elyon Pro активирована (до {until_str}).") except: pass return jsonify({"ok":True,"user_id":user_id,"tier":"pro","until":until_str}) except Exception as e: return jsonify({"ok":False,"error":str(e)}), 500 @app.route("/api/admin/remove_sub", methods=["POST","OPTIONS"]) def api_admin_remove_sub(): """ Снять подписку из веб-панели. Headers: X-Admin-Id: OWNER_ID Body: {"target":"@username"} """ if request.method == "OPTIONS": return "", 204 if not _check_admin_auth(): return jsonify({"ok":False,"error":"Unauthorized"}), 403 try: target = (request.json or {}).get("target","").strip().lstrip("@") user = get_user_by_username(target) if not user: return jsonify({"ok":False,"error":f"User @{target} not found"}), 404 user_id = user[0] remove_subscription(user_id) try: _notify(user_id, "ℹ️ Твоя подписка деактивирована администратором.") except: pass return jsonify({"ok":True,"user_id":user_id}) except Exception as e: return jsonify({"ok":False,"error":str(e)}), 500 @app.route("/api/admin/test_keys", methods=["GET","OPTIONS"]) def api_admin_test_keys(): """Проверить API ключи из веб-панели.""" if request.method == "OPTIONS": return "", 204 if not _check_admin_auth(): return jsonify({"ok":False,"error":"Unauthorized"}), 403 try: status = check_keys_status() return jsonify({"ok":True,"keys":status}) except Exception as e: return jsonify({"ok":False,"error":str(e)}), 500 @app.route("/", methods=["GET"]) def index(): # HF Space открывает "/" по умолчанию и показывал 404 — сюда заходят люди, а не только пингер. return jsonify({"status": "ok", "service": "Elyon AI backend", "docs": "https://elyon-ai-web.vercel.app/app.html"}) @app.route("/health", methods=["GET"]) def health(): return jsonify({"status": "ok"})