neuroinfoapi-client 2.10.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- neuroinfoapi_client/__init__.py +24 -0
- neuroinfoapi_client/_internal.py +132 -0
- neuroinfoapi_client/_version.py +6 -0
- neuroinfoapi_client/client.py +386 -0
- neuroinfoapi_client/errors.py +32 -0
- neuroinfoapi_client/py.typed +2 -0
- neuroinfoapi_client/types.py +438 -0
- neuroinfoapi_client/utils.py +98 -0
- neuroinfoapi_client/websocket.py +759 -0
- neuroinfoapi_client-2.10.0.dist-info/METADATA +322 -0
- neuroinfoapi_client-2.10.0.dist-info/RECORD +13 -0
- neuroinfoapi_client-2.10.0.dist-info/WHEEL +4 -0
- neuroinfoapi_client-2.10.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
"""Python client for NeuroInfoAPI.
|
|
2
|
+
|
|
3
|
+
- :class:`NeuroInfoApiClient` - synchronous HTTP client
|
|
4
|
+
- :class:`AsyncNeuroInfoApiClient` - asyncio HTTP client
|
|
5
|
+
- :class:`NeuroInfoApiWebsocketClient` - asyncio WebSocket client for real-time events
|
|
6
|
+
|
|
7
|
+
API docs: https://neuroinfoapi.dev/api/docs
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from . import types, utils
|
|
11
|
+
from ._version import __version__
|
|
12
|
+
from .client import AsyncNeuroInfoApiClient, NeuroInfoApiClient
|
|
13
|
+
from .errors import NeuroApiError
|
|
14
|
+
from .websocket import NeuroInfoApiWebsocketClient
|
|
15
|
+
|
|
16
|
+
__all__ = [
|
|
17
|
+
"__version__",
|
|
18
|
+
"AsyncNeuroInfoApiClient",
|
|
19
|
+
"NeuroApiError",
|
|
20
|
+
"NeuroInfoApiClient",
|
|
21
|
+
"NeuroInfoApiWebsocketClient",
|
|
22
|
+
"types",
|
|
23
|
+
"utils",
|
|
24
|
+
]
|
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import logging
|
|
4
|
+
import os
|
|
5
|
+
import re
|
|
6
|
+
import threading
|
|
7
|
+
import warnings
|
|
8
|
+
from dataclasses import dataclass
|
|
9
|
+
from typing import Any, Optional
|
|
10
|
+
from urllib.parse import urlsplit, urlunsplit
|
|
11
|
+
|
|
12
|
+
from ._version import __version__
|
|
13
|
+
|
|
14
|
+
logger = logging.getLogger("neuroinfoapi_client")
|
|
15
|
+
|
|
16
|
+
API_VERSION = "v2"
|
|
17
|
+
USER_AGENT = f"niac_py@{__version__}"
|
|
18
|
+
DEFAULT_API_BASE_URL = f"neuroinfoapi.dev/api/{API_VERSION}"
|
|
19
|
+
DEFAULT_TIMEOUT = 10.0
|
|
20
|
+
|
|
21
|
+
_PROTOCOL_RE = re.compile(r"^(https?|wss?)://", re.IGNORECASE)
|
|
22
|
+
_ANY_SCHEME_RE = re.compile(r"^[a-zA-Z][a-zA-Z\d+.-]*://")
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
@dataclass(frozen=True)
|
|
26
|
+
class ClientUrls:
|
|
27
|
+
api: str
|
|
28
|
+
websocket: str
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def create_client_urls(api_base_url: Optional[str] = None, use_tls: Optional[bool] = None) -> ClientUrls:
|
|
32
|
+
"""Builds the HTTP and WebSocket base URLs from ``api_base_url`` (host + path, no protocol)."""
|
|
33
|
+
raw = api_base_url if api_base_url is not None else DEFAULT_API_BASE_URL
|
|
34
|
+
match = _PROTOCOL_RE.match(raw)
|
|
35
|
+
protocol = match.group(1).lower() if match else None
|
|
36
|
+
if protocol:
|
|
37
|
+
warnings.warn(
|
|
38
|
+
"Protocols in api_base_url are deprecated. Remove the protocol and use use_tls instead.",
|
|
39
|
+
DeprecationWarning,
|
|
40
|
+
stacklevel=3,
|
|
41
|
+
)
|
|
42
|
+
base = _PROTOCOL_RE.sub("", raw).strip("/")
|
|
43
|
+
if not base or _ANY_SCHEME_RE.match(base) or "?" in base or "#" in base:
|
|
44
|
+
raise ValueError("api_base_url must contain a host and API path without query or hash")
|
|
45
|
+
tls = use_tls if use_tls is not None else (protocol.endswith("s") if protocol else True)
|
|
46
|
+
return ClientUrls(
|
|
47
|
+
api=f"{'https' if tls else 'http'}://{base}",
|
|
48
|
+
websocket=f"{'wss' if tls else 'ws'}://{base}/ws",
|
|
49
|
+
)
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def derive_api_url(websocket_url: str) -> str:
|
|
53
|
+
"""Derives the HTTP API base URL from a full WebSocket URL."""
|
|
54
|
+
parts = urlsplit(websocket_url)
|
|
55
|
+
scheme = "http" if parts.scheme == "ws" else "https"
|
|
56
|
+
path = re.sub(r"/ws(?:/.*)?$", "", parts.path)
|
|
57
|
+
return urlunsplit((scheme, parts.netloc, path, "", "")).rstrip("/")
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def parse_api_error(body: Any, status: Optional[int]):
|
|
61
|
+
"""Extracts the structured API error from a response body, if present."""
|
|
62
|
+
from .errors import NeuroApiError
|
|
63
|
+
|
|
64
|
+
error = body.get("error") if isinstance(body, dict) else None
|
|
65
|
+
if isinstance(error, dict) and error.get("code") and error.get("message"):
|
|
66
|
+
timestamp = error.get("timestamp")
|
|
67
|
+
path = error.get("path")
|
|
68
|
+
return NeuroApiError(
|
|
69
|
+
str(error["code"]),
|
|
70
|
+
str(error["message"]),
|
|
71
|
+
status,
|
|
72
|
+
int(timestamp) if isinstance(timestamp, (int, float)) else None,
|
|
73
|
+
path if isinstance(path, str) else None,
|
|
74
|
+
)
|
|
75
|
+
return None
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
# ----- Boot check -----
|
|
79
|
+
|
|
80
|
+
_boot_check_lock = threading.Lock()
|
|
81
|
+
_boot_check_fired = False
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def _run_boot_check(api_url: str, client_api_version: str) -> None:
|
|
85
|
+
import httpx
|
|
86
|
+
|
|
87
|
+
try:
|
|
88
|
+
info_url = re.sub(r"/api/v\d+.*$", "/api", api_url) + "/info"
|
|
89
|
+
resp = httpx.get(info_url, headers={"User-Agent": USER_AGENT}, timeout=DEFAULT_TIMEOUT)
|
|
90
|
+
if not resp.is_success:
|
|
91
|
+
return
|
|
92
|
+
data = (resp.json() or {}).get("data") or {}
|
|
93
|
+
latest = data.get("latestVersion")
|
|
94
|
+
if not isinstance(latest, str) or latest == client_api_version:
|
|
95
|
+
return
|
|
96
|
+
versions = data.get("versions") or {}
|
|
97
|
+
current = versions.get(client_api_version) or {}
|
|
98
|
+
latest_info = versions.get(latest) or {}
|
|
99
|
+
status = current.get("status")
|
|
100
|
+
if status == "deprecated":
|
|
101
|
+
sunset = current.get("sunset")
|
|
102
|
+
logger.warning(
|
|
103
|
+
"API %s is deprecated and will be turned off%s.",
|
|
104
|
+
client_api_version,
|
|
105
|
+
f" on {sunset}" if isinstance(sunset, str) else "",
|
|
106
|
+
)
|
|
107
|
+
elif status == "removed":
|
|
108
|
+
docs = latest_info.get("docsUrl")
|
|
109
|
+
logger.warning(
|
|
110
|
+
"API %s is no longer available. Please update to the latest version.%s",
|
|
111
|
+
client_api_version,
|
|
112
|
+
f" See {docs}" if isinstance(docs, str) else "",
|
|
113
|
+
)
|
|
114
|
+
else:
|
|
115
|
+
logger.warning(
|
|
116
|
+
"API %s is not the latest version. The latest version is %s.", client_api_version, latest
|
|
117
|
+
)
|
|
118
|
+
except Exception:
|
|
119
|
+
# Boot check is non-critical.
|
|
120
|
+
pass
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def boot_check(api_url: str, client_api_version: str = API_VERSION) -> None:
|
|
124
|
+
"""Runs once per process in a background thread and warns when the API version is outdated."""
|
|
125
|
+
global _boot_check_fired
|
|
126
|
+
if os.environ.get("NEUROINFOAPI_DISABLE_BOOT_CHECK"):
|
|
127
|
+
return
|
|
128
|
+
with _boot_check_lock:
|
|
129
|
+
if _boot_check_fired:
|
|
130
|
+
return
|
|
131
|
+
_boot_check_fired = True
|
|
132
|
+
threading.Thread(target=_run_boot_check, args=(api_url, client_api_version), daemon=True).start()
|
|
@@ -0,0 +1,386 @@
|
|
|
1
|
+
"""HTTP clients for the NeuroInfoAPI (synchronous and asynchronous).
|
|
2
|
+
|
|
3
|
+
All methods return the response data directly and raise :class:`NeuroApiError` on errors.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import json
|
|
9
|
+
import warnings
|
|
10
|
+
from typing import Any, Dict, List, Literal, Mapping, Optional
|
|
11
|
+
from urllib.parse import urlsplit
|
|
12
|
+
|
|
13
|
+
import httpx
|
|
14
|
+
|
|
15
|
+
from ._internal import DEFAULT_TIMEOUT, USER_AGENT, boot_check, create_client_urls, parse_api_error
|
|
16
|
+
from .errors import NeuroApiError
|
|
17
|
+
from .types import (
|
|
18
|
+
BlogFeedData,
|
|
19
|
+
LatestScheduleData,
|
|
20
|
+
ScheduleData,
|
|
21
|
+
ScheduleEntryType,
|
|
22
|
+
ScheduleLinkedStreamInfo,
|
|
23
|
+
ScheduleSearchCursor,
|
|
24
|
+
ScheduleSearchResponse,
|
|
25
|
+
ScheduleWeeksResponse,
|
|
26
|
+
ShopProduct,
|
|
27
|
+
SubathonData,
|
|
28
|
+
SubathonYearsResponse,
|
|
29
|
+
TwitchStreamState,
|
|
30
|
+
TwitchVod,
|
|
31
|
+
XFeedAccount,
|
|
32
|
+
XFeedEntry,
|
|
33
|
+
)
|
|
34
|
+
|
|
35
|
+
__all__ = ["NeuroInfoApiClient", "AsyncNeuroInfoApiClient"]
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def _query_value(value: Any) -> str:
|
|
39
|
+
if isinstance(value, bool):
|
|
40
|
+
return "true" if value else "false"
|
|
41
|
+
return str(value)
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _clean_query(params: Optional[Mapping[str, Any]]) -> Optional[Dict[str, str]]:
|
|
45
|
+
if params is None:
|
|
46
|
+
return None
|
|
47
|
+
return {key: _query_value(value) for key, value in params.items() if value is not None}
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def _schedule_search_params(
|
|
51
|
+
query: str,
|
|
52
|
+
limit: Optional[int],
|
|
53
|
+
year: Optional[int],
|
|
54
|
+
sort: Optional[str],
|
|
55
|
+
type: Optional[str],
|
|
56
|
+
cursor: Optional[ScheduleSearchCursor],
|
|
57
|
+
) -> Dict[str, Any]:
|
|
58
|
+
params: Dict[str, Any] = {"query": query, "limit": limit, "year": year, "sort": sort, "type": type}
|
|
59
|
+
if cursor:
|
|
60
|
+
params["cursorYear"] = cursor["year"]
|
|
61
|
+
params["cursorWeek"] = cursor["week"]
|
|
62
|
+
return params
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def _check_path(path: str) -> str:
|
|
66
|
+
"""Only API paths are allowed, so the token is never sent to a different host."""
|
|
67
|
+
parts = urlsplit(path)
|
|
68
|
+
if parts.scheme or parts.netloc or not path.startswith("/"):
|
|
69
|
+
raise ValueError(f"Expected an API path like '/twitch/stream', got {path!r}")
|
|
70
|
+
return path
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def _parse_response(response: httpx.Response) -> Any:
|
|
74
|
+
"""Returns the unwrapped ``data`` of a response or raises :class:`NeuroApiError`."""
|
|
75
|
+
try:
|
|
76
|
+
body: Any = response.json()
|
|
77
|
+
except (json.JSONDecodeError, UnicodeDecodeError, ValueError):
|
|
78
|
+
if response.is_success and response.status_code not in (204, 205):
|
|
79
|
+
raise NeuroApiError("INVALID_JSON", "Invalid JSON response", response.status_code) from None
|
|
80
|
+
body = None
|
|
81
|
+
|
|
82
|
+
if not response.is_success:
|
|
83
|
+
raise parse_api_error(body, response.status_code) or NeuroApiError(
|
|
84
|
+
"HTTP_ERROR", f"Request failed with status {response.status_code}", response.status_code
|
|
85
|
+
)
|
|
86
|
+
|
|
87
|
+
# Unwrap the { "data": ... } envelope.
|
|
88
|
+
return body["data"] if isinstance(body, dict) and "data" in body else body
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def _network_error(error: httpx.HTTPError) -> NeuroApiError:
|
|
92
|
+
if isinstance(error, httpx.TimeoutException):
|
|
93
|
+
return NeuroApiError("NETWORK", "Request timeout")
|
|
94
|
+
return NeuroApiError("NETWORK", str(error) or "Network error")
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
class _BaseClient:
|
|
98
|
+
def __init__(
|
|
99
|
+
self,
|
|
100
|
+
token: Optional[str],
|
|
101
|
+
api_base_url: Optional[str],
|
|
102
|
+
use_tls: Optional[bool],
|
|
103
|
+
timeout: Optional[float],
|
|
104
|
+
base_url: Optional[str],
|
|
105
|
+
) -> None:
|
|
106
|
+
if api_base_url is None and base_url is not None:
|
|
107
|
+
warnings.warn("base_url is deprecated. Use api_base_url with use_tls instead.", DeprecationWarning, stacklevel=3)
|
|
108
|
+
self.api_url = base_url.rstrip("/")
|
|
109
|
+
else:
|
|
110
|
+
self.api_url = create_client_urls(api_base_url, use_tls).api
|
|
111
|
+
if timeout is None or timeout < 0:
|
|
112
|
+
timeout = DEFAULT_TIMEOUT
|
|
113
|
+
self.timeout = timeout
|
|
114
|
+
self._token: Optional[str] = token
|
|
115
|
+
boot_check(self.api_url)
|
|
116
|
+
|
|
117
|
+
def set_api_token(self, token: Optional[str]) -> None:
|
|
118
|
+
"""Sets the API token for authentication. Pass ``None`` to remove the token."""
|
|
119
|
+
self._token = token
|
|
120
|
+
|
|
121
|
+
def _headers(self) -> Dict[str, str]:
|
|
122
|
+
headers = {"User-Agent": USER_AGENT, "Content-Type": "application/json"}
|
|
123
|
+
if self._token is not None:
|
|
124
|
+
headers["Authorization"] = f"Bearer {self._token}"
|
|
125
|
+
return headers
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
class NeuroInfoApiClient(_BaseClient):
|
|
129
|
+
"""Synchronous client for the NeuroInfoAPI.
|
|
130
|
+
|
|
131
|
+
Methods return the data directly and raise :class:`NeuroApiError` on errors::
|
|
132
|
+
|
|
133
|
+
client = NeuroInfoApiClient()
|
|
134
|
+
try:
|
|
135
|
+
stream = client.get_current_stream()
|
|
136
|
+
except NeuroApiError as error:
|
|
137
|
+
print(error.code, error.message)
|
|
138
|
+
|
|
139
|
+
:param token: Optional API token. Required for VODs, ``get_schedule``, schedule search,
|
|
140
|
+
``get_subathon``, blog, X feed and shop.
|
|
141
|
+
:param api_base_url: Host and API path without protocol. Default ``neuroinfoapi.dev/api/v2``.
|
|
142
|
+
:param use_tls: Use HTTPS (default) or plain HTTP.
|
|
143
|
+
:param timeout: Request timeout in seconds. Default ``10``.
|
|
144
|
+
"""
|
|
145
|
+
|
|
146
|
+
def __init__(
|
|
147
|
+
self,
|
|
148
|
+
token: Optional[str] = None,
|
|
149
|
+
*,
|
|
150
|
+
api_base_url: Optional[str] = None,
|
|
151
|
+
use_tls: Optional[bool] = None,
|
|
152
|
+
timeout: Optional[float] = None,
|
|
153
|
+
base_url: Optional[str] = None,
|
|
154
|
+
transport: Optional[httpx.BaseTransport] = None,
|
|
155
|
+
) -> None:
|
|
156
|
+
super().__init__(token, api_base_url, use_tls, timeout, base_url)
|
|
157
|
+
self._http = httpx.Client(base_url=self.api_url, timeout=self.timeout, transport=transport)
|
|
158
|
+
|
|
159
|
+
def close(self) -> None:
|
|
160
|
+
"""Closes the underlying HTTP connection pool."""
|
|
161
|
+
self._http.close()
|
|
162
|
+
|
|
163
|
+
def __enter__(self) -> NeuroInfoApiClient:
|
|
164
|
+
return self
|
|
165
|
+
|
|
166
|
+
def __exit__(self, *exc: object) -> None:
|
|
167
|
+
self.close()
|
|
168
|
+
|
|
169
|
+
def request(self, path: str, params: Optional[Mapping[str, Any]] = None) -> Any:
|
|
170
|
+
"""Low-level GET request to an API path, e.g. ``client.request("/twitch/stream")``."""
|
|
171
|
+
try:
|
|
172
|
+
response = self._http.get(_check_path(path), params=_clean_query(params), headers=self._headers())
|
|
173
|
+
except httpx.HTTPError as error:
|
|
174
|
+
raise _network_error(error) from error
|
|
175
|
+
return _parse_response(response)
|
|
176
|
+
|
|
177
|
+
# ----- Twitch -----
|
|
178
|
+
|
|
179
|
+
def get_current_stream(self) -> TwitchStreamState:
|
|
180
|
+
"""Current Twitch stream state. Check with ``utils.is_live(stream)``."""
|
|
181
|
+
return self.request("/twitch/stream")
|
|
182
|
+
|
|
183
|
+
def get_schedule_linked_streams(self) -> List[ScheduleLinkedStreamInfo]:
|
|
184
|
+
"""Channels watched right now because a schedule entry takes place on them."""
|
|
185
|
+
return self.request("/twitch/scheduleLinkedStreams")
|
|
186
|
+
|
|
187
|
+
def get_all_vods(self) -> List[TwitchVod]:
|
|
188
|
+
"""All Twitch VODs. Requires an API token."""
|
|
189
|
+
return self.request("/twitch/vods")
|
|
190
|
+
|
|
191
|
+
def get_vod(self, id: str) -> TwitchVod:
|
|
192
|
+
"""A VOD by stream ID. Requires an API token."""
|
|
193
|
+
return self.request("/twitch/vod", {"id": id})
|
|
194
|
+
|
|
195
|
+
# ----- Schedule -----
|
|
196
|
+
|
|
197
|
+
def get_schedule(self, week: int, year: Optional[int] = None) -> ScheduleData:
|
|
198
|
+
"""Schedule for a specific week (and optional year). Requires an API token."""
|
|
199
|
+
return self.request("/schedule", {"week": week, "year": year})
|
|
200
|
+
|
|
201
|
+
def get_latest_schedule(self) -> LatestScheduleData:
|
|
202
|
+
"""Latest weekly schedule."""
|
|
203
|
+
return self.request("/schedule/latest")
|
|
204
|
+
|
|
205
|
+
def get_schedule_weeks(self) -> ScheduleWeeksResponse:
|
|
206
|
+
"""Available schedule weeks grouped by year."""
|
|
207
|
+
return self.request("/schedule/weeks")
|
|
208
|
+
|
|
209
|
+
def get_devstream_times(self) -> List[int]:
|
|
210
|
+
"""Devstream schedule timestamps."""
|
|
211
|
+
return self.request("/devstream/times")
|
|
212
|
+
|
|
213
|
+
def get_schedule_search(
|
|
214
|
+
self,
|
|
215
|
+
query: str,
|
|
216
|
+
*,
|
|
217
|
+
limit: Optional[int] = None,
|
|
218
|
+
year: Optional[int] = None,
|
|
219
|
+
sort: Optional[Literal["asc", "desc"]] = None,
|
|
220
|
+
type: Optional[ScheduleEntryType] = None,
|
|
221
|
+
cursor: Optional[ScheduleSearchCursor] = None,
|
|
222
|
+
) -> ScheduleSearchResponse:
|
|
223
|
+
"""Searches schedule entries by message text with optional filters and cursor pagination. Requires an API token."""
|
|
224
|
+
return self.request("/schedule/search", _schedule_search_params(query, limit, year, sort, type, cursor))
|
|
225
|
+
|
|
226
|
+
# ----- Subathon -----
|
|
227
|
+
|
|
228
|
+
def get_current_subathons(self) -> List[SubathonData]:
|
|
229
|
+
"""Currently active subathons (error code ``SB1`` when there is none)."""
|
|
230
|
+
return self.request("/subathon")
|
|
231
|
+
|
|
232
|
+
def get_subathon(self, year: int) -> SubathonData:
|
|
233
|
+
"""Subathon data for a specific year. Requires an API token."""
|
|
234
|
+
return self.request("/subathon", {"year": year})
|
|
235
|
+
|
|
236
|
+
def get_subathon_years(self) -> SubathonYearsResponse:
|
|
237
|
+
"""Years for which subathon data is available."""
|
|
238
|
+
return self.request("/subathon/years")
|
|
239
|
+
|
|
240
|
+
# ----- Feeds (token required) -----
|
|
241
|
+
|
|
242
|
+
def get_blog_feed(self, raw: bool = False) -> BlogFeedData:
|
|
243
|
+
"""Neuro-sama blog feed. Requires an API token."""
|
|
244
|
+
return self.request("/blog", {"raw": True} if raw else None)
|
|
245
|
+
|
|
246
|
+
def get_x_feed(self, user: XFeedAccount) -> List[XFeedEntry]:
|
|
247
|
+
"""Cached X feed for one of the supported accounts. Requires an API token."""
|
|
248
|
+
return self.request("/x-feed", {"user": user})
|
|
249
|
+
|
|
250
|
+
# ----- Shop (token required) -----
|
|
251
|
+
|
|
252
|
+
def get_shop_products(self, currency: Optional[str] = None) -> List[ShopProduct]:
|
|
253
|
+
"""Full shop catalog. Requires an API token."""
|
|
254
|
+
return self.request("/shop/products", {"currency": currency})
|
|
255
|
+
|
|
256
|
+
def get_shop_product(self, id: str, currency: Optional[str] = None) -> ShopProduct:
|
|
257
|
+
"""A shop product by ID. Requires an API token."""
|
|
258
|
+
return self.request("/shop/product", {"id": id, "currency": currency})
|
|
259
|
+
|
|
260
|
+
|
|
261
|
+
class AsyncNeuroInfoApiClient(_BaseClient):
|
|
262
|
+
"""Asynchronous (``asyncio``) client. Same methods as :class:`NeuroInfoApiClient`, but awaited::
|
|
263
|
+
|
|
264
|
+
async with AsyncNeuroInfoApiClient() as client:
|
|
265
|
+
stream = await client.get_current_stream()
|
|
266
|
+
|
|
267
|
+
:param token: Optional API token. Required for VODs, ``get_schedule``, schedule search,
|
|
268
|
+
``get_subathon``, blog, X feed and shop.
|
|
269
|
+
:param api_base_url: Host and API path without protocol. Default ``neuroinfoapi.dev/api/v2``.
|
|
270
|
+
:param use_tls: Use HTTPS (default) or plain HTTP.
|
|
271
|
+
:param timeout: Request timeout in seconds. Default ``10``.
|
|
272
|
+
"""
|
|
273
|
+
|
|
274
|
+
def __init__(
|
|
275
|
+
self,
|
|
276
|
+
token: Optional[str] = None,
|
|
277
|
+
*,
|
|
278
|
+
api_base_url: Optional[str] = None,
|
|
279
|
+
use_tls: Optional[bool] = None,
|
|
280
|
+
timeout: Optional[float] = None,
|
|
281
|
+
base_url: Optional[str] = None,
|
|
282
|
+
transport: Optional[httpx.AsyncBaseTransport] = None,
|
|
283
|
+
) -> None:
|
|
284
|
+
super().__init__(token, api_base_url, use_tls, timeout, base_url)
|
|
285
|
+
self._http = httpx.AsyncClient(base_url=self.api_url, timeout=self.timeout, transport=transport)
|
|
286
|
+
|
|
287
|
+
async def aclose(self) -> None:
|
|
288
|
+
"""Closes the underlying HTTP connection pool."""
|
|
289
|
+
await self._http.aclose()
|
|
290
|
+
|
|
291
|
+
async def __aenter__(self) -> AsyncNeuroInfoApiClient:
|
|
292
|
+
return self
|
|
293
|
+
|
|
294
|
+
async def __aexit__(self, *exc: object) -> None:
|
|
295
|
+
await self.aclose()
|
|
296
|
+
|
|
297
|
+
async def request(self, path: str, params: Optional[Mapping[str, Any]] = None) -> Any:
|
|
298
|
+
"""Low-level GET request to an API path, e.g. ``await client.request("/twitch/stream")``."""
|
|
299
|
+
try:
|
|
300
|
+
response = await self._http.get(_check_path(path), params=_clean_query(params), headers=self._headers())
|
|
301
|
+
except httpx.HTTPError as error:
|
|
302
|
+
raise _network_error(error) from error
|
|
303
|
+
return _parse_response(response)
|
|
304
|
+
|
|
305
|
+
# ----- Twitch -----
|
|
306
|
+
|
|
307
|
+
async def get_current_stream(self) -> TwitchStreamState:
|
|
308
|
+
"""Current Twitch stream state. Check with ``utils.is_live(stream)``."""
|
|
309
|
+
return await self.request("/twitch/stream")
|
|
310
|
+
|
|
311
|
+
async def get_schedule_linked_streams(self) -> List[ScheduleLinkedStreamInfo]:
|
|
312
|
+
"""Channels watched right now because a schedule entry takes place on them."""
|
|
313
|
+
return await self.request("/twitch/scheduleLinkedStreams")
|
|
314
|
+
|
|
315
|
+
async def get_all_vods(self) -> List[TwitchVod]:
|
|
316
|
+
"""All Twitch VODs. Requires an API token."""
|
|
317
|
+
return await self.request("/twitch/vods")
|
|
318
|
+
|
|
319
|
+
async def get_vod(self, id: str) -> TwitchVod:
|
|
320
|
+
"""A VOD by stream ID. Requires an API token."""
|
|
321
|
+
return await self.request("/twitch/vod", {"id": id})
|
|
322
|
+
|
|
323
|
+
# ----- Schedule -----
|
|
324
|
+
|
|
325
|
+
async def get_schedule(self, week: int, year: Optional[int] = None) -> ScheduleData:
|
|
326
|
+
"""Schedule for a specific week (and optional year). Requires an API token."""
|
|
327
|
+
return await self.request("/schedule", {"week": week, "year": year})
|
|
328
|
+
|
|
329
|
+
async def get_latest_schedule(self) -> LatestScheduleData:
|
|
330
|
+
"""Latest weekly schedule."""
|
|
331
|
+
return await self.request("/schedule/latest")
|
|
332
|
+
|
|
333
|
+
async def get_schedule_weeks(self) -> ScheduleWeeksResponse:
|
|
334
|
+
"""Available schedule weeks grouped by year."""
|
|
335
|
+
return await self.request("/schedule/weeks")
|
|
336
|
+
|
|
337
|
+
async def get_devstream_times(self) -> List[int]:
|
|
338
|
+
"""Devstream schedule timestamps."""
|
|
339
|
+
return await self.request("/devstream/times")
|
|
340
|
+
|
|
341
|
+
async def get_schedule_search(
|
|
342
|
+
self,
|
|
343
|
+
query: str,
|
|
344
|
+
*,
|
|
345
|
+
limit: Optional[int] = None,
|
|
346
|
+
year: Optional[int] = None,
|
|
347
|
+
sort: Optional[Literal["asc", "desc"]] = None,
|
|
348
|
+
type: Optional[ScheduleEntryType] = None,
|
|
349
|
+
cursor: Optional[ScheduleSearchCursor] = None,
|
|
350
|
+
) -> ScheduleSearchResponse:
|
|
351
|
+
"""Searches schedule entries by message text with optional filters and cursor pagination. Requires an API token."""
|
|
352
|
+
return await self.request("/schedule/search", _schedule_search_params(query, limit, year, sort, type, cursor))
|
|
353
|
+
|
|
354
|
+
# ----- Subathon -----
|
|
355
|
+
|
|
356
|
+
async def get_current_subathons(self) -> List[SubathonData]:
|
|
357
|
+
"""Currently active subathons (error code ``SB1`` when there is none)."""
|
|
358
|
+
return await self.request("/subathon")
|
|
359
|
+
|
|
360
|
+
async def get_subathon(self, year: int) -> SubathonData:
|
|
361
|
+
"""Subathon data for a specific year. Requires an API token."""
|
|
362
|
+
return await self.request("/subathon", {"year": year})
|
|
363
|
+
|
|
364
|
+
async def get_subathon_years(self) -> SubathonYearsResponse:
|
|
365
|
+
"""Years for which subathon data is available."""
|
|
366
|
+
return await self.request("/subathon/years")
|
|
367
|
+
|
|
368
|
+
# ----- Feeds (token required) -----
|
|
369
|
+
|
|
370
|
+
async def get_blog_feed(self, raw: bool = False) -> BlogFeedData:
|
|
371
|
+
"""Neuro-sama blog feed. Requires an API token."""
|
|
372
|
+
return await self.request("/blog", {"raw": True} if raw else None)
|
|
373
|
+
|
|
374
|
+
async def get_x_feed(self, user: XFeedAccount) -> List[XFeedEntry]:
|
|
375
|
+
"""Cached X feed for one of the supported accounts. Requires an API token."""
|
|
376
|
+
return await self.request("/x-feed", {"user": user})
|
|
377
|
+
|
|
378
|
+
# ----- Shop (token required) -----
|
|
379
|
+
|
|
380
|
+
async def get_shop_products(self, currency: Optional[str] = None) -> List[ShopProduct]:
|
|
381
|
+
"""Full shop catalog. Requires an API token."""
|
|
382
|
+
return await self.request("/shop/products", {"currency": currency})
|
|
383
|
+
|
|
384
|
+
async def get_shop_product(self, id: str, currency: Optional[str] = None) -> ShopProduct:
|
|
385
|
+
"""A shop product by ID. Requires an API token."""
|
|
386
|
+
return await self.request("/shop/product", {"id": id, "currency": currency})
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from typing import Optional
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class NeuroApiError(Exception):
|
|
7
|
+
"""Error returned by the API or raised by the client.
|
|
8
|
+
|
|
9
|
+
``code`` is the API error code (e.g. ``"SB1"``) or a client code such as
|
|
10
|
+
``"NETWORK"``, ``"HTTP_ERROR"``, ``"INVALID_JSON"``, ``"WS_ERROR"`` ...
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
def __init__(
|
|
14
|
+
self,
|
|
15
|
+
code: str,
|
|
16
|
+
message: str,
|
|
17
|
+
status: Optional[int] = None,
|
|
18
|
+
timestamp: Optional[int] = None,
|
|
19
|
+
path: Optional[str] = None,
|
|
20
|
+
) -> None:
|
|
21
|
+
super().__init__(message)
|
|
22
|
+
self.code = code
|
|
23
|
+
self.message = message
|
|
24
|
+
self.status = status
|
|
25
|
+
self.timestamp = timestamp
|
|
26
|
+
self.path = path
|
|
27
|
+
|
|
28
|
+
def __repr__(self) -> str:
|
|
29
|
+
return f"NeuroApiError(code={self.code!r}, message={self.message!r}, status={self.status!r})"
|
|
30
|
+
|
|
31
|
+
def __str__(self) -> str:
|
|
32
|
+
return f"[{self.code}] {self.message}"
|