This repository was archived by the owner on Aug 28, 2024. It is now read-only.
forked from Ljzd-PRO/nonebot-plugin-mystool
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsimple_api.py
More file actions
1392 lines (1286 loc) · 61.7 KB
/
simple_api.py
File metadata and controls
1392 lines (1286 loc) · 61.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
### 米游社一些简单API相关
"""
from typing import List, Optional, Tuple, Dict, Any, Union, Type
from urllib.parse import urlencode
import httpx
import tenacity
from pydantic import ValidationError, BaseModel
from requests.utils import dict_from_cookiejar
from .data_model import GameRecord, GameInfo, Good, Address, BaseApiStatus, MmtData, GeetestResult, \
GetCookieStatus, \
CreateMobileCaptchaStatus, GetGoodDetailStatus, ExchangeStatus, GeetestResultV4, GenshinBoard, GenshinBoardStatus
from .plugin_data import PluginDataManager
from .user_data import UserAccount, BBSCookies, ExchangePlan, ExchangeResult
from .utils import generate_device_id, logger, generate_ds, \
NtpTime, get_async_retry
_conf = PluginDataManager.plugin_data_obj
URL_LOGIN_TICKET_BY_CAPTCHA = "https://webapi.account.mihoyo.com/Api/login_by_mobilecaptcha"
URL_LOGIN_TICKET_BY_PASSWORD = "https://webapi.account.mihoyo.com/Api/login_by_password"
URL_MULTI_TOKEN_BY_LOGIN_TICKET = "https://api-takumi.mihoyo.com/auth/api/getMultiTokenByLoginTicket?login_ticket={0}&token_types=3&uid={1}"
URL_COOKIE_TOKEN_BY_CAPTCHA = "https://api-takumi.mihoyo.com/account/auth/api/webLoginByMobile"
URL_COOKIE_TOKEN_BY_STOKEN = "https://passport-api.mihoyo.com/account/auth/api/getCookieAccountInfoBySToken"
URL_LTOKEN_BY_STOKEN = "https://passport-api.mihoyo.com/account/auth/api/getLTokenBySToken"
URL_STOKEN_V2_BY_V1 = "https://passport-api.mihoyo.com/account/ma-cn-session/app/getTokenBySToken"
URL_ACTION_TICKET = "https://api-takumi.mihoyo.com/auth/api/getActionTicketBySToken?action_type=game_role&stoken={stoken}&uid={bbs_uid}"
URL_GAME_RECORD = "https://api-takumi-record.mihoyo.com/game_record/card/wapi/getGameRecordCard?uid={}"
URL_GAME_LIST = "https://bbs-api.mihoyo.com/apihub/api/getGameList"
URL_MYB = "https://api-takumi.mihoyo.com/common/homutreasure/v1/web/user/point?app_id=1&point_sn=myb"
URL_DEVICE_LOGIN = "https://bbs-api.mihoyo.com/apihub/api/deviceLogin"
URL_DEVICE_SAVE = "https://bbs-api.mihoyo.com/apihub/api/saveDevice"
URL_GOOD_LIST = "https://api-takumi.mihoyo.com/mall/v1/web/goods/list?app_id=1&point_sn=myb&page_size=20&page={" \
"page}&game={game} "
URL_CHECK_GOOD = "https://api-takumi.mihoyo.com/mall/v1/web/goods/detail?app_id=1&point_sn=myb&goods_id={}"
URL_EXCHANGE = "https://api-takumi.mihoyo.com/mall/v1/web/goods/exchange"
URL_ADDRESS = "https://api-takumi.mihoyo.com/account/address/list?t={}"
URL_REGISTRABLE = "https://webapi.account.mihoyo.com/Api/is_mobile_registrable?mobile={mobile}&t={t}"
URL_CREATE_MMT = "https://webapi.account.mihoyo.com/Api/create_mmt?scene_type=1&now={now}&reason=user.mihoyo.com%2523%252Flogin%252Fcaptcha&action_type=login_by_mobile_captcha&t={t}"
URL_CREATE_MOBILE_CAPTCHA = "https://webapi.account.mihoyo.com/Api/create_mobile_captcha"
URL_GET_USER_INFO = "https://bbs-api.miyoushe.com/user/api/getUserFullInfo?uid={uid}"
URL_GENSHIN_STATUS_WIDGET = "https://api-takumi-record.mihoyo.com/game_record/app/card/api/getWidgetData?game_id=2"
URL_GENSHEN_STATUS_BBS = "https://api-takumi-record.mihoyo.com/game_record/app/genshin/api/dailyNote"
URL_GENSHEN_STATUS_WIDGET = "https://api-takumi-record.mihoyo.com/game_record/genshin/aapi/widget/v2"
HEADERS_WEBAPI = {
"Host": "webapi.account.mihoyo.com",
"Connection": "keep-alive",
"sec-ch-ua": _conf.device_config.UA,
"DNT": "1",
"x-rpc-device_model": _conf.device_config.X_RPC_DEVICE_MODEL_PC,
"sec-ch-ua-mobile": "?0",
"User-Agent": _conf.device_config.USER_AGENT_PC,
"x-rpc-device_id": None,
"Accept": "application/json, text/plain, */*",
"x-rpc-device_name": _conf.device_config.X_RPC_DEVICE_NAME_PC,
"Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
"x-rpc-client_type": "4",
"sec-ch-ua-platform": _conf.device_config.UA_PLATFORM,
"Origin": "https://user.mihoyo.com",
"Sec-Fetch-Site": "same-site",
"Sec-Fetch-Mode": "cors",
"Sec-Fetch-Dest": "empty",
"Referer": "https://user.mihoyo.com/",
"Accept-Encoding": "gzip, deflate, br",
"Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6"
}
HEADERS_PASSPORT_API = {
"Host": "passport-api.mihoyo.com",
"Content-Type": "application/json",
"Accept": "*/*",
# "x-rpc-device_fp": "",
"x-rpc-client_type": "1",
"x-rpc-device_id": None,
# "x-rpc-app_id": "bll8iq97cem8",
"Accept-Language": "zh-CN,zh-Hans;q=0.9",
"x-rpc-game_biz": "bbs_cn",
"Accept-Encoding": "gzip, deflate, br",
"x-rpc-device_model": _conf.device_config.X_RPC_DEVICE_MODEL_MOBILE,
"User-Agent": _conf.device_config.USER_AGENT_OTHER,
"x-rpc-device_name": _conf.device_config.X_RPC_DEVICE_NAME_MOBILE,
"x-rpc-app_version": _conf.device_config.X_RPC_APP_VERSION,
# 抓包时 "2.47.1"
"x-rpc-sdk_version": "1.6.1",
"Connection": "keep-alive",
"x-rpc-sys_version": _conf.device_config.X_RPC_SYS_VERSION
}
HEADERS_API_TAKUMI_PC = {
"Host": "api-takumi.mihoyo.com",
"Content-Type": "application/json;charset=utf-8",
"Origin": "https://bbs.mihoyo.com",
"Accept-Encoding": "gzip, deflate, br",
"Connection": "keep-alive",
"Accept": "application/json, text/plain, */*",
"User-Agent": _conf.device_config.USER_AGENT_PC,
"Referer": "https://bbs.mihoyo.com/",
"Accept-Language": "zh-CN,zh-Hans;q=0.9"
}
HEADERS_API_TAKUMI_MOBILE = {
"Host": "api-takumi.mihoyo.com",
"x-rpc-device_model": _conf.device_config.X_RPC_DEVICE_MODEL_MOBILE,
"User-Agent": _conf.device_config.USER_AGENT_MOBILE,
"Referer": "https://webstatic.mihoyo.com/",
"x-rpc-device_name": _conf.device_config.X_RPC_DEVICE_NAME_MOBILE,
"Origin": "https://webstatic.mihoyo.com",
"Connection": "keep-alive",
"x-rpc-channel": _conf.device_config.X_RPC_CHANNEL,
"x-rpc-app_version": _conf.device_config.X_RPC_APP_VERSION,
"Accept-Language": "zh-CN,zh-Hans;q=0.9",
"x-rpc-device_id": None,
"x-rpc-client_type": "5",
"Accept": "application/json, text/plain, */*",
"Content-Type": "application/json;charset=utf-8",
"Accept-Encoding": "gzip, deflate, br",
"x-rpc-sys_version": _conf.device_config.X_RPC_SYS_VERSION,
"x-rpc-platform": _conf.device_config.X_RPC_PLATFORM,
"DS": None
}
HEADERS_GAME_RECORD = {
"Host": "api-takumi-record.mihoyo.com",
"Origin": "https://webstatic.mihoyo.com",
"Connection": "keep-alive",
"Accept": "application/json, text/plain, */*",
"User-Agent": _conf.device_config.USER_AGENT_MOBILE,
"Accept-Language": "zh-CN,zh-Hans;q=0.9",
"Referer": "https://webstatic.mihoyo.com/",
"Accept-Encoding": "gzip, deflate, br"
}
HEADERS_GAME_LIST = {
"Host": "bbs-api.mihoyo.com",
"DS": None,
"Accept": "*/*",
"x-rpc-device_id": generate_device_id(),
"x-rpc-client_type": "1",
"x-rpc-channel": _conf.device_config.X_RPC_CHANNEL,
"Accept-Language": "zh-CN,zh-Hans;q=0.9",
"Accept-Encoding": "gzip, deflate, br",
"x-rpc-sys_version": _conf.device_config.X_RPC_SYS_VERSION,
"Referer": "https://app.mihoyo.com",
"x-rpc-device_name": _conf.device_config.X_RPC_DEVICE_NAME_MOBILE,
"x-rpc-app_version": _conf.device_config.X_RPC_APP_VERSION,
"User-Agent": _conf.device_config.USER_AGENT_OTHER,
"Connection": "keep-alive",
"x-rpc-device_model": _conf.device_config.X_RPC_DEVICE_MODEL_MOBILE
}
HEADERS_MYB = {
"Host": "api-takumi.mihoyo.com",
"Origin": "https://webstatic.mihoyo.com",
"Connection": "keep-alive",
"Accept": "application/json, text/plain, */*",
"User-Agent": _conf.device_config.USER_AGENT_MOBILE,
"Accept-Language": "zh-CN,zh-Hans;q=0.9",
"Referer": "https://webstatic.mihoyo.com/",
"Accept-Encoding": "gzip, deflate, br"
}
HEADERS_DEVICE = {
"DS": None,
"x-rpc-client_type": "2",
"x-rpc-app_version": _conf.device_config.X_RPC_APP_VERSION,
"x-rpc-sys_version": _conf.device_config.X_RPC_SYS_VERSION_ANDROID,
"x-rpc-channel": _conf.device_config.X_RPC_CHANNEL_ANDROID,
"x-rpc-device_id": None,
"x-rpc-device_name": _conf.device_config.X_RPC_DEVICE_NAME_ANDROID,
"x-rpc-device_model": _conf.device_config.X_RPC_DEVICE_MODEL_ANDROID,
"Referer": "https://app.mihoyo.com",
"Content-Type": "application/json; charset=UTF-8",
"Host": "bbs-api.mihoyo.com",
"Connection": "Keep-Alive",
"Accept-Encoding": "gzip",
"User-Agent": _conf.device_config.USER_AGENT_ANDROID_OTHER
}
HEADERS_GOOD_LIST = {
"Host":
"api-takumi.mihoyo.com",
"Accept":
"application/json, text/plain, */*",
"Origin":
"https://user.mihoyo.com",
"Connection":
"keep-alive",
"x-rpc-device_id": generate_device_id(),
"x-rpc-client_type":
"5",
"User-Agent":
_conf.device_config.USER_AGENT_MOBILE,
"Referer":
"https://user.mihoyo.com/",
"Accept-Language":
"zh-CN,zh-Hans;q=0.9",
"Accept-Encoding":
"gzip, deflate, br"
}
HEADERS_EXCHANGE = {
"Accept":
"application/json, text/plain, */*",
"Accept-Encoding":
"gzip, deflate, br",
"Accept-Language":
"zh-CN,zh-Hans;q=0.9",
"Connection":
"keep-alive",
"Content-Type":
"application/json;charset=utf-8",
"Host":
"api-takumi.mihoyo.com",
"User-Agent":
_conf.device_config.USER_AGENT_MOBILE,
"x-rpc-app_version":
_conf.device_config.X_RPC_APP_VERSION,
"x-rpc-channel":
"appstore",
"x-rpc-client_type":
"1",
"x-rpc-device_id": None,
"x-rpc-device_model":
_conf.device_config.X_RPC_DEVICE_MODEL_MOBILE,
"x-rpc-device_name":
_conf.device_config.X_RPC_DEVICE_NAME_MOBILE,
"x-rpc-sys_version":
_conf.device_config.X_RPC_SYS_VERSION
}
HEADERS_ADDRESS = {
"Host": "api-takumi.mihoyo.com",
"Accept": "application/json, text/plain, */*",
"Origin": "https://user.mihoyo.com",
"Connection": "keep-alive",
"x-rpc-device_id": None,
"x-rpc-client_type": "5",
"User-Agent": _conf.device_config.USER_AGENT_MOBILE,
"Referer": "https://user.mihoyo.com/",
"Accept-Language": "zh-CN,zh-Hans;q=0.9",
"Accept-Encoding": "gzip, deflate, br"
}
HEADERS_GENSHIN_STATUS_WIDGET = {
"Host": "api-takumi-record.mihoyo.com",
"DS": None,
"Accept": "*/*",
"x-rpc-device_id": None,
"x-rpc-client_type": "1",
"x-rpc-channel": "appstore",
"Accept-Language": "zh-CN,zh-Hans;q=0.9",
"Accept-Encoding": "gzip, deflate, br",
"x-rpc-device_model": _conf.device_config.X_RPC_DEVICE_MODEL_MOBILE,
"Referer": "https://app.mihoyo.com",
"x-rpc-device_name": _conf.device_config.X_RPC_DEVICE_NAME_MOBILE,
"x-rpc-app_version": _conf.device_config.X_RPC_APP_VERSION,
"User-Agent": _conf.device_config.USER_AGENT_WIDGET,
"Connection": "keep-alive",
"x-rpc-sys_version": _conf.device_config.X_RPC_SYS_VERSION
}
HEADERS_GENSHIN_STATUS_BBS = {
"DS": None,
"x-rpc-device_id": None,
"Accept": "application/json,text/plain,*/*",
"Origin": "https://webstatic.mihoyo.com",
"User-agent": _conf.device_config.USER_AGENT_ANDROID,
"Referer": "https://webstatic.mihoyo.com/",
"x-rpc-app_version": _conf.device_config.X_RPC_APP_VERSION,
"X-Requested-With": "com.mihoyo.hyperion",
"x-rpc-client_type": "5"
}
IncorrectReturn = (KeyError, TypeError, AttributeError, IndexError, ValidationError)
"""米游社API返回数据无效会触发的异常组合"""
def is_incorrect_return(exception: Exception, *addition_exceptions: Type[Exception]) -> bool:
"""
判断是否是米游社API返回数据无效的异常
:param exception: 异常对象
:param addition_exceptions: 额外的异常类型,用于触发判断
"""
"""
return exception in IncorrectReturn or
exception.__cause__ in IncorrectReturn or
isinstance(exception, IncorrectReturn) or
isinstance(exception.__cause__, IncorrectReturn)
"""
exceptions = IncorrectReturn + addition_exceptions
return isinstance(exception, exceptions) or isinstance(exception.__cause__, exceptions)
class ApiResultHandler(BaseModel):
"""
API返回的数据处理器
"""
content: Dict[str, Any]
"""API返回的JSON对象序列化以后的Dict对象"""
data: Optional[Dict[str, Any]]
"""API返回的数据体"""
message: Optional[str]
"""API返回的消息内容"""
retcode: Optional[int]
"""API返回的状态码"""
def __init__(self, content: Dict[str, Any]):
super().__init__(content=content)
self.data = self.content.get("data")
for key in ["retcode", "status"]:
if not self.retcode:
self.retcode = self.content.get(key)
if not self.retcode:
self.retcode = self.data.get(key) if self.data else None
self.message: Optional[str] = None
for key in ["message", "msg"]:
if not self.message:
self.message = self.content.get(key)
if not self.message:
self.message = self.data.get(key) if self.data else None
@property
def success(self):
"""
是否成功
"""
return self.retcode == 1 or self.message in ["成功", "OK"]
@property
def wrong_captcha(self):
"""
是否返回验证码错误
"""
return self.retcode in [-201, -302] or self.message in ["验证码错误", "Captcha not match Err"]
@property
def login_expired(self):
"""
是否返回登录失效
"""
return self.retcode in [-100, 10001] or self.message in ["登录失效,请重新登录"]
@property
def invalid_ds(self):
"""
Headers里的DS是否无效
"""
# TODO 2023/4/13: 待补充状态码
# return True if self.retcode == -... or self.message in ["invalid request"] else False
return self.message in ["invalid request"]
async def get_game_record(account: UserAccount, retry: bool = True) -> Tuple[BaseApiStatus, Optional[List[GameRecord]]]:
"""
获取用户绑定的游戏账户信息,返回一个GameRecord对象的列表
:param account: 用户账户数据
:param retry: 是否允许重试
"""
try:
async for attempt in get_async_retry(retry):
with attempt:
async with httpx.AsyncClient() as client:
res = await client.get(URL_GAME_RECORD.format(account.bbs_uid), headers=HEADERS_GAME_RECORD,
cookies=account.cookies.dict(v2_stoken=True, cookie_type=True),
timeout=_conf.preference.timeout)
api_result = ApiResultHandler(res.json())
if api_result.login_expired:
logger.info(
f"获取用户游戏数据(GameRecord) - 用户 {account.bbs_uid} 登录失效")
logger.debug(f"网络请求返回: {res.text}")
return BaseApiStatus(login_expired=True), None
return BaseApiStatus(success=True), list(
map(GameRecord.parse_obj, api_result.data["list"]))
except tenacity.RetryError as e:
if is_incorrect_return(e):
logger.exception("获取用户游戏数据(GameRecord) - 服务器没有正确返回")
logger.debug(f"网络请求返回: {res.text}")
return BaseApiStatus(incorrect_return=True), None
else:
logger.exception("获取用户游戏数据(GameRecord) - 请求失败")
return BaseApiStatus(network_error=True), None
async def get_game_list(retry: bool = True) -> Tuple[BaseApiStatus, Optional[List[GameInfo]]]:
"""
获取米哈游游戏的详细信息,若返回`None`说明获取失败
:param retry: 是否允许重试
"""
headers = HEADERS_GAME_LIST.copy()
try:
async for attempt in get_async_retry(retry):
with attempt:
headers["DS"] = generate_ds()
async with httpx.AsyncClient() as client:
res = await client.get(URL_GAME_LIST, headers=headers, timeout=_conf.preference.timeout)
api_result = ApiResultHandler(res.json())
return BaseApiStatus(success=True), list(
map(GameInfo.parse_obj, api_result.data["list"]))
except tenacity.RetryError as e:
if is_incorrect_return(e):
logger.exception("获取游戏信息(GameInfo) - 服务器没有正确返回")
logger.debug(f"网络请求返回: {res.text}")
return BaseApiStatus(incorrect_return=True), None
else:
logger.exception(f"获取游戏信息(GameInfo) - 请求失败")
return BaseApiStatus(network_error=True), None
async def get_user_myb(account: UserAccount, retry: bool = True) -> Tuple[BaseApiStatus, Optional[int]]:
"""
获取用户当前米游币数量
:param account: 用户账户数据
:param retry: 是否允许重试
"""
try:
async for attempt in get_async_retry(retry):
with attempt:
async with httpx.AsyncClient() as client:
res = await client.get(URL_MYB, headers=HEADERS_MYB,
cookies=account.cookies.dict(v2_stoken=True, cookie_type=True),
timeout=_conf.preference.timeout)
api_result = ApiResultHandler(res.json())
if api_result.login_expired:
logger.info(
f"获取用户米游币 - 用户 {account.bbs_uid} 登录失效")
logger.debug(f"网络请求返回: {res.text}")
return BaseApiStatus(login_expired=True), None
return BaseApiStatus(success=True), int(api_result.data["points"])
except tenacity.RetryError as e:
if is_incorrect_return(e):
logger.exception(f"获取用户米游币 - 服务器没有正确返回")
logger.debug(f"网络请求返回: {res.text}")
return BaseApiStatus(incorrect_return=True), None
else:
logger.exception(f"获取用户米游币 - 请求失败")
return BaseApiStatus(network_error=True), None
async def device_login(account: UserAccount, retry: bool = True):
"""
设备登录(deviceLogin)(适用于安卓设备)
:param account: 用户账户数据
:param retry: 是否允许重试
"""
data = {
"app_version": _conf.device_config.X_RPC_APP_VERSION,
"device_id": account.device_id_android,
"device_name": _conf.device_config.X_RPC_DEVICE_NAME_ANDROID,
"os_version": "30",
"platform": "Android",
"registration_id": "1a0018970a5c00e814d"
}
headers = HEADERS_DEVICE.copy()
headers["x-rpc-device_id"] = account.device_id_android
try:
async for attempt in get_async_retry(retry):
with attempt:
headers["DS"] = generate_ds(data)
async with httpx.AsyncClient() as client:
res = await client.post(URL_DEVICE_LOGIN, headers=headers, json=data,
cookies=account.cookies.dict(v2_stoken=True, cookie_type=True),
timeout=_conf.preference.timeout)
api_result = ApiResultHandler(res.json())
if api_result.login_expired:
logger.info(
f"设备登录(device_login) - 用户 {account.bbs_uid} 登录失效")
logger.debug(f"网络请求返回: {res.text}")
return BaseApiStatus(login_expired=True)
if res.json()["message"] != "OK":
raise ValueError
else:
return BaseApiStatus(success=True)
except tenacity.RetryError as e:
if is_incorrect_return(e):
logger.exception(f"设备登录(device_login) - 服务器没有正确返回")
logger.debug(f"网络请求返回: {res.text}")
return BaseApiStatus(incorrect_return=True)
else:
logger.exception(f"设备登录(device_login) - 请求失败")
return BaseApiStatus(network_error=True)
async def device_save(account: UserAccount, retry: bool = True):
"""
设备保存(saveDevice)(适用于安卓设备)
:param account: 用户账户数据
:param retry: 是否允许重试
"""
data = {
"app_version": _conf.device_config.X_RPC_APP_VERSION,
"device_id": account.device_id_android,
"device_name": _conf.device_config.X_RPC_DEVICE_NAME_ANDROID,
"os_version": "30",
"platform": "Android",
"registration_id": "1a0018970a5c00e814d"
}
headers = HEADERS_DEVICE.copy()
headers["x-rpc-device_id"] = account.device_id_android
try:
async for attempt in get_async_retry(retry):
with attempt:
headers["DS"] = generate_ds(data)
async with httpx.AsyncClient() as client:
res = await client.post(URL_DEVICE_SAVE, headers=headers, json=data,
cookies=account.cookies.dict(v2_stoken=True, cookie_type=True),
timeout=_conf.preference.timeout)
api_result = ApiResultHandler(res.json())
if api_result.login_expired:
logger.info(
f"设备保存(device_save) - 用户 {account.bbs_uid} 登录失效")
logger.debug(f"网络请求返回: {res.text}")
return BaseApiStatus(login_expired=True)
if res.json()["message"] != "OK":
raise ValueError
else:
return BaseApiStatus(success=True)
except tenacity.RetryError as e:
if is_incorrect_return(e):
logger.exception(f"设备保存(device_save) - 服务器没有正确返回")
logger.debug(f"网络请求返回: {res.text}")
return BaseApiStatus(incorrect_return=True)
else:
logger.exception(f"设备保存(device_save) - 请求失败")
return BaseApiStatus(network_error=True)
async def get_good_detail(good: Union[Good, str], retry: bool = True) -> Tuple[GetGoodDetailStatus, Optional[Good]]:
"""
获取某商品的详细信息
:param good: 商品对象 / 商品ID,如果指定为商品对象,则会更新商品对象的数据并返回其引用
:param retry: 是否允许重试
:return: 商品数据
"""
good_id = good.goods_id if isinstance(good, Good) else good
try:
async for attempt in get_async_retry(retry):
with attempt:
async with httpx.AsyncClient() as client:
res = await client.get(URL_CHECK_GOOD.format(good_id), timeout=_conf.preference.timeout)
api_result = ApiResultHandler(res.json())
# TODO 2023/4/13: 待改成对象方法判断
if api_result.message == '商品不存在' or api_result.message == '商品已下架':
return GetGoodDetailStatus(good_not_existed=True), None
if isinstance(good, Good):
return GetGoodDetailStatus(success=True), good.update(api_result.data)
else:
return GetGoodDetailStatus(success=True), Good.parse_obj(api_result.data)
except tenacity.RetryError as e:
if is_incorrect_return(e):
logger.exception(f"米游币商品兑换 - 获取商品详细信息: 服务器没有正确返回")
logger.debug(f"网络请求返回: {res.text}")
return GetGoodDetailStatus(incorrect_return=True), None
else:
logger.exception(f"米游币商品兑换 - 获取商品详细信息: 网络请求失败")
return GetGoodDetailStatus(network_error=True), None
async def get_good_games(retry: bool = True) -> Tuple[BaseApiStatus, Optional[List[Tuple[str, str]]]]:
"""
获取商品分区列表
:param retry: 是否允许重试
:return: (商品分区全名, 字母简称) 的列表
"""
try:
async for attempt in get_async_retry(retry):
with attempt:
async with httpx.AsyncClient() as client:
res = await client.get(URL_GOOD_LIST.format(page=1,
game=""),
headers=HEADERS_GOOD_LIST,
timeout=_conf.preference.timeout)
api_result = ApiResultHandler(res.json())
return BaseApiStatus(success=True), list(map(lambda x: (x["name"], x["key"]), api_result.data["games"]))
except tenacity.RetryError as e:
if is_incorrect_return(e):
logger.exception(f"米游币商品兑换 - 获取商品列表: 服务器没有正确返回")
logger.debug(f"网络请求返回: {res.text}")
return BaseApiStatus(incorrect_return=True), None
else:
logger.exception("米游币商品兑换 - 获取商品列表: 网络请求失败")
return BaseApiStatus(network_error=True), None
async def get_good_list(game: str = "", retry: bool = True) -> Tuple[
BaseApiStatus, Optional[List[Good]]]:
"""
获取商品信息列表
:param game: 游戏简称(默认为空,即获取所有游戏的商品)
:param retry: 是否允许重试
:return: 商品信息列表
"""
good_list = []
page = 1
try:
async for attempt in get_async_retry(retry):
with attempt:
async with httpx.AsyncClient() as client:
res = await client.get(URL_GOOD_LIST.format(page=page,
game=game), headers=HEADERS_GOOD_LIST,
timeout=_conf.preference.timeout)
api_result = ApiResultHandler(res.json())
goods = map(Good.parse_obj, api_result.data["list"])
# 判断是否已经读完所有商品
if not goods:
break
else:
good_list += goods
page += 1
except tenacity.RetryError as e:
if is_incorrect_return(e):
logger.exception("获取商品信息列表 - 获取商品列表: 服务器没有正确返回")
logger.debug(f"网络请求返回: {res.text}")
return BaseApiStatus(incorrect_return=True), None
else:
logger.exception("获取商品信息列表 - 获取商品列表: 网络请求失败")
return BaseApiStatus(network_error=True), None
return BaseApiStatus(success=True), good_list
async def get_address(account: UserAccount, retry: bool = True) -> Tuple[BaseApiStatus, Optional[List[Address]]]:
"""
获取用户的地址数据
:param account: 用户账户数据
:param retry: 是否允许重试
"""
headers = HEADERS_ADDRESS.copy()
headers["x-rpc-device_id"] = account.device_id_ios
try:
async for attempt in get_async_retry(retry):
with attempt:
async with httpx.AsyncClient() as client:
res = await client.get(URL_ADDRESS.format(
round(NtpTime.time() * 1000)), headers=headers,
cookies=account.cookies.dict(v2_stoken=True, cookie_type=True),
timeout=_conf.preference.timeout)
api_result = ApiResultHandler(res.json())
if api_result.login_expired:
logger.info(
f"获取地址数据 - 用户 {account.bbs_uid} 登录失效")
logger.debug(f"网络请求返回: {res.text}")
return BaseApiStatus(login_expired=True), None
address_list = list(map(Address.parse_obj, api_result.data["list"]))
except tenacity.RetryError as e:
if is_incorrect_return(e):
logger.exception("获取地址数据 - 服务器没有正确返回")
logger.debug(f"网络请求返回: {res.text}")
return BaseApiStatus(incorrect_return=True), None
else:
logger.exception("获取地址数据 - 请求失败")
return BaseApiStatus(network_error=True), None
return BaseApiStatus(success=True), address_list
async def check_registrable(phone_number: int, keep_client: bool = False, retry: bool = True) -> Tuple[
BaseApiStatus, Optional[bool], str, Optional[httpx.AsyncClient]]:
"""
检查用户是否可以注册
:param keep_client: httpx.AsyncClient 连接是否需要关闭
:param phone_number: 手机号
:param retry: 是否允许重试
:return: (API返回状态, 用户是否可以注册, 设备ID, httpx.AsyncClient连接对象)
"""
headers = HEADERS_WEBAPI.copy()
device_id = generate_device_id()
headers["x-rpc-device_id"] = device_id
async def request():
"""
发送请求的闭包函数
"""
time_now = round(NtpTime.time() * 1000)
# await client.options(URL_REGISTRABLE.format(mobile=phone_number, t=time_now),
# headers=headers, timeout=conf.preference.timeout)
return await client.get(URL_REGISTRABLE.format(mobile=phone_number, t=time_now),
headers=headers, timeout=_conf.preference.timeout)
try:
async for attempt in get_async_retry(retry):
with attempt:
if keep_client:
client = httpx.AsyncClient()
else:
async with httpx.AsyncClient() as client:
res = await request()
res = await request()
api_result = ApiResultHandler(res.json())
return BaseApiStatus(success=True), bool(api_result.data["is_registable"]), device_id, client
except tenacity.RetryError as e:
if keep_client:
await client.aclose()
if is_incorrect_return(e):
logger.exception(f"检查用户 {phone_number} 是否可以注册 - 服务器没有正确返回")
logger.debug(f"网络请求返回: {res.text}")
return BaseApiStatus(incorrect_return=True), None, device_id, client
else:
logger.exception(f"检查用户 {phone_number} 是否可以注册 - 请求失败")
return BaseApiStatus(network_error=True), None, device_id, None
async def create_mmt(client: Optional[httpx.AsyncClient] = None,
use_v4: bool = True,
device_id: str = generate_device_id(),
retry: bool = True) -> Tuple[
BaseApiStatus, Optional[MmtData], str, Optional[httpx.AsyncClient]]:
"""
发送短信验证前所需的人机验证任务申请
:param client: httpx.AsyncClient 连接
:param use_v4: 是否使用极验第四代人机验证
:param device_id: 设备 ID
:param retry: 是否允许重试
:return: (API返回状态, 人机验证任务数据, 设备ID, httpx.AsyncClient连接对象)
"""
headers = HEADERS_WEBAPI.copy()
headers["x-rpc-device_id"] = device_id
if use_v4:
headers.setdefault("x-rpc-source", "accountWebsite")
async def request():
"""
发送请求的闭包函数
"""
time_now = round(NtpTime.time() * 1000)
# await client.options(URL_CREATE_MMT.format(now=time_now, t=time_now),
# headers=headers, timeout=conf.preference.timeout)
return await client.get(URL_CREATE_MMT.format(now=time_now, t=time_now),
headers=headers, timeout=_conf.preference.timeout)
try:
async for attempt in get_async_retry(retry):
with attempt:
if client:
res = await request()
else:
async with httpx.AsyncClient() as client:
res = await request()
api_result = ApiResultHandler(res.json())
return BaseApiStatus(success=True), MmtData.parse_obj(api_result.data["mmt_data"]), device_id, client
except tenacity.RetryError as e:
if client:
await client.aclose()
if is_incorrect_return(e):
logger.exception("获取短信验证-人机验证任务(create_mmt) - 服务器没有正确返回")
logger.debug(f"网络请求返回: {res.text}")
return BaseApiStatus(incorrect_return=True), None, device_id, client
else:
logger.exception("获取短信验证-人机验证任务(create_mmt) - 请求失败")
return BaseApiStatus(network_error=True), None, device_id, None
async def create_mobile_captcha(phone_number: int,
mmt_data: MmtData,
geetest_result: Union[GeetestResult, GeetestResultV4],
client: Optional[httpx.AsyncClient] = None,
use_v4: bool = True,
device_id: str = generate_device_id(),
retry: bool = True
) -> Tuple[CreateMobileCaptchaStatus, Optional[httpx.AsyncClient]]:
"""
发送短信验证码
:param phone_number: 手机号
:param mmt_data: 人机验证任务数据
:param geetest_result: 人机验证结果数据
:param client: httpx.AsyncClient 连接
:param use_v4: 是否使用极验第四代人机验证
:param device_id: 设备 ID
:param retry: 是否允许重试
"""
headers = HEADERS_WEBAPI.copy()
headers["x-rpc-device_id"] = device_id
if use_v4 and isinstance(geetest_result, GeetestResultV4):
params = {
"action_type": "login",
"mmt_key": mmt_data.mmt_key,
"geetest_v4_data": geetest_result.dict(skip_defaults=True),
"mobile": phone_number,
"t": round(NtpTime.time() * 1000)
}
else:
params = {
"action_type": "login",
"mmt_key": mmt_data.mmt_key,
"geetest_challenge": mmt_data.challenge,
"geetest_validate": geetest_result.validate,
"geetest_seccode": geetest_result.seccode,
"mobile": phone_number,
"t": round(NtpTime.time() * 1000)
}
encoded_params = urlencode(params)
async def request():
"""
发送请求的闭包函数
"""
return await client.post(URL_CREATE_MOBILE_CAPTCHA,
content=encoded_params,
headers=headers,
timeout=_conf.preference.timeout)
try:
async for attempt in get_async_retry(retry):
with attempt:
# FIXME 2023/4/13: 似乎会导致卡在连接状态,暂时弃用
# res = await client.options(URL_CREATE_MOBILE_CAPTCHA,
# headers=headers,
# timeout=conf.preference.timeout)
# cookies.update(res.cookies)
if client and not client.is_closed:
res = await request()
else:
async with httpx.AsyncClient() as client:
res = await request()
api_result = ApiResultHandler(res.json())
if api_result.success:
return CreateMobileCaptchaStatus(success=True), client
elif api_result.wrong_captcha:
return CreateMobileCaptchaStatus(incorrect_geetest=True), client
except tenacity.RetryError as e:
if client:
await client.aclose()
if is_incorrect_return(e):
logger.exception("发送短信验证码 - 服务器没有正确返回")
logger.debug(f"网络请求返回: {res.text}")
return CreateMobileCaptchaStatus(incorrect_return=True), client
else:
logger.exception("发送短信验证码 - 请求失败")
return CreateMobileCaptchaStatus(network_error=True), None
async def get_login_ticket_by_captcha(phone_number: str,
captcha: int,
client: Optional[httpx.AsyncClient] = None,
retry: bool = True) -> \
Tuple[
GetCookieStatus, Optional[BBSCookies]]:
"""
通过短信验证码获取 login_ticket
:param phone_number: 手机号
:param captcha: 短信验证码
:param client: httpx.AsyncClient 连接
:param retry: 是否允许重试
>>> import asyncio
>>> coroutine = get_cookie_token_by_captcha("12345678910", 123456)
>>> assert asyncio.new_event_loop().run_until_complete(coroutine)[0].incorrect_captcha is True
"""
headers = HEADERS_WEBAPI.copy()
headers["x-rpc-device_id"] = generate_device_id()
params = {
"mobile": phone_number,
"mobile_captcha": captcha,
"source": "user.mihoyo.com",
"t": round(NtpTime.time() * 1000),
}
encoded_params = urlencode(params)
async def request():
"""
发送请求的闭包函数
"""
# TODO 还需要进一步简化代码
return await client.post(URL_LOGIN_TICKET_BY_CAPTCHA,
headers=headers,
content=encoded_params,
timeout=_conf.preference.timeout
)
try:
async for attempt in get_async_retry(retry):
with attempt:
if client is not None:
res = await request()
else:
async with httpx.AsyncClient() as client:
res = await request()
api_result = ApiResultHandler(res.json())
if api_result.success:
cookies = BBSCookies.parse_obj(dict_from_cookiejar(
res.cookies.jar))
if not cookies.login_ticket:
return GetCookieStatus(missing_login_ticket=True), None
else:
if client:
await client.aclose()
return GetCookieStatus(success=True), cookies
elif api_result.wrong_captcha:
logger.info(
"通过短信验证码获取 login_ticket - 验证码错误,但你可以再次尝试登录")
return GetCookieStatus(incorrect_captcha=True), None
else:
raise IncorrectReturn
except tenacity.RetryError as e:
if is_incorrect_return(e):
logger.exception(f"通过短信验证码获取 login_ticket: 服务器没有正确返回")
logger.debug(f"网络请求返回: {res.text}")
return GetCookieStatus(incorrect_return=True), None
else:
logger.exception(f"通过短信验证码获取 login_ticket: 网络请求失败")
return GetCookieStatus(network_error=True), None
async def get_multi_token_by_login_ticket(cookies: BBSCookies, retry: bool = True) -> Tuple[
GetCookieStatus, Optional[BBSCookies]]:
"""
通过 login_ticket 获取 `stoken 和 ltoken
:param cookies: 米游社Cookies,需要包含 login_ticket 和 bbs_uid
:param retry: 是否允许重试
"""
if not cookies.login_ticket:
return GetCookieStatus(missing_login_ticket=True), None
elif not cookies.bbs_uid:
return GetCookieStatus(missing_bbs_uid=True), None
try:
async for attempt in get_async_retry(retry):
with attempt:
async with httpx.AsyncClient() as client:
res = await client.get(
URL_MULTI_TOKEN_BY_LOGIN_TICKET.format(cookies.login_ticket, cookies.bbs_uid),
headers=HEADERS_API_TAKUMI_PC,
timeout=_conf.preference.timeout)
api_result = ApiResultHandler(res.json())
if api_result.login_expired:
logger.warning(f"通过 login_ticket 获取 stoken: 登录失效")
return GetCookieStatus(login_expired=True), None
else:
cookies.stoken = list(filter(
lambda x: x["name"] == "stoken", api_result.data["list"]))[0]["token"]
cookies.ltoken = list(filter(
lambda x: x["name"] == "ltoken", api_result.data["list"]))[0]["token"]
return GetCookieStatus(success=True), cookies
except tenacity.RetryError as e:
if is_incorrect_return(e):
logger.exception(f"通过 login_ticket 获取 stoken: 服务器没有正确返回")
logger.debug(f"网络请求返回: {res.text}")
return GetCookieStatus(incorrect_return=True), None
else:
logger.exception(f"通过 login_ticket 获取 stoken: 网络请求失败")
return GetCookieStatus(network_error=True), None
async def get_cookie_token_by_captcha(phone_number: str, captcha: int, retry: bool = True) -> Tuple[
GetCookieStatus, Optional[BBSCookies]]:
"""
通过短信验证码获取 cookie_token
:param phone_number: 手机号
:param captcha: 验证码
:param retry: 是否允许重试
>>> import asyncio
>>> coroutine = get_cookie_token_by_captcha("12345678910", 123456)
>>> assert asyncio.new_event_loop().run_until_complete(coroutine)[0].incorrect_captcha is True
"""
try:
async for attempt in get_async_retry(retry):
with attempt:
async with httpx.AsyncClient() as client:
res = await client.post(URL_COOKIE_TOKEN_BY_CAPTCHA,
headers=HEADERS_API_TAKUMI_PC,
json={
"is_bh2": False,
"mobile": phone_number,
"captcha": str(captcha),
"action_type": "login",
"token_type": 6
},
timeout=_conf.preference.timeout
)
api_result = ApiResultHandler(res.json())
if api_result.wrong_captcha:
logger.info(f"登录米哈游账号 - 验证码错误")
return GetCookieStatus(incorrect_captcha=True), None
else:
cookies = BBSCookies.parse_obj(dict_from_cookiejar(res.cookies.jar))
if not cookies.cookie_token:
return GetCookieStatus(missing_cookie_token=True), None
elif not cookies.bbs_uid:
return GetCookieStatus(missing_bbs_uid=True), None
else:
return GetCookieStatus(success=True), cookies
except tenacity.RetryError as e:
if is_incorrect_return(e):
logger.exception(f"通过短信验证码获取 cookie_token: 服务器没有正确返回")
logger.debug(f"网络请求返回: {res.text}")
return GetCookieStatus(incorrect_return=True), None
else:
logger.exception(f"通过短信验证码获取 cookie_token: 网络请求失败")
return GetCookieStatus(network_error=True), None