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 """ File2Link Bot

🤖 File2Link Bot

Online. EnvĂ­a archivos al bot de Telegram para generar links directos del Space.

Soporta Range para reanudar descargas con ADM / 1DM / IDM.

""" @app.get("/health") async def health(): return {"status": "ok", "bot": "file2link", "max_file_mb": MAX_FILE_MB} @app.get("/file/{token}/{name:path}") async def download_file(token: str, name: str, request: Request): path = find_file_by_token(token) if not path or not path.exists() or not path.is_file(): raise HTTPException(status_code=404, detail="Archivo no encontrado o expirado") total = path.stat().st_size download_name = path.name.split("_", 1)[1] if "_" in path.name else path.name range_header = request.headers.get("range") or request.headers.get("Range") start, end, status_code = 0, total - 1, 200 if range_header: m = re.match(r"bytes=(\d*)-(\d*)", range_header) if not m: raise HTTPException(status_code=416, detail="Rango inválido") start_s, end_s = m.groups() if start_s: start = int(start_s) if end_s: end = int(end_s) if start_s == "" and end_s: suffix = int(end_s) start = max(total - suffix, 0) end = total - 1 if start > end or start >= total: return PlainTextResponse("Rango no disponible", status_code=416, headers={"Content-Range": f"bytes */{total}"}) end = min(end, total - 1) status_code = 206 headers = make_headers(path, download_name, start, end, total, status_code) return StreamingResponse(file_iterator(path, start, end), status_code=status_code, headers=headers)