python-xiaobiu 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.
- python_xiaobiu-0.1.0.dist-info/METADATA +68 -0
- python_xiaobiu-0.1.0.dist-info/RECORD +9 -0
- python_xiaobiu-0.1.0.dist-info/WHEEL +4 -0
- python_xiaobiu-0.1.0.dist-info/entry_points.txt +2 -0
- xiaobiu/__init__.py +35 -0
- xiaobiu/captcha_bridge.py +405 -0
- xiaobiu/client.py +1558 -0
- xiaobiu/crypto.py +66 -0
- xiaobiu/models.py +133 -0
xiaobiu/client.py
ADDED
|
@@ -0,0 +1,1558 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import argparse
|
|
4
|
+
import base64
|
|
5
|
+
import hashlib
|
|
6
|
+
import html
|
|
7
|
+
import hmac
|
|
8
|
+
import json
|
|
9
|
+
import re
|
|
10
|
+
import time
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
from typing import Any
|
|
13
|
+
from urllib.parse import urlsplit
|
|
14
|
+
from uuid import uuid4
|
|
15
|
+
|
|
16
|
+
import requests
|
|
17
|
+
from requests.cookies import create_cookie
|
|
18
|
+
|
|
19
|
+
from .captcha_bridge import LocalCaptchaBridge
|
|
20
|
+
from .crypto import SuAESCipher, rsa_encrypt_base64
|
|
21
|
+
from .models import (
|
|
22
|
+
AirConditionerStatus,
|
|
23
|
+
AuthState,
|
|
24
|
+
CaptchaSolution,
|
|
25
|
+
FamilyInfo,
|
|
26
|
+
HAClimatePreview,
|
|
27
|
+
LoginPageConfig,
|
|
28
|
+
PersistedSessionState,
|
|
29
|
+
SerializedCookie,
|
|
30
|
+
SignedRequestTemplate,
|
|
31
|
+
)
|
|
32
|
+
|
|
33
|
+
DEFAULT_LOGIN_URL = "https://passport.suning.com/ids/login"
|
|
34
|
+
DEFAULT_TARGET_URL = "https://www.suning.com/"
|
|
35
|
+
DEFAULT_TIMEOUT = 20.0
|
|
36
|
+
DEFAULT_USER_AGENT = (
|
|
37
|
+
"Mozilla/5.0 (X11; Linux x86_64) "
|
|
38
|
+
"AppleWebKit/537.36 (KHTML, like Gecko) "
|
|
39
|
+
"Chrome/134.0.0.0 Safari/537.36"
|
|
40
|
+
)
|
|
41
|
+
DEFAULT_APP_USER_AGENT = "SmartHome/6.4.7 (Android; Android 14; Scale/3.00)"
|
|
42
|
+
DEFAULT_APP_TERMINAL_TYPE = "SHCSS_ANDROID"
|
|
43
|
+
DEFAULT_APP_ACCEPT_LANGUAGE = "zh-Hans-US;q=1, zh-Hant-US;q=0.9, en-US;q=0.8, ja-US;q=0.7"
|
|
44
|
+
APP_API_GS_SIGN_SECRET = "ad71cef5-c46a-48f7-a810-61f4be3a207a"
|
|
45
|
+
MOBILE_SMS_LOGIN_APP_CODE = "7b8e1574afdd47a8a14766c4f003cff7"
|
|
46
|
+
MOBILE_SMS_LOGIN_SCENE_ID = "PASSPORT_XIAOBIU"
|
|
47
|
+
MOBILE_SMS_LOGIN_CHANNEL = "MOBILE"
|
|
48
|
+
MOBILE_SMS_LOGIN_ORDER_CHANNEL = "208000201090"
|
|
49
|
+
MOBILE_SMS_LOGIN_THEME = "zn"
|
|
50
|
+
MOBILE_SMS_LOGIN_APP_VERSION = "6.4.5"
|
|
51
|
+
MOBILE_SMS_LOGIN_SUB_MODE = "11"
|
|
52
|
+
MOBILE_SMS_LOGIN_REMEMBER_ME_TYPE = "app"
|
|
53
|
+
SMS_RATE_LIMIT_ERROR_CODE = "00201"
|
|
54
|
+
MEMBER_BASE_INFO_URL = "https://shcss.suning.com/shcss-web/api/member/queryMemberBaseInfo.do"
|
|
55
|
+
FAMILY_LIST_URL = "https://itapig.suning.com/api/trade/shcss/queryAllFamily"
|
|
56
|
+
DEVICE_LIST_URL = "https://itapig.suning.com/api/trade/shcss/all"
|
|
57
|
+
OPENSH_GET_KEY_URL = "https://opensh.suning.com/shsys-web/cc/api/v3/getKey"
|
|
58
|
+
SUCCESS_RESPONSE_CODES = {"0", "SUCCESS"}
|
|
59
|
+
AIR_CONDITIONER_CATEGORY_ID = "0002"
|
|
60
|
+
AIR_CONDITIONER_NAME_KEYWORD = "空调"
|
|
61
|
+
SERVICE_BOOTSTRAP_URLS = {
|
|
62
|
+
"shcss": MEMBER_BASE_INFO_URL,
|
|
63
|
+
"itapig": "http://itapig.suning.com/api/trade/shcss/queryAllFamily",
|
|
64
|
+
"opensh": OPENSH_GET_KEY_URL,
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
DEFAULT_LOGIN_PAGE_CONFIG = LoginPageConfig(
|
|
68
|
+
login_pbk=(
|
|
69
|
+
"MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQComqoAyvbCqO1EGsADwfNTWFQIUbm8"
|
|
70
|
+
"CLdeb9TgjGLcz95mAo204SqTYdSEUxFsOnPfROOTxhkhfjbRxBV4/xjS06Y+kkUdiMG"
|
|
71
|
+
"FtABIxRQHQIh0LrVvEZQs4NrixxcPI+b1bpE0gO/GAFSNWm9ejhZGj7UnqiHphnSJAVQ"
|
|
72
|
+
"Nz2lgowIDAQAB"
|
|
73
|
+
),
|
|
74
|
+
rdsy_key=(
|
|
75
|
+
"MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDZnlkciI+qxNATzQOOcU8rxtfJxlbj"
|
|
76
|
+
"RKEhoz1WhuAFuCe6ZHEh85UjGiG0FN0oBCKoC4aprTlzNDEr/cU2bzTJELhs9xoU80Um"
|
|
77
|
+
"364GY0zbMr1qnnSouyv0Wb/sgrB/cTDmw8HNiX77mCmX+R4Un/6Xj3BBpm52CHn3RXI9"
|
|
78
|
+
"HeE/xwIDAQAB"
|
|
79
|
+
),
|
|
80
|
+
rdsy_app_code="9FAD2DDEFE754D604779F7BB8264C80F",
|
|
81
|
+
step_flag="8763EC7BB5D7EEE18EDD1E4BD59A1679",
|
|
82
|
+
step_two_flag="3D58885D2B0CB135703770C03852E8CB",
|
|
83
|
+
step_three_flag="08DD83216388DA0A29B5B3CEE0CC0E6F",
|
|
84
|
+
rdsy_scene_id="PASSPORT",
|
|
85
|
+
rdsy_scene_id_yghk="PASSPORT_YGHK",
|
|
86
|
+
channel="PC",
|
|
87
|
+
check_account_key=(
|
|
88
|
+
"MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCOuozMgVH/glMcCOIDKjXP83zDmgi6"
|
|
89
|
+
"hKvwB9VLQG6RWcxm/lNmB/Uq3LGdKUnm+JBFy1GeHA8oNKLFROF/ebzSqr6kOkuSsAZm"
|
|
90
|
+
"cvsvgaigD7cSzIipdfJpE3bZd9y7X8Mq+uDhNKpvlH9lR+OmTgMFAKq8w6QMYY+ksHjW"
|
|
91
|
+
"INSDIwIDAQAB"
|
|
92
|
+
),
|
|
93
|
+
)
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
class SuningError(RuntimeError):
|
|
97
|
+
pass
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
class CaptchaRequiredError(SuningError):
|
|
101
|
+
def __init__(self, risk_type: str, message: str, sms_ticket: str | None = None) -> None:
|
|
102
|
+
super().__init__(message)
|
|
103
|
+
self.risk_type = risk_type
|
|
104
|
+
self.sms_ticket = sms_ticket
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
class SmsRateLimitedError(SuningError):
|
|
108
|
+
def __init__(self, message: str, *, error_code: str = SMS_RATE_LIMIT_ERROR_CODE) -> None:
|
|
109
|
+
super().__init__(message)
|
|
110
|
+
self.error_code = error_code
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
class AuthenticationError(SuningError):
|
|
114
|
+
pass
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def parse_jsonp_or_json(payload: str) -> dict[str, Any]:
|
|
118
|
+
text = payload.strip()
|
|
119
|
+
if not text:
|
|
120
|
+
raise SuningError("empty response")
|
|
121
|
+
if text[0] == "{":
|
|
122
|
+
return json.loads(text)
|
|
123
|
+
match = re.match(r"^[^(]+\((.*)\)\s*;?\s*$", text, re.S)
|
|
124
|
+
if not match:
|
|
125
|
+
raise SuningError(f"unable to parse jsonp payload: {text[:120]!r}")
|
|
126
|
+
return json.loads(match.group(1))
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def _extract_business_error_code(*values: Any) -> str | None:
|
|
130
|
+
for value in values:
|
|
131
|
+
if value is None:
|
|
132
|
+
continue
|
|
133
|
+
text = str(value).strip()
|
|
134
|
+
if not text:
|
|
135
|
+
continue
|
|
136
|
+
if re.fullmatch(r"\d{5}", text):
|
|
137
|
+
return text
|
|
138
|
+
match = re.search(r"\((\d{5})\)\s*$", text)
|
|
139
|
+
if match:
|
|
140
|
+
return match.group(1)
|
|
141
|
+
return None
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def parse_login_page_config(html: str) -> LoginPageConfig:
|
|
145
|
+
def extract(pattern: str, name: str) -> str:
|
|
146
|
+
match = re.search(pattern, html, re.S)
|
|
147
|
+
if not match:
|
|
148
|
+
raise SuningError(f"missing {name} in login page")
|
|
149
|
+
return match.group(1)
|
|
150
|
+
|
|
151
|
+
config = LoginPageConfig(
|
|
152
|
+
login_pbk=extract(r'var\s+loginPBK="([^"]+)"', "loginPBK"),
|
|
153
|
+
rdsy_key=extract(r'var\s+rdsyKey="([^"]+)"', "rdsyKey"),
|
|
154
|
+
rdsy_app_code=extract(r'rdsyAppCode:"([^"]+)"', "rdsyAppCode"),
|
|
155
|
+
step_flag=extract(r'stepFlag:"([^"]+)"', "stepFlag"),
|
|
156
|
+
step_two_flag=extract(r'stepTwoFlag:"([^"]+)"', "stepTwoFlag"),
|
|
157
|
+
step_three_flag=extract(r'stepThreeFlag:"([^"]+)"', "stepThreeFlag"),
|
|
158
|
+
rdsy_scene_id=extract(r'rdsySceneId:"([^"]+)"', "rdsySceneId"),
|
|
159
|
+
rdsy_scene_id_yghk=extract(r'rdsySceneIdYGHK:"([^"]+)"', "rdsySceneIdYGHK"),
|
|
160
|
+
channel=extract(r'channel:"([^"]+)"', "channel"),
|
|
161
|
+
check_account_key=extract(r'checkAccountKey:\s*"([^"]+)"', "checkAccountKey"),
|
|
162
|
+
)
|
|
163
|
+
return config
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def extract_risk_context_script_urls(html_text: str) -> list[str]:
|
|
167
|
+
patterns = [
|
|
168
|
+
r'<script[^>]+src="(https://mmds\.suning\.com/mmds/mmds\.js[^"]+)"',
|
|
169
|
+
r'<script[^>]+src="(https://oss\.suning\.com/mmds/mmds/js/[^"]+\.js)"',
|
|
170
|
+
r'<script[^>]+src="(https://dfp\.suning\.com/dfprs-collect/dist/fp\.js[^"]+)"',
|
|
171
|
+
]
|
|
172
|
+
urls: list[str] = []
|
|
173
|
+
for pattern in patterns:
|
|
174
|
+
match = re.search(pattern, html_text, re.I)
|
|
175
|
+
if not match:
|
|
176
|
+
continue
|
|
177
|
+
url = html.unescape(match.group(1))
|
|
178
|
+
if url not in urls:
|
|
179
|
+
urls.append(url)
|
|
180
|
+
return urls
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
def _normalize_url(url: str) -> str:
|
|
184
|
+
parts = urlsplit(url)
|
|
185
|
+
return f"{parts.scheme}://{parts.netloc}{parts.path}"
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
def _canonicalize_request_body(raw_body: str | None, content_type: str | None = None) -> str:
|
|
189
|
+
if not raw_body:
|
|
190
|
+
return ""
|
|
191
|
+
body = raw_body.strip()
|
|
192
|
+
if "json" in (content_type or "").lower():
|
|
193
|
+
try:
|
|
194
|
+
return json.dumps(json.loads(body), separators=(",", ":"), ensure_ascii=False)
|
|
195
|
+
except json.JSONDecodeError:
|
|
196
|
+
return body
|
|
197
|
+
return body
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
def _build_gs_sign_payload(url_path: str, request_time: int | str, body: str | None) -> str:
|
|
201
|
+
canonical_body = _canonicalize_request_body(body, "application/json")
|
|
202
|
+
payload = f"url={url_path}&requestTime={request_time}&data={canonical_body}"
|
|
203
|
+
return payload.replace(" ", "").replace("\n", "").replace("\r", "")
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
def _build_gs_sign(url_path: str, request_time: int | str, body: str | None) -> str:
|
|
207
|
+
payload = _build_gs_sign_payload(url_path, request_time, body)
|
|
208
|
+
return hmac.new(
|
|
209
|
+
APP_API_GS_SIGN_SECRET.encode("utf-8"),
|
|
210
|
+
payload.encode("utf-8"),
|
|
211
|
+
hashlib.sha256,
|
|
212
|
+
).hexdigest()
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
def _decode_har_content(content: dict[str, Any]) -> str:
|
|
216
|
+
text = content.get("text") or ""
|
|
217
|
+
if content.get("encoding") == "base64":
|
|
218
|
+
return base64.b64decode(text).decode("utf-8", "replace")
|
|
219
|
+
return text
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
def _extract_har_headers(entry: dict[str, Any]) -> dict[str, str]:
|
|
223
|
+
return {
|
|
224
|
+
item["name"]: item["value"]
|
|
225
|
+
for item in entry.get("request", {}).get("headers", [])
|
|
226
|
+
if "name" in item and "value" in item
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
|
|
230
|
+
def _har_response_payload(entry: dict[str, Any]) -> dict[str, Any] | None:
|
|
231
|
+
content = entry.get("response", {}).get("content") or {}
|
|
232
|
+
text = _decode_har_content(content).strip()
|
|
233
|
+
if not text:
|
|
234
|
+
return None
|
|
235
|
+
try:
|
|
236
|
+
return json.loads(text)
|
|
237
|
+
except json.JSONDecodeError:
|
|
238
|
+
return parse_jsonp_or_json(text)
|
|
239
|
+
|
|
240
|
+
|
|
241
|
+
def _har_entry_is_success(entry: dict[str, Any]) -> bool:
|
|
242
|
+
if entry.get("response", {}).get("status") != 200:
|
|
243
|
+
return False
|
|
244
|
+
payload = _har_response_payload(entry)
|
|
245
|
+
if not payload:
|
|
246
|
+
return False
|
|
247
|
+
return str(payload.get("responseCode") or payload.get("code") or "").upper() in SUCCESS_RESPONSE_CODES
|
|
248
|
+
|
|
249
|
+
|
|
250
|
+
def _template_key(method: str, url: str, body: str) -> tuple[str, str, str]:
|
|
251
|
+
return (method.upper(), _normalize_url(url), body)
|
|
252
|
+
|
|
253
|
+
|
|
254
|
+
def _coalesce(*values: Any) -> Any:
|
|
255
|
+
for value in values:
|
|
256
|
+
if value is None:
|
|
257
|
+
continue
|
|
258
|
+
if isinstance(value, str) and not value.strip():
|
|
259
|
+
continue
|
|
260
|
+
return value
|
|
261
|
+
return None
|
|
262
|
+
|
|
263
|
+
|
|
264
|
+
def _parse_bool_flag(value: Any) -> bool | None:
|
|
265
|
+
normalized = str(value).strip().lower()
|
|
266
|
+
if not normalized:
|
|
267
|
+
return None
|
|
268
|
+
if normalized in {"1", "true", "on", "yes"}:
|
|
269
|
+
return True
|
|
270
|
+
if normalized in {"0", "false", "off", "no"}:
|
|
271
|
+
return False
|
|
272
|
+
return None
|
|
273
|
+
|
|
274
|
+
|
|
275
|
+
def _parse_float_value(value: Any) -> float | None:
|
|
276
|
+
if value is None:
|
|
277
|
+
return None
|
|
278
|
+
normalized = str(value).strip()
|
|
279
|
+
if not normalized:
|
|
280
|
+
return None
|
|
281
|
+
try:
|
|
282
|
+
return float(normalized)
|
|
283
|
+
except ValueError:
|
|
284
|
+
return None
|
|
285
|
+
|
|
286
|
+
|
|
287
|
+
def _strip_html_text(value: Any) -> str | None:
|
|
288
|
+
if value is None:
|
|
289
|
+
return None
|
|
290
|
+
text = html.unescape(str(value))
|
|
291
|
+
text = re.sub(r"<[^>]+>", "", text)
|
|
292
|
+
normalized = text.strip()
|
|
293
|
+
return normalized or None
|
|
294
|
+
|
|
295
|
+
|
|
296
|
+
def _infer_swing_mode(horizontal: bool | None, vertical: bool | None) -> str | None:
|
|
297
|
+
if horizontal is True and vertical is True:
|
|
298
|
+
return "both"
|
|
299
|
+
if horizontal is True:
|
|
300
|
+
return "horizontal"
|
|
301
|
+
if vertical is True:
|
|
302
|
+
return "vertical"
|
|
303
|
+
if horizontal is False and vertical is False:
|
|
304
|
+
return "off"
|
|
305
|
+
return None
|
|
306
|
+
|
|
307
|
+
|
|
308
|
+
def _serialize_cookie(cookie: Any) -> SerializedCookie:
|
|
309
|
+
return SerializedCookie(
|
|
310
|
+
name=cookie.name,
|
|
311
|
+
value=cookie.value,
|
|
312
|
+
domain=cookie.domain,
|
|
313
|
+
path=cookie.path,
|
|
314
|
+
secure=cookie.secure,
|
|
315
|
+
expires=cookie.expires,
|
|
316
|
+
rest=getattr(cookie, "_rest", {}) or {},
|
|
317
|
+
)
|
|
318
|
+
|
|
319
|
+
|
|
320
|
+
def _restore_cookie(serialized_cookie: SerializedCookie) -> Any:
|
|
321
|
+
return create_cookie(
|
|
322
|
+
name=serialized_cookie.name,
|
|
323
|
+
value=serialized_cookie.value,
|
|
324
|
+
domain=serialized_cookie.domain,
|
|
325
|
+
path=serialized_cookie.path,
|
|
326
|
+
secure=serialized_cookie.secure,
|
|
327
|
+
expires=serialized_cookie.expires,
|
|
328
|
+
rest=serialized_cookie.rest,
|
|
329
|
+
)
|
|
330
|
+
|
|
331
|
+
|
|
332
|
+
class SuningSmartHomeClient:
|
|
333
|
+
def __init__(
|
|
334
|
+
self,
|
|
335
|
+
*,
|
|
336
|
+
state_path: str | Path | None = None,
|
|
337
|
+
har_path: str | Path | None = None,
|
|
338
|
+
load_state: bool = True,
|
|
339
|
+
detect: str | None = None,
|
|
340
|
+
dfp_token: str | None = None,
|
|
341
|
+
timeout: float = DEFAULT_TIMEOUT,
|
|
342
|
+
user_agent: str = DEFAULT_USER_AGENT,
|
|
343
|
+
app_user_agent: str = DEFAULT_APP_USER_AGENT,
|
|
344
|
+
app_terminal_type: str = DEFAULT_APP_TERMINAL_TYPE,
|
|
345
|
+
) -> None:
|
|
346
|
+
self.timeout = timeout
|
|
347
|
+
self.state_path = Path(state_path) if state_path else None
|
|
348
|
+
self.har_path = Path(har_path) if har_path else None
|
|
349
|
+
self.app_user_agent = app_user_agent
|
|
350
|
+
self.app_terminal_type = app_terminal_type
|
|
351
|
+
self.session = requests.Session()
|
|
352
|
+
self.session.headers.update(
|
|
353
|
+
{
|
|
354
|
+
"Accept": "*/*",
|
|
355
|
+
"User-Agent": user_agent,
|
|
356
|
+
}
|
|
357
|
+
)
|
|
358
|
+
self.suaes = SuAESCipher()
|
|
359
|
+
self.config = DEFAULT_LOGIN_PAGE_CONFIG
|
|
360
|
+
self.state = AuthState()
|
|
361
|
+
self.signed_templates: dict[tuple[str, str, str], SignedRequestTemplate] = {}
|
|
362
|
+
self.risk_context_script_urls: list[str] = []
|
|
363
|
+
if detect:
|
|
364
|
+
self.state.detect = detect
|
|
365
|
+
if dfp_token:
|
|
366
|
+
self.state.dfp_token = dfp_token
|
|
367
|
+
if load_state and self.state_path and self.state_path.exists():
|
|
368
|
+
self.load_state()
|
|
369
|
+
if self.har_path:
|
|
370
|
+
self.load_signed_templates()
|
|
371
|
+
|
|
372
|
+
def update_risk_context(self, *, detect: str | None = None, dfp_token: str | None = None) -> None:
|
|
373
|
+
if detect:
|
|
374
|
+
self.state.detect = detect
|
|
375
|
+
if dfp_token:
|
|
376
|
+
self.state.dfp_token = dfp_token
|
|
377
|
+
self._touch_state()
|
|
378
|
+
|
|
379
|
+
def reset_sms_login_state(self) -> None:
|
|
380
|
+
self.state.risk_type = None
|
|
381
|
+
self.state.sms_ticket = None
|
|
382
|
+
self.state.login_ticket = None
|
|
383
|
+
self._touch_state()
|
|
384
|
+
|
|
385
|
+
def initialize(self) -> LoginPageConfig:
|
|
386
|
+
response = self.session.get(
|
|
387
|
+
DEFAULT_LOGIN_URL,
|
|
388
|
+
timeout=self.timeout,
|
|
389
|
+
)
|
|
390
|
+
response.raise_for_status()
|
|
391
|
+
try:
|
|
392
|
+
self.config = parse_login_page_config(response.text)
|
|
393
|
+
except SuningError:
|
|
394
|
+
self.config = DEFAULT_LOGIN_PAGE_CONFIG
|
|
395
|
+
script_urls = extract_risk_context_script_urls(response.text)
|
|
396
|
+
if script_urls:
|
|
397
|
+
self.risk_context_script_urls = script_urls
|
|
398
|
+
self._touch_state()
|
|
399
|
+
return self.config
|
|
400
|
+
|
|
401
|
+
def prepare_sms_login(
|
|
402
|
+
self,
|
|
403
|
+
phone_number: str,
|
|
404
|
+
*,
|
|
405
|
+
international_code: str = "0086",
|
|
406
|
+
) -> dict[str, Any]:
|
|
407
|
+
self.initialize()
|
|
408
|
+
self.state.phone_number = phone_number
|
|
409
|
+
self.state.international_code = international_code
|
|
410
|
+
request_body = self._build_prepare_sms_login_payload(
|
|
411
|
+
phone_number=phone_number,
|
|
412
|
+
international_code=international_code,
|
|
413
|
+
)
|
|
414
|
+
payload = {
|
|
415
|
+
"_x_rdsy_block_": self.suaes.encrypt(
|
|
416
|
+
json.dumps(request_body, separators=(",", ":"), ensure_ascii=False)
|
|
417
|
+
),
|
|
418
|
+
"callback": self._rdsy_callback(international_code, "needVerifyCode"),
|
|
419
|
+
}
|
|
420
|
+
response = self.session.post(
|
|
421
|
+
"https://rdsy.suning.com/rdsy/needVerifyCode.do",
|
|
422
|
+
data=payload,
|
|
423
|
+
timeout=self.timeout,
|
|
424
|
+
headers={
|
|
425
|
+
"Content-Type": "application/x-www-form-urlencoded",
|
|
426
|
+
"Referer": DEFAULT_LOGIN_URL,
|
|
427
|
+
},
|
|
428
|
+
)
|
|
429
|
+
response.raise_for_status()
|
|
430
|
+
outer = parse_jsonp_or_json(response.text)
|
|
431
|
+
inner = self._decrypt_rdsy_response(outer)
|
|
432
|
+
if inner.get("status") != "COMPLETE":
|
|
433
|
+
raise SuningError(inner.get("msg") or "failed to prepare sms login")
|
|
434
|
+
self.state.sms_ticket = inner["data"].get("ticket")
|
|
435
|
+
self.state.risk_type = inner["data"].get("riskType")
|
|
436
|
+
self._touch_state()
|
|
437
|
+
return inner
|
|
438
|
+
|
|
439
|
+
def send_sms_code(
|
|
440
|
+
self,
|
|
441
|
+
phone_number: str | None = None,
|
|
442
|
+
*,
|
|
443
|
+
international_code: str | None = None,
|
|
444
|
+
captcha: CaptchaSolution | None = None,
|
|
445
|
+
) -> dict[str, Any]:
|
|
446
|
+
target_phone = phone_number or self.state.phone_number
|
|
447
|
+
if not target_phone:
|
|
448
|
+
raise SuningError("phone number is required")
|
|
449
|
+
area_code = international_code or self.state.international_code
|
|
450
|
+
if not self.state.sms_ticket or not self.state.risk_type:
|
|
451
|
+
self.prepare_sms_login(target_phone, international_code=area_code)
|
|
452
|
+
if self.state.risk_type and self.state.risk_type != "isNullVerifyCode" and not captcha:
|
|
453
|
+
raise CaptchaRequiredError(
|
|
454
|
+
self.state.risk_type,
|
|
455
|
+
"captcha token is required before sending sms code",
|
|
456
|
+
self.state.sms_ticket,
|
|
457
|
+
)
|
|
458
|
+
params = self._build_send_sms_code_payload(
|
|
459
|
+
phone_number=target_phone,
|
|
460
|
+
international_code=area_code,
|
|
461
|
+
captcha=captcha,
|
|
462
|
+
)
|
|
463
|
+
payload = {
|
|
464
|
+
"_x_rdsy_block_": self.suaes.encrypt(
|
|
465
|
+
json.dumps(params, separators=(",", ":"), ensure_ascii=False)
|
|
466
|
+
),
|
|
467
|
+
"callback": self._rdsy_callback(area_code, "sendCode"),
|
|
468
|
+
}
|
|
469
|
+
response = self.session.post(
|
|
470
|
+
"https://rdsy.suning.com/rdsy/sendCode.do",
|
|
471
|
+
data=payload,
|
|
472
|
+
timeout=self.timeout,
|
|
473
|
+
headers={
|
|
474
|
+
"Content-Type": "application/x-www-form-urlencoded",
|
|
475
|
+
"Referer": DEFAULT_LOGIN_URL,
|
|
476
|
+
},
|
|
477
|
+
)
|
|
478
|
+
response.raise_for_status()
|
|
479
|
+
outer = parse_jsonp_or_json(response.text)
|
|
480
|
+
inner = self._decrypt_rdsy_response(outer)
|
|
481
|
+
if inner.get("status") == "COMPLETE":
|
|
482
|
+
self.state.login_ticket = inner["data"].get("ticket")
|
|
483
|
+
self.state.risk_type = None
|
|
484
|
+
self._touch_state()
|
|
485
|
+
return inner
|
|
486
|
+
if inner.get("code") == "R0004":
|
|
487
|
+
data = inner.get("data") or {}
|
|
488
|
+
self.state.sms_ticket = data.get("ticket") or self.state.sms_ticket
|
|
489
|
+
self.state.risk_type = data.get("riskType") or self.state.risk_type
|
|
490
|
+
self._touch_state()
|
|
491
|
+
raise CaptchaRequiredError(
|
|
492
|
+
self.state.risk_type or "unknown",
|
|
493
|
+
inner.get("msg") or "captcha is required again",
|
|
494
|
+
self.state.sms_ticket,
|
|
495
|
+
)
|
|
496
|
+
message = inner.get("msg") or "failed to send sms code"
|
|
497
|
+
error_code = _extract_business_error_code(
|
|
498
|
+
inner.get("code"),
|
|
499
|
+
inner.get("resCode"),
|
|
500
|
+
inner.get("errCode"),
|
|
501
|
+
inner.get("errorCode"),
|
|
502
|
+
message,
|
|
503
|
+
)
|
|
504
|
+
if error_code == SMS_RATE_LIMIT_ERROR_CODE:
|
|
505
|
+
raise SmsRateLimitedError(message, error_code=error_code)
|
|
506
|
+
raise SuningError(message)
|
|
507
|
+
|
|
508
|
+
def request_iar_verify_code_ticket(self, phone_number: str) -> str:
|
|
509
|
+
response = self.session.post(
|
|
510
|
+
"https://passport.suning.com/ids/iarVerifyCodeTicket",
|
|
511
|
+
data={
|
|
512
|
+
"deviceId": "",
|
|
513
|
+
"dfpToken": self.state.dfp_token,
|
|
514
|
+
"username": phone_number,
|
|
515
|
+
},
|
|
516
|
+
timeout=self.timeout,
|
|
517
|
+
headers={
|
|
518
|
+
"Content-Type": "application/x-www-form-urlencoded",
|
|
519
|
+
"Referer": DEFAULT_LOGIN_URL,
|
|
520
|
+
},
|
|
521
|
+
)
|
|
522
|
+
response.raise_for_status()
|
|
523
|
+
data = response.json()
|
|
524
|
+
if str(data.get("result")).lower() != "true" or not data.get("ticket"):
|
|
525
|
+
raise SuningError("申请 IAR 验证 ticket 失败")
|
|
526
|
+
return data["ticket"]
|
|
527
|
+
|
|
528
|
+
def login_with_sms_code(
|
|
529
|
+
self,
|
|
530
|
+
*,
|
|
531
|
+
phone_number: str | None = None,
|
|
532
|
+
sms_code: str,
|
|
533
|
+
international_code: str | None = None,
|
|
534
|
+
) -> dict[str, Any]:
|
|
535
|
+
target_phone = phone_number or self.state.phone_number
|
|
536
|
+
if not target_phone:
|
|
537
|
+
raise SuningError("phone number is required")
|
|
538
|
+
area_code = international_code or self.state.international_code
|
|
539
|
+
if not self.state.login_ticket:
|
|
540
|
+
raise SuningError("login ticket is missing, send sms code first")
|
|
541
|
+
params = self._build_sms_login_payload(
|
|
542
|
+
phone_number=target_phone,
|
|
543
|
+
sms_code=sms_code,
|
|
544
|
+
international_code=area_code,
|
|
545
|
+
)
|
|
546
|
+
response = self.session.post(
|
|
547
|
+
"https://passport.suning.com/ids/smartLogin/sms",
|
|
548
|
+
data=params,
|
|
549
|
+
timeout=self.timeout,
|
|
550
|
+
headers={
|
|
551
|
+
"Content-Type": "application/x-www-form-urlencoded",
|
|
552
|
+
"Referer": DEFAULT_LOGIN_URL,
|
|
553
|
+
},
|
|
554
|
+
)
|
|
555
|
+
response.raise_for_status()
|
|
556
|
+
data = parse_jsonp_or_json(response.text)
|
|
557
|
+
if not self._is_login_success(data):
|
|
558
|
+
raise AuthenticationError(data.get("msg") or data.get("res_message") or "sms login failed")
|
|
559
|
+
self.state.login_response = data
|
|
560
|
+
self._touch_state()
|
|
561
|
+
self.bootstrap_service("shcss")
|
|
562
|
+
self.bootstrap_service("itapig")
|
|
563
|
+
return data
|
|
564
|
+
|
|
565
|
+
def bootstrap_service(self, service_name: str) -> dict[str, Any]:
|
|
566
|
+
if service_name not in SERVICE_BOOTSTRAP_URLS:
|
|
567
|
+
raise SuningError(f"unsupported service bootstrap: {service_name}")
|
|
568
|
+
response = self.session.get(
|
|
569
|
+
SERVICE_BOOTSTRAP_URLS[service_name],
|
|
570
|
+
timeout=self.timeout,
|
|
571
|
+
allow_redirects=True,
|
|
572
|
+
)
|
|
573
|
+
if "/ids/login" in response.url:
|
|
574
|
+
raise AuthenticationError(f"service bootstrap failed for {service_name}")
|
|
575
|
+
self._touch_state()
|
|
576
|
+
return {
|
|
577
|
+
"service": service_name,
|
|
578
|
+
"status_code": response.status_code,
|
|
579
|
+
"final_url": response.url,
|
|
580
|
+
"history": [item.status_code for item in response.history],
|
|
581
|
+
}
|
|
582
|
+
|
|
583
|
+
def query_member_base_info(self) -> dict[str, Any]:
|
|
584
|
+
response = self.session.get(
|
|
585
|
+
MEMBER_BASE_INFO_URL,
|
|
586
|
+
timeout=self.timeout,
|
|
587
|
+
allow_redirects=False,
|
|
588
|
+
)
|
|
589
|
+
if self._is_login_redirect(response):
|
|
590
|
+
self.bootstrap_service("shcss")
|
|
591
|
+
response = self.session.get(
|
|
592
|
+
MEMBER_BASE_INFO_URL,
|
|
593
|
+
timeout=self.timeout,
|
|
594
|
+
allow_redirects=False,
|
|
595
|
+
)
|
|
596
|
+
response.raise_for_status()
|
|
597
|
+
data = response.json()
|
|
598
|
+
if data.get("code") != "0":
|
|
599
|
+
raise AuthenticationError(data.get("desc") or "member base info request failed")
|
|
600
|
+
self._touch_state()
|
|
601
|
+
return data
|
|
602
|
+
|
|
603
|
+
def _build_app_api_headers(self, url: str, *, body: str) -> dict[str, str]:
|
|
604
|
+
request_time = str(int(time.time() * 1000))
|
|
605
|
+
trace_id = uuid4().hex
|
|
606
|
+
return {
|
|
607
|
+
"Accept": "*/*",
|
|
608
|
+
"Accept-Language": DEFAULT_APP_ACCEPT_LANGUAGE,
|
|
609
|
+
"Content-Type": "application/json",
|
|
610
|
+
"TerminalVersion": self.app_user_agent,
|
|
611
|
+
"User-Agent": self.app_user_agent,
|
|
612
|
+
"terminalType": self.app_terminal_type,
|
|
613
|
+
"requestTime": request_time,
|
|
614
|
+
"gsSign": _build_gs_sign(urlsplit(url).path, request_time, body),
|
|
615
|
+
"snTraceId": trace_id,
|
|
616
|
+
"hiro_trace_id": trace_id,
|
|
617
|
+
"snTraceType": "SDK",
|
|
618
|
+
}
|
|
619
|
+
|
|
620
|
+
def _request_app_api(self, url: str, *, body: str = "") -> requests.Response:
|
|
621
|
+
payload = _canonicalize_request_body(body, "application/json")
|
|
622
|
+
|
|
623
|
+
def send_request() -> requests.Response:
|
|
624
|
+
return self.session.request(
|
|
625
|
+
"POST",
|
|
626
|
+
url,
|
|
627
|
+
headers=self._build_app_api_headers(url, body=payload),
|
|
628
|
+
data=payload,
|
|
629
|
+
timeout=self.timeout,
|
|
630
|
+
allow_redirects=False,
|
|
631
|
+
)
|
|
632
|
+
|
|
633
|
+
response = send_request()
|
|
634
|
+
if self._is_login_redirect(response):
|
|
635
|
+
self.bootstrap_service("itapig")
|
|
636
|
+
response = send_request()
|
|
637
|
+
if self._is_login_redirect(response):
|
|
638
|
+
raise AuthenticationError("itapig service bootstrap failed")
|
|
639
|
+
return response
|
|
640
|
+
|
|
641
|
+
def _decode_app_api_response(
|
|
642
|
+
self,
|
|
643
|
+
response: requests.Response,
|
|
644
|
+
*,
|
|
645
|
+
action: str,
|
|
646
|
+
) -> dict[str, Any]:
|
|
647
|
+
response.raise_for_status()
|
|
648
|
+
try:
|
|
649
|
+
data = response.json()
|
|
650
|
+
except ValueError as error:
|
|
651
|
+
raise SuningError(f"{action} 返回了无法解析的 JSON 响应。") from error
|
|
652
|
+
if data.get("responseCode") != "0":
|
|
653
|
+
raise SuningError(data.get("responseMsg") or f"{action} failed")
|
|
654
|
+
self._touch_state()
|
|
655
|
+
return data
|
|
656
|
+
|
|
657
|
+
def list_families(self) -> dict[str, Any]:
|
|
658
|
+
response = self._request_app_api(FAMILY_LIST_URL)
|
|
659
|
+
return self._decode_app_api_response(response, action="家庭列表请求")
|
|
660
|
+
|
|
661
|
+
def list_family_infos(self) -> list[FamilyInfo]:
|
|
662
|
+
payload = self.list_families()
|
|
663
|
+
response_data = payload.get("responseData")
|
|
664
|
+
if isinstance(response_data, list):
|
|
665
|
+
raw_families = response_data
|
|
666
|
+
elif isinstance(response_data, dict):
|
|
667
|
+
raw_families = response_data.get("families") or response_data.get("familyList")
|
|
668
|
+
else:
|
|
669
|
+
raw_families = None
|
|
670
|
+
if not isinstance(raw_families, list):
|
|
671
|
+
raise SuningError("家庭列表返回格式不正确,缺少 families 数组。")
|
|
672
|
+
|
|
673
|
+
families: list[FamilyInfo] = []
|
|
674
|
+
for item in raw_families:
|
|
675
|
+
if not isinstance(item, dict):
|
|
676
|
+
raise SuningError("家庭列表项返回格式不正确。")
|
|
677
|
+
family_id = item.get("familyId", item.get("id"))
|
|
678
|
+
family_name = item.get("familyName")
|
|
679
|
+
if family_id is None or family_name is None:
|
|
680
|
+
raise SuningError("家庭列表项缺少 familyId 或 familyName。")
|
|
681
|
+
families.append(
|
|
682
|
+
FamilyInfo(
|
|
683
|
+
family_id=str(family_id),
|
|
684
|
+
name=str(family_name),
|
|
685
|
+
raw=item,
|
|
686
|
+
)
|
|
687
|
+
)
|
|
688
|
+
return families
|
|
689
|
+
|
|
690
|
+
def list_devices(self, family_id: str | int) -> dict[str, Any]:
|
|
691
|
+
request_body = json.dumps(
|
|
692
|
+
{"familyId": str(family_id)},
|
|
693
|
+
separators=(",", ":"),
|
|
694
|
+
ensure_ascii=False,
|
|
695
|
+
)
|
|
696
|
+
response = self._request_app_api(DEVICE_LIST_URL, body=request_body)
|
|
697
|
+
return self._decode_app_api_response(response, action="设备列表请求")
|
|
698
|
+
|
|
699
|
+
def get_device(
|
|
700
|
+
self,
|
|
701
|
+
family_id: str | int,
|
|
702
|
+
*,
|
|
703
|
+
device_id: str | None = None,
|
|
704
|
+
) -> dict[str, Any]:
|
|
705
|
+
payload = self.list_devices(family_id)
|
|
706
|
+
devices = payload.get("responseData", {}).get("devices") or []
|
|
707
|
+
if not devices:
|
|
708
|
+
raise SuningError(f"familyId={family_id} 下没有设备")
|
|
709
|
+
|
|
710
|
+
if device_id:
|
|
711
|
+
for device in devices:
|
|
712
|
+
if str(device.get("id")) == str(device_id):
|
|
713
|
+
return device
|
|
714
|
+
raise SuningError(f"familyId={family_id} 下未找到 deviceId={device_id} 的设备")
|
|
715
|
+
|
|
716
|
+
if len(devices) == 1:
|
|
717
|
+
return devices[0]
|
|
718
|
+
|
|
719
|
+
climate_candidates = [
|
|
720
|
+
device for device in devices
|
|
721
|
+
if str(device.get("categoryId")) == AIR_CONDITIONER_CATEGORY_ID
|
|
722
|
+
or AIR_CONDITIONER_NAME_KEYWORD in str(device.get("name", ""))
|
|
723
|
+
]
|
|
724
|
+
if len(climate_candidates) == 1:
|
|
725
|
+
return climate_candidates[0]
|
|
726
|
+
|
|
727
|
+
device_hints = ", ".join(f"{item.get('id')}:{item.get('name')}" for item in devices)
|
|
728
|
+
raise SuningError(
|
|
729
|
+
f"familyId={family_id} 下有多个设备,请通过 --device-id 指定。可选设备: {device_hints}"
|
|
730
|
+
)
|
|
731
|
+
|
|
732
|
+
def get_air_conditioner_status(
|
|
733
|
+
self,
|
|
734
|
+
family_id: str | int,
|
|
735
|
+
*,
|
|
736
|
+
device_id: str | None = None,
|
|
737
|
+
) -> AirConditionerStatus:
|
|
738
|
+
device = self.get_device(family_id, device_id=device_id)
|
|
739
|
+
return self._normalize_air_conditioner_status(device)
|
|
740
|
+
|
|
741
|
+
def list_air_conditioner_statuses(self, family_id: str | int) -> list[AirConditionerStatus]:
|
|
742
|
+
payload = self.list_devices(family_id)
|
|
743
|
+
devices = payload.get("responseData", {}).get("devices")
|
|
744
|
+
if not isinstance(devices, list):
|
|
745
|
+
raise SuningError("设备列表返回格式不正确,缺少 devices 数组。")
|
|
746
|
+
return [
|
|
747
|
+
self._normalize_air_conditioner_status(device)
|
|
748
|
+
for device in devices
|
|
749
|
+
if self._is_air_conditioner_device(device)
|
|
750
|
+
]
|
|
751
|
+
|
|
752
|
+
def _normalize_air_conditioner_status(self, device: dict[str, Any]) -> AirConditionerStatus:
|
|
753
|
+
raw_status = device.get("status") or {}
|
|
754
|
+
online_flag = _coalesce(raw_status.get("onlineStatus"), device.get("online"))
|
|
755
|
+
online = bool(_parse_bool_flag(online_flag))
|
|
756
|
+
summary = _strip_html_text(device.get("p1"))
|
|
757
|
+
power_on = _parse_bool_flag(_coalesce(raw_status.get("SN_POWER"), raw_status.get("C_POWER")))
|
|
758
|
+
current_temperature = _parse_float_value(
|
|
759
|
+
_coalesce(raw_status.get("SN_INDOORTEMP"), raw_status.get("C_INDOORTEMP"))
|
|
760
|
+
)
|
|
761
|
+
target_temperature = _parse_float_value(
|
|
762
|
+
_coalesce(raw_status.get("SN_TEMPERATURE"), raw_status.get("C_TEMPERATURE"))
|
|
763
|
+
)
|
|
764
|
+
outdoor_temperature = _parse_float_value(raw_status.get("C_OUTDOORTEMP"))
|
|
765
|
+
swing_horizontal = _parse_bool_flag(
|
|
766
|
+
_coalesce(raw_status.get("SN_AIRHORIZONTAL"), raw_status.get("C_AIRHORIZONTAL"))
|
|
767
|
+
)
|
|
768
|
+
swing_vertical = _parse_bool_flag(
|
|
769
|
+
_coalesce(raw_status.get("SN_AIRVERTICAL"), raw_status.get("C_AIRVERTICAL"))
|
|
770
|
+
)
|
|
771
|
+
eco_enabled = _parse_bool_flag(_coalesce(raw_status.get("SN_ECO"), raw_status.get("C_ECO")))
|
|
772
|
+
purify_enabled = _parse_bool_flag(raw_status.get("SN_PURIFY"))
|
|
773
|
+
fresh_air_enabled = _parse_bool_flag(raw_status.get("C_FRESHAIR"))
|
|
774
|
+
electric_heating_enabled = _parse_bool_flag(
|
|
775
|
+
_coalesce(raw_status.get("SN_ELECHEATING"), raw_status.get("C_ELECHEATING"))
|
|
776
|
+
)
|
|
777
|
+
|
|
778
|
+
status = AirConditionerStatus(
|
|
779
|
+
device_id=str(device.get("id")),
|
|
780
|
+
name=str(device.get("name") or device.get("id") or "unknown-device"),
|
|
781
|
+
model=device.get("model"),
|
|
782
|
+
family_id=str(device.get("fId")) if device.get("fId") is not None else None,
|
|
783
|
+
group_id=str(device.get("gId")) if device.get("gId") is not None else None,
|
|
784
|
+
group_name=device.get("gName"),
|
|
785
|
+
category_id=str(device.get("categoryId")) if device.get("categoryId") is not None else None,
|
|
786
|
+
available=online,
|
|
787
|
+
online=online,
|
|
788
|
+
summary=summary,
|
|
789
|
+
device_record_time=device.get("time"),
|
|
790
|
+
refresh_time=raw_status.get("refreshTime"),
|
|
791
|
+
power_on=power_on,
|
|
792
|
+
current_temperature=current_temperature,
|
|
793
|
+
target_temperature=target_temperature,
|
|
794
|
+
outdoor_temperature=outdoor_temperature,
|
|
795
|
+
mode_raw=_coalesce(raw_status.get("SN_MODE"), raw_status.get("C_MODE")),
|
|
796
|
+
fan_mode_raw=_coalesce(raw_status.get("SN_FANSPEED"), raw_status.get("C_FANSPEED")),
|
|
797
|
+
swing_horizontal=swing_horizontal,
|
|
798
|
+
swing_vertical=swing_vertical,
|
|
799
|
+
eco_enabled=eco_enabled,
|
|
800
|
+
purify_enabled=purify_enabled,
|
|
801
|
+
fresh_air_enabled=fresh_air_enabled,
|
|
802
|
+
electric_heating_enabled=electric_heating_enabled,
|
|
803
|
+
ha_climate_preview=None,
|
|
804
|
+
raw_status=raw_status,
|
|
805
|
+
raw_device=device,
|
|
806
|
+
)
|
|
807
|
+
return status.model_copy(
|
|
808
|
+
update={"ha_climate_preview": self._build_ha_climate_preview(status)}
|
|
809
|
+
)
|
|
810
|
+
|
|
811
|
+
def _is_air_conditioner_device(self, device: dict[str, Any]) -> bool:
|
|
812
|
+
return str(device.get("categoryId")) == AIR_CONDITIONER_CATEGORY_ID or (
|
|
813
|
+
AIR_CONDITIONER_NAME_KEYWORD in str(device.get("name", ""))
|
|
814
|
+
)
|
|
815
|
+
|
|
816
|
+
def _build_ha_climate_preview(self, status: AirConditionerStatus) -> HAClimatePreview:
|
|
817
|
+
notes: list[str] = []
|
|
818
|
+
hvac_mode: str | None = None
|
|
819
|
+
if not status.available:
|
|
820
|
+
notes.append("设备当前离线,Home Assistant 中应标记为 unavailable。")
|
|
821
|
+
elif status.power_on is False:
|
|
822
|
+
hvac_mode = "off"
|
|
823
|
+
|
|
824
|
+
if status.power_on is True:
|
|
825
|
+
notes.append("设备当前上报为开机,但模式枚举尚未确认,暂不映射标准 HVACMode。")
|
|
826
|
+
elif status.power_on is None:
|
|
827
|
+
notes.append("未能从原始字段中稳定解析电源状态。")
|
|
828
|
+
|
|
829
|
+
if status.mode_raw is not None:
|
|
830
|
+
notes.append(f"原始模式值为 {status.mode_raw},后续需要控制抓包后确认枚举含义。")
|
|
831
|
+
|
|
832
|
+
supported_features_preview = [
|
|
833
|
+
feature for feature in [
|
|
834
|
+
"target_temperature" if status.target_temperature is not None else None,
|
|
835
|
+
"current_temperature" if status.current_temperature is not None else None,
|
|
836
|
+
"fan_mode" if status.fan_mode_raw is not None else None,
|
|
837
|
+
"swing_mode"
|
|
838
|
+
if _infer_swing_mode(status.swing_horizontal, status.swing_vertical) is not None
|
|
839
|
+
else None,
|
|
840
|
+
"turn_on_off" if status.power_on is not None else None,
|
|
841
|
+
]
|
|
842
|
+
if feature is not None
|
|
843
|
+
]
|
|
844
|
+
|
|
845
|
+
return HAClimatePreview(
|
|
846
|
+
entity_domain="climate",
|
|
847
|
+
translation_key="suning_air_conditioner",
|
|
848
|
+
available=status.available,
|
|
849
|
+
hvac_mode=hvac_mode,
|
|
850
|
+
current_temperature=status.current_temperature,
|
|
851
|
+
target_temperature=status.target_temperature,
|
|
852
|
+
fan_mode=status.fan_mode_raw,
|
|
853
|
+
swing_mode=_infer_swing_mode(status.swing_horizontal, status.swing_vertical),
|
|
854
|
+
preset_mode="eco" if status.eco_enabled else None,
|
|
855
|
+
supported_features_preview=supported_features_preview,
|
|
856
|
+
raw_mapping={
|
|
857
|
+
"power": {
|
|
858
|
+
"preferred": "SN_POWER",
|
|
859
|
+
"fallback": "C_POWER",
|
|
860
|
+
"value": status.raw_status.get("SN_POWER") or status.raw_status.get("C_POWER"),
|
|
861
|
+
},
|
|
862
|
+
"mode": {
|
|
863
|
+
"preferred": "SN_MODE",
|
|
864
|
+
"fallback": "C_MODE",
|
|
865
|
+
"value": status.mode_raw,
|
|
866
|
+
},
|
|
867
|
+
"target_temperature": {
|
|
868
|
+
"preferred": "SN_TEMPERATURE",
|
|
869
|
+
"fallback": "C_TEMPERATURE",
|
|
870
|
+
"value": status.raw_status.get("SN_TEMPERATURE") or status.raw_status.get("C_TEMPERATURE"),
|
|
871
|
+
},
|
|
872
|
+
"current_temperature": {
|
|
873
|
+
"preferred": "SN_INDOORTEMP",
|
|
874
|
+
"fallback": "C_INDOORTEMP",
|
|
875
|
+
"value": status.raw_status.get("SN_INDOORTEMP") or status.raw_status.get("C_INDOORTEMP"),
|
|
876
|
+
},
|
|
877
|
+
"fan_mode": {
|
|
878
|
+
"preferred": "SN_FANSPEED",
|
|
879
|
+
"fallback": "C_FANSPEED",
|
|
880
|
+
"value": status.fan_mode_raw,
|
|
881
|
+
},
|
|
882
|
+
},
|
|
883
|
+
notes=notes,
|
|
884
|
+
)
|
|
885
|
+
|
|
886
|
+
def keep_alive(self) -> dict[str, Any]:
|
|
887
|
+
member_info = self.query_member_base_info()
|
|
888
|
+
family_info = self.list_families()
|
|
889
|
+
return {
|
|
890
|
+
"member": member_info,
|
|
891
|
+
"families": family_info,
|
|
892
|
+
}
|
|
893
|
+
|
|
894
|
+
def save_state(self) -> None:
|
|
895
|
+
if not self.state_path:
|
|
896
|
+
return
|
|
897
|
+
self.state_path.parent.mkdir(parents=True, exist_ok=True)
|
|
898
|
+
payload = PersistedSessionState(
|
|
899
|
+
state=self.state,
|
|
900
|
+
cookies=[_serialize_cookie(cookie) for cookie in self.session.cookies],
|
|
901
|
+
)
|
|
902
|
+
self.state_path.write_text(
|
|
903
|
+
json.dumps(payload.model_dump(mode="json"), ensure_ascii=False, indent=2),
|
|
904
|
+
encoding="utf-8",
|
|
905
|
+
)
|
|
906
|
+
|
|
907
|
+
def load_state(self) -> None:
|
|
908
|
+
if not self.state_path or not self.state_path.exists():
|
|
909
|
+
return
|
|
910
|
+
payload = PersistedSessionState.model_validate_json(
|
|
911
|
+
self.state_path.read_text(encoding="utf-8")
|
|
912
|
+
)
|
|
913
|
+
self.state = payload.state
|
|
914
|
+
self.session.cookies.clear()
|
|
915
|
+
for serialized_cookie in payload.cookies:
|
|
916
|
+
self.session.cookies.set_cookie(_restore_cookie(serialized_cookie))
|
|
917
|
+
|
|
918
|
+
def load_signed_templates(self) -> None:
|
|
919
|
+
self.signed_templates = {}
|
|
920
|
+
for har_path in self._candidate_har_paths():
|
|
921
|
+
self._load_signed_templates_from_har(har_path)
|
|
922
|
+
|
|
923
|
+
def _candidate_har_paths(self) -> list[Path]:
|
|
924
|
+
if not self.har_path:
|
|
925
|
+
return []
|
|
926
|
+
return [self.har_path]
|
|
927
|
+
|
|
928
|
+
def _load_signed_templates_from_har(self, har_path: Path) -> None:
|
|
929
|
+
if not har_path.exists():
|
|
930
|
+
return
|
|
931
|
+
try:
|
|
932
|
+
payload = json.loads(har_path.read_text(encoding="utf-8"))
|
|
933
|
+
except (OSError, json.JSONDecodeError):
|
|
934
|
+
return
|
|
935
|
+
entries = payload.get("log", {}).get("entries", [])
|
|
936
|
+
supported_urls = {
|
|
937
|
+
_normalize_url(FAMILY_LIST_URL),
|
|
938
|
+
_normalize_url(DEVICE_LIST_URL),
|
|
939
|
+
_normalize_url(OPENSH_GET_KEY_URL),
|
|
940
|
+
}
|
|
941
|
+
for entry in entries:
|
|
942
|
+
request = entry.get("request", {})
|
|
943
|
+
method = str(request.get("method", "")).upper()
|
|
944
|
+
url = request.get("url", "")
|
|
945
|
+
normalized_url = _normalize_url(url)
|
|
946
|
+
if normalized_url not in supported_urls or not _har_entry_is_success(entry):
|
|
947
|
+
continue
|
|
948
|
+
headers = _extract_har_headers(entry)
|
|
949
|
+
body = _canonicalize_request_body(
|
|
950
|
+
request.get("postData", {}).get("text"),
|
|
951
|
+
headers.get("Content-Type") or headers.get("content-type"),
|
|
952
|
+
)
|
|
953
|
+
template = SignedRequestTemplate(
|
|
954
|
+
method=method,
|
|
955
|
+
url=normalized_url,
|
|
956
|
+
headers=headers,
|
|
957
|
+
body=body,
|
|
958
|
+
har_path=str(har_path),
|
|
959
|
+
)
|
|
960
|
+
self.signed_templates.setdefault(
|
|
961
|
+
_template_key(method, normalized_url, body),
|
|
962
|
+
template,
|
|
963
|
+
)
|
|
964
|
+
|
|
965
|
+
def _find_signed_template(
|
|
966
|
+
self,
|
|
967
|
+
method: str,
|
|
968
|
+
url: str,
|
|
969
|
+
body: str,
|
|
970
|
+
) -> SignedRequestTemplate | None:
|
|
971
|
+
return self.signed_templates.get(_template_key(method, url, body))
|
|
972
|
+
|
|
973
|
+
def _request_with_signed_template(
|
|
974
|
+
self,
|
|
975
|
+
template: SignedRequestTemplate,
|
|
976
|
+
*,
|
|
977
|
+
body: str | None = None,
|
|
978
|
+
) -> requests.Response:
|
|
979
|
+
payload = template.body if body is None else body
|
|
980
|
+
request_kwargs: dict[str, Any] = {
|
|
981
|
+
"headers": template.build_headers(),
|
|
982
|
+
"timeout": self.timeout,
|
|
983
|
+
"allow_redirects": False,
|
|
984
|
+
}
|
|
985
|
+
if payload:
|
|
986
|
+
request_kwargs["data"] = payload
|
|
987
|
+
response = self.session.request(
|
|
988
|
+
template.method,
|
|
989
|
+
template.url,
|
|
990
|
+
**request_kwargs,
|
|
991
|
+
)
|
|
992
|
+
if self._is_login_redirect(response):
|
|
993
|
+
self.query_member_base_info()
|
|
994
|
+
response = self.session.request(
|
|
995
|
+
template.method,
|
|
996
|
+
template.url,
|
|
997
|
+
**request_kwargs,
|
|
998
|
+
)
|
|
999
|
+
return response
|
|
1000
|
+
|
|
1001
|
+
def available_device_template_family_ids(self) -> list[str]:
|
|
1002
|
+
family_ids: set[str] = set()
|
|
1003
|
+
for template in self.signed_templates.values():
|
|
1004
|
+
if template.method != "POST" or template.url != _normalize_url(DEVICE_LIST_URL):
|
|
1005
|
+
continue
|
|
1006
|
+
if not template.body:
|
|
1007
|
+
continue
|
|
1008
|
+
try:
|
|
1009
|
+
payload = json.loads(template.body)
|
|
1010
|
+
except json.JSONDecodeError:
|
|
1011
|
+
continue
|
|
1012
|
+
family_id = payload.get("familyId")
|
|
1013
|
+
if family_id is not None:
|
|
1014
|
+
family_ids.add(str(family_id))
|
|
1015
|
+
return sorted(family_ids)
|
|
1016
|
+
|
|
1017
|
+
def _touch_state(self) -> None:
|
|
1018
|
+
self.state.updated_at = time.time()
|
|
1019
|
+
self.save_state()
|
|
1020
|
+
|
|
1021
|
+
def _uses_mobile_sms_login(self, international_code: str) -> bool:
|
|
1022
|
+
return international_code == "0086"
|
|
1023
|
+
|
|
1024
|
+
def _mobile_sms_login_data(self, phone_number: str) -> dict[str, str]:
|
|
1025
|
+
return {
|
|
1026
|
+
"mode": "1",
|
|
1027
|
+
"subMode": MOBILE_SMS_LOGIN_SUB_MODE,
|
|
1028
|
+
"channel": MOBILE_SMS_LOGIN_CHANNEL,
|
|
1029
|
+
"dfpToken": self.state.dfp_token,
|
|
1030
|
+
"orderChannel": MOBILE_SMS_LOGIN_ORDER_CHANNEL,
|
|
1031
|
+
"custType": "0",
|
|
1032
|
+
"ways": "duanxindl",
|
|
1033
|
+
"userName": phone_number,
|
|
1034
|
+
"source": "",
|
|
1035
|
+
"token": "",
|
|
1036
|
+
"detect": self.state.detect,
|
|
1037
|
+
"referenceURL": "",
|
|
1038
|
+
"miniType": "",
|
|
1039
|
+
"result": "",
|
|
1040
|
+
"cntctMobileNum": phone_number,
|
|
1041
|
+
"loginTheme": MOBILE_SMS_LOGIN_THEME,
|
|
1042
|
+
"appVersion": MOBILE_SMS_LOGIN_APP_VERSION,
|
|
1043
|
+
"openId": "",
|
|
1044
|
+
}
|
|
1045
|
+
|
|
1046
|
+
def _build_prepare_sms_login_payload(
|
|
1047
|
+
self,
|
|
1048
|
+
*,
|
|
1049
|
+
phone_number: str,
|
|
1050
|
+
international_code: str,
|
|
1051
|
+
) -> dict[str, Any]:
|
|
1052
|
+
if self._uses_mobile_sms_login(international_code):
|
|
1053
|
+
return {
|
|
1054
|
+
"sceneId": MOBILE_SMS_LOGIN_SCENE_ID,
|
|
1055
|
+
"stepFlag": self.config.step_flag,
|
|
1056
|
+
"appCode": MOBILE_SMS_LOGIN_APP_CODE,
|
|
1057
|
+
"data": self._mobile_sms_login_data(phone_number),
|
|
1058
|
+
}
|
|
1059
|
+
return {
|
|
1060
|
+
"sceneId": self._scene_id(international_code),
|
|
1061
|
+
"stepFlag": self.config.step_flag,
|
|
1062
|
+
"appCode": self.config.rdsy_app_code,
|
|
1063
|
+
"data": {
|
|
1064
|
+
"ways": "duanxindl",
|
|
1065
|
+
"channel": self.config.channel,
|
|
1066
|
+
"orderChannel": self._channel(international_code),
|
|
1067
|
+
"dfpToken": self.state.dfp_token,
|
|
1068
|
+
"detect": self.state.detect,
|
|
1069
|
+
"loginTheme": "defaultTheme",
|
|
1070
|
+
"referenceURL": DEFAULT_LOGIN_URL,
|
|
1071
|
+
"userName": phone_number,
|
|
1072
|
+
"cntctMobileNum": phone_number,
|
|
1073
|
+
"mode": "1",
|
|
1074
|
+
"subMode": "4",
|
|
1075
|
+
},
|
|
1076
|
+
}
|
|
1077
|
+
|
|
1078
|
+
def _build_send_sms_code_payload(
|
|
1079
|
+
self,
|
|
1080
|
+
*,
|
|
1081
|
+
phone_number: str,
|
|
1082
|
+
international_code: str,
|
|
1083
|
+
captcha: CaptchaSolution | None,
|
|
1084
|
+
) -> dict[str, Any]:
|
|
1085
|
+
if self._uses_mobile_sms_login(international_code):
|
|
1086
|
+
params: dict[str, Any] = {
|
|
1087
|
+
"sceneId": MOBILE_SMS_LOGIN_SCENE_ID,
|
|
1088
|
+
"stepFlag": self.config.step_two_flag,
|
|
1089
|
+
"appCode": MOBILE_SMS_LOGIN_APP_CODE,
|
|
1090
|
+
"riskType": self.state.risk_type or "",
|
|
1091
|
+
"phoneNum": rsa_encrypt_base64(phone_number, self.config.rdsy_key),
|
|
1092
|
+
"ticket": self.state.sms_ticket or "",
|
|
1093
|
+
"code": "",
|
|
1094
|
+
"uuid": "",
|
|
1095
|
+
"data": self._mobile_sms_login_data(phone_number),
|
|
1096
|
+
}
|
|
1097
|
+
if captcha:
|
|
1098
|
+
params.update(self._mobile_captcha_fields(captcha))
|
|
1099
|
+
return params
|
|
1100
|
+
params = {
|
|
1101
|
+
"sceneId": self._scene_id(international_code),
|
|
1102
|
+
"stepFlag": self.config.step_two_flag,
|
|
1103
|
+
"appCode": self.config.rdsy_app_code,
|
|
1104
|
+
"riskType": self.state.risk_type or "",
|
|
1105
|
+
"phoneNum": rsa_encrypt_base64(phone_number, self.config.rdsy_key),
|
|
1106
|
+
"internationalCode": international_code,
|
|
1107
|
+
"callback": self._jsonp_callback("sendCode"),
|
|
1108
|
+
"ticket": self.state.sms_ticket or "",
|
|
1109
|
+
"code": "",
|
|
1110
|
+
"uuid": "",
|
|
1111
|
+
"data": {
|
|
1112
|
+
"ways": "duanxindl",
|
|
1113
|
+
"channel": self.config.channel,
|
|
1114
|
+
"orderChannel": self._channel(international_code),
|
|
1115
|
+
"dfpToken": self.state.dfp_token,
|
|
1116
|
+
"detect": self.state.detect,
|
|
1117
|
+
"loginTheme": "defaultTheme",
|
|
1118
|
+
"userName": phone_number,
|
|
1119
|
+
"cntctMobileNum": phone_number,
|
|
1120
|
+
"checkAliasName": "0",
|
|
1121
|
+
"referenceURL": DEFAULT_LOGIN_URL,
|
|
1122
|
+
},
|
|
1123
|
+
}
|
|
1124
|
+
if captcha:
|
|
1125
|
+
params.update(self._captcha_fields(captcha))
|
|
1126
|
+
return params
|
|
1127
|
+
|
|
1128
|
+
def _build_sms_login_payload(
|
|
1129
|
+
self,
|
|
1130
|
+
*,
|
|
1131
|
+
phone_number: str,
|
|
1132
|
+
sms_code: str,
|
|
1133
|
+
international_code: str,
|
|
1134
|
+
) -> dict[str, str]:
|
|
1135
|
+
if self._uses_mobile_sms_login(international_code):
|
|
1136
|
+
return {
|
|
1137
|
+
"appVersion": MOBILE_SMS_LOGIN_APP_VERSION,
|
|
1138
|
+
"detect": self.state.detect,
|
|
1139
|
+
"dfpToken": self.state.dfp_token,
|
|
1140
|
+
"jsonViewType": "true",
|
|
1141
|
+
"loginChannel": MOBILE_SMS_LOGIN_ORDER_CHANNEL,
|
|
1142
|
+
"phoneNumber": rsa_encrypt_base64(phone_number, self.config.check_account_key),
|
|
1143
|
+
"rememberMe": "true",
|
|
1144
|
+
"rememberMeType": MOBILE_SMS_LOGIN_REMEMBER_ME_TYPE,
|
|
1145
|
+
"sceneId": MOBILE_SMS_LOGIN_SCENE_ID,
|
|
1146
|
+
"smsCode": sms_code,
|
|
1147
|
+
"stepFlag": self.config.step_three_flag,
|
|
1148
|
+
"terminal": MOBILE_SMS_LOGIN_CHANNEL,
|
|
1149
|
+
"ticket": self.state.login_ticket,
|
|
1150
|
+
}
|
|
1151
|
+
return {
|
|
1152
|
+
"callback": self._jsonp_callback("smsLogin"),
|
|
1153
|
+
"ticket": self.state.login_ticket,
|
|
1154
|
+
"phoneNumber": rsa_encrypt_base64(phone_number, self.config.check_account_key),
|
|
1155
|
+
"internationalCode": international_code,
|
|
1156
|
+
"channel": self.config.channel,
|
|
1157
|
+
"smsCode": sms_code,
|
|
1158
|
+
"rememberMe": "true",
|
|
1159
|
+
"type": "1",
|
|
1160
|
+
"sceneId": self._scene_id(international_code),
|
|
1161
|
+
"targetUrl": DEFAULT_TARGET_URL,
|
|
1162
|
+
"service": "",
|
|
1163
|
+
"detect": self.state.detect,
|
|
1164
|
+
"secondFlag": "100000000010",
|
|
1165
|
+
"dfpToken": self.state.dfp_token,
|
|
1166
|
+
"terminal": self.config.channel,
|
|
1167
|
+
"createChannel": self._channel(international_code),
|
|
1168
|
+
"loginChannel": self._channel(international_code),
|
|
1169
|
+
"smsCodeVersion": "1.0",
|
|
1170
|
+
"jsonViewType": "true",
|
|
1171
|
+
"viewType": "json",
|
|
1172
|
+
"loginOrRegFlag": "0",
|
|
1173
|
+
"version": "2.0",
|
|
1174
|
+
}
|
|
1175
|
+
|
|
1176
|
+
def _decrypt_rdsy_response(self, outer_payload: dict[str, Any]) -> dict[str, Any]:
|
|
1177
|
+
encrypted = outer_payload.get("_x_rdsy_resp_")
|
|
1178
|
+
if not encrypted:
|
|
1179
|
+
raise SuningError("missing _x_rdsy_resp_ in rdsy response")
|
|
1180
|
+
return json.loads(self.suaes.decrypt(encrypted))
|
|
1181
|
+
|
|
1182
|
+
def _captcha_fields(self, captcha: CaptchaSolution) -> dict[str, str]:
|
|
1183
|
+
mapping = {
|
|
1184
|
+
"iar": {
|
|
1185
|
+
"uuid": "iarVerifyCode",
|
|
1186
|
+
"iarVerifyCode": captcha.value,
|
|
1187
|
+
"code": captcha.value,
|
|
1188
|
+
},
|
|
1189
|
+
"slide": {
|
|
1190
|
+
"uuid": "sillerVerifyCode",
|
|
1191
|
+
"sillerCode": captcha.value,
|
|
1192
|
+
"code": captcha.value,
|
|
1193
|
+
},
|
|
1194
|
+
"image": {
|
|
1195
|
+
"uuid": "19da7909-9b5d-4aee-99ee-28016002eaac",
|
|
1196
|
+
"imgCode": captcha.value,
|
|
1197
|
+
"code": captcha.value,
|
|
1198
|
+
},
|
|
1199
|
+
}
|
|
1200
|
+
if captcha.kind not in mapping:
|
|
1201
|
+
raise SuningError(f"unsupported captcha kind: {captcha.kind}")
|
|
1202
|
+
return mapping[captcha.kind]
|
|
1203
|
+
|
|
1204
|
+
def _mobile_captcha_fields(self, captcha: CaptchaSolution) -> dict[str, str]:
|
|
1205
|
+
mapping = {
|
|
1206
|
+
"iar": {
|
|
1207
|
+
"uuid": "",
|
|
1208
|
+
"code": captcha.value,
|
|
1209
|
+
},
|
|
1210
|
+
"slide": {
|
|
1211
|
+
"uuid": "sillerVerifyCode",
|
|
1212
|
+
"sillerCode": captcha.value,
|
|
1213
|
+
"code": captcha.value,
|
|
1214
|
+
},
|
|
1215
|
+
"image": {
|
|
1216
|
+
"uuid": "19da7909-9b5d-4aee-99ee-28016002eaac",
|
|
1217
|
+
"imgCode": captcha.value,
|
|
1218
|
+
"code": captcha.value,
|
|
1219
|
+
},
|
|
1220
|
+
}
|
|
1221
|
+
if captcha.kind not in mapping:
|
|
1222
|
+
raise SuningError(f"unsupported captcha kind: {captcha.kind}")
|
|
1223
|
+
return mapping[captcha.kind]
|
|
1224
|
+
|
|
1225
|
+
def _scene_id(self, international_code: str) -> str:
|
|
1226
|
+
if international_code == "00852":
|
|
1227
|
+
return self.config.rdsy_scene_id_yghk
|
|
1228
|
+
return self.config.rdsy_scene_id
|
|
1229
|
+
|
|
1230
|
+
def _channel(self, international_code: str) -> str:
|
|
1231
|
+
if international_code == "00852":
|
|
1232
|
+
return "208000104024"
|
|
1233
|
+
return "208000103001"
|
|
1234
|
+
|
|
1235
|
+
def _jsonp_callback(self, prefix: str) -> str:
|
|
1236
|
+
return f"{prefix}_{int(time.time() * 1000)}"
|
|
1237
|
+
|
|
1238
|
+
def _rdsy_callback(self, international_code: str, prefix: str) -> str:
|
|
1239
|
+
if self._uses_mobile_sms_login(international_code):
|
|
1240
|
+
return ""
|
|
1241
|
+
return self._jsonp_callback(prefix)
|
|
1242
|
+
|
|
1243
|
+
def _is_login_success(self, payload: dict[str, Any]) -> bool:
|
|
1244
|
+
return bool(
|
|
1245
|
+
payload.get("success")
|
|
1246
|
+
or (
|
|
1247
|
+
payload.get("res_message") == "SUCCESS"
|
|
1248
|
+
and str(payload.get("res_code")) == "0"
|
|
1249
|
+
)
|
|
1250
|
+
)
|
|
1251
|
+
|
|
1252
|
+
def _is_login_redirect(self, response: requests.Response) -> bool:
|
|
1253
|
+
return response.status_code in {301, 302, 303, 307, 308} and "passport.suning.com/ids/login" in (
|
|
1254
|
+
response.headers.get("Location", "")
|
|
1255
|
+
)
|
|
1256
|
+
|
|
1257
|
+
|
|
1258
|
+
def _build_parser() -> argparse.ArgumentParser:
|
|
1259
|
+
def add_shared_arguments(target: argparse.ArgumentParser) -> None:
|
|
1260
|
+
target.add_argument("--state-file", default=".suning-session.json")
|
|
1261
|
+
target.add_argument("--har-file")
|
|
1262
|
+
target.add_argument("--detect")
|
|
1263
|
+
target.add_argument("--dfp-token")
|
|
1264
|
+
|
|
1265
|
+
parser = argparse.ArgumentParser(prog="xiaobiucli")
|
|
1266
|
+
add_shared_arguments(parser)
|
|
1267
|
+
subparsers = parser.add_subparsers(dest="command", required=True)
|
|
1268
|
+
|
|
1269
|
+
send_sms = subparsers.add_parser("send-sms")
|
|
1270
|
+
add_shared_arguments(send_sms)
|
|
1271
|
+
send_sms.add_argument("--phone", required=True)
|
|
1272
|
+
send_sms.add_argument("--international-code", default="0086")
|
|
1273
|
+
send_sms.add_argument("--captcha-kind", choices=["iar", "slide", "image"])
|
|
1274
|
+
send_sms.add_argument("--captcha-value")
|
|
1275
|
+
|
|
1276
|
+
login = subparsers.add_parser("login")
|
|
1277
|
+
add_shared_arguments(login)
|
|
1278
|
+
login.add_argument("--phone", required=True)
|
|
1279
|
+
login.add_argument("--sms-code")
|
|
1280
|
+
login.add_argument("--international-code", default="0086")
|
|
1281
|
+
login.add_argument("--captcha-kind", choices=["iar", "slide", "image"])
|
|
1282
|
+
login.add_argument("--captcha-value")
|
|
1283
|
+
|
|
1284
|
+
check = subparsers.add_parser("check")
|
|
1285
|
+
add_shared_arguments(check)
|
|
1286
|
+
families = subparsers.add_parser("families")
|
|
1287
|
+
add_shared_arguments(families)
|
|
1288
|
+
|
|
1289
|
+
devices = subparsers.add_parser("devices")
|
|
1290
|
+
add_shared_arguments(devices)
|
|
1291
|
+
devices.add_argument("--family-id", required=True)
|
|
1292
|
+
|
|
1293
|
+
device_status = subparsers.add_parser("device-status")
|
|
1294
|
+
add_shared_arguments(device_status)
|
|
1295
|
+
device_status.add_argument("--family-id", required=True)
|
|
1296
|
+
device_status.add_argument("--device-id")
|
|
1297
|
+
device_status.add_argument("--raw", action="store_true")
|
|
1298
|
+
|
|
1299
|
+
keep_alive = subparsers.add_parser("keep-alive")
|
|
1300
|
+
add_shared_arguments(keep_alive)
|
|
1301
|
+
return parser
|
|
1302
|
+
|
|
1303
|
+
|
|
1304
|
+
def _client_from_args(args: argparse.Namespace) -> SuningSmartHomeClient:
|
|
1305
|
+
return SuningSmartHomeClient(
|
|
1306
|
+
state_path=args.state_file,
|
|
1307
|
+
har_path=args.har_file,
|
|
1308
|
+
detect=args.detect,
|
|
1309
|
+
dfp_token=args.dfp_token,
|
|
1310
|
+
)
|
|
1311
|
+
|
|
1312
|
+
|
|
1313
|
+
def _print_payload(payload: Any) -> None:
|
|
1314
|
+
print(json.dumps(payload, ensure_ascii=False, indent=2))
|
|
1315
|
+
|
|
1316
|
+
|
|
1317
|
+
def _air_conditioner_status_payload(
|
|
1318
|
+
status: AirConditionerStatus,
|
|
1319
|
+
*,
|
|
1320
|
+
include_raw: bool = False,
|
|
1321
|
+
) -> dict[str, Any]:
|
|
1322
|
+
payload = status.model_dump(mode="json")
|
|
1323
|
+
if not include_raw:
|
|
1324
|
+
payload.pop("raw_status", None)
|
|
1325
|
+
payload.pop("raw_device", None)
|
|
1326
|
+
return payload
|
|
1327
|
+
|
|
1328
|
+
|
|
1329
|
+
def _build_captcha_from_args(args: argparse.Namespace) -> CaptchaSolution | None:
|
|
1330
|
+
captcha_kind = getattr(args, "captcha_kind", None)
|
|
1331
|
+
captcha_value = getattr(args, "captcha_value", None)
|
|
1332
|
+
if captcha_kind or captcha_value:
|
|
1333
|
+
if not captcha_kind or not captcha_value:
|
|
1334
|
+
raise SuningError("captcha-kind 和 captcha-value 必须一起提供")
|
|
1335
|
+
return CaptchaSolution(kind=captcha_kind, value=captcha_value)
|
|
1336
|
+
return None
|
|
1337
|
+
|
|
1338
|
+
|
|
1339
|
+
def _prompt_nonempty(prompt: str) -> str:
|
|
1340
|
+
while True:
|
|
1341
|
+
value = input(prompt).strip()
|
|
1342
|
+
if value:
|
|
1343
|
+
return value
|
|
1344
|
+
print("输入不能为空,请重新输入。")
|
|
1345
|
+
|
|
1346
|
+
|
|
1347
|
+
def _captcha_kind_from_risk_type(risk_type: str | None) -> str | None:
|
|
1348
|
+
mapping = {
|
|
1349
|
+
"isIarVerifyCode": "iar",
|
|
1350
|
+
"isSlideVerifyCode": "slide",
|
|
1351
|
+
"isImgVerifyCode": "image",
|
|
1352
|
+
}
|
|
1353
|
+
if not risk_type:
|
|
1354
|
+
return None
|
|
1355
|
+
return mapping.get(risk_type)
|
|
1356
|
+
|
|
1357
|
+
|
|
1358
|
+
def _send_sms_with_optional_prompt(
|
|
1359
|
+
client: SuningSmartHomeClient,
|
|
1360
|
+
*,
|
|
1361
|
+
phone_number: str,
|
|
1362
|
+
international_code: str,
|
|
1363
|
+
captcha: CaptchaSolution | None = None,
|
|
1364
|
+
) -> dict[str, Any]:
|
|
1365
|
+
active_captcha = captcha
|
|
1366
|
+
while True:
|
|
1367
|
+
try:
|
|
1368
|
+
return client.send_sms_code(
|
|
1369
|
+
phone_number,
|
|
1370
|
+
international_code=international_code,
|
|
1371
|
+
captcha=active_captcha,
|
|
1372
|
+
)
|
|
1373
|
+
except CaptchaRequiredError as error:
|
|
1374
|
+
captcha_kind = _captcha_kind_from_risk_type(error.risk_type)
|
|
1375
|
+
if not captcha_kind:
|
|
1376
|
+
print(
|
|
1377
|
+
f"发送短信前需要验证码 token,但未识别的 riskType={error.risk_type}。"
|
|
1378
|
+
)
|
|
1379
|
+
captcha_kind = _prompt_nonempty("请输入验证码类型 (iar/slide/image): ")
|
|
1380
|
+
if captcha_kind not in {"iar", "slide", "image"}:
|
|
1381
|
+
print("验证码类型只能是 iar、slide 或 image。")
|
|
1382
|
+
active_captcha = None
|
|
1383
|
+
continue
|
|
1384
|
+
else:
|
|
1385
|
+
print(
|
|
1386
|
+
f"发送短信前需要验证码 token,当前风控类型是 {error.risk_type},将按 {captcha_kind} 处理。"
|
|
1387
|
+
)
|
|
1388
|
+
if captcha_kind == "iar":
|
|
1389
|
+
captcha_result = _obtain_iar_captcha_result(
|
|
1390
|
+
client,
|
|
1391
|
+
phone_number=phone_number,
|
|
1392
|
+
)
|
|
1393
|
+
client.update_risk_context(
|
|
1394
|
+
detect=captcha_result.detect,
|
|
1395
|
+
dfp_token=captcha_result.dfp_token,
|
|
1396
|
+
)
|
|
1397
|
+
captcha_value = captcha_result.token
|
|
1398
|
+
else:
|
|
1399
|
+
captcha_value = _prompt_nonempty("请输入验证码 token: ")
|
|
1400
|
+
active_captcha = CaptchaSolution(kind=captcha_kind, value=captcha_value)
|
|
1401
|
+
|
|
1402
|
+
|
|
1403
|
+
def _obtain_iar_captcha_result(
|
|
1404
|
+
client: SuningSmartHomeClient,
|
|
1405
|
+
*,
|
|
1406
|
+
phone_number: str,
|
|
1407
|
+
) -> CaptchaBridgeResult:
|
|
1408
|
+
iar_ticket = client.request_iar_verify_code_ticket(phone_number)
|
|
1409
|
+
bridge = LocalCaptchaBridge(
|
|
1410
|
+
ticket=iar_ticket,
|
|
1411
|
+
script_urls=client.risk_context_script_urls or None,
|
|
1412
|
+
)
|
|
1413
|
+
bridge.start()
|
|
1414
|
+
try:
|
|
1415
|
+
print("请在浏览器打开以下链接。进入页面后,请先点击“开始验证”,再完成苏宁拼图验证:")
|
|
1416
|
+
print(bridge.url)
|
|
1417
|
+
print("验证完成后,终端会自动继续。")
|
|
1418
|
+
result = bridge.wait_for_token(timeout=300.0)
|
|
1419
|
+
if result.detect or result.dfp_token:
|
|
1420
|
+
print("已收到 IAR 验证结果,并回收浏览器风控上下文,继续请求短信。")
|
|
1421
|
+
else:
|
|
1422
|
+
print("已收到 IAR 验证结果,继续请求短信。")
|
|
1423
|
+
return result
|
|
1424
|
+
finally:
|
|
1425
|
+
bridge.close()
|
|
1426
|
+
|
|
1427
|
+
|
|
1428
|
+
def _interactive_login(
|
|
1429
|
+
client: SuningSmartHomeClient,
|
|
1430
|
+
*,
|
|
1431
|
+
phone_number: str,
|
|
1432
|
+
international_code: str,
|
|
1433
|
+
sms_code: str | None,
|
|
1434
|
+
captcha: CaptchaSolution | None,
|
|
1435
|
+
) -> dict[str, Any]:
|
|
1436
|
+
if sms_code:
|
|
1437
|
+
return client.login_with_sms_code(
|
|
1438
|
+
phone_number=phone_number,
|
|
1439
|
+
sms_code=sms_code,
|
|
1440
|
+
international_code=international_code,
|
|
1441
|
+
)
|
|
1442
|
+
|
|
1443
|
+
sms_result = _send_sms_with_optional_prompt(
|
|
1444
|
+
client,
|
|
1445
|
+
phone_number=phone_number,
|
|
1446
|
+
international_code=international_code,
|
|
1447
|
+
captcha=captcha,
|
|
1448
|
+
)
|
|
1449
|
+
print("短信验证码已请求发送。")
|
|
1450
|
+
_print_payload(
|
|
1451
|
+
{
|
|
1452
|
+
"status": "sms_sent",
|
|
1453
|
+
"riskType": client.state.risk_type,
|
|
1454
|
+
"smsTicket": client.state.sms_ticket,
|
|
1455
|
+
"loginTicket": client.state.login_ticket,
|
|
1456
|
+
"response": sms_result,
|
|
1457
|
+
}
|
|
1458
|
+
)
|
|
1459
|
+
sms_code_input = _prompt_nonempty("请输入收到的短信验证码: ")
|
|
1460
|
+
return client.login_with_sms_code(
|
|
1461
|
+
phone_number=phone_number,
|
|
1462
|
+
sms_code=sms_code_input,
|
|
1463
|
+
international_code=international_code,
|
|
1464
|
+
)
|
|
1465
|
+
|
|
1466
|
+
|
|
1467
|
+
def main(argv: list[str] | None = None) -> int:
|
|
1468
|
+
parser = _build_parser()
|
|
1469
|
+
args = parser.parse_args(argv)
|
|
1470
|
+
client = _client_from_args(args)
|
|
1471
|
+
try:
|
|
1472
|
+
if args.command == "send-sms":
|
|
1473
|
+
captcha = _build_captcha_from_args(args)
|
|
1474
|
+
payload = client.send_sms_code(
|
|
1475
|
+
args.phone,
|
|
1476
|
+
international_code=args.international_code,
|
|
1477
|
+
captcha=captcha,
|
|
1478
|
+
)
|
|
1479
|
+
_print_payload(
|
|
1480
|
+
{
|
|
1481
|
+
"status": "sms_sent",
|
|
1482
|
+
"riskType": client.state.risk_type,
|
|
1483
|
+
"smsTicket": client.state.sms_ticket,
|
|
1484
|
+
"loginTicket": client.state.login_ticket,
|
|
1485
|
+
"response": payload,
|
|
1486
|
+
}
|
|
1487
|
+
)
|
|
1488
|
+
return 0
|
|
1489
|
+
if args.command == "login":
|
|
1490
|
+
captcha = _build_captcha_from_args(args)
|
|
1491
|
+
payload = _interactive_login(
|
|
1492
|
+
client,
|
|
1493
|
+
phone_number=args.phone,
|
|
1494
|
+
sms_code=args.sms_code,
|
|
1495
|
+
international_code=args.international_code,
|
|
1496
|
+
captcha=captcha,
|
|
1497
|
+
)
|
|
1498
|
+
check_result = client.query_member_base_info()
|
|
1499
|
+
_print_payload(
|
|
1500
|
+
{
|
|
1501
|
+
"status": "logged_in",
|
|
1502
|
+
"response": payload,
|
|
1503
|
+
"member": check_result,
|
|
1504
|
+
}
|
|
1505
|
+
)
|
|
1506
|
+
return 0
|
|
1507
|
+
if args.command == "check":
|
|
1508
|
+
_print_payload(client.query_member_base_info())
|
|
1509
|
+
return 0
|
|
1510
|
+
if args.command == "families":
|
|
1511
|
+
_print_payload(client.list_families())
|
|
1512
|
+
return 0
|
|
1513
|
+
if args.command == "devices":
|
|
1514
|
+
_print_payload(client.list_devices(args.family_id))
|
|
1515
|
+
return 0
|
|
1516
|
+
if args.command == "device-status":
|
|
1517
|
+
_print_payload(
|
|
1518
|
+
_air_conditioner_status_payload(
|
|
1519
|
+
client.get_air_conditioner_status(
|
|
1520
|
+
args.family_id,
|
|
1521
|
+
device_id=args.device_id,
|
|
1522
|
+
),
|
|
1523
|
+
include_raw=args.raw,
|
|
1524
|
+
)
|
|
1525
|
+
)
|
|
1526
|
+
return 0
|
|
1527
|
+
if args.command == "keep-alive":
|
|
1528
|
+
_print_payload(client.keep_alive())
|
|
1529
|
+
return 0
|
|
1530
|
+
except CaptchaRequiredError as error:
|
|
1531
|
+
_print_payload(
|
|
1532
|
+
{
|
|
1533
|
+
"status": "captcha_required",
|
|
1534
|
+
"riskType": error.risk_type,
|
|
1535
|
+
"smsTicket": error.sms_ticket,
|
|
1536
|
+
"message": str(error),
|
|
1537
|
+
}
|
|
1538
|
+
)
|
|
1539
|
+
return 2
|
|
1540
|
+
except SmsRateLimitedError as error:
|
|
1541
|
+
_print_payload(
|
|
1542
|
+
{
|
|
1543
|
+
"status": "sms_rate_limited",
|
|
1544
|
+
"errorCode": error.error_code,
|
|
1545
|
+
"message": "短信发送过于频繁,请稍后再试。",
|
|
1546
|
+
"detail": str(error),
|
|
1547
|
+
}
|
|
1548
|
+
)
|
|
1549
|
+
return 1
|
|
1550
|
+
except SuningError as error:
|
|
1551
|
+
_print_payload(
|
|
1552
|
+
{
|
|
1553
|
+
"status": "error",
|
|
1554
|
+
"message": str(error),
|
|
1555
|
+
}
|
|
1556
|
+
)
|
|
1557
|
+
return 1
|
|
1558
|
+
return 0
|