import logging import mimetypes import os import re from contextlib import asynccontextmanager from pathlib import Path from urllib.parse import quote from fastapi import FastAPI, Request, HTTPException from fastapi.responses import HTMLResponse, StreamingResponse, PlainTextResponse from bot import start_bot, stop_bot, DOWNLOAD_DIR, MAX_FILE_MB log = logging.getLogger("file2link.app") def find_file_by_token(token: str): if not re.fullmatch(r"[a-f0-9]{32}", token): return None matches = list(DOWNLOAD_DIR.glob(f"{token}_*")) return matches[0] if matches else None def make_headers(path: Path, download_name: str, start: int, end: int, total: int, status_code: int): mime_type, _ = mimetypes.guess_type(path.name) mime_type = mime_type or "application/octet-stream" quoted = quote(download_name) ascii_fallback = download_name.encode("ascii", "ignore").decode("ascii") or "download" ascii_fallback = ascii_fallback.replace('"', "") headers = { "Accept-Ranges": "bytes", "Content-Type": mime_type, "Content-Disposition": f"attachment; filename=\"{ascii_fallback}\"; filename*=UTF-8''{quoted}", "Cache-Control": "public, max-age=86400", "Content-Length": str(end - start + 1), } if status_code == 206: headers["Content-Range"] = f"bytes {start}-{end}/{total}" return headers def file_iterator(path: Path, start: int, end: int): with path.open("rb") as f: f.seek(start) remaining = end - start + 1 while remaining > 0: chunk = f.read(min(1024 * 1024, remaining)) if not chunk: break remaining -= len(chunk) yield chunk @asynccontextmanager async def lifespan(app: FastAPI): log.info("Arrancando bot File2Link dentro del mismo loop de FastAPI...") await start_bot() yield await stop_bot() app = FastAPI(title="File2Link Telegram Bot", version="5.0", lifespan=lifespan) @app.get("/", response_class=HTMLResponse) async def index(): return """
Online. EnvĂa archivos al bot de Telegram para generar links directos del Space.
Soporta Range para reanudar descargas con ADM / 1DM / IDM.