Files
api/endpoints/yt.py

54 lines
1.6 KiB
Python
Raw Normal View History

2024-08-13 10:50:11 -04:00
import importlib
2025-07-01 11:38:38 -04:00
from fastapi import FastAPI, Depends
2025-02-15 21:09:33 -05:00
from fastapi.responses import JSONResponse
2025-07-01 11:38:38 -04:00
from fastapi_throttle import RateLimiter
2025-02-15 21:09:33 -05:00
from typing import Optional, Union
2025-02-11 11:19:52 -05:00
from .constructors import ValidYTSearchRequest
2024-08-13 10:50:11 -04:00
2024-08-13 10:50:11 -04:00
class YT(FastAPI):
2025-02-15 21:09:33 -05:00
"""
YT Endpoints
"""
def __init__(self, app: FastAPI, util, constants) -> None:
2025-02-15 21:09:33 -05:00
self.app: FastAPI = app
2024-08-13 10:50:11 -04:00
self.util = util
self.constants = constants
self.ytsearch = importlib.import_module("youtube_search_async").YoutubeSearch()
2025-02-11 20:01:07 -05:00
self.endpoints: dict = {
2025-02-05 20:23:06 -05:00
"yt/search": self.yt_video_search_handler,
}
2024-08-13 10:50:11 -04:00
for endpoint, handler in self.endpoints.items():
app.add_api_route(
f"/{endpoint}",
handler,
methods=["POST"],
include_in_schema=True,
dependencies=[Depends(RateLimiter(times=2, seconds=2))],
)
2025-02-15 21:09:33 -05:00
async def yt_video_search_handler(self, data: ValidYTSearchRequest) -> JSONResponse:
2025-05-21 07:28:42 -04:00
"""Search for YT Video by Title (closest match returned)"""
2025-02-11 20:01:07 -05:00
title: str = data.t
yts_res: Optional[list[dict]] = await self.ytsearch.search(title)
if not yts_res:
return JSONResponse(
status_code=404,
content={
"err": True,
"errorText": "No result.",
},
)
yt_video_id: Union[str, bool] = yts_res[0].get("id", False)
return JSONResponse(
content={
"video_id": yt_video_id,
"extras": yts_res[0],
}
)