File size: 1,644 Bytes
6af0541
a9b9784
8e8728a
 
 
6af0541
8e8728a
6af0541
98dcab9
8e8728a
a9b9784
6af0541
8e8728a
98dcab9
8e8728a
 
98dcab9
8e8728a
 
 
 
98dcab9
8e8728a
 
 
 
 
 
 
 
 
6af0541
 
 
8e8728a
6af0541
98dcab9
8e8728a
a9b9784
8e8728a
6af0541
8e8728a
 
a9b9784
98dcab9
6af0541
8e8728a
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# 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)}")