1322-python 0.1.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.
- 1322_python-0.1.0.dist-info/METADATA +273 -0
- 1322_python-0.1.0.dist-info/RECORD +18 -0
- 1322_python-0.1.0.dist-info/WHEEL +4 -0
- 1322_python-0.1.0.dist-info/licenses/LICENSE +21 -0
- client1322/__init__.py +48 -0
- client1322/_backoff.py +76 -0
- client1322/_merge.py +199 -0
- client1322/client.py +114 -0
- client1322/exceptions.py +40 -0
- client1322/platforms/__init__.py +1 -0
- client1322/platforms/_base.py +191 -0
- client1322/platforms/binance.py +219 -0
- client1322/platforms/instagram.py +146 -0
- client1322/platforms/news.py +150 -0
- client1322/platforms/truth.py +189 -0
- client1322/platforms/x.py +577 -0
- client1322/platforms/youtube.py +155 -0
- client1322/py.typed +0 -0
client1322/client.py
ADDED
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
"""The unified ``Client`` facade covering all six 1322 platforms.
|
|
2
|
+
|
|
3
|
+
.. code-block:: python
|
|
4
|
+
|
|
5
|
+
from client1322 import Client
|
|
6
|
+
|
|
7
|
+
async with Client(platform="x", api_key="...") as client:
|
|
8
|
+
async for event in client.stream():
|
|
9
|
+
print(event)
|
|
10
|
+
|
|
11
|
+
Every platform is reached through the same shape: construct a
|
|
12
|
+
:class:`Client`, use it as an async context manager, and iterate
|
|
13
|
+
:meth:`Client.stream`. What differs -- necessarily, since 1322 documents a
|
|
14
|
+
different REST/WebSocket contract per platform -- is the constructor
|
|
15
|
+
keyword arguments (see each adapter's docstring under
|
|
16
|
+
:mod:`client1322.platforms`) and the type of event object ``stream()``
|
|
17
|
+
yields. REST helpers (``track``, ``untrack``, ``list_tracked``, ``health``,
|
|
18
|
+
...) are looked up on the underlying adapter, so only the methods that
|
|
19
|
+
platform's documented API actually has are available.
|
|
20
|
+
"""
|
|
21
|
+
|
|
22
|
+
from __future__ import annotations
|
|
23
|
+
|
|
24
|
+
from typing import Any, AsyncIterator, Literal
|
|
25
|
+
|
|
26
|
+
from .exceptions import ConfigurationError
|
|
27
|
+
from .platforms._base import BaseAdapter
|
|
28
|
+
from .platforms.binance import BinanceAdapter
|
|
29
|
+
from .platforms.instagram import InstagramAdapter
|
|
30
|
+
from .platforms.news import NewsAdapter
|
|
31
|
+
from .platforms.truth import TruthAdapter
|
|
32
|
+
from .platforms.x import XAdapter
|
|
33
|
+
from .platforms.youtube import YouTubeAdapter
|
|
34
|
+
|
|
35
|
+
Platform = Literal["x", "twitter", "truth", "instagram", "news", "youtube", "binance"]
|
|
36
|
+
|
|
37
|
+
_ADAPTERS: dict[str, type[BaseAdapter]] = {
|
|
38
|
+
"x": XAdapter,
|
|
39
|
+
"twitter": XAdapter,
|
|
40
|
+
"truth": TruthAdapter,
|
|
41
|
+
"instagram": InstagramAdapter,
|
|
42
|
+
"news": NewsAdapter,
|
|
43
|
+
"youtube": YouTubeAdapter,
|
|
44
|
+
"binance": BinanceAdapter,
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
class Client:
|
|
49
|
+
"""Unified async client for the 1322 real-time monitoring API.
|
|
50
|
+
|
|
51
|
+
:param platform: one of ``"x"`` (alias ``"twitter"``), ``"truth"``,
|
|
52
|
+
``"instagram"``, ``"news"``, ``"youtube"``, ``"binance"``.
|
|
53
|
+
:param api_key: the API key for that platform (from your 1322 dashboard).
|
|
54
|
+
:param kwargs: forwarded to the platform's adapter constructor. Common
|
|
55
|
+
ones: ``session`` (an existing ``aiohttp.ClientSession`` to reuse),
|
|
56
|
+
``auto_reconnect`` (default ``True``), ``backoff_base``/``backoff_cap``
|
|
57
|
+
(default 1s / 30s, matching 1322's documented reconnect policy).
|
|
58
|
+
X also takes ``tier`` (``"normal"`` or ``"ultimate"``). Truth Social
|
|
59
|
+
takes ``ws_path``/``ws_key`` (or ``ws_url``). News and Binance Square
|
|
60
|
+
take optional ``ws_path``/``ws_key``/``ws_url`` -- if omitted, they
|
|
61
|
+
are fetched automatically from that platform's ``/v1/dashboard``.
|
|
62
|
+
YouTube requires ``ws_url`` explicitly (see
|
|
63
|
+
:mod:`client1322.platforms.youtube`).
|
|
64
|
+
"""
|
|
65
|
+
|
|
66
|
+
def __init__(self, platform: Platform | str, api_key: str, **kwargs: Any) -> None:
|
|
67
|
+
key = platform.lower()
|
|
68
|
+
adapter_cls = _ADAPTERS.get(key)
|
|
69
|
+
if adapter_cls is None:
|
|
70
|
+
raise ConfigurationError(
|
|
71
|
+
f"Unknown platform {platform!r}. Choose one of: "
|
|
72
|
+
"x (or twitter), truth, instagram, news, youtube, binance."
|
|
73
|
+
)
|
|
74
|
+
self.platform: str = "x" if key == "twitter" else key
|
|
75
|
+
self._adapter: BaseAdapter = adapter_cls(api_key, **kwargs)
|
|
76
|
+
|
|
77
|
+
@property
|
|
78
|
+
def adapter(self) -> BaseAdapter:
|
|
79
|
+
"""The underlying platform adapter, for advanced/typed access."""
|
|
80
|
+
return self._adapter
|
|
81
|
+
|
|
82
|
+
async def __aenter__(self) -> "Client":
|
|
83
|
+
await self._adapter.__aenter__()
|
|
84
|
+
return self
|
|
85
|
+
|
|
86
|
+
async def __aexit__(self, *exc_info: Any) -> None:
|
|
87
|
+
await self._adapter.__aexit__(*exc_info)
|
|
88
|
+
|
|
89
|
+
async def close(self) -> None:
|
|
90
|
+
await self._adapter.close()
|
|
91
|
+
|
|
92
|
+
def stream(self) -> AsyncIterator[Any]:
|
|
93
|
+
"""Connect (with auto-reconnect) and yield typed events forever."""
|
|
94
|
+
return self._adapter.stream()
|
|
95
|
+
|
|
96
|
+
def __getattr__(self, name: str) -> Any:
|
|
97
|
+
# Delegates platform-specific REST helpers (track/untrack/list_tracked/
|
|
98
|
+
# health/dashboard/...) to the adapter, so each platform exposes
|
|
99
|
+
# exactly the methods its documented REST API actually has.
|
|
100
|
+
if name == "_adapter":
|
|
101
|
+
# Guards against recursion if __init__ raised before this was set.
|
|
102
|
+
raise AttributeError(name)
|
|
103
|
+
try:
|
|
104
|
+
return getattr(self._adapter, name)
|
|
105
|
+
except AttributeError as exc:
|
|
106
|
+
raise AttributeError(
|
|
107
|
+
f"{self.platform!r} client has no attribute {name!r}"
|
|
108
|
+
) from exc
|
|
109
|
+
|
|
110
|
+
def __repr__(self) -> str: # pragma: no cover - cosmetic
|
|
111
|
+
return f"Client(platform={self.platform!r})"
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
__all__ = ["Client", "Platform"]
|
client1322/exceptions.py
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
"""Exceptions raised by client1322."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class Client1322Error(Exception):
|
|
9
|
+
"""Base class for all errors raised by this library."""
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class ConfigurationError(Client1322Error):
|
|
13
|
+
"""Raised when a :class:`~client1322.client.Client` is misconfigured.
|
|
14
|
+
|
|
15
|
+
Examples: an unknown ``platform`` name, or a platform (Truth Social,
|
|
16
|
+
News, Binance Square, YouTube) that needs WebSocket connection details
|
|
17
|
+
the caller did not supply and that 1322 does not expose a way to infer.
|
|
18
|
+
"""
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class UnknownEventError(Client1322Error):
|
|
22
|
+
"""Raised when a WebSocket frame does not match any documented event shape."""
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class APIError(Client1322Error):
|
|
26
|
+
"""Raised when a 1322 REST call returns an HTTP error status."""
|
|
27
|
+
|
|
28
|
+
def __init__(
|
|
29
|
+
self,
|
|
30
|
+
message: str,
|
|
31
|
+
*,
|
|
32
|
+
status: int | None = None,
|
|
33
|
+
payload: Any | None = None,
|
|
34
|
+
) -> None:
|
|
35
|
+
super().__init__(message)
|
|
36
|
+
self.status = status
|
|
37
|
+
self.payload = payload
|
|
38
|
+
|
|
39
|
+
def __repr__(self) -> str: # pragma: no cover - cosmetic
|
|
40
|
+
return f"APIError({str(self)!r}, status={self.status!r}, payload={self.payload!r})"
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Per-platform adapters and typed event models."""
|
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
"""Shared WebSocket reconnect loop + REST plumbing for one 1322 platform.
|
|
2
|
+
|
|
3
|
+
Each concrete adapter (:mod:`client1322.platforms.x`,
|
|
4
|
+
:mod:`client1322.platforms.truth`, etc.) implements the small set of
|
|
5
|
+
abstract hooks below; everything else -- connecting, auto-reconnect with
|
|
6
|
+
backoff, JSON decoding, dispatching to the per-platform parser, and REST
|
|
7
|
+
request plumbing -- lives here once.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import asyncio
|
|
13
|
+
import json
|
|
14
|
+
import logging
|
|
15
|
+
from abc import ABC, abstractmethod
|
|
16
|
+
from types import TracebackType
|
|
17
|
+
from typing import Any, AsyncIterator
|
|
18
|
+
|
|
19
|
+
import aiohttp
|
|
20
|
+
|
|
21
|
+
from .._backoff import BackoffPolicy
|
|
22
|
+
from ..exceptions import APIError
|
|
23
|
+
|
|
24
|
+
logger = logging.getLogger("client1322")
|
|
25
|
+
|
|
26
|
+
#: aiohttp message types that mean "this connection is over, reconnect."
|
|
27
|
+
_TERMINAL_WS_TYPES = (
|
|
28
|
+
aiohttp.WSMsgType.CLOSED,
|
|
29
|
+
aiohttp.WSMsgType.CLOSE,
|
|
30
|
+
aiohttp.WSMsgType.CLOSING,
|
|
31
|
+
aiohttp.WSMsgType.ERROR,
|
|
32
|
+
)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class BaseAdapter(ABC):
|
|
36
|
+
"""Base class for a single platform's connection + REST logic."""
|
|
37
|
+
|
|
38
|
+
#: REST base URL for this platform, e.g. "https://api.1322.io".
|
|
39
|
+
rest_base: str
|
|
40
|
+
|
|
41
|
+
def __init__(
|
|
42
|
+
self,
|
|
43
|
+
api_key: str,
|
|
44
|
+
*,
|
|
45
|
+
session: aiohttp.ClientSession | None = None,
|
|
46
|
+
auto_reconnect: bool = True,
|
|
47
|
+
backoff_base: float = 1.0,
|
|
48
|
+
backoff_cap: float = 30.0,
|
|
49
|
+
) -> None:
|
|
50
|
+
if not api_key:
|
|
51
|
+
raise ValueError("api_key is required")
|
|
52
|
+
self.api_key = api_key
|
|
53
|
+
self._session = session
|
|
54
|
+
self._owns_session = session is None
|
|
55
|
+
self.auto_reconnect = auto_reconnect
|
|
56
|
+
self._backoff = BackoffPolicy(base=backoff_base, cap=backoff_cap)
|
|
57
|
+
self._closed = False
|
|
58
|
+
self._ws: aiohttp.ClientWebSocketResponse | None = None
|
|
59
|
+
|
|
60
|
+
# -- lifecycle ---------------------------------------------------------
|
|
61
|
+
|
|
62
|
+
async def __aenter__(self) -> "BaseAdapter":
|
|
63
|
+
if self._session is None:
|
|
64
|
+
self._session = aiohttp.ClientSession()
|
|
65
|
+
self._owns_session = True
|
|
66
|
+
self._closed = False
|
|
67
|
+
return self
|
|
68
|
+
|
|
69
|
+
async def __aexit__(
|
|
70
|
+
self,
|
|
71
|
+
exc_type: type[BaseException] | None,
|
|
72
|
+
exc: BaseException | None,
|
|
73
|
+
tb: TracebackType | None,
|
|
74
|
+
) -> None:
|
|
75
|
+
await self.close()
|
|
76
|
+
|
|
77
|
+
async def close(self) -> None:
|
|
78
|
+
self._closed = True
|
|
79
|
+
if self._ws is not None and not self._ws.closed:
|
|
80
|
+
await self._ws.close()
|
|
81
|
+
self._ws = None
|
|
82
|
+
if self._owns_session and self._session is not None:
|
|
83
|
+
await self._session.close()
|
|
84
|
+
|
|
85
|
+
def _require_session(self) -> aiohttp.ClientSession:
|
|
86
|
+
if self._session is None:
|
|
87
|
+
raise RuntimeError(
|
|
88
|
+
"No open session. Use 'async with Client(...) as client:' "
|
|
89
|
+
"(or await adapter.__aenter__()) before streaming or making "
|
|
90
|
+
"REST calls."
|
|
91
|
+
)
|
|
92
|
+
return self._session
|
|
93
|
+
|
|
94
|
+
# -- hooks implemented by each platform ---------------------------------
|
|
95
|
+
|
|
96
|
+
@abstractmethod
|
|
97
|
+
def _ws_url(self) -> str:
|
|
98
|
+
"""Return the WebSocket URL to connect to."""
|
|
99
|
+
|
|
100
|
+
@abstractmethod
|
|
101
|
+
def _ws_headers(self) -> dict[str, str]:
|
|
102
|
+
"""Return extra headers to send on the WebSocket handshake."""
|
|
103
|
+
|
|
104
|
+
@abstractmethod
|
|
105
|
+
def _rest_headers(self) -> dict[str, str]:
|
|
106
|
+
"""Return auth headers to send on REST requests."""
|
|
107
|
+
|
|
108
|
+
@abstractmethod
|
|
109
|
+
def _parse(self, raw: dict[str, Any]) -> Any:
|
|
110
|
+
"""Turn one decoded JSON frame into a typed event object."""
|
|
111
|
+
|
|
112
|
+
# -- streaming -----------------------------------------------------------
|
|
113
|
+
|
|
114
|
+
async def stream(self) -> AsyncIterator[Any]:
|
|
115
|
+
"""Connect (with auto-reconnect) and yield parsed events forever.
|
|
116
|
+
|
|
117
|
+
Reconnection follows 1322's documented policy: exponential backoff
|
|
118
|
+
starting at 1s, doubling, capped at 30s (see
|
|
119
|
+
:mod:`client1322._backoff`). No events are queued while
|
|
120
|
+
disconnected -- this matches the documented server behavior, so a
|
|
121
|
+
client that is offline will simply miss whatever happened during
|
|
122
|
+
that window, the same as any other 1322 WebSocket client.
|
|
123
|
+
|
|
124
|
+
aiohttp answers server-sent WebSocket pings with pongs at the
|
|
125
|
+
protocol layer automatically; callers do not need to handle this.
|
|
126
|
+
"""
|
|
127
|
+
self._closed = False
|
|
128
|
+
while not self._closed:
|
|
129
|
+
session = self._require_session()
|
|
130
|
+
url = self._ws_url()
|
|
131
|
+
try:
|
|
132
|
+
async with session.ws_connect(
|
|
133
|
+
url, headers=self._ws_headers(), heartbeat=30
|
|
134
|
+
) as ws:
|
|
135
|
+
self._ws = ws
|
|
136
|
+
self._backoff.reset()
|
|
137
|
+
logger.debug("client1322: connected to %s", url)
|
|
138
|
+
async for message in ws:
|
|
139
|
+
if message.type == aiohttp.WSMsgType.TEXT:
|
|
140
|
+
try:
|
|
141
|
+
payload = json.loads(message.data)
|
|
142
|
+
except json.JSONDecodeError:
|
|
143
|
+
logger.warning(
|
|
144
|
+
"client1322: dropped non-JSON frame: %.200s",
|
|
145
|
+
message.data,
|
|
146
|
+
)
|
|
147
|
+
continue
|
|
148
|
+
try:
|
|
149
|
+
yield self._parse(payload)
|
|
150
|
+
except Exception:
|
|
151
|
+
logger.exception(
|
|
152
|
+
"client1322: failed to parse event: %.200s",
|
|
153
|
+
message.data,
|
|
154
|
+
)
|
|
155
|
+
elif message.type in _TERMINAL_WS_TYPES:
|
|
156
|
+
break
|
|
157
|
+
# BINARY/PING/PONG frames: nothing to surface to callers.
|
|
158
|
+
except (aiohttp.ClientError, OSError) as exc:
|
|
159
|
+
logger.warning("client1322: websocket connection lost: %s", exc)
|
|
160
|
+
finally:
|
|
161
|
+
self._ws = None
|
|
162
|
+
|
|
163
|
+
if self._closed or not self.auto_reconnect:
|
|
164
|
+
return
|
|
165
|
+
|
|
166
|
+
delay = self._backoff.next()
|
|
167
|
+
logger.info("client1322: reconnecting in %.1fs", delay)
|
|
168
|
+
await asyncio.sleep(delay)
|
|
169
|
+
|
|
170
|
+
# -- REST ------------------------------------------------------------
|
|
171
|
+
|
|
172
|
+
async def _request(self, method: str, path: str, **kwargs: Any) -> Any:
|
|
173
|
+
session = self._require_session()
|
|
174
|
+
url = f"{self.rest_base}{path}"
|
|
175
|
+
extra_headers = kwargs.pop("headers", None) or {}
|
|
176
|
+
headers = {**self._rest_headers(), **extra_headers}
|
|
177
|
+
async with session.request(method, url, headers=headers, **kwargs) as resp:
|
|
178
|
+
text = await resp.text()
|
|
179
|
+
data: Any = None
|
|
180
|
+
if text:
|
|
181
|
+
try:
|
|
182
|
+
data = json.loads(text)
|
|
183
|
+
except json.JSONDecodeError:
|
|
184
|
+
data = text
|
|
185
|
+
if resp.status >= 400:
|
|
186
|
+
raise APIError(
|
|
187
|
+
f"{method} {path} failed with HTTP {resp.status}",
|
|
188
|
+
status=resp.status,
|
|
189
|
+
payload=data,
|
|
190
|
+
)
|
|
191
|
+
return data
|
|
@@ -0,0 +1,219 @@
|
|
|
1
|
+
"""Binance Square: REST management API + WebSocket event envelope.
|
|
2
|
+
|
|
3
|
+
Ground truth: https://1322.io/docs ("Binance Square" reference).
|
|
4
|
+
|
|
5
|
+
- REST base: https://binance.1322.io
|
|
6
|
+
- WebSocket: wss://binance.1322.io/{ws_path}?key={ws_key} -- path and key
|
|
7
|
+
come from GET /v1/dashboard. If you don't pass them explicitly, the
|
|
8
|
+
adapter fetches /v1/dashboard once before connecting.
|
|
9
|
+
- Auth: header X-Api-Key (REST). WebSocket: key= query parameter.
|
|
10
|
+
- Every WS frame is ``{type, data}``; ``type`` is ``"binance.post"`` or
|
|
11
|
+
``"binance.pin.update"``.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
from dataclasses import dataclass
|
|
17
|
+
from typing import Any, Literal, TypedDict, Union
|
|
18
|
+
|
|
19
|
+
from ..exceptions import UnknownEventError
|
|
20
|
+
from ._base import BaseAdapter
|
|
21
|
+
|
|
22
|
+
REST_BASE = "https://binance.1322.io"
|
|
23
|
+
WS_HOST = "binance.1322.io"
|
|
24
|
+
|
|
25
|
+
ContentType = Literal["post", "video", "space", "article"]
|
|
26
|
+
Tendency = Literal["bullish", "bearish", ""]
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class MediaItem(TypedDict, total=False):
|
|
30
|
+
url: str
|
|
31
|
+
type: str
|
|
32
|
+
width: int
|
|
33
|
+
height: int
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class PostPollOption(TypedDict, total=False):
|
|
37
|
+
label: str
|
|
38
|
+
votes: int
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
class PostPoll(TypedDict, total=False):
|
|
42
|
+
options: list[PostPollOption]
|
|
43
|
+
ends_at: str
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
class PostQuote(TypedDict, total=False):
|
|
47
|
+
id: str
|
|
48
|
+
username: str
|
|
49
|
+
text: str
|
|
50
|
+
url: str
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
class PostTranslation(TypedDict, total=False):
|
|
54
|
+
language: str
|
|
55
|
+
text: str
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
class SpaceLiveReplay(TypedDict, total=False):
|
|
59
|
+
url: str
|
|
60
|
+
duration_seconds: int
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
class PostResolvedLink(TypedDict, total=False):
|
|
64
|
+
url: str
|
|
65
|
+
title: str
|
|
66
|
+
description: str
|
|
67
|
+
image: str
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
class BinancePost(TypedDict, total=False):
|
|
71
|
+
id: str
|
|
72
|
+
username: str
|
|
73
|
+
display_name: str
|
|
74
|
+
avatar_url: str
|
|
75
|
+
square_uid: str
|
|
76
|
+
content_type: ContentType
|
|
77
|
+
title: str
|
|
78
|
+
text: str
|
|
79
|
+
web_link: str
|
|
80
|
+
share_link: str
|
|
81
|
+
is_reply: bool
|
|
82
|
+
parent_id: str
|
|
83
|
+
reply_count: int
|
|
84
|
+
like_count: int
|
|
85
|
+
comment_count: int
|
|
86
|
+
share_count: int
|
|
87
|
+
view_count: int
|
|
88
|
+
tendency: Tendency
|
|
89
|
+
bullish_ratio: float
|
|
90
|
+
bearish_ratio: float
|
|
91
|
+
coin_pairs: list[str]
|
|
92
|
+
hashtags: list[str]
|
|
93
|
+
mentions: list[str]
|
|
94
|
+
media: list[MediaItem]
|
|
95
|
+
poll: PostPoll
|
|
96
|
+
quote: PostQuote
|
|
97
|
+
reply_to: PostQuote
|
|
98
|
+
translation: PostTranslation
|
|
99
|
+
live_replay: SpaceLiveReplay
|
|
100
|
+
resolved_links: list[PostResolvedLink]
|
|
101
|
+
published_at: str
|
|
102
|
+
detected_at: str
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
class PinUpdate(TypedDict, total=False):
|
|
106
|
+
username: str
|
|
107
|
+
display_name: str
|
|
108
|
+
avatar_url: str
|
|
109
|
+
square_uid: str
|
|
110
|
+
added: list[BinancePost]
|
|
111
|
+
removed: list[BinancePost]
|
|
112
|
+
removed_ids: list[str]
|
|
113
|
+
note: str
|
|
114
|
+
detected_at: str
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
@dataclass(slots=True)
|
|
118
|
+
class BinancePostEvent:
|
|
119
|
+
type: Literal["binance.post"]
|
|
120
|
+
post: BinancePost
|
|
121
|
+
raw: dict[str, Any]
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
@dataclass(slots=True)
|
|
125
|
+
class BinancePinUpdateEvent:
|
|
126
|
+
type: Literal["binance.pin.update"]
|
|
127
|
+
pin: PinUpdate
|
|
128
|
+
raw: dict[str, Any]
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
BinanceEvent = Union[BinancePostEvent, BinancePinUpdateEvent]
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def parse_binance_event(raw: dict[str, Any]) -> BinanceEvent:
|
|
135
|
+
"""Parse one decoded Binance Square WebSocket frame: ``{type, data}``."""
|
|
136
|
+
event_type = raw.get("type")
|
|
137
|
+
data = raw.get("data", {})
|
|
138
|
+
if event_type == "binance.post":
|
|
139
|
+
return BinancePostEvent(type=event_type, post=data, raw=raw)
|
|
140
|
+
if event_type == "binance.pin.update":
|
|
141
|
+
return BinancePinUpdateEvent(type=event_type, pin=data, raw=raw)
|
|
142
|
+
raise UnknownEventError(f"Unrecognized Binance Square event type: {event_type!r}")
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
class BinanceAdapter(BaseAdapter):
|
|
146
|
+
"""Binance Square connection + REST management API."""
|
|
147
|
+
|
|
148
|
+
rest_base = REST_BASE
|
|
149
|
+
|
|
150
|
+
def __init__(
|
|
151
|
+
self,
|
|
152
|
+
api_key: str,
|
|
153
|
+
*,
|
|
154
|
+
ws_path: str | None = None,
|
|
155
|
+
ws_key: str | None = None,
|
|
156
|
+
ws_url: str | None = None,
|
|
157
|
+
**kwargs: Any,
|
|
158
|
+
) -> None:
|
|
159
|
+
super().__init__(api_key, **kwargs)
|
|
160
|
+
self.ws_path = ws_path
|
|
161
|
+
self.ws_key = ws_key
|
|
162
|
+
self._ws_url_override = ws_url
|
|
163
|
+
|
|
164
|
+
async def _resolve_ws(self) -> None:
|
|
165
|
+
if self._ws_url_override:
|
|
166
|
+
return
|
|
167
|
+
if self.ws_path and self.ws_key:
|
|
168
|
+
return
|
|
169
|
+
data = await self.dashboard()
|
|
170
|
+
self.ws_path = self.ws_path or data.get("ws_path")
|
|
171
|
+
self.ws_key = self.ws_key or data.get("ws_key")
|
|
172
|
+
|
|
173
|
+
def _ws_url(self) -> str:
|
|
174
|
+
if self._ws_url_override:
|
|
175
|
+
return self._ws_url_override
|
|
176
|
+
if not (self.ws_path and self.ws_key):
|
|
177
|
+
raise RuntimeError(
|
|
178
|
+
"ws_path/ws_key not resolved yet; call 'await adapter._resolve_ws()' "
|
|
179
|
+
"(done automatically by stream()), or pass ws_path/ws_key/ws_url "
|
|
180
|
+
"explicitly."
|
|
181
|
+
)
|
|
182
|
+
path = self.ws_path if self.ws_path.startswith("/") else f"/{self.ws_path}"
|
|
183
|
+
return f"wss://{WS_HOST}{path}?key={self.ws_key}"
|
|
184
|
+
|
|
185
|
+
def _ws_headers(self) -> dict[str, str]:
|
|
186
|
+
return {}
|
|
187
|
+
|
|
188
|
+
def _rest_headers(self) -> dict[str, str]:
|
|
189
|
+
return {"X-Api-Key": self.api_key}
|
|
190
|
+
|
|
191
|
+
def _parse(self, raw: dict[str, Any]) -> BinanceEvent:
|
|
192
|
+
return parse_binance_event(raw)
|
|
193
|
+
|
|
194
|
+
async def stream(self): # type: ignore[override]
|
|
195
|
+
await self._resolve_ws()
|
|
196
|
+
async for event in super().stream():
|
|
197
|
+
yield event
|
|
198
|
+
|
|
199
|
+
# -- REST: GET /v1/dashboard, POST /v1/track, POST /v1/untrack
|
|
200
|
+
|
|
201
|
+
async def dashboard(self) -> dict[str, Any]:
|
|
202
|
+
return await self._request("GET", "/v1/dashboard")
|
|
203
|
+
|
|
204
|
+
async def track(self, username: str) -> dict[str, Any]:
|
|
205
|
+
return await self._request("POST", "/v1/track", json={"username": username})
|
|
206
|
+
|
|
207
|
+
async def untrack(self, username: str) -> dict[str, Any]:
|
|
208
|
+
return await self._request("POST", "/v1/untrack", json={"username": username})
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
__all__ = [
|
|
212
|
+
"BinanceAdapter",
|
|
213
|
+
"BinanceEvent",
|
|
214
|
+
"BinancePostEvent",
|
|
215
|
+
"BinancePinUpdateEvent",
|
|
216
|
+
"BinancePost",
|
|
217
|
+
"PinUpdate",
|
|
218
|
+
"parse_binance_event",
|
|
219
|
+
]
|