File size: 2,255 Bytes
e80493e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
import yt_dlp
import requests
import tempfile
import os
import json
import time
from fastapi import FastAPI, Query
from fastapi.responses import JSONResponse, FileResponse

app = FastAPI()

def process(url, audio=False):
    tmpdir = tempfile.mkdtemp()
    filename = os.path.join(tmpdir, "%(title)s.%(ext)s")
    ydl_opts = {
        "outtmpl": filename,
        "quiet": True,
        "format": "bestaudio/best" if audio else "bestvideo+bestaudio/best",
        "postprocessors": [
            {"key": "FFmpegExtractAudio", "preferredcodec": "mp3", "preferredquality": "192"}
        ] if audio else [
            {"key": "FFmpegVideoConvertor", "preferedformat": "mp4"}
        ],
    }
    with yt_dlp.YoutubeDL(ydl_opts) as ydl:
        info = ydl.extract_info(url, download=True)
        final_file = ydl.prepare_filename(info)
        if audio:
            final_file = os.path.splitext(final_file)[0] + ".mp3"
        else:
            final_file = os.path.splitext(final_file)[0] + ".mp4"
    video_id = info.get("id")
    dislikes = {}
    try:
        r = requests.get(f"https://returnyoutubedislikeapi.com/votes?videoId={video_id}")
        dislikes = r.json()
    except:
        pass
    metadata = {
        "title": info.get("title"),
        "uploader": info.get("uploader"),
        "duration": info.get("duration"),
        "view_count": info.get("view_count"),
        "like_count": info.get("like_count"),
        "dislikes": dislikes.get("dislikes"),
        "id": video_id,
        "ext": "mp3" if audio else "mp4",
        "download_path": final_file
    }
    return metadata

@app.get("/download")
async def download(url: str = Query(...), type: str = Query("video")):
    audio = type == "audio"
    meta = process(url, audio)
    return JSONResponse(meta)

@app.get("/file")
async def file(path: str):
    if os.path.exists(path):
        resp = FileResponse(path, filename=os.path.basename(path))
        def cleanup():
            time.sleep(2)
            if os.path.exists(path):
                os.remove(path)
                os.rmdir(os.path.dirname(path))
        import threading
        threading.Thread(target=cleanup).start()
        return resp
    return JSONResponse({"error": "file not found"}, status_code=404)