oopz-sdk 0.4.3__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.
oopz/client.py ADDED
@@ -0,0 +1,370 @@
1
+ """Oopz WebSocket 客户端,支持自动重连。"""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import logging
7
+ import threading
8
+ import time
9
+ from typing import Callable, Optional
10
+
11
+ import websocket
12
+
13
+ from .config import OopzConfig
14
+ from .models import ChatMessageEvent, LifecycleEvent
15
+ from .response import error_message_from_payload, is_success_payload
16
+
17
+ logger = logging.getLogger("oopz.client")
18
+
19
+ _json_loads = json.loads
20
+
21
+ EVENT_SERVER_ID = 1
22
+ EVENT_CHAT_MESSAGE = 9
23
+ EVENT_AUTH = 253
24
+ EVENT_HEARTBEAT = 254
25
+
26
+
27
+ class OopzClient:
28
+ """Oopz WebSocket 客户端,支持自动重连。
29
+
30
+ 用法::
31
+
32
+ config = OopzConfig(...)
33
+ client = OopzClient(config, on_chat_message=my_handler)
34
+ client.start() # 阻塞运行
35
+ # 或
36
+ client.start_async() # 后台线程运行
37
+
38
+ Args:
39
+ config: SDK 配置对象。
40
+ on_chat_message: 收到聊天消息时的回调,参数为解析后的 msg_data 字典。
41
+ on_other_event: 收到非聊天事件时的回调,参数为 (event_type, data)。
42
+ reconnect_interval: 初始重连间隔(秒)。
43
+ max_reconnect_interval: 最大重连间隔(秒)。
44
+ heartbeat_interval: 心跳间隔(秒)。
45
+ """
46
+
47
+ def __init__(
48
+ self,
49
+ config: OopzConfig,
50
+ on_chat_message: Optional[Callable[[ChatMessageEvent], None]] = None,
51
+ on_other_event: Optional[Callable[[int, dict[str, object]], None]] = None,
52
+ on_lifecycle_event: Optional[Callable[[LifecycleEvent], None]] = None,
53
+ reconnect_interval: float = 2.0,
54
+ max_reconnect_interval: float = 120.0,
55
+ heartbeat_interval: float = 10.0,
56
+ ):
57
+ self._config = config
58
+ self.on_chat_message = on_chat_message
59
+ self.on_other_event = on_other_event
60
+ self.on_lifecycle_event = on_lifecycle_event
61
+ self._base_reconnect = reconnect_interval
62
+ self._max_reconnect = max_reconnect_interval
63
+ self.heartbeat_interval = heartbeat_interval
64
+
65
+ self._ws: Optional[websocket.WebSocketApp] = None
66
+ self._running = False
67
+ self._thread: Optional[threading.Thread] = None
68
+ self._consecutive_failures = 0
69
+ self._fail_lock = threading.Lock()
70
+ self._hb_body = json.dumps({"person": config.person_uid})
71
+ self._auth_confirmed = False
72
+
73
+ def _emit_lifecycle(
74
+ self,
75
+ state: str,
76
+ *,
77
+ attempt: int = 0,
78
+ code: int | None = None,
79
+ reason: str = "",
80
+ error: str = "",
81
+ payload: dict[str, object] | None = None,
82
+ ) -> None:
83
+ if not self.on_lifecycle_event:
84
+ return
85
+ try:
86
+ self.on_lifecycle_event(
87
+ LifecycleEvent(
88
+ state=state,
89
+ attempt=attempt,
90
+ code=code,
91
+ reason=reason,
92
+ error=error,
93
+ payload=payload or {},
94
+ )
95
+ )
96
+ except Exception as exc:
97
+ logger.debug("on_lifecycle_event 处理异常: %s", exc)
98
+
99
+ # ------------------------------------------------------------------
100
+ # 公共接口
101
+ # ------------------------------------------------------------------
102
+
103
+ def _next_reconnect_delay(self) -> float:
104
+ with self._fail_lock:
105
+ delay = min(
106
+ self._base_reconnect * (2 ** self._consecutive_failures),
107
+ self._max_reconnect,
108
+ )
109
+ self._consecutive_failures += 1
110
+ return delay
111
+
112
+ def start(self):
113
+ """阻塞运行(带指数退避自动重连)。"""
114
+ self._running = True
115
+ while self._running:
116
+ try:
117
+ self._emit_lifecycle("connecting", attempt=self._consecutive_failures)
118
+ self._connect_and_run()
119
+ except Exception as e:
120
+ logger.error("WebSocket 异常: %s", e)
121
+ self._emit_lifecycle("error", attempt=self._consecutive_failures, error=str(e))
122
+
123
+ if self._running:
124
+ delay = self._next_reconnect_delay()
125
+ logger.info("%.1fs 后重连 (第 %d 次)", delay, self._consecutive_failures)
126
+ self._emit_lifecycle("reconnecting", attempt=self._consecutive_failures)
127
+ time.sleep(delay)
128
+
129
+ def start_async(self):
130
+ """在后台线程中运行。"""
131
+ self._thread = threading.Thread(target=self.start, daemon=True)
132
+ self._thread.start()
133
+ return self._thread
134
+
135
+ def stop(self):
136
+ """停止客户端。"""
137
+ self._running = False
138
+ if self._ws:
139
+ self._ws.close()
140
+
141
+ # ------------------------------------------------------------------
142
+ # 内部实现
143
+ # ------------------------------------------------------------------
144
+
145
+ def _connect_and_run(self):
146
+ headers = self._config.get_headers()
147
+ ws_headers = {
148
+ "User-Agent": headers.get("User-Agent", ""),
149
+ "Origin": headers.get("Origin", ""),
150
+ "Cache-Control": headers.get("Cache-Control", ""),
151
+ "Accept-Language": headers.get("Accept-Language", ""),
152
+ "Accept-Encoding": headers.get("Accept-Encoding", ""),
153
+ }
154
+
155
+ self._ws = websocket.WebSocketApp(
156
+ self._config.ws_url,
157
+ header=ws_headers,
158
+ on_open=self._on_open,
159
+ on_message=self._on_message,
160
+ on_error=self._on_error,
161
+ on_close=self._on_close,
162
+ )
163
+
164
+ logger.info("正在连接 %s ...", self._config.ws_url)
165
+ self._ws.run_forever(
166
+ ping_interval=0,
167
+ ping_timeout=None,
168
+ )
169
+
170
+ # -- WebSocket 回调 --
171
+
172
+ def _on_open(self, ws):
173
+ logger.info("WebSocket 连接已建立")
174
+ with self._fail_lock:
175
+ self._consecutive_failures = 0
176
+ self._auth_confirmed = False
177
+ self._emit_lifecycle("connected")
178
+ self._send_auth(ws)
179
+ threading.Thread(target=self._heartbeat_loop, args=(ws,), daemon=True).start()
180
+
181
+ def _on_message(self, ws, message: str):
182
+ try:
183
+ data = _json_loads(message)
184
+ except (json.JSONDecodeError, ValueError):
185
+ logger.warning("无法解析消息: %s", message[:200])
186
+ return
187
+
188
+ event = data.get("event")
189
+
190
+ if event == EVENT_HEARTBEAT:
191
+ body_raw = data.get("body", {})
192
+ if isinstance(body_raw, str):
193
+ try:
194
+ body = _json_loads(body_raw)
195
+ except (json.JSONDecodeError, ValueError):
196
+ body = {}
197
+ elif isinstance(body_raw, dict):
198
+ body = body_raw
199
+ else:
200
+ body = {}
201
+ if body.get("r") == 1:
202
+ self._confirm_auth({"event": EVENT_HEARTBEAT, **body})
203
+ self._send_heartbeat(ws)
204
+ return
205
+
206
+ if event == EVENT_SERVER_ID:
207
+ self._confirm_auth({"event": EVENT_SERVER_ID, **data})
208
+ self._send_heartbeat(ws)
209
+ logger.info("收到 serverId,已发送首次心跳")
210
+ return
211
+
212
+ if event == EVENT_AUTH:
213
+ self._handle_auth_event(ws, data)
214
+ if self.on_other_event:
215
+ try:
216
+ self.on_other_event(event, data)
217
+ except Exception as e:
218
+ logger.debug("on_other_event 处理异常: %s", e)
219
+ return
220
+
221
+ if event == EVENT_CHAT_MESSAGE:
222
+ self._confirm_auth({"event": EVENT_CHAT_MESSAGE})
223
+ self._handle_chat(data)
224
+ return
225
+
226
+ self._confirm_auth({"event": int(event) if isinstance(event, int) else -1})
227
+ if self.on_other_event:
228
+ try:
229
+ self.on_other_event(event, data)
230
+ except Exception as e:
231
+ logger.debug("on_other_event 处理异常: %s", e)
232
+
233
+ def _on_error(self, ws, error):
234
+ logger.error("WebSocket 错误: %s", error)
235
+ self._emit_lifecycle("error", error=str(error))
236
+
237
+ def _on_close(self, ws, code, reason):
238
+ logger.warning("连接关闭 (code=%s, reason=%s)", code, reason)
239
+ self._emit_lifecycle("closed", code=code, reason=str(reason or ""))
240
+
241
+ # -- 认证 --
242
+
243
+ def _send_auth(self, ws):
244
+ cfg = self._config
245
+ auth_body = {
246
+ "person": cfg.person_uid,
247
+ "deviceId": cfg.device_id,
248
+ "signature": cfg.jwt_token,
249
+ "deviceName": cfg.device_id,
250
+ "platformName": "web",
251
+ "reconnect": 0,
252
+ }
253
+ payload = {
254
+ "time": str(int(time.time() * 1000)),
255
+ "body": json.dumps(auth_body),
256
+ "event": EVENT_AUTH,
257
+ }
258
+ ws.send(json.dumps(payload))
259
+ logger.info("已发送认证信息")
260
+ self._emit_lifecycle("auth_sent")
261
+
262
+ def _confirm_auth(self, payload: dict[str, object] | None = None) -> None:
263
+ if self._auth_confirmed:
264
+ return
265
+ self._auth_confirmed = True
266
+ logger.info("WebSocket 认证已确认")
267
+ self._emit_lifecycle("auth_ok", payload=payload or {})
268
+
269
+ def _handle_auth_event(self, ws, data: dict[str, object]) -> None:
270
+ body = self._safe_json_parse(data.get("body", {}))
271
+ candidates: list[dict[str, object]] = []
272
+ if isinstance(body, dict):
273
+ candidates.append(body)
274
+ for key in ("data", "result"):
275
+ nested = body.get(key)
276
+ if isinstance(nested, dict):
277
+ candidates.append(nested)
278
+
279
+ for candidate in candidates:
280
+ if "status" not in candidate and "success" not in candidate and "code" not in candidate:
281
+ continue
282
+ if is_success_payload(candidate):
283
+ self._confirm_auth(candidate)
284
+ return
285
+
286
+ reason = error_message_from_payload(candidate, "WebSocket 认证失败")
287
+ code = candidate.get("code")
288
+ try:
289
+ code_value = int(code) if code is not None else None
290
+ except (TypeError, ValueError):
291
+ code_value = None
292
+ logger.warning("WebSocket 认证失败: %s", reason)
293
+ self._emit_lifecycle("auth_failed", code=code_value, reason=reason, payload=candidate)
294
+ try:
295
+ ws.close()
296
+ except Exception:
297
+ logger.debug("关闭认证失败的连接时出现异常")
298
+ return
299
+
300
+ # -- 心跳 --
301
+
302
+ def _send_heartbeat(self, ws):
303
+ try:
304
+ ws.send(json.dumps({
305
+ "time": str(int(time.time() * 1000)),
306
+ "body": self._hb_body,
307
+ "event": EVENT_HEARTBEAT,
308
+ }))
309
+ except Exception as e:
310
+ logger.debug("发送心跳失败(连接可能已关闭): %s", e)
311
+
312
+ def _heartbeat_loop(self, ws):
313
+ while self._running:
314
+ time.sleep(self.heartbeat_interval)
315
+ if ws.sock and ws.sock.connected:
316
+ self._send_heartbeat(ws)
317
+ else:
318
+ break
319
+
320
+ # -- 聊天消息处理 --
321
+
322
+ @staticmethod
323
+ def _safe_json_parse(raw, fallback=None):
324
+ if isinstance(raw, dict):
325
+ return raw
326
+ if isinstance(raw, str):
327
+ try:
328
+ return _json_loads(raw)
329
+ except (json.JSONDecodeError, ValueError):
330
+ return fallback if fallback is not None else {}
331
+ return fallback if fallback is not None else {}
332
+
333
+ def _handle_chat(self, data: dict[str, object]) -> None:
334
+ try:
335
+ body = self._safe_json_parse(data.get("body", {}))
336
+ msg_data = self._safe_json_parse(body.get("data", {}))
337
+ if not msg_data:
338
+ return
339
+
340
+ if msg_data.get("person") == self._config.person_uid:
341
+ return
342
+
343
+ person_id = msg_data.get("person", "")
344
+ channel_id = msg_data.get("channel", "")
345
+ area_id = msg_data.get("area", "")
346
+
347
+ logger.info(
348
+ "[聊天] 域=%s 频道=%s 用户=%s 内容=%s",
349
+ area_id, channel_id, person_id,
350
+ msg_data.get("content", "")[:100],
351
+ )
352
+
353
+ if self.on_chat_message:
354
+ event = ChatMessageEvent(
355
+ message_id=str(msg_data.get("messageId") or msg_data.get("id") or ""),
356
+ area=str(area_id),
357
+ channel=str(channel_id),
358
+ person=str(person_id),
359
+ content=str(msg_data.get("content") or ""),
360
+ timestamp=str(msg_data.get("timestamp") or ""),
361
+ attachments=[
362
+ item for item in msg_data.get("attachments", [])
363
+ if isinstance(item, dict)
364
+ ] if isinstance(msg_data.get("attachments"), list) else [],
365
+ raw=msg_data,
366
+ )
367
+ self.on_chat_message(event)
368
+
369
+ except Exception as e:
370
+ logger.error("解析聊天消息失败: %s", e)
oopz/config.py ADDED
@@ -0,0 +1,140 @@
1
+ """Oopz SDK 配置模型。"""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass, field
6
+ from typing import Protocol
7
+
8
+
9
+ class SupportsSign(Protocol):
10
+ """最小私钥协议。"""
11
+
12
+ def sign(self, data: bytes, padding: object, algorithm: object) -> bytes:
13
+ """执行签名。"""
14
+
15
+
16
+ @dataclass
17
+ class OopzConfig:
18
+ """Oopz 平台连接所需的完整配置。
19
+
20
+ 必填字段:
21
+ device_id, person_uid, jwt_token, private_key
22
+ """
23
+
24
+ device_id: str
25
+ person_uid: str
26
+ jwt_token: str
27
+
28
+ # RSA 私钥:接受 PEM 字符串或已加载的 cryptography 私钥对象
29
+ private_key: str | bytes | SupportsSign | None = None
30
+
31
+ base_url: str = "https://gateway.oopz.cn"
32
+ ws_url: str = "wss://ws.oopz.cn"
33
+ app_version: str = "69514"
34
+ channel: str = "Web"
35
+ platform: str = "windows"
36
+ web: bool = True
37
+
38
+ default_area: str = ""
39
+ default_channel: str = ""
40
+ use_announcement_style: bool = True
41
+
42
+ agora_app_id: str = "358eebceadb94c2a9fd91ecd7b341602"
43
+ agora_init_timeout: int = 1800
44
+
45
+ # 自动撤回
46
+ auto_recall_enabled: bool = False
47
+ auto_recall_delay: int = 30
48
+
49
+ # 速率控制
50
+ rate_limit_interval: float = 0.35
51
+ request_timeout: float | tuple[float, float] = (10, 30)
52
+
53
+ # 成员缓存
54
+ area_members_cache_ttl: float = 15.0
55
+ area_members_stale_ttl: float = 300.0
56
+ query_cache_ttl: float = 15.0
57
+ query_cache_stale_ttl: float = 300.0
58
+ cache_max_entries: int = 200
59
+
60
+ # 自定义请求头(留空则使用 DEFAULT_HEADERS)
61
+ headers: dict[str, str] = field(default_factory=dict)
62
+
63
+ def __post_init__(self) -> None:
64
+ self.device_id = self._require_non_empty(self.device_id, "device_id")
65
+ self.person_uid = self._require_non_empty(self.person_uid, "person_uid")
66
+ self.jwt_token = self._require_non_empty(self.jwt_token, "jwt_token")
67
+ if self.private_key is None:
68
+ raise ValueError("private_key 不能为空")
69
+
70
+ self.default_area = str(self.default_area or "").strip()
71
+ self.default_channel = str(self.default_channel or "").strip()
72
+ self.headers = {
73
+ str(key): str(value)
74
+ for key, value in self.headers.items()
75
+ if str(key).strip()
76
+ }
77
+ self._validate_timeouts()
78
+ self._validate_cache_settings()
79
+
80
+ @staticmethod
81
+ def _require_non_empty(value: str, field_name: str) -> str:
82
+ text = str(value or "").strip()
83
+ if not text:
84
+ raise ValueError(f"{field_name} 不能为空")
85
+ return text
86
+
87
+ def _validate_timeouts(self) -> None:
88
+ timeout = self.request_timeout
89
+ if isinstance(timeout, tuple):
90
+ if len(timeout) != 2 or any(float(item) <= 0 for item in timeout):
91
+ raise ValueError("request_timeout 必须是正数或长度为 2 的正数元组")
92
+ return
93
+ if float(timeout) <= 0:
94
+ raise ValueError("request_timeout 必须大于 0")
95
+
96
+ def _validate_cache_settings(self) -> None:
97
+ for field_name in (
98
+ "area_members_cache_ttl",
99
+ "area_members_stale_ttl",
100
+ "query_cache_ttl",
101
+ "query_cache_stale_ttl",
102
+ ):
103
+ value = float(getattr(self, field_name))
104
+ if value <= 0:
105
+ raise ValueError(f"{field_name} 必须大于 0")
106
+
107
+ def require_default_area(self) -> str:
108
+ """返回默认域,未配置则抛错。"""
109
+ return self._require_non_empty(self.default_area, "default_area")
110
+
111
+ def require_default_channel(self) -> str:
112
+ """返回默认频道,未配置则抛错。"""
113
+ return self._require_non_empty(self.default_channel, "default_channel")
114
+
115
+ def get_headers(self) -> dict[str, str]:
116
+ """返回实际使用的 HTTP 请求头。"""
117
+ return self.headers if self.headers else dict(DEFAULT_HEADERS)
118
+
119
+
120
+ DEFAULT_HEADERS: dict[str, str] = {
121
+ "Accept": "*/*",
122
+ "Accept-Encoding": "gzip, deflate, br, zstd",
123
+ "Accept-Language": "zh-CN,zh;q=0.9",
124
+ "Cache-Control": "no-cache",
125
+ "Content-Type": "application/json;charset=utf-8",
126
+ "Origin": "https://web.oopz.cn",
127
+ "Pragma": "no-cache",
128
+ "Priority": "u=1, i",
129
+ "Sec-Ch-Ua": '"Chromium";v="140", "Not=A?Brand";v="24", "Google Chrome";v="140"',
130
+ "Sec-Ch-Ua-Mobile": "?0",
131
+ "Sec-Ch-Ua-Platform": '"Windows"',
132
+ "Sec-Fetch-Dest": "empty",
133
+ "Sec-Fetch-Mode": "cors",
134
+ "Sec-Fetch-Site": "same-site",
135
+ "User-Agent": (
136
+ "Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
137
+ "AppleWebKit/537.36 (KHTML, like Gecko) "
138
+ "Chrome/140.0.0.0 Safari/537.36"
139
+ ),
140
+ }
oopz/exceptions.py ADDED
@@ -0,0 +1,30 @@
1
+ """Oopz SDK 异常定义。"""
2
+
3
+
4
+ class OopzError(Exception):
5
+ """SDK 基础异常。"""
6
+
7
+
8
+ class OopzApiError(OopzError):
9
+ """平台 API 调用失败(HTTP 非 200 或业务状态异常)。"""
10
+
11
+ def __init__(self, message: str, status_code: int | None = None, response: dict | None = None):
12
+ super().__init__(message)
13
+ self.status_code = status_code
14
+ self.response = response
15
+
16
+
17
+ class OopzAuthError(OopzError):
18
+ """认证相关错误(签名失败、JWT 无效等)。"""
19
+
20
+
21
+ class OopzConnectionError(OopzError):
22
+ """WebSocket 连接错误。"""
23
+
24
+
25
+ class OopzRateLimitError(OopzApiError):
26
+ """请求被限流(HTTP 429)。"""
27
+
28
+ def __init__(self, message: str = "HTTP 429", retry_after: int = 0, **kwargs):
29
+ super().__init__(message, status_code=429, **kwargs)
30
+ self.retry_after = retry_after