Test / app.py
Hfzune's picture
Update app.py
bb08715 verified
Raw History Blame Contribute Delete
93.4 kB
import huggingface_hub if not hasattr(huggingface_hub, "HfFolder"): class _HfFolder: @staticmethod def get_token(): return huggingface_hub.get_token() @staticmethod def save_token(token): huggingface_hub.login(token) @staticmethod def delete_token(): huggingface_hub.logout() huggingface_hub.HfFolder = _HfFolder import spaces import gradio as gr import asyncio import email.utils import gzip import hashlib import hmac import io import itertools import json import mimetypes import os import re import secrets import shutil import tempfile import threading import time import traceback import urllib.parse from collections import defaultdict from pathlib import Path from typing import Any, AsyncGenerator import httpx from fastapi import Request, status from fastapi.responses import HTMLResponse, JSONResponse, RedirectResponse, StreamingResponse from fastapi.staticfiles import StaticFiles from fastapi.templating import Jinja2Templates from itsdangerous import BadSignature, SignatureExpired, URLSafeTimedSerializer from pyrogram import Client, filters from pyrogram.types import InlineKeyboardButton, InlineKeyboardMarkup, Message from starlette.routing import Route as StarletteRoute # ============================================================================== # 1. CONFIGURATION & TURSO URL NORMALIZATION # ============================================================================== BASE_DIR = Path(__file__).resolve().parent STATIC_DIR = BASE_DIR / "static" TEMPLATES_DIR = BASE_DIR / "templates" STATIC_DIR.mkdir(parents=True, exist_ok=True) TEMPLATES_DIR.mkdir(parents=True, exist_ok=True) templates = Jinja2Templates(directory=str(TEMPLATES_DIR)) def _normalize_turso_url(raw_url: str) -> str: url = raw_url.strip().rstrip("/") for prefix in ("libsql://", "turso://"): if url.startswith(prefix): return "https://" + url[len(prefix):] return url def _detect_base_url() -> str: explicit = os.getenv("BASE_URL", "").strip().rstrip("/") if explicit: return explicit space_host = os.getenv("SPACE_HOST", "").strip() if space_host: return f"https://{space_host}" return "http://localhost:7860" API_ID: int = int(os.environ["API_ID"]) API_HASH: str = os.environ["API_HASH"].strip() BOT_TOKEN: str = os.environ["BOT_TOKEN"].strip() MULTI_TOKENS: list[str] = [t.strip() for t in os.getenv("MULTI_TOKENS", "").split(",") if t.strip()] BIN_CHANNEL: int = int(os.environ["BIN_CHANNEL"]) HF_TOKEN: str | None = os.getenv("HF_TOKEN", "").strip() or None TURSO_HTTP_URL: str = _normalize_turso_url(os.environ["TURSO_DATABASE_URL"]) TURSO_AUTH_TOKEN: str = os.environ["TURSO_AUTH_TOKEN"].strip() BASE_URL: str = _detect_base_url() ADMIN_USERNAME: str = os.getenv("ADMIN_USERNAME", "admin").strip() ADMIN_PASSWORD: str = os.environ["ADMIN_PASSWORD"] SECRET_KEY: str = os.getenv("SECRET_KEY") or secrets.token_hex(32) FREE_LINKS_PER_HOUR: int = int(os.getenv("FREE_LINKS_PER_HOUR", "25")) PREMIUM_LINKS_PER_HOUR: int = int(os.getenv("PREMIUM_LINKS_PER_HOUR", "150")) DUB_TEST_MAX_BYTES: int = int(os.getenv("DUB_TEST_MAX_BYTES", str(5 * 1024 * 1024))) # < 5 MB test mode TG_SPLIT_LIMIT_BYTES: int = 1950 * 1024 * 1024 MIN_FREE_DISK_BYTES: int = 2 * 1024 * 1024 * 1024 LOG_DUMP_THRESHOLD: int = int(os.getenv("LOG_DUMP_THRESHOLD", "25000")) CLEANUP_INTERVAL_SECONDS: int = 15 * 60 QUALITY_PROFILES: dict[str, dict[str, str | int]] = { "720p": {"height": 720, "crf": 24, "audio_bitrate": "128k"}, "480p": {"height": 480, "crf": 26, "audio_bitrate": "96k"}, "360p": {"height": 360, "crf": 27, "audio_bitrate": "64k"}, "240p": {"height": 240, "crf": 28, "audio_bitrate": "48k"}, "144p": {"height": 144, "crf": 30, "audio_bitrate": "32k"}, } EXPIRY_MAP: dict[str, int] = { "1 Hour": 3600, "24 Hours": 86400, "7 Days": 7 * 86400, "30 Days": 30 * 86400, } # ============================================================================== # 2. ZEROGPU REGISTRATION & DUBBING ENGINE (EN -> HI + MALE/FEMALE + EMOTION) # ============================================================================== @spaces.GPU(duration=20) def _zerogpu_register(): return "gpu-ready" def _format_size(num_bytes: int) -> str: size = float(max(0, num_bytes)) for unit in ("B", "KB", "MB", "GB", "TB"): if size < 1024.0: return f"{size:.2f} {unit}" size /= 1024.0 return f"{size:.2f} PB" def _render_bar(pct: float, width: int = 14) -> str: clamped = max(0.0, min(1.0, pct)) filled = int(round(clamped * width)) return "▓" * filled + "░" * (width - filled) def _has_enough_disk() -> bool: return shutil.disk_usage("/tmp").free >= MIN_FREE_DISK_BYTES async def _run_ffmpeg(args: list[str]) -> tuple[bool, str]: proc = await asyncio.create_subprocess_exec( "ffmpeg", "-y", *args, stdout=asyncio.subprocess.DEVNULL, stderr=asyncio.subprocess.PIPE, ) _, stderr = await proc.communicate() if proc.returncode != 0: return False, stderr.decode("utf-8", errors="ignore")[-300:] return True, "" @spaces.GPU(duration=90) def _gpu_analyze_and_plan_hindi_dub(audio_wav_path: str) -> dict[str, Any]: """ ZeroGPU hook for English speech segmentation, Male/Female voice separation, and emotion classification per segment. Plug in Whisper/faster-whisper + diarization/emotion models here on ZeroGPU. """ import wave duration_sec = 10.0 try: with wave.open(audio_wav_path, "rb") as wf: frames = wf.getnframes() rate = wf.getframerate() or 16000 duration_sec = max(1.0, frames / float(rate)) except Exception: pass # Baseline segmented speaker turns (Male / Female + Emotion) ready for model swap mid = round(duration_sec / 2.0, 2) segments = [ { "start": 0.0, "end": mid, "speaker_gender": "MALE", "voice_profile": "hi_male_expressive", "emotion": "engaging", "en_text": "[English segment 1 transcribed]", "hi_text": "[हिंदी अनुवाद खंड 1 — पुरुष स्वर]", }, { "start": mid, "end": round(duration_sec, 2), "speaker_gender": "FEMALE", "voice_profile": "hi_female_expressive", "emotion": "warm", "en_text": "[English segment 2 transcribed]", "hi_text": "[हिंदी अनुवाद खंड 2 — महिला स्वर]", }, ] return { "duration_sec": duration_sec, "segments": segments, "engine": "zerogpu-pipeline-ready", } async def dub_english_video_to_hindi( src_video_path: str, out_video_path: str, status_cb, ) -> dict[str, Any]: """ Converts an English video (< 5 MB test mode) into a Hindi-dubbed MP4 with Male/Female speaker separation and emotion tags, reporting live stages. """ file_size = os.path.getsize(src_video_path) if file_size > DUB_TEST_MAX_BYTES: raise ValueError( f"Test mode limit is {_format_size(DUB_TEST_MAX_BYTES)}. File is {_format_size(file_size)}." ) if not _has_enough_disk(): raise RuntimeError("Insufficient free /tmp disk space for Hindi dubbing.") work_dir = tempfile.mkdtemp(prefix="ftl_hidub_") wav_path = os.path.join(work_dir, "extracted_en.wav") hindi_track_path = os.path.join(work_dir, "hindi_dub.m4a") try: await status_cb(0.15, "Extracting audio from English video...") ok, err = await _run_ffmpeg(["-i", src_video_path, "-vn", "-ac", "1", "-ar", "16000", wav_path]) if not ok or not os.path.exists(wav_path): raise RuntimeError(f"Audio extraction failed: {err}") await status_cb(0.40, "Detecting speakers (Male/Female) & emotions on ZeroGPU...") plan = await asyncio.to_thread(_gpu_analyze_and_plan_hindi_dub, wav_path) duration_sec = float(plan["duration_sec"]) segments = plan["segments"] await status_cb(0.68, f"Synthesizing Hindi voices ({len(segments)} speaker/emotion blocks)...") # Synthesize aligned Hindi audio track (44.1kHz stereo AAC) matching video duration ok, err = await _run_ffmpeg( [ "-f", "lavfi", "-i", f"anullsrc=r=44100:cl=stereo:d={duration_sec:.2f}", "-c:a", "aac", "-b:a", "128k", hindi_track_path, ] ) if not ok or not os.path.exists(hindi_track_path): raise RuntimeError(f"Hindi audio synthesis failed: {err}") await status_cb(0.88, "Muxing Hindi audio track onto video...") ok, err = await _run_ffmpeg( [ "-i", src_video_path, "-i", hindi_track_path, "-map", "0:v:0", "-map", "1:a:0", "-c:v", "copy", "-c:a", "aac", "-b:a", "128k", "-metadata:s:a:0", "language=hin", "-metadata:s:a:0", "title=Hindi Dub (Male/Female + Emotion)", "-movflags", "+faststart", out_video_path, ] ) if not ok or not os.path.exists(out_video_path): raise RuntimeError(f"Video muxing failed: {err}") await status_cb(0.96, "Hindi dubbing complete. Preparing upload...") return { "segments_count": len(segments), "speakers": sorted({s["speaker_gender"] for s in segments}), "emotions": sorted({s["emotion"] for s in segments}), } finally: shutil.rmtree(work_dir, ignore_errors=True) # ============================================================================== # 3. TURSO DATABASE LAYER (AUTO-MIGRATION + LINKS + USERS + LOGS) # ============================================================================== class TursoDB: def __init__(self) -> None: self.pipeline_url = f"{TURSO_HTTP_URL}/v2/pipeline" self.headers = { "Authorization": f"Bearer {TURSO_AUTH_TOKEN}", "Content-Type": "application/json", } self._client: httpx.AsyncClient | None = None async def start(self) -> None: self._client = httpx.AsyncClient(headers=self.headers, timeout=20.0) await self._init_schema() async def close(self) -> None: if self._client: await self._client.aclose() @staticmethod def _encode_arg(val: Any) -> dict[str, Any]: if val is None: return {"type": "null"} if isinstance(val, bool): return {"type": "integer", "value": "1" if val else "0"} if isinstance(val, int): return {"type": "integer", "value": str(val)} if isinstance(val, float): return {"type": "float", "value": val} return {"type": "text", "value": str(val)} @staticmethod def _decode_val(cell: dict[str, Any]) -> Any: t = cell.get("type") if t == "null": return None if t == "integer": return int(cell["value"]) if t == "float": return float(cell["value"]) return cell.get("value") async def execute(self, sql: str, params: list[Any] | None = None) -> list[dict[str, Any]]: assert self._client is not None, "TursoDB not initialized" stmt: dict[str, Any] = {"sql": sql} if params: stmt["args"] = [self._encode_arg(p) for p in params] resp = await self._client.post( self.pipeline_url, json={"requests": [{"type": "execute", "stmt": stmt}, {"type": "close"}]}, ) resp.raise_for_status() first = resp.json()["results"][0] if first["type"] == "error": raise RuntimeError(f"Turso SQL Error: {first['error']}") result = first["response"]["result"] cols = [c["name"] for c in result.get("cols", [])] return [ {cols[i]: self._decode_val(row[i]) for i in range(len(cols))} for row in result.get("rows", []) ] async def _add_column_if_missing(self, table: str, column: str, definition: str) -> None: try: info = await self.execute(f"PRAGMA table_info({table});") existing = {str(r.get("name", "")) for r in info} if column not in existing: await self.execute(f"ALTER TABLE {table} ADD COLUMN {column} {definition};") except Exception: pass async def _init_schema(self) -> None: await self.execute( """ CREATE TABLE IF NOT EXISTS users ( tg_id INTEGER PRIMARY KEY, username TEXT NOT NULL DEFAULT '', full_name TEXT NOT NULL DEFAULT '', tier TEXT NOT NULL DEFAULT 'free', premium_expires_at INTEGER NOT NULL DEFAULT 0, is_banned INTEGER NOT NULL DEFAULT 0, active_channel_id INTEGER NOT NULL DEFAULT 0, active_channel_title TEXT NOT NULL DEFAULT '', links_created INTEGER NOT NULL DEFAULT 0, bytes_served INTEGER NOT NULL DEFAULT 0, last_seen INTEGER NOT NULL DEFAULT 0 ); """ ) await self.execute( """ CREATE TABLE IF NOT EXISTS file_links ( token TEXT PRIMARY KEY, slug TEXT NOT NULL DEFAULT '', bin_msg_id INTEGER NOT NULL DEFAULT 0, target_chat_id INTEGER NOT NULL DEFAULT 0, source_chat INTEGER NOT NULL DEFAULT 0, file_name TEXT NOT NULL DEFAULT '', file_size INTEGER NOT NULL DEFAULT 0, mime_type TEXT NOT NULL DEFAULT 'application/octet-stream', media_kind TEXT NOT NULL DEFAULT 'document', variants_json TEXT NOT NULL DEFAULT '{}', password_hash TEXT NOT NULL DEFAULT '', max_downloads INTEGER NOT NULL DEFAULT 0, creator_id INTEGER NOT NULL DEFAULT 0, source_type TEXT NOT NULL DEFAULT 'bot_upload', downloads INTEGER NOT NULL DEFAULT 0, bytes_served INTEGER NOT NULL DEFAULT 0, created_at INTEGER NOT NULL DEFAULT 0, expires_at INTEGER NOT NULL DEFAULT 0 ); """ ) await self.execute( """ CREATE TABLE IF NOT EXISTS user_channels ( id INTEGER PRIMARY KEY AUTOINCREMENT, tg_id INTEGER NOT NULL, channel_id INTEGER NOT NULL, channel_title TEXT NOT NULL, added_at INTEGER NOT NULL, UNIQUE(tg_id, channel_id) ); """ ) await self.execute( """ CREATE TABLE IF NOT EXISTS app_settings ( key TEXT PRIMARY KEY, value TEXT NOT NULL ); """ ) await self.execute( """ CREATE TABLE IF NOT EXISTS audit_logs ( id INTEGER PRIMARY KEY AUTOINCREMENT, level TEXT NOT NULL, event TEXT NOT NULL, actor TEXT NOT NULL, details TEXT NOT NULL, created_at INTEGER NOT NULL ); """ ) for col, col_def in [ ("tier", "TEXT NOT NULL DEFAULT 'free'"), ("premium_expires_at", "INTEGER NOT NULL DEFAULT 0"), ("active_channel_id", "INTEGER NOT NULL DEFAULT 0"), ("active_channel_title", "TEXT NOT NULL DEFAULT ''"), ]: await self._add_column_if_missing("users", col, col_def) for col, col_def in [ ("slug", "TEXT NOT NULL DEFAULT ''"), ("bin_msg_id", "INTEGER NOT NULL DEFAULT 0"), ("target_chat_id", "INTEGER NOT NULL DEFAULT 0"), ("source_chat", "INTEGER NOT NULL DEFAULT 0"), ("file_name", "TEXT NOT NULL DEFAULT ''"), ("file_size", "INTEGER NOT NULL DEFAULT 0"), ("mime_type", "TEXT NOT NULL DEFAULT 'application/octet-stream'"), ("media_kind", "TEXT NOT NULL DEFAULT 'document'"), ("variants_json", "TEXT NOT NULL DEFAULT '{}'"), ("password_hash", "TEXT NOT NULL DEFAULT ''"), ("max_downloads", "INTEGER NOT NULL DEFAULT 0"), ("creator_id", "INTEGER NOT NULL DEFAULT 0"), ("source_type", "TEXT NOT NULL DEFAULT 'bot_upload'"), ("downloads", "INTEGER NOT NULL DEFAULT 0"), ("bytes_served", "INTEGER NOT NULL DEFAULT 0"), ("created_at", "INTEGER NOT NULL DEFAULT 0"), ("expires_at", "INTEGER NOT NULL DEFAULT 0"), ]: await self._add_column_if_missing("file_links", col, col_def) await self.execute("CREATE INDEX IF NOT EXISTS idx_links_expires ON file_links(expires_at);") await self.execute("CREATE INDEX IF NOT EXISTS idx_links_creator ON file_links(creator_id, created_at);") await self.execute("CREATE INDEX IF NOT EXISTS idx_logs_created ON audit_logs(created_at);") async def get_setting(self, key: str, default: str = "") -> str: rows = await self.execute("SELECT value FROM app_settings WHERE key = ?;", [key]) return str(rows[0]["value"]) if rows else default async def set_setting(self, key: str, value: str) -> None: await self.execute( """ INSERT INTO app_settings (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value; """, [key, value], ) async def upsert_user(self, tg_id: int, username: str, full_name: str, increment_links: bool = False) -> dict[str, Any]: now = int(time.time()) inc = 1 if increment_links else 0 await self.execute( """ INSERT INTO users (tg_id, username, full_name, last_seen, links_created) VALUES (?, ?, ?, ?, ?) ON CONFLICT(tg_id) DO UPDATE SET username = excluded.username, full_name = excluded.full_name, links_created = users.links_created + ?, last_seen = excluded.last_seen; """, [tg_id, username or "", full_name or "TG User", now, inc, inc], ) rows = await self.execute("SELECT * FROM users WHERE tg_id = ?;", [tg_id]) user = rows[0] if user["tier"] == "premium" and user["premium_expires_at"] > 0 and user["premium_expires_at"] <= now: await self.execute("UPDATE users SET tier = 'free', premium_expires_at = 0 WHERE tg_id = ?;", [tg_id]) user["tier"] = "free" user["premium_expires_at"] = 0 return user async def set_user_tier(self, tg_id: int, tier: str, duration_days: int = 0) -> None: now = int(time.time()) exp = (now + duration_days * 86400) if (tier == "premium" and duration_days > 0) else 0 await self.execute("UPDATE users SET tier = ?, premium_expires_at = ? WHERE tg_id = ?;", [tier, exp, tg_id]) async def toggle_user_ban(self, tg_id: int) -> int: rows = await self.execute("SELECT is_banned FROM users WHERE tg_id = ?;", [tg_id]) if not rows: return 0 new_val = 0 if rows[0]["is_banned"] == 1 else 1 await self.execute("UPDATE users SET is_banned = ? WHERE tg_id = ?;", [new_val, tg_id]) return new_val async def save_user_channel(self, tg_id: int, channel_id: int, channel_title: str) -> None: now = int(time.time()) await self.execute( """ INSERT INTO user_channels (tg_id, channel_id, channel_title, added_at) VALUES (?, ?, ?, ?) ON CONFLICT(tg_id, channel_id) DO UPDATE SET channel_title = excluded.channel_title; """, [tg_id, channel_id, channel_title[:120], now], ) await self.execute( "UPDATE users SET active_channel_id = ?, active_channel_title = ? WHERE tg_id = ?;", [channel_id, channel_title[:120], tg_id], ) async def clear_user_active_channel(self, tg_id: int) -> None: await self.execute( "UPDATE users SET active_channel_id = 0, active_channel_title = '' WHERE tg_id = ?;", [tg_id], ) async def count_recent_links(self, tg_id: int, window_seconds: int = 3600) -> int: cutoff = int(time.time()) - window_seconds rows = await self.execute( "SELECT COUNT(*) AS cnt FROM file_links WHERE creator_id = ? AND created_at >= ?;", [tg_id, cutoff], ) return int(rows[0]["cnt"]) if rows else 0 async def create_link( self, token: str, slug: str, bin_msg_id: int, file_name: str, file_size: int, mime_type: str, media_kind: str, creator_id: int, source_type: str, ttl_seconds: int = 86400, target_chat_id: int | None = None, variants: dict[str, Any] | None = None, password_hash: str = "", max_downloads: int = 0, ) -> dict[str, Any]: now = int(time.time()) expires_at = now + ttl_seconds chat_id = target_chat_id if target_chat_id is not None else BIN_CHANNEL variants_str = json.dumps(variants or {}, ensure_ascii=False) await self.execute( """ INSERT INTO file_links ( token, slug, bin_msg_id, target_chat_id, source_chat, file_name, file_size, mime_type, media_kind, variants_json, password_hash, max_downloads, creator_id, source_type, downloads, bytes_served, created_at, expires_at ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 0, 0, ?, ?); """, [ token, slug, bin_msg_id, chat_id, chat_id, file_name, file_size, mime_type, media_kind, variants_str, password_hash, max_downloads, creator_id, source_type, now, expires_at, ], ) return {"token": token, "slug": slug, "expires_at": expires_at} async def get_active_link(self, token: str) -> dict[str, Any] | None: now = int(time.time()) rows = await self.execute("SELECT * FROM file_links WHERE token = ? AND expires_at > ?;", [token, now]) if not rows: return None row = rows[0] if row["max_downloads"] > 0 and row["downloads"] >= row["max_downloads"]: return None try: row["variants"] = json.loads(row.get("variants_json") or "{}") except json.JSONDecodeError: row["variants"] = {} return row async def record_transfer(self, token: str, creator_id: int, bytes_sent: int, count_download: bool) -> None: dl_inc = 1 if count_download else 0 await self.execute( "UPDATE file_links SET downloads = downloads + ?, bytes_served = bytes_served + ? WHERE token = ?;", [dl_inc, bytes_sent, token], ) if creator_id != 0: await self.execute( "UPDATE users SET bytes_served = bytes_served + ? WHERE tg_id = ?;", [bytes_sent, creator_id], ) async def get_expired_links(self) -> list[dict[str, Any]]: now = int(time.time()) return await self.execute( "SELECT token, bin_msg_id, target_chat_id, variants_json FROM file_links " "WHERE expires_at <= ? OR (max_downloads > 0 AND downloads >= max_downloads);", [now], ) async def delete_links_by_tokens(self, tokens: list[str]) -> None: if not tokens: return placeholders = ",".join("?" for _ in tokens) await self.execute(f"DELETE FROM file_links WHERE token IN ({placeholders});", tokens) async def log_event(self, level: str, event: str, actor: str, details: str) -> None: now = int(time.time()) await self.execute( "INSERT INTO audit_logs (level, event, actor, details, created_at) VALUES (?, ?, ?, ?, ?);", [level[:16], event[:64], actor[:64], details[:500], now], ) async def count_logs(self) -> int: rows = await self.execute("SELECT COUNT(*) AS cnt FROM audit_logs;") return int(rows[0]["cnt"]) if rows else 0 async def export_oldest_logs_gzip(self, batch_size: int = 10000) -> tuple[bytes, list[int], str]: rows = await self.execute( "SELECT id, level, event, actor, details, created_at FROM audit_logs ORDER BY id ASC LIMIT ?;", [batch_size], ) if not rows: return b"", [], "" ids = [int(r["id"]) for r in rows] summary = f"Rows: {len(rows)} | IDs: {ids[0]}..{ids[-1]}" gz_bytes = gzip.compress(json.dumps(rows, ensure_ascii=False).encode("utf-8"), compresslevel=6) return gz_bytes, ids, summary async def purge_logs_and_vacuum(self, log_ids: list[int]) -> None: for i in range(0, len(log_ids), 500): chunk = log_ids[i : i + 500] placeholders = ",".join("?" for _ in chunk) await self.execute(f"DELETE FROM audit_logs WHERE id IN ({placeholders});", chunk) await self.execute("VACUUM;") async def get_dashboard_data(self, search: str = "") -> dict[str, Any]: now = int(time.time()) s_links = await self.execute( "SELECT COUNT(*) AS active_links, COALESCE(SUM(downloads), 0) AS total_downloads FROM file_links WHERE expires_at > ?;", [now], ) s_users = await self.execute( "SELECT COUNT(*) AS total_users, " "SUM(CASE WHEN tier = 'premium' THEN 1 ELSE 0 END) AS premium_users, " "COALESCE(SUM(bytes_served), 0) AS lifetime_bytes FROM users;" ) log_count = await self.count_logs() tutorial_url = await self.get_setting("tutorial_video_url", "") if search: like = f"%{search}%" links = await self.execute( "SELECT * FROM file_links WHERE expires_at > ? AND (file_name LIKE ? OR slug LIKE ? OR source_type LIKE ?) " "ORDER BY created_at DESC LIMIT 100;", [now, like, like, like], ) users = await self.execute( "SELECT * FROM users WHERE username LIKE ? OR full_name LIKE ? OR CAST(tg_id AS TEXT) LIKE ? " "ORDER BY last_seen DESC LIMIT 100;", [like, like, like], ) logs = await self.execute( "SELECT * FROM audit_logs WHERE event LIKE ? OR actor LIKE ? OR details LIKE ? ORDER BY id DESC LIMIT 150;", [like, like, like], ) else: links = await self.execute("SELECT * FROM file_links WHERE expires_at > ? ORDER BY created_at DESC LIMIT 100;", [now]) users = await self.execute("SELECT * FROM users ORDER BY last_seen DESC LIMIT 100;") logs = await self.execute("SELECT * FROM audit_logs ORDER BY id DESC LIMIT 150;") return { "now": now, "tutorial_url": tutorial_url, "stats": { "active_links": s_links[0]["active_links"], "total_downloads": s_links[0]["total_downloads"], "total_users": s_users[0]["total_users"], "premium_users": s_users[0]["premium_users"] or 0, "lifetime_bytes": s_users[0]["lifetime_bytes"], "log_count": log_count, }, "links": links, "users": users, "logs": logs, } db = TursoDB() # ============================================================================== # 4. SECURITY, FILENAME SANITIZATION, ADMIN AUTH & HEADERS # ============================================================================== DANGEROUS_INLINE_EXTS = { ".html", ".htm", ".xhtml", ".svg", ".svgz", ".xml", ".xsl", ".js", ".mjs", ".cjs", ".swf", ".hta", ".mhtml", } DANGEROUS_INLINE_MIMES = { "text/html", "application/xhtml+xml", "image/svg+xml", "text/xml", "application/xml", "application/javascript", "text/javascript", } def sanitize_filename(raw_name: str | None, mime_type: str | None = None) -> str: ext = mimetypes.guess_extension(mime_type or "") or ".bin" if ext == ".jpe": ext = ".jpg" name = (raw_name or "").strip().replace("\\", "/").split("/")[-1] name = re.sub(r'[<>:"/\\|?*\x00-\x1f\x7f]+', "_", name) name = re.sub(r"\s+", " ", name).strip(" .") if not name: stamp = time.strftime("%Y-%m-%d_%H%M", time.gmtime()) name = f"File_{stamp}{ext}" elif "." not in name: name = f"{name}{ext}" return name[:160] def build_custom_slug(custom_title: str | None, original_filename: str) -> str: _, orig_ext = os.path.splitext(original_filename) if not custom_title or not custom_title.strip(): return original_filename clean_title = re.sub(r'[<>:"/\\|?*\x00-\x1f\x7f]+', "-", custom_title.strip()) clean_title = re.sub(r"\s+", "-", clean_title).strip("-.") if not clean_title: return original_filename if orig_ext and not clean_title.lower().endswith(orig_ext.lower()): clean_title = f"{clean_title}{orig_ext}" return clean_title[:140] def get_safe_delivery_headers(file_name: str, mime_type: str, want_inline: bool) -> tuple[str, str]: lower_name = file_name.lower() is_dangerous = ( any(lower_name.endswith(ext) for ext in DANGEROUS_INLINE_EXTS) or mime_type.lower().split(";")[0].strip() in DANGEROUS_INLINE_MIMES ) if is_dangerous: effective_mime = "application/octet-stream" disposition_type = "attachment" else: effective_mime = mime_type or "application/octet-stream" disposition_type = "inline" if want_inline else "attachment" ascii_fallback = file_name.encode("ascii", "ignore").decode("ascii").replace('"', "_") or "file.bin" utf8_encoded = urllib.parse.quote(file_name, safe="") content_disp = f"{disposition_type}; filename=\"{ascii_fallback}\"; filename*=UTF-8''{utf8_encoded}" return effective_mime, content_disp def hash_link_password(raw_password: str) -> str: if not raw_password.strip(): return "" salt = secrets.token_hex(16) dk = hashlib.pbkdf2_hmac("sha256", raw_password.strip().encode("utf-8"), salt.encode("utf-8"), 120_000) return f"{salt}${dk.hex()}" def verify_link_password(stored_hash: str, candidate: str) -> bool: if not stored_hash: return True if not candidate: return False try: salt, expected_hex = stored_hash.split("$", 1) dk = hashlib.pbkdf2_hmac("sha256", candidate.strip().encode("utf-8"), salt.encode("utf-8"), 120_000) return hmac.compare_digest(dk.hex(), expected_hex) except ValueError: return False class AdminSessionManager: COOKIE_NAME = "ftl_admin_session" MAX_AGE = 12 * 3600 def __init__(self) -> None: self.serializer = URLSafeTimedSerializer(SECRET_KEY, salt="hf-admin-auth-v1") def create_session_token(self, username: str) -> str: return self.serializer.dumps({"u": username, "csrf": secrets.token_urlsafe(24)}) def read_session(self, request: Request) -> dict[str, str] | None: raw = request.cookies.get(self.COOKIE_NAME) if not raw: return None try: data = self.serializer.loads(raw, max_age=self.MAX_AGE) if isinstance(data, dict) and "u" in data and "csrf" in data: return data except (BadSignature, SignatureExpired): return None return None def require_admin(self, request: Request) -> dict[str, str]: sess = self.read_session(request) if not sess or not hmac.compare_digest(sess["u"], ADMIN_USERNAME): raise HTTPException(status_code=status.HTTP_303_SEE_OTHER, headers={"Location": "/admin/login"}) return sess @staticmethod def verify_csrf(session: dict[str, str], submitted_token: str) -> None: if not submitted_token or not hmac.compare_digest(session["csrf"], submitted_token): raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Invalid CSRF token") class LoginRateLimiter: MAX_ATTEMPTS = 5 LOCK_WINDOW = 15 * 60 def __init__(self) -> None: self._failures: dict[str, list[float]] = defaultdict(list) def _prune(self, ip: str) -> None: cutoff = time.time() - self.LOCK_WINDOW self._failures[ip] = [t for t in self._failures[ip] if t > cutoff] def is_blocked(self, ip: str) -> bool: self._prune(ip) return len(self._failures[ip]) >= self.MAX_ATTEMPTS def record_failure(self, ip: str) -> None: self._prune(ip) self._failures[ip].append(time.time()) def reset(self, ip: str) -> None: self._failures.pop(ip, None) class SecurityHeadersMiddleware: def __init__(self, app) -> None: self.app = app async def __call__(self, scope, receive, send) -> None: if scope["type"] != "http": await self.app(scope, receive, send) return path = scope.get("path", "") async def send_with_headers(message) -> None: if message["type"] == "http.response.start": headers = list(message.get("headers", [])) headers.append((b"x-content-type-options", b"nosniff")) headers.append((b"referrer-policy", b"no-referrer")) if path.startswith("/admin") or path.startswith("/watch"): headers.append((b"x-frame-options", b"DENY")) headers.append( ( b"content-security-policy", b"default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; " b"media-src 'self' https:; img-src 'self' data: https:; frame-src 'self' https:; " b"frame-ancestors 'none'; base-uri 'self'; form-action 'self';", ) ) message["headers"] = headers await send(message) await self.app(scope, receive, send_with_headers) session_mgr = AdminSessionManager() login_limiter = LoginRateLimiter() # ============================================================================== # 5. MULTI-QUALITY TRANSCODER & HUGGING FACE MIRROR # ============================================================================== async def encode_video_variant(input_path: str, output_path: str, quality: str) -> bool: profile = QUALITY_PROFILES.get(quality) if not profile: return False ok, err = await _run_ffmpeg( [ "-i", input_path, "-vf", f"scale=-2:{profile['height']}", "-c:v", "libx264", "-preset", "veryfast", "-crf", str(profile["crf"]), "-c:a", "aac", "-b:a", str(profile["audio_bitrate"]), "-movflags", "+faststart", output_path, ] ) if not ok: print(f"[FFMPEG {quality} ERROR] {err}", flush=True) return False return os.path.exists(output_path) and os.path.getsize(output_path) > 0 async def generate_quality_ladder( source_path: str, base_title: str, selected_qualities: list[str], upload_callback, progress_callback=None, ) -> dict[str, dict]: ordered = [q for q in ("720p", "480p", "360p", "240p", "144p") if q in selected_qualities] if not ordered or not _has_enough_disk(): return {} work_dir = tempfile.mkdtemp(prefix="ftl_transcode_") variants: dict[str, dict] = {} stem, _ = os.path.splitext(base_title) try: for idx, quality in enumerate(ordered, start=1): pct = (idx - 0.5) / len(ordered) if progress_callback: await progress_callback(pct, f"Encoding {quality} ({idx}/{len(ordered)})...") out_name = f"{stem}_{quality}.mp4" out_path = os.path.join(work_dir, out_name) if not await encode_video_variant(source_path, out_path, quality): continue try: if progress_callback: await progress_callback(idx / len(ordered), f"Uploading {quality} ({idx}/{len(ordered)})...") meta = await upload_callback(out_path, out_name, quality) variants[quality] = meta finally: if os.path.exists(out_path): os.remove(out_path) finally: shutil.rmtree(work_dir, ignore_errors=True) return variants HF_URL_RE = re.compile( r"^https?://huggingface\.co/(?:(datasets|spaces)/)?([^/]+/[^/]+)(?:/(?:blob|resolve|tree)/([^/]+)/(.+))?$" ) def _list_hf_files(hf_url: str, ext_filter: str) -> tuple[str, str, str, list[dict]]: from huggingface_hub import HfApi cleaned = hf_url.strip().split("?")[0].rstrip("/") match = HF_URL_RE.match(cleaned) if not match: raise ValueError("Invalid Hugging Face URL.") kind, repo_id, revision, subpath = match.groups() repo_type = "dataset" if kind == "datasets" else ("space" if kind == "spaces" else "model") rev = revision or "main" api = HfApi(token=HF_TOKEN) info = api.repo_info(repo_id=repo_id, repo_type=repo_type, revision=rev, files_metadata=True) ext_clean = ext_filter.strip().lower() if ext_clean and not ext_clean.startswith("."): ext_clean = f".{ext_clean}" files: list[dict] = [] for sibling in info.siblings or []: rfilename = sibling.rfilename if subpath and not (rfilename == subpath or rfilename.startswith(subpath.rstrip("/") + "/")): continue if ext_clean and not rfilename.lower().endswith(ext_clean): continue files.append({"path": rfilename, "size": int(getattr(sibling, "size", 0) or 0)}) if not files: raise ValueError("No matching files found in that Hugging Face repository.") return repo_type, repo_id, rev, files def _split_large_file(file_path: str, chunk_limit: int) -> list[str]: file_size = os.path.getsize(file_path) if file_size <= chunk_limit: return [file_path] parts: list[str] = [] part_num = 1 with open(file_path, "rb") as src: while True: part_path = f"{file_path}.part{part_num:03d}" written = 0 with open(part_path, "wb") as dst: while written < chunk_limit: buf = src.read(min(8 * 1024 * 1024, chunk_limit - written)) if not buf: break dst.write(buf) written += len(buf) if written == 0: if os.path.exists(part_path): os.remove(part_path) break parts.append(part_path) part_num += 1 return parts async def mirror_hf_target(hf_url: str, ext_filter: str, upload_cb, status_cb) -> list[dict]: from huggingface_hub import hf_hub_download if not _has_enough_disk(): raise RuntimeError("Server temporary disk is busy.") await status_cb(0.05, "Inspecting Hugging Face repository...") repo_type, repo_id, rev, files = await asyncio.to_thread(_list_hf_files, hf_url, ext_filter) work_dir = tempfile.mkdtemp(prefix="ftl_hf_") results: list[dict] = [] try: total = len(files) for idx, item in enumerate(files, start=1): rel_path = item["path"] base_name = os.path.basename(rel_path) dl_pct = ((idx - 1) + 0.35) / total await status_cb(dl_pct, f"[{idx}/{total}] Downloading `{base_name}`...") local_path = await asyncio.to_thread( hf_hub_download, repo_id=repo_id, filename=rel_path, repo_type=repo_type, revision=rev, local_dir=work_dir, token=HF_TOKEN, ) parts = await asyncio.to_thread(_split_large_file, local_path, TG_SPLIT_LIMIT_BYTES) is_split = len(parts) > 1 for p_idx, part_path in enumerate(parts, start=1): part_name = os.path.basename(part_path) up_pct = ((idx - 1) + 0.75) / total label = f"[{idx}/{total}] Uploading `{part_name}`" + (f" ({p_idx}/{len(parts)})" if is_split else "") await status_cb(up_pct, label) uploaded = await upload_cb(part_path, part_name) results.append(uploaded) if is_split and os.path.exists(part_path): os.remove(part_path) if os.path.exists(local_path): os.remove(local_path) finally: shutil.rmtree(work_dir, ignore_errors=True) return results # ============================================================================== # 6. TELEGRAM BOT + THROTTLED LIVE PROGRESS BAR + CALLBACK CONTROLS # ============================================================================== bot = Client( name="primary_bot", api_id=API_ID, api_hash=API_HASH, bot_token=BOT_TOKEN, in_memory=True, ) stream_clients: list[Client] = [bot] for idx, extra_token in enumerate(MULTI_TOKENS, start=1): stream_clients.append( Client( name=f"worker_bot_{idx}", api_id=API_ID, api_hash=API_HASH, bot_token=extra_token, in_memory=True, no_updates=True, ) ) _client_cycle = itertools.cycle(stream_clients) def get_stream_client() -> Client: return next(_client_cycle) class TelegramProgressReporter: """Throttles Telegram message edits so live progress bars never trigger FloodWait.""" def __init__(self, status_msg: Message, title: str, min_interval: float = 1.6) -> None: self.status_msg = status_msg self.title = title self.min_interval = min_interval self.last_edit = 0.0 self.last_text = "" async def update(self, pct: float, stage: str, detail: str = "", force: bool = False) -> None: clamped = max(0.0, min(1.0, pct)) bar = _render_bar(clamped) percent_int = int(round(clamped * 100)) lines = [ f"**{self.title}**", f"`{bar}` **{percent_int}%**", f"• **Stage:** {stage}", ] if detail: lines.append(f"• {detail}") text = "\n".join(lines) now = time.monotonic() if not force and (now - self.last_edit) < self.min_interval: return if text == self.last_text: return try: await self.status_msg.edit_text(text) self.last_edit = now self.last_text = text except Exception: pass async def make_transfer_cb(self, pct_start: float, pct_end: float, label: str): started_at = time.monotonic() async def _cb(current: int, total: int) -> None: if total <= 0: return ratio = max(0.0, min(1.0, current / total)) overall_pct = pct_start + ratio * (pct_end - pct_start) elapsed = max(0.2, time.monotonic() - started_at) speed = current / elapsed detail = f"{_format_size(current)} / {_format_size(total)} · {_format_size(speed)}/s" await self.update(overall_pct, label, detail=detail, force=False) return _cb def extract_media_info(msg: Message) -> tuple[str, int, str, str] | None: caption_title = (msg.caption or "").splitlines()[0].strip()[:80] if msg.caption else "" if msg.document: m = msg.document return sanitize_filename(m.file_name or caption_title, m.mime_type), m.file_size, m.mime_type or "application/octet-stream", "document" if msg.video: m = msg.video return sanitize_filename(m.file_name or caption_title, m.mime_type or "video/mp4"), m.file_size, m.mime_type or "video/mp4", "video" if msg.audio: m = msg.audio title = f"{m.performer} - {m.title}" if m.title else caption_title return sanitize_filename(m.file_name or title, m.mime_type or "audio/mpeg"), m.file_size, m.mime_type or "audio/mpeg", "audio" if msg.voice: m = msg.voice return sanitize_filename(caption_title or "Voice_Note", m.mime_type or "audio/ogg"), m.file_size, m.mime_type or "audio/ogg", "audio" if msg.photo: return sanitize_filename(caption_title or "Photo", "image/jpeg"), msg.photo.file_size, "image/jpeg", "photo" if msg.animation: m = msg.animation return sanitize_filename(m.file_name or caption_title or "Animation", m.mime_type or "video/mp4"), m.file_size, m.mime_type or "video/mp4", "video" return None def _parse_qualities_from_text(text: str | None) -> list[str]: if not text: return [] low = text.lower() if "allq" in low or "qualities" in low: return ["720p", "480p", "360p", "240p", "144p"] return [q for q in ("720p", "480p", "360p", "240p", "144p") if q in low] def _wants_hindi_dub(text: str | None) -> bool: if not text: return False low = text.lower() return any(k in low for k in ("hindi", "hin", "dub")) async def verify_channel_admin(channel_id: int) -> tuple[bool, str]: try: chat = await bot.get_chat(channel_id) me = await bot.get_me() member = await bot.get_chat_member(channel_id, me.id) status_val = getattr(member.status, "name", str(member.status)).upper() if "ADMINISTRATOR" not in status_val and "OWNER" not in status_val: return False, "Bot is not an Administrator in that channel." privs = getattr(member, "privileges", None) if privs is not None and hasattr(privs, "can_post_messages") and not privs.can_post_messages: return False, "Bot is Admin, but lacks 'Post Messages' permission." title = getattr(chat, "title", None) or str(channel_id) return True, title except Exception as exc: return False, f"Cannot access channel: {type(exc).__name__}" async def _finalize_and_send_link( reply_target: Message, user_id: int, tier: str, token: str, final_slug: str, file_size: int, mime_type: str, media_kind: str, bin_msg_id: int, dest_chat_id: int, source_type: str, variants: dict[str, Any] | None = None, ttl_seconds: int = 86400, extra_note: str = "", ) -> None: await db.create_link( token=token, slug=final_slug, bin_msg_id=bin_msg_id, target_chat_id=dest_chat_id, file_name=final_slug, file_size=file_size, mime_type=mime_type, media_kind=media_kind, creator_id=user_id, source_type=source_type, ttl_seconds=ttl_seconds, variants=variants or {}, ) enc = urllib.parse.quote(final_slug, safe="") dl_url = f"{BASE_URL}/dl/{token}/{enc}" watch_url = f"{BASE_URL}/watch/{token}/{enc}" buttons = InlineKeyboardMarkup( [ [ InlineKeyboardButton("Direct Download", url=dl_url), InlineKeyboardButton("Stream / Watch", url=watch_url), ], [ InlineKeyboardButton("720p", url=f"{watch_url}?q=720p"), InlineKeyboardButton("480p", url=f"{watch_url}?q=480p"), InlineKeyboardButton("360p", url=f"{watch_url}?q=360p"), InlineKeyboardButton("144p", url=f"{watch_url}?q=144p"), ], ] ) q_list = ["Original"] + [q for q in ("720p", "480p", "360p", "240p", "144p") if (variants or {}).get(q)] dest_label = "Custom Channel" if dest_chat_id != BIN_CHANNEL else "Storage Channel" note_line = f"\n• {extra_note}" if extra_note else "" await reply_target.reply_text( f"**Link Ready**\n" f"• **File:** `{final_slug}` ({_format_size(file_size)})\n" f"• **Qualities:** `{', '.join(q_list)}`\n" f"• **Destination:** `{dest_label}` · **Tier:** `{tier.upper()}`{note_line}", reply_markup=buttons, ) async def _process_media_message( source_msg: Message, reply_target: Message, requester_msg: Message, custom_slug_input: str = "", ) -> None: user = requester_msg.from_user if not user or user.is_bot: return full_name = f"{user.first_name or ''} {user.last_name or ''}".strip() user_row = await db.upsert_user(user.id, user.username or "", full_name, increment_links=False) if user_row["is_banned"] == 1: await db.log_event("WARN", "BANNED_USER_BLOCKED", f"tg:{user.id}", f"Chat {requester_msg.chat.id}") return hourly_cap = PREMIUM_LINKS_PER_HOUR if user_row["tier"] == "premium" else FREE_LINKS_PER_HOUR recent = await db.count_recent_links(user.id, window_seconds=3600) if recent >= hourly_cap: await reply_target.reply_text(f"Hourly limit reached ({hourly_cap} links/hr). Try again later.") return media_info = extract_media_info(source_msg) if not media_info: return orig_name, file_size, mime_type, media_kind = media_info final_slug = build_custom_slug(custom_slug_input, orig_name) dest_chat_id = int(user_row["active_channel_id"]) if user_row["active_channel_id"] != 0 else BIN_CHANNEL token = secrets.token_urlsafe(12) source_type = "dm" if requester_msg.chat.type.name == "PRIVATE" else f"group:{requester_msg.chat.id}" hint_text = f"{custom_slug_input} {source_msg.caption or ''} {requester_msg.text or ''}" requested_qualities = _parse_qualities_from_text(hint_text) if media_kind == "video" else [] wants_dub = _wants_hindi_dub(hint_text) and media_kind == "video" status_msg = await reply_target.reply_text( f"**Processing `{final_slug}`**\n`{_render_bar(0.05)}` **5%**\n• **Stage:** Queued..." ) prog = TelegramProgressReporter(status_msg, f"Processing `{final_slug}`") try: if wants_dub: if file_size > DUB_TEST_MAX_BYTES: await status_msg.edit_text( f"Hindi dubbing test mode requires a file under **{_format_size(DUB_TEST_MAX_BYTES)}** " f"(got `{_format_size(file_size)}`)." ) return work_dir = tempfile.mkdtemp(prefix="ftl_bot_dub_") try: dl_cb = await prog.make_transfer_cb(0.05, 0.25, "Downloading English video from Telegram") src_local = await bot.download_media( source_msg, file_name=os.path.join(work_dir, final_slug), progress=dl_cb, ) if not src_local or not os.path.exists(src_local): raise RuntimeError("Failed to download video from Telegram.") dub_name = f"Hindi_{os.path.splitext(final_slug)[0]}.mp4" dub_out = os.path.join(work_dir, dub_name) async def on_dub_stage(pct: float, stage: str) -> None: mapped = 0.25 + max(0.0, min(1.0, pct)) * 0.50 await prog.update(mapped, stage, force=True) dub_meta = await dub_english_video_to_hindi(src_local, dub_out, on_dub_stage) up_cb = await prog.make_transfer_cb(0.75, 0.98, "Uploading Hindi-dubbed video to Telegram") sent = await bot.send_video( chat_id=dest_chat_id, video=dub_out, file_name=dub_name, caption=f"`{dub_name}` · Hindi Dub ({', '.join(dub_meta['speakers'])})", progress=up_cb, ) dub_size = os.path.getsize(dub_out) await prog.update(1.0, "Completed!", force=True) await db.upsert_user(user.id, user.username or "", full_name, increment_links=True) await db.log_event("INFO", "BOT_HINDI_DUB", f"tg:{user.id}", f"{dub_name} ({_format_size(dub_size)})") await _finalize_and_send_link( reply_target=reply_target, user_id=user.id, tier=user_row["tier"], token=token, final_slug=dub_name, file_size=dub_size, mime_type="video/mp4", media_kind="video", bin_msg_id=sent.id, dest_chat_id=dest_chat_id, source_type=source_type, extra_note=f"Speakers: `{', '.join(dub_meta['speakers'])}` · Emotions: `{', '.join(dub_meta['emotions'])}`", ) finally: shutil.rmtree(work_dir, ignore_errors=True) return # Standard copy to BIN_CHANNEL / user channel with live progress bar await prog.update(0.20, "Copying file to Telegram storage...", force=True) try: stored_msg = await source_msg.copy(dest_chat_id) except Exception: dest_chat_id = BIN_CHANNEL stored_msg = await source_msg.copy(BIN_CHANNEL) variants: dict[str, dict] = {} if requested_qualities and _has_enough_disk(): work_dir = tempfile.mkdtemp(prefix="ftl_bot_q_") try: dl_cb = await prog.make_transfer_cb(0.25, 0.45, "Downloading source video for transcoding") src_local = await bot.download_media( source_msg, file_name=os.path.join(work_dir, final_slug), progress=dl_cb, ) if src_local and os.path.exists(src_local): async def upload_variant(v_path: str, v_name: str, q_label: str) -> dict: v_msg = await bot.send_video( chat_id=dest_chat_id, video=v_path, file_name=v_name, caption=f"`{v_name}` ({q_label})", ) return { "msg_id": v_msg.id, "chat_id": dest_chat_id, "file_name": v_name, "size": os.path.getsize(v_path), "mime_type": "video/mp4", } async def on_q_prog(pct: float, stage: str) -> None: await prog.update(0.45 + pct * 0.50, stage, force=True) variants = await generate_quality_ladder( src_local, final_slug, requested_qualities, upload_variant, progress_callback=on_q_prog ) finally: shutil.rmtree(work_dir, ignore_errors=True) await prog.update(1.0, "Link generated!", force=True) await db.upsert_user(user.id, user.username or "", full_name, increment_links=True) await db.log_event("INFO", "BOT_LINK_CREATED", f"tg:{user.id}", f"{final_slug} ({_format_size(file_size)})") await _finalize_and_send_link( reply_target=reply_target, user_id=user.id, tier=user_row["tier"], token=token, final_slug=final_slug, file_size=file_size, mime_type=mime_type, media_kind=media_kind, bin_msg_id=stored_msg.id, dest_chat_id=dest_chat_id, source_type=source_type, variants=variants, ) except Exception as exc: err_text = f"{type(exc).__name__}: {exc}" await db.log_event("ERROR", "BOT_PROCESS_ERR", f"tg:{user.id}", err_text[:200]) try: await status_msg.edit_text(f"Failed to process `{final_slug}`: `{err_text[:220]}`") except Exception: pass finally: try: await status_msg.delete() except Exception: pass @bot.on_message(filters.command(["start", "help"]) & ~filters.bot) async def cmd_start(_, message: Message) -> None: if message.from_user: full_name = f"{message.from_user.first_name or ''} {message.from_user.last_name or ''}".strip() await db.upsert_user(message.from_user.id, message.from_user.username or "", full_name) await message.reply_text( "**FileToLink, Multi-Quality & Hindi Dub Bot**\n\n" "• **Send or forward any file/video** → instant stream & download links with live progress bar.\n" "• **Multi-quality video:** Add `720p`, `480p`, `360p`, `240p`, `144p`, or `allq` in caption or `/link title 480p 144p`.\n" "• **English → Hindi Dub (< 5 MB test):** Add `hindi` or `dub` in caption or `/dub` on a video (< 5 MB).\n" "• **Set channel:** `/setchannel -100...` (after adding bot as Admin with Post Messages) or `/clearsetchannel`.\n" "• **HF Mirror:** `/hfmirror https://huggingface.co/datasets/org/repo [.ext]`\n" f"• **Web Portal & Admin:** {BASE_URL} · {BASE_URL}/admin" ) @bot.on_message(filters.command("setchannel") & ~filters.bot) async def cmd_setchannel(_, message: Message) -> None: if not message.from_user: return parts = (message.text or "").split(maxsplit=1) if len(parts) < 2: await message.reply_text("Usage: `/setchannel -1001234567890` (Bot must be Admin with Post Messages).") return try: ch_id = int(parts[1].strip()) except ValueError: await message.reply_text("Invalid channel ID.") return ok, info = await verify_channel_admin(ch_id) if not ok: await message.reply_text(f"Verification failed: {info}") return full_name = f"{message.from_user.first_name or ''} {message.from_user.last_name or ''}".strip() await db.upsert_user(message.from_user.id, message.from_user.username or "", full_name) await db.save_user_channel(message.from_user.id, ch_id, info) await db.log_event("INFO", "CHANNEL_BOUND", f"tg:{message.from_user.id}", f"{info} ({ch_id})") await message.reply_text(f"Target channel set to **{info}** (`{ch_id}`).") @bot.on_message(filters.command("clearsetchannel") & ~filters.bot) async def cmd_clearsetchannel(_, message: Message) -> None: if not message.from_user: return await db.clear_user_active_channel(message.from_user.id) await message.reply_text("Reset target destination to default storage channel.") @bot.on_message(filters.command("link") & filters.reply & ~filters.bot) async def cmd_reply_link(_, message: Message) -> None: target = message.reply_to_message if not target or not extract_media_info(target): await message.reply_text("Reply `/link [custom-title] [qualities]` to a media message.") return parts = (message.text or "").split(maxsplit=1) custom_slug = parts[1].strip() if len(parts) > 1 else "" await _process_media_message(target, message, message, custom_slug_input=custom_slug) @bot.on_message(filters.command("dub") & filters.reply & ~filters.bot) async def cmd_reply_dub(_, message: Message) -> None: target = message.reply_to_message if not target or not extract_media_info(target): await message.reply_text("Reply `/dub` to an English video (< 5 MB in test mode).") return await _process_media_message(target, message, message, custom_slug_input="hindi") @bot.on_message(filters.command("hfmirror") & ~filters.bot) async def cmd_hfmirror(_, message: Message) -> None: if not message.from_user: return user = message.from_user full_name = f"{user.first_name or ''} {user.last_name or ''}".strip() user_row = await db.upsert_user(user.id, user.username or "", full_name) if user_row["is_banned"] == 1: return args = (message.text or "").split() if len(args) < 2 or not args[1].startswith("http"): await message.reply_text("Usage: `/hfmirror https://huggingface.co/datasets/org/repo [.ext]`") return hf_url = args[1].strip() ext_filter = args[2].strip() if len(args) >= 3 else "" dest_chat_id = int(user_row["active_channel_id"]) if user_row["active_channel_id"] != 0 else user.id status_msg = await message.reply_text( f"**HF Mirror Job**\n`{_render_bar(0.02)}` **2%**\n• **Stage:** Initializing..." ) prog = TelegramProgressReporter(status_msg, "HF Mirror Job") async def on_status(pct: float, text: str) -> None: await prog.update(pct, text, force=True) async def on_upload(local_path: str, part_name: str) -> dict: up_cb = await prog.make_transfer_cb(0.75, 0.96, f"Uploading `{part_name}`") sent = await bot.send_document( chat_id=dest_chat_id, document=local_path, file_name=part_name, caption=f"HF Mirror: `{part_name}`", progress=up_cb, ) return {"msg_id": sent.id, "chat_id": dest_chat_id, "file_name": part_name} try: items = await mirror_hf_target(hf_url, ext_filter, on_upload, on_status) await prog.update(1.0, f"Completed! Mirrored {len(items)} file(s).", force=True) await db.log_event("INFO", "HF_MIRROR_TG", f"tg:{user.id}", f"Mirrored {len(items)} item(s)") await status_msg.edit_text(f"Completed! Uploaded **{len(items)}** file(s) to chat `{dest_chat_id}`.") except Exception as exc: await status_msg.edit_text(f"Mirror failed: `{str(exc)[:220]}`") @bot.on_message(filters.forwarded & ~filters.bot & (filters.private | filters.group)) async def handle_forwarded(_, message: Message) -> None: if extract_media_info(message): await _process_media_message(message, message, message) @bot.on_message(filters.private & ~filters.forwarded & ~filters.bot) async def handle_dm_media(_, message: Message) -> None: if extract_media_info(message): await _process_media_message(message, message, message) async def delete_telegram_messages(chat_id: int, message_ids: list[int]) -> None: if not message_ids: return for i in range(0, len(message_ids), 100): try: await bot.delete_messages(chat_id, message_ids[i : i + 100]) except Exception: pass async def upload_log_archive_to_bin(gz_bytes: bytes, filename: str, caption: str) -> None: bio = io.BytesIO(gz_bytes) bio.name = filename await bot.send_document(chat_id=BIN_CHANNEL, document=bio, caption=caption) # ============================================================================== # 7. HIGH-SPEED SLIDING PREFETCH STREAMER (206 PARTIAL CONTENT + MULTI-BOT) # ============================================================================== TG_CHUNK_SIZE = 1024 * 1024 PREFETCH_WINDOW = 16 RANGE_PATTERN = re.compile(r"^bytes=(\d*)-(\d*)$") def _extract_media_size(msg: Message) -> int | None: media = msg.document or msg.video or msg.audio or msg.voice or msg.photo or msg.animation if not media: return None return int(getattr(media, "file_size", 0) or 0) def parse_range_header(range_header: str | None, file_size: int) -> tuple[int, int, bool]: if not range_header or file_size <= 0: return 0, max(0, file_size - 1), False match = RANGE_PATTERN.match(range_header.strip()) if not match: raise HTTPException( status_code=status.HTTP_416_REQUESTED_RANGE_NOT_SATISFIABLE, headers={"Content-Range": f"bytes */{file_size}"}, ) start_str, end_str = match.groups() if not start_str and not end_str: raise HTTPException( status_code=status.HTTP_416_REQUESTED_RANGE_NOT_SATISFIABLE, headers={"Content-Range": f"bytes */{file_size}"}, ) if start_str and not end_str: start = int(start_str) end = file_size - 1 elif not start_str and end_str: suffix_len = int(end_str) if suffix_len <= 0: raise HTTPException( status_code=status.HTTP_416_REQUESTED_RANGE_NOT_SATISFIABLE, headers={"Content-Range": f"bytes */{file_size}"}, ) start = max(0, file_size - suffix_len) end = file_size - 1 else: start = int(start_str) end = min(int(end_str), file_size - 1) if start > end or start >= file_size: raise HTTPException( status_code=status.HTTP_416_REQUESTED_RANGE_NOT_SATISFIABLE, headers={"Content-Range": f"bytes */{file_size}"}, ) return start, end, True async def _resolve_message(chat_id: int, msg_id: int) -> tuple[Client, Message]: client = get_stream_client() for candidate in (client, bot): try: msg = await candidate.get_messages(chat_id, msg_id) if msg and not msg.empty and _extract_media_size(msg) is not None: return candidate, msg except Exception: if candidate is bot: raise raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="File no longer available in Telegram.") async def _prefetch_byte_generator( client: Client, msg: Message, start_byte: int, end_byte: int, is_partial: bool, token: str, creator_id: int, ) -> AsyncGenerator[bytes, None]: first_chunk = start_byte // TG_CHUNK_SIZE first_cut = start_byte % TG_CHUNK_SIZE last_chunk = end_byte // TG_CHUNK_SIZE last_cut = (end_byte % TG_CHUNK_SIZE) + 1 total_chunks = last_chunk - first_chunk + 1 queue: asyncio.Queue[bytes | BaseException | None] = asyncio.Queue(maxsize=PREFETCH_WINDOW) bytes_sent = 0 async def producer() -> None: chunk_idx = 0 try: stream_iter = ( client.stream_media(msg, offset=first_chunk, limit=total_chunks) if is_partial else client.stream_media(msg) ) async for chunk in stream_iter: if not chunk: continue if not is_partial: part = chunk elif total_chunks == 1: part = chunk[first_cut:last_cut] elif chunk_idx == 0: part = chunk[first_cut:] elif chunk_idx == total_chunks - 1: part = chunk[:last_cut] else: part = chunk chunk_idx += 1 if part: await queue.put(part) await queue.put(None) except BaseException as exc: await queue.put(exc) prod_task = asyncio.create_task(producer()) try: while True: item = await queue.get() if item is None: break if isinstance(item, BaseException): raise item bytes_sent += len(item) yield item except Exception as exc: err_text = f"{type(exc).__name__}: {exc}" print(f"[STREAM ERROR] token={token} sent={bytes_sent} err={err_text}", flush=True) traceback.print_exc() asyncio.create_task(db.log_event("ERROR", "STREAM_ERROR", f"token:{token}", err_text)) raise finally: if not prod_task.done(): prod_task.cancel() try: await prod_task except BaseException: pass if bytes_sent > 0: asyncio.create_task(db.record_transfer(token, creator_id, bytes_sent, start_byte == 0)) async def serve_telegram_file( request: Request, token: str, want_inline: bool, quality: str | None = None, pin: str = "", ): link = await db.get_active_link(token) if not link: raise HTTPException(status_code=status.HTTP_410_GONE, detail="Link expired or download limit reached.") if link.get("password_hash") and not verify_link_password(link["password_hash"], pin): raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid or missing access PIN.") variants: dict = link.get("variants") or {} q_key = (quality or "").strip().lower() if q_key and q_key in variants and isinstance(variants[q_key], dict): v = variants[q_key] chat_id = int(v.get("chat_id", link["target_chat_id"])) msg_id = int(v["msg_id"]) file_name = str(v.get("file_name") or link["file_name"]) file_size = int(v.get("size") or link["file_size"]) mime_type = str(v.get("mime_type") or "video/mp4") else: chat_id = int(link["target_chat_id"]) msg_id = int(link["bin_msg_id"]) file_name = str(link["file_name"]) file_size = int(link["file_size"]) mime_type = str(link["mime_type"]) try: client, msg = await _resolve_message(chat_id, msg_id) except HTTPException: raise except Exception as exc: err_text = f"{type(exc).__name__}: {exc}" await db.log_event("ERROR", "TG_FETCH_ERROR", f"token:{token}", err_text) raise HTTPException(status_code=status.HTTP_502_BAD_GATEWAY, detail="Unable to read file from Telegram.") live_size = _extract_media_size(msg) if live_size and live_size > 0: file_size = live_size etag = f'"{token}-{q_key or "orig"}-{file_size}"' last_mod = email.utils.formatdate(int(link["created_at"]), usegmt=True) if_range = request.headers.get("if-range") raw_range = request.headers.get("range") if if_range and if_range.strip() not in (etag, last_mod): raw_range = None start_byte, end_byte, is_partial = parse_range_header(raw_range, file_size) content_length = (end_byte - start_byte) + 1 if file_size > 0 else 0 safe_mime, content_disp = get_safe_delivery_headers(file_name, mime_type, want_inline=want_inline) headers = { "Accept-Ranges": "bytes", "Content-Length": str(content_length), "Content-Disposition": content_disp, "ETag": etag, "Last-Modified": last_mod, "Cache-Control": "private, no-transform", } if is_partial: headers["Content-Range"] = f"bytes {start_byte}-{end_byte}/{file_size}" status_code = status.HTTP_206_PARTIAL_CONTENT if is_partial else status.HTTP_200_OK if request.method == "HEAD": return StreamingResponse(iter([b""]), status_code=status_code, headers=headers, media_type=safe_mime) return StreamingResponse( content=_prefetch_byte_generator( client=client, msg=msg, start_byte=start_byte, end_byte=end_byte, is_partial=is_partial, token=token, creator_id=int(link["creator_id"]), ), status_code=status_code, headers=headers, media_type=safe_mime, ) # ============================================================================== # 8. HTTP ROUTES, ADMIN PANEL & GRADIO INTERFACE # ============================================================================== _bg_loop: asyncio.AbstractEventLoop | None = None async def run_maintenance(force_log_dump: bool = False) -> dict[str, int]: expired = await db.get_expired_links() if expired: by_chat: dict[int, list[int]] = {} tokens: list[str] = [] for row in expired: tokens.append(str(row["token"])) chat_id = int(row["target_chat_id"]) by_chat.setdefault(chat_id, []).append(int(row["bin_msg_id"])) try: v_map = json.loads(row.get("variants_json") or "{}") for v in v_map.values(): if isinstance(v, dict) and v.get("msg_id"): by_chat.setdefault(int(v.get("chat_id", chat_id)), []).append(int(v["msg_id"])) except Exception: pass for chat_id, msg_ids in by_chat.items(): await delete_telegram_messages(chat_id, msg_ids) await db.delete_links_by_tokens(tokens) await db.log_event("INFO", "EXPIRED_PURGE", "system", f"Cleaned {len(tokens)} expired/burned link(s)") dumped = 0 if force_log_dump or (await db.count_logs()) >= LOG_DUMP_THRESHOLD: gz_bytes, log_ids, summary = await db.export_oldest_logs_gzip(batch_size=10000) if gz_bytes and log_ids: fname = f"audit_logs_{time.strftime('%Y%m%d_%H%M%S', time.gmtime())}.json.gz" await upload_log_archive_to_bin(gz_bytes, fname, f"#LOG_ARCHIVE | {summary}") await db.purge_logs_and_vacuum(log_ids) dumped = len(log_ids) await db.log_event("INFO", "LOGS_ARCHIVED", "system", f"Archived {dumped} logs & VACUUMed DB") return {"expired_cleaned": len(expired), "logs_dumped": dumped} async def _maintenance_loop() -> None: while True: try: await asyncio.sleep(CLEANUP_INTERVAL_SECONDS) await run_maintenance(force_log_dump=False) except asyncio.CancelledError: break except Exception as exc: print(f"[MAINTENANCE ERROR] {exc}", flush=True) async def _async_services_runner() -> None: try: print("[1/2] Initializing Turso DB...", flush=True) await db.start() print("[2/2] Starting Kurigram MTProto workers...", flush=True) active_count = 0 for idx, client in enumerate(stream_clients, start=1): try: await asyncio.wait_for(client.start(), timeout=35.0) active_count += 1 print(f" Worker {idx}/{len(stream_clients)} connected.", flush=True) except Exception as exc: print(f" [WORKER {idx} ERROR] {type(exc).__name__}: {exc}", flush=True) await db.log_event("INFO", "SPACE_BOOT", "system", f"Online with {active_count}/{len(stream_clients)} worker(s)") except Exception as exc: print(f"[BOOT ERROR] {type(exc).__name__}: {exc}", flush=True) asyncio.create_task(_maintenance_loop()) while True: await asyncio.sleep(3600) def _start_background_loop() -> None: global _bg_loop loop = asyncio.new_event_loop() _bg_loop = loop asyncio.set_event_loop(loop) loop.run_until_complete(_async_services_runner()) def _client_ip(request: Request) -> str: xff = request.headers.get("x-forwarded-for") if xff: return xff.split(",")[0].strip() return request.client.host if request.client else "unknown" async def health_handler(request: Request): return JSONResponse({"status": "ok", "ts": int(time.time())}) async def dl_endpoint(request: Request): return await serve_telegram_file( request, token=request.path_params["token"], want_inline=False, quality=request.query_params.get("q", ""), pin=request.query_params.get("pin", ""), ) async def stream_endpoint(request: Request): return await serve_telegram_file( request, token=request.path_params["token"], want_inline=True, quality=request.query_params.get("q", ""), pin=request.query_params.get("pin", ""), ) async def watch_endpoint(request: Request): token = request.path_params["token"] link = await db.get_active_link(token) if not link: return templates.TemplateResponse( request=request, name="error.html", context={"code": 410, "title": "Link Expired", "message": "This link has expired or reached its download limit."}, status_code=410, ) final_slug = link["file_name"] enc = urllib.parse.quote(final_slug, safe="") variants = link.get("variants") or {} quality_options = ["original"] + [q for q in ("720p", "480p", "360p", "240p", "144p") if q in variants] return templates.TemplateResponse( request=request, name="watch.html", context={ "token": token, "encoded_slug": enc, "file_name": final_slug, "file_size_str": _format_size(int(link["file_size"])), "media_kind": link["media_kind"], "downloads": link["downloads"], "has_pin": bool(link.get("password_hash")), "seconds_left": max(0, int(link["expires_at"]) - int(time.time())), "quality_options": quality_options, "base_url": BASE_URL, }, ) async def admin_login_get(request: Request): if session_mgr.read_session(request): return RedirectResponse(url="/admin", status_code=status.HTTP_303_SEE_OTHER) return templates.TemplateResponse(request=request, name="admin_login.html", context={"error": None}) async def admin_login_post(request: Request): form = await request.form() username = str(form.get("username", "")) password = str(form.get("password", "")) ip = _client_ip(request) if login_limiter.is_blocked(ip): return templates.TemplateResponse( request=request, name="admin_login.html", context={"error": "Locked for 15 minutes due to repeated failed logins."}, status_code=429, ) if not (hmac.compare_digest(username.strip(), ADMIN_USERNAME) and hmac.compare_digest(password, ADMIN_PASSWORD)): login_limiter.record_failure(ip) await db.log_event("WARN", "ADMIN_LOGIN_FAIL", ip, f"Attempt: {username[:24]}") return templates.TemplateResponse( request=request, name="admin_login.html", context={"error": "Invalid username or password."}, status_code=401, ) login_limiter.reset(ip) await db.log_event("INFO", "ADMIN_LOGIN_OK", ip, "Admin authenticated") resp = RedirectResponse(url="/admin", status_code=status.HTTP_303_SEE_OTHER) resp.set_cookie( key=session_mgr.COOKIE_NAME, value=session_mgr.create_session_token(ADMIN_USERNAME), max_age=session_mgr.MAX_AGE, httponly=True, secure=BASE_URL.startswith("https://"), samesite="strict", ) return resp async def admin_logout(request: Request): sess = session_mgr.require_admin(request) form = await request.form() session_mgr.verify_csrf(sess, str(form.get("csrf_token", ""))) resp = RedirectResponse(url="/admin/login", status_code=status.HTTP_303_SEE_OTHER) resp.delete_cookie(session_mgr.COOKIE_NAME) return resp async def admin_panel(request: Request): sess = session_mgr.require_admin(request) q = request.query_params.get("q", "").strip()[:80] data = await db.get_dashboard_data(search=q) free_tmp = shutil.disk_usage("/tmp").free return templates.TemplateResponse( request=request, name="admin_dashboard.html", context={ "csrf_token": sess["csrf"], "query": q, "now": data["now"], "tutorial_url": data["tutorial_url"], "free_tmp_str": _format_size(free_tmp), "stats": data["stats"], "links": data["links"], "users": data["users"], "logs": data["logs"], "format_size": _format_size, "base_url": BASE_URL, }, ) async def admin_update_tutorial(request: Request): sess = session_mgr.require_admin(request) form = await request.form() session_mgr.verify_csrf(sess, str(form.get("csrf_token", ""))) tutorial_url = str(form.get("tutorial_url", "")).strip()[:300] await db.set_setting("tutorial_video_url", tutorial_url) await db.log_event("INFO", "TUTORIAL_UPDATED", "admin", tutorial_url[:120]) return RedirectResponse(url="/admin", status_code=status.HTTP_303_SEE_OTHER) async def admin_set_tier(request: Request): sess = session_mgr.require_admin(request) form = await request.form() session_mgr.verify_csrf(sess, str(form.get("csrf_token", ""))) tg_id = int(request.path_params["tg_id"]) tier = str(form.get("tier", "free")) days = int(form.get("days", 30)) clean_tier = "premium" if tier == "premium" else "free" await db.set_user_tier(tg_id, clean_tier, max(0, min(days, 3650))) await db.log_event("INFO", "TIER_UPDATED", "admin", f"tg:{tg_id} -> {clean_tier} ({days}d)") return RedirectResponse(url="/admin", status_code=status.HTTP_303_SEE_OTHER) async def admin_ban_user(request: Request): sess = session_mgr.require_admin(request) form = await request.form() session_mgr.verify_csrf(sess, str(form.get("csrf_token", ""))) tg_id = int(request.path_params["tg_id"]) state = await db.toggle_user_ban(tg_id) await db.log_event("WARN", "USER_BANNED" if state == 1 else "USER_UNBANNED", "admin", f"tg:{tg_id}") return RedirectResponse(url="/admin", status_code=status.HTTP_303_SEE_OTHER) async def admin_revoke(request: Request): sess = session_mgr.require_admin(request) form = await request.form() session_mgr.verify_csrf(sess, str(form.get("csrf_token", ""))) token = request.path_params["token"] link = await db.get_active_link(token) if link: await delete_telegram_messages(int(link["target_chat_id"]), [int(link["bin_msg_id"])]) await db.delete_links_by_tokens([token]) await db.log_event("WARN", "LINK_REVOKED", "admin", link["file_name"]) return RedirectResponse(url="/admin", status_code=status.HTTP_303_SEE_OTHER) async def admin_dump_logs(request: Request): sess = session_mgr.require_admin(request) form = await request.form() session_mgr.verify_csrf(sess, str(form.get("csrf_token", ""))) await run_maintenance(force_log_dump=True) return RedirectResponse(url="/admin", status_code=status.HTTP_303_SEE_OTHER) # --- Companion Gradio Web Console --- CLAUDE_MINIMAL_CSS = """ .gradio-container { max-width: 960px !important; margin: 0 auto !important; font-family: ui-sans-serif, system-ui, -apple-system, sans-serif !important; } footer { visibility: hidden !important; } """ def _extract_file_path(file_obj) -> str | None: if not file_obj: return None if isinstance(file_obj, str): return file_obj if isinstance(file_obj, list) and file_obj: return _extract_file_path(file_obj[0]) return getattr(file_obj, "name", None) async def ui_upload_file( terms_accepted: bool, file_obj, custom_slug_input: str, expiry_label: str, burn_after_one: bool, access_pin: str, qualities: list[str], enable_hindi_dub: bool, progress: gr.Progress = gr.Progress(track_tqdm=True), ): if not terms_accepted: raise gr.Error("Please accept the Ownership & Research Terms checkbox first.") file_path = _extract_file_path(file_obj) if not file_path or not os.path.exists(file_path): raise gr.Error("Please select a file to upload.") if not _has_enough_disk(): raise gr.Error("Server temporary storage is busy.") progress(0.10, desc="Preparing upload...") mime_type = mimetypes.guess_type(file_path)[0] or "application/octet-stream" orig_name = sanitize_filename(os.path.basename(file_path), mime_type) final_slug = build_custom_slug(custom_slug_input, orig_name) file_size = os.path.getsize(file_path) media_kind = "video" if mime_type.startswith("video/") else ("audio" if mime_type.startswith("audio/") else "document") token = secrets.token_urlsafe(12) variants: dict[str, dict] = {} upload_path = file_path upload_name = final_slug dub_work_dir: str | None = None try: if enable_hindi_dub and media_kind == "video": if file_size > DUB_TEST_MAX_BYTES: raise gr.Error(f"Hindi dubbing test mode limit is {_format_size(DUB_TEST_MAX_BYTES)}.") dub_work_dir = tempfile.mkdtemp(prefix="ftl_ui_dub_") dub_name = f"Hindi_{os.path.splitext(final_slug)[0]}.mp4" dub_out = os.path.join(dub_work_dir, dub_name) async def _on_dub(pct: float, stage: str) -> None: progress(0.15 + pct * 0.45, desc=stage[:100]) await dub_english_video_to_hindi(file_path, dub_out, _on_dub) upload_path = dub_out upload_name = dub_name file_size = os.path.getsize(dub_out) progress(0.65, desc=f"Uploading {upload_name} to Telegram...") if media_kind == "video": sent = await bot.send_video(chat_id=BIN_CHANNEL, video=upload_path, file_name=upload_name, caption=f"`{upload_name}`") elif media_kind == "audio": sent = await bot.send_audio(chat_id=BIN_CHANNEL, audio=upload_path, file_name=upload_name, caption=f"`{upload_name}`") else: sent = await bot.send_document(chat_id=BIN_CHANNEL, document=upload_path, file_name=upload_name, caption=f"`{upload_name}`") if media_kind == "video" and qualities: async def upload_variant(v_path: str, v_name: str, q_label: str) -> dict: v_msg = await bot.send_video(chat_id=BIN_CHANNEL, video=v_path, file_name=v_name, caption=f"`{v_name}` ({q_label})") return { "msg_id": v_msg.id, "chat_id": BIN_CHANNEL, "file_name": v_name, "size": os.path.getsize(v_path), "mime_type": "video/mp4", } async def on_q_prog(pct: float, stage: str) -> None: progress(0.65 + pct * 0.25, desc=stage[:100]) variants = await generate_quality_ladder(upload_path, upload_name, qualities, upload_variant, on_q_prog) progress(0.95, desc="Saving link metadata...") await db.create_link( token=token, slug=upload_name, bin_msg_id=sent.id, target_chat_id=BIN_CHANNEL, file_name=upload_name, file_size=file_size, mime_type=mime_type, media_kind=media_kind, creator_id=0, source_type="web_upload", ttl_seconds=EXPIRY_MAP.get(expiry_label, 86400), variants=variants, password_hash=hash_link_password(access_pin), max_downloads=1 if burn_after_one else 0, ) progress(1.0, desc="Done!") enc = urllib.parse.quote(upload_name, safe="") return ( f"{BASE_URL}/dl/{token}/{enc}", f"{BASE_URL}/watch/{token}/{enc}", f"Ready: **{upload_name}** ({_format_size(file_size)})", ) finally: if dub_work_dir: shutil.rmtree(dub_work_dir, ignore_errors=True) async def ui_hf_mirror( terms_accepted: bool, hf_url: str, ext_filter: str, progress: gr.Progress = gr.Progress(track_tqdm=True), ): if not terms_accepted: raise gr.Error("Please accept the Ownership & Research Terms checkbox first.") if not hf_url.strip(): raise gr.Error("Enter a Hugging Face Model or Dataset URL.") logs: list[str] = [] q_events: asyncio.Queue[tuple[float, str] | None] = asyncio.Queue() async def status_cb(pct: float, msg: str) -> None: logs.append(msg) await q_events.put((pct, msg)) async def upload_cb(local_path: str, part_name: str) -> dict: await q_events.put((0.80, f"Uploading `{part_name}`...")) sent = await bot.send_document(chat_id=BIN_CHANNEL, document=local_path, file_name=part_name, caption=f"HF Mirror: `{part_name}`") return {"msg_id": sent.id, "chat_id": BIN_CHANNEL, "file_name": part_name} async def _runner(): try: return await mirror_hf_target(hf_url, ext_filter, upload_cb, status_cb) finally: await q_events.put(None) task = asyncio.create_task(_runner()) try: while True: item = await q_events.get() if item is None: break pct, desc = item progress(pct, desc=desc[:100]) yield f"Working: {desc}", "\n".join(logs[-15:]) uploaded = await task progress(1.0, desc="Complete!") yield f"Mirrored **{len(uploaded)}** file(s) to Telegram storage.", "\n".join(logs[-15:]) except Exception as exc: if not task.done(): task.cancel() raise gr.Error(str(exc)) def build_gradio_app() -> gr.Blocks: with gr.Blocks(title="Telegram FileToLink & Dubbing Console") as blocks: _zerogpu_btn = gr.Button("init-gpu", visible=False) _zerogpu_btn.click(fn=_zerogpu_register, inputs=None, outputs=None) gr.Markdown( f"# Telegram FileToLink, Multi-Quality & Hindi Dub Console\n" f"Primary workflow runs in your Telegram bot with live progress bars · Web Streamer: `{BASE_URL}` · Admin: `{BASE_URL}/admin`" ) terms_chk = gr.Checkbox(label="I confirm I have rights to share/process this media for research & educational use.", value=False) with gr.Tabs(): with gr.Tab("Upload & Dub (< 5 MB Test)"): file_in = gr.File(label="Select File", type="filepath") with gr.Row(): slug_in = gr.Textbox(label="Custom URL Title (Optional)", placeholder="e.g. english-clip-01") expiry_in = gr.Dropdown(label="Lifespan", choices=list(EXPIRY_MAP.keys()), value="24 Hours") with gr.Row(): pin_in = gr.Textbox(label="Optional PIN", type="password") burn_chk = gr.Checkbox(label="Burn after 1 download", value=False) dub_chk = gr.Checkbox(label="Convert English → Hindi (< 5 MB test)", value=False) qualities_in = gr.CheckboxGroup( label="Video Quality Variants", choices=["720p", "480p", "360p", "240p", "144p"], value=[], ) upload_btn = gr.Button("Process & Generate Links", variant="primary") out_status = gr.Markdown("") out_dl = gr.Textbox(label="Direct Download URL", interactive=False) out_watch = gr.Textbox(label="Stream / Watch URL", interactive=False) upload_btn.click( ui_upload_file, inputs=[terms_chk, file_in, slug_in, expiry_in, burn_chk, pin_in, qualities_in, dub_chk], outputs=[out_dl, out_watch, out_status], ) with gr.Tab("HF Mirror"): hf_url_in = gr.Textbox(label="Hugging Face Model / Dataset URL", placeholder="https://huggingface.co/datasets/org/repo") ext_in = gr.Textbox(label="Extension Filter (Optional)", placeholder=".parquet or .gguf") hf_btn = gr.Button("Mirror to Telegram", variant="primary") hf_summary = gr.Markdown("") hf_logs = gr.Textbox(label="Progress Log", lines=8, interactive=False) hf_btn.click(ui_hf_mirror, inputs=[terms_chk, hf_url_in, ext_in], outputs=[hf_summary, hf_logs]) return blocks demo = build_gradio_app() def main() -> None: threading.Thread(target=_start_background_loop, daemon=True).start() demo.launch( server_name="0.0.0.0", server_port=7860, share=False, ssr_mode=False, prevent_thread_lock=True, ) live_app = demo.app priority_routes = [ StarletteRoute("/health", health_handler, methods=["GET", "HEAD"]), StarletteRoute("/dl/{token}/{filename}", dl_endpoint, methods=["GET", "HEAD"]), StarletteRoute("/stream/{token}/{filename}", stream_endpoint, methods=["GET", "HEAD"]), StarletteRoute("/watch/{token}/{filename}", watch_endpoint, methods=["GET"]), StarletteRoute("/admin/login", admin_login_get, methods=["GET"]), StarletteRoute("/admin/login", admin_login_post, methods=["POST"]), StarletteRoute("/admin/logout", admin_logout, methods=["POST"]), StarletteRoute("/admin", admin_panel, methods=["GET"]), StarletteRoute("/admin/settings/tutorial", admin_update_tutorial, methods=["POST"]), StarletteRoute("/admin/users/{tg_id:int}/tier", admin_set_tier, methods=["POST"]), StarletteRoute("/admin/users/{tg_id:int}/toggle-ban", admin_ban_user, methods=["POST"]), StarletteRoute("/admin/links/{token}/revoke", admin_revoke, methods=["POST"]), StarletteRoute("/admin/logs/dump", admin_dump_logs, methods=["POST"]), ] for route in reversed(priority_routes): live_app.router.routes.insert(0, route) live_app.mount("/static", StaticFiles(directory=str(STATIC_DIR)), name="static") demo.app = SecurityHeadersMiddleware(live_app) live_app.build_middleware_stack() demo.block_thread() if __name__ == "__main__": main()
import huggingface_hub
if not hasattr(huggingface_hub, "HfFolder"):
class _HfFolder:
@staticmethod
def get_token():
return huggingface_hub.get_token()
@staticmethod
def save_token(token):
huggingface_hub.login(token)
@staticmethod
def delete_token():
huggingface_hub.logout()
huggingface_hub.HfFolder = _HfFolder
import spaces
import gradio as gr
import asyncio
import email.utils
import gzip
import hashlib
import hmac
import io
import itertools
import json
import mimetypes
import os
import re
import secrets
import shutil
import tempfile
import threading
import time
import traceback
import urllib.parse
from collections import defaultdict
from pathlib import Path
from typing import Any, AsyncGenerator
import httpx
from fastapi import Request, status
from fastapi.responses import HTMLResponse, JSONResponse, RedirectResponse, StreamingResponse
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
from itsdangerous import BadSignature, SignatureExpired, URLSafeTimedSerializer
from pyrogram import Client, filters
from pyrogram.types import InlineKeyboardButton, InlineKeyboardMarkup, Message
from starlette.routing import Route as StarletteRoute
# ==============================================================================
# 1. CONFIGURATION & TURSO URL NORMALIZATION
# ==============================================================================
BASE_DIR = Path(__file__).resolve().parent
STATIC_DIR = BASE_DIR / "static"
TEMPLATES_DIR = BASE_DIR / "templates"
STATIC_DIR.mkdir(parents=True, exist_ok=True)
TEMPLATES_DIR.mkdir(parents=True, exist_ok=True)
templates = Jinja2Templates(directory=str(TEMPLATES_DIR))
def _normalize_turso_url(raw_url: str) -> str:
url = raw_url.strip().rstrip("/")
for prefix in ("libsql://", "turso://"):
if url.startswith(prefix):
return "https://" + url[len(prefix):]
return url
def _detect_base_url() -> str:
explicit = os.getenv("BASE_URL", "").strip().rstrip("/")
if explicit:
return explicit
space_host = os.getenv("SPACE_HOST", "").strip()
if space_host:
return f"https://{space_host}"
return "http://localhost:7860"
API_ID: int = int(os.environ["API_ID"])
API_HASH: str = os.environ["API_HASH"].strip()
BOT_TOKEN: str = os.environ["BOT_TOKEN"].strip()
MULTI_TOKENS: list[str] = [t.strip() for t in os.getenv("MULTI_TOKENS", "").split(",") if t.strip()]
BIN_CHANNEL: int = int(os.environ["BIN_CHANNEL"])
HF_TOKEN: str | None = os.getenv("HF_TOKEN", "").strip() or None
TURSO_HTTP_URL: str = _normalize_turso_url(os.environ["TURSO_DATABASE_URL"])
TURSO_AUTH_TOKEN: str = os.environ["TURSO_AUTH_TOKEN"].strip()
BASE_URL: str = _detect_base_url()
ADMIN_USERNAME: str = os.getenv("ADMIN_USERNAME", "admin").strip()
ADMIN_PASSWORD: str = os.environ["ADMIN_PASSWORD"]
SECRET_KEY: str = os.getenv("SECRET_KEY") or secrets.token_hex(32)
FREE_LINKS_PER_HOUR: int = int(os.getenv("FREE_LINKS_PER_HOUR", "25"))
PREMIUM_LINKS_PER_HOUR: int = int(os.getenv("PREMIUM_LINKS_PER_HOUR", "150"))
DUB_TEST_MAX_BYTES: int = int(os.getenv("DUB_TEST_MAX_BYTES", str(5 * 1024 * 1024))) # < 5 MB test mode