api/endpoints/yt.py

46 lines
1.5 KiB
Python
Raw Normal View History

2024-08-13 10:50:11 -04:00
#!/usr/bin/env python3.12
import importlib
from fastapi import FastAPI
2025-02-15 21:09:33 -05:00
from fastapi.responses import JSONResponse
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
class YT(FastAPI):
2025-02-15 21:09:33 -05:00
"""
YT Endpoints
"""
def __init__(self, app: FastAPI, util,
constants) -> None: # pylint: disable=super-init-not-called
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():
2025-01-29 15:48:47 -05:00
app.add_api_route(f"/{endpoint}", handler, methods=["POST"],
2025-02-05 20:23:06 -05:00
include_in_schema=True)
2024-08-13 10:50:11 -04:00
2025-02-15 21:09:33 -05:00
async def yt_video_search_handler(self, data: ValidYTSearchRequest) -> JSONResponse:
2024-08-13 10:50:11 -04:00
"""
Search for YT Video by Title (closest match returned)
2025-02-05 20:23:06 -05:00
- **t**: Title to search
2024-08-13 10:50:11 -04:00
"""
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:
2025-02-15 21:09:33 -05:00
return JSONResponse(status_code=404, content={
2025-02-11 20:01:07 -05:00
'err': True,
'errorText': 'No result.',
2025-02-15 21:09:33 -05:00
})
yt_video_id: Union[str, bool] = yts_res[0].get('id', False)
2024-08-13 10:50:11 -04:00
2025-02-15 21:09:33 -05:00
return JSONResponse(content={
2024-08-13 10:50:11 -04:00
'video_id': yt_video_id,
2025-02-15 21:09:33 -05:00
'extras': yts_res[0],
})