rawlink / app.py
Neon-AI's picture
Update app.py
8e8728a verified
# main.py
import shutil
import tempfile
import requests
from fastapi import FastAPI, Query, HTTPException
from fastapi.responses import FileResponse
import os
from urllib.parse import urlparse
app = FastAPI(title="Telegram-Friendly Video Proxy")
@app.get("/download")
def download_video(url: str = Query(..., description="Public video URL")):
"""
Downloads a video from a streaming/HTML-wrapped URL and serves it
as a raw file Telegram can accept.
"""
# Validate URL
parsed = urlparse(url)
if not parsed.scheme.startswith("http"):
raise HTTPException(status_code=400, detail="Invalid URL")
# Extract file extension for naming
_, ext = os.path.splitext(parsed.path)
if ext.lower() not in [".mp4", ".mkv", ".webm", ".mov", ".avi"]:
ext = ".mp4" # default fallback
# Temp file to download
tmp_file = tempfile.mktemp(suffix=ext)
try:
# Download the video
with requests.get(url, stream=True, timeout=60) as r:
r.raise_for_status()
with open(tmp_file, "wb") as f:
shutil.copyfileobj(r.raw, f)
# Serve with Content-Disposition so Telegram sees it as a file
return FileResponse(
tmp_file,
media_type="application/octet-stream",
filename=f"video{ext}",
headers={"Content-Disposition": f'attachment; filename="video{ext}"'}
)
except Exception as e:
# Clean up in case of failure
if os.path.exists(tmp_file):
os.remove(tmp_file)
raise HTTPException(status_code=500, detail=f"Failed to download file: {repr(e)}")