|
| 1 | +"""The YouTube API.""" |
| 2 | + |
| 3 | +import asyncio |
| 4 | +from collections.abc import AsyncGenerator |
| 5 | +from dataclasses import dataclass |
| 6 | +from importlib import metadata |
| 7 | +from typing import Any, cast |
| 8 | + |
| 9 | +import async_timeout |
| 10 | +from aiohttp import ClientResponseError, ClientSession |
| 11 | +from aiohttp.hdrs import METH_GET |
| 12 | +from yarl import URL |
| 13 | + |
| 14 | +from async_python_youtube.const import HttpStatusCode |
| 15 | +from async_python_youtube.exceptions import ( |
| 16 | + YouTubeConnectionError, |
| 17 | + YouTubeError, |
| 18 | + YouTubeNotFoundError, |
| 19 | +) |
| 20 | +from async_python_youtube.helper import chunk, first |
| 21 | +from async_python_youtube.models import YouTubeVideo |
| 22 | + |
| 23 | +__all__ = [ |
| 24 | + "YouTube", |
| 25 | +] |
| 26 | + |
| 27 | +MAX_RESULTS_FOR_VIDEO = 50 |
| 28 | + |
| 29 | + |
| 30 | +@dataclass |
| 31 | +class YouTube: |
| 32 | + """YouTube API client.""" |
| 33 | + |
| 34 | + session: ClientSession | None = None |
| 35 | + request_timeout: int = 10 |
| 36 | + api_host: str = "youtube.googleapis.com" |
| 37 | + _close_session: bool = False |
| 38 | + |
| 39 | + async def _request( |
| 40 | + self, |
| 41 | + uri: str, |
| 42 | + *, |
| 43 | + data: dict[str, Any] | None = None, |
| 44 | + error_handler: dict[int, BaseException] | None = None, |
| 45 | + ) -> dict[str, Any]: |
| 46 | + """Handle a request to OpenSky. |
| 47 | +
|
| 48 | + A generic method for sending/handling HTTP requests done against |
| 49 | + OpenSky. |
| 50 | +
|
| 51 | + Args: |
| 52 | + ---- |
| 53 | + uri: the path to call. |
| 54 | + data: the query parameters to add. |
| 55 | +
|
| 56 | + Returns: |
| 57 | + ------- |
| 58 | + A Python dictionary (JSON decoded) with the response from |
| 59 | + the API. |
| 60 | +
|
| 61 | + Raises: |
| 62 | + ------ |
| 63 | + OpenSkyConnectionError: An error occurred while communicating with |
| 64 | + the OpenSky API. |
| 65 | + OpenSkyrror: Received an unexpected response from the OpenSky API. |
| 66 | + """ |
| 67 | + version = metadata.version(__package__) |
| 68 | + url = URL.build( |
| 69 | + scheme="https", |
| 70 | + host=self.api_host, |
| 71 | + port=443, |
| 72 | + path="/youtube/v3/", |
| 73 | + ).joinpath(uri) |
| 74 | + |
| 75 | + headers = { |
| 76 | + "User-Agent": f"PythonOpenSky/{version}", |
| 77 | + "Accept": "application/json, text/plain, */*", |
| 78 | + } |
| 79 | + |
| 80 | + if self.session is None: |
| 81 | + self.session = ClientSession() |
| 82 | + self._close_session = True |
| 83 | + |
| 84 | + try: |
| 85 | + async with async_timeout.timeout(self.request_timeout): |
| 86 | + response = await self.session.request( |
| 87 | + METH_GET, |
| 88 | + url.with_query(data), |
| 89 | + headers=headers, |
| 90 | + ) |
| 91 | + response.raise_for_status() |
| 92 | + except asyncio.TimeoutError as exception: |
| 93 | + msg = "Timeout occurred while connecting to the YouTube API" |
| 94 | + raise YouTubeConnectionError(msg) from exception |
| 95 | + except ClientResponseError as exception: |
| 96 | + if error_handler and exception.status in error_handler: |
| 97 | + raise error_handler[exception.status] from exception |
| 98 | + msg = "Error occurred while communicating with YouTube API" |
| 99 | + raise YouTubeConnectionError(msg) from exception |
| 100 | + |
| 101 | + content_type = response.headers.get("Content-Type", "") |
| 102 | + |
| 103 | + if "application/json" not in content_type: |
| 104 | + text = await response.text() |
| 105 | + msg = "Unexpected response from the YouTube API" |
| 106 | + raise YouTubeError( |
| 107 | + msg, |
| 108 | + {"Content-Type": content_type, "response": text}, |
| 109 | + ) |
| 110 | + |
| 111 | + return cast(dict[str, Any], await response.json()) |
| 112 | + |
| 113 | + async def get_video(self, video_id: str) -> YouTubeVideo | None: |
| 114 | + """Get a single video.""" |
| 115 | + return await first(self.get_videos([video_id])) |
| 116 | + |
| 117 | + async def get_videos( |
| 118 | + self, |
| 119 | + video_ids: list[str], |
| 120 | + ) -> AsyncGenerator[YouTubeVideo, None]: |
| 121 | + """Get a list of videos.""" |
| 122 | + error_handler: dict[int, BaseException] = { |
| 123 | + HttpStatusCode.NOT_FOUND: YouTubeNotFoundError("Video not found"), |
| 124 | + } |
| 125 | + for video_chunk in chunk(video_ids, MAX_RESULTS_FOR_VIDEO): |
| 126 | + ids = ",".join(video_chunk) |
| 127 | + data = { |
| 128 | + "part": "snippet", |
| 129 | + "id": ids, |
| 130 | + "maxResults": MAX_RESULTS_FOR_VIDEO, |
| 131 | + } |
| 132 | + res = await self._request("videos", data=data, error_handler=error_handler) |
| 133 | + for item in res["items"]: |
| 134 | + yield YouTubeVideo.parse_obj(item) |
| 135 | + |
| 136 | + async def close(self) -> None: |
| 137 | + """Close open client session.""" |
| 138 | + if self.session and self._close_session: |
| 139 | + await self.session.close() |
| 140 | + |
| 141 | + async def __aenter__(self) -> Any: |
| 142 | + """Async enter. |
| 143 | +
|
| 144 | + Returns |
| 145 | + ------- |
| 146 | + The YouTube object. |
| 147 | + """ |
| 148 | + return self |
| 149 | + |
| 150 | + async def __aexit__(self, *_exc_info: Any) -> None: |
| 151 | + """Async exit. |
| 152 | +
|
| 153 | + Args: |
| 154 | + ---- |
| 155 | + _exc_info: Exec type. |
| 156 | + """ |
| 157 | + await self.close() |
0 commit comments