This repository has been 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
/
myb_missions_api.py
498 lines (455 loc) · 21.5 KB
/
myb_missions_api.py
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
"""
### 米游社的米游币任务相关API
"""
import asyncio
from typing import List, Optional, Tuple, Set, Type
import httpx
import tenacity
from .data_model import BaseApiStatus, MissionStatus, MissionData, \
MissionState
from .plugin_data import PluginDataManager
from .simple_api import ApiResultHandler, is_incorrect_return
from .user_data import UserAccount
from .utils import logger, generate_ds, \
get_async_retry
_conf = PluginDataManager.plugin_data_obj
URL_SIGN = "https://bbs-api.mihoyo.com/apihub/app/api/signIn"
URL_GET_POST = "https://bbs-api.miyoushe.com/post/api/feeds/posts?fresh_action=1&gids={}&is_first_initialize=false" \
"&last_id="
URL_READ = "https://bbs-api.miyoushe.com/post/api/getPostFull?post_id={}"
URL_LIKE = "https://bbs-api.miyoushe.com/apihub/sapi/upvotePost"
URL_SHARE = "https://bbs-api.miyoushe.com/apihub/api/getShareConf?entity_id={}&entity_type=1"
URL_MISSION = "https://api-takumi.mihoyo.com/apihub/wapi/getMissions?point_sn=myb"
URL_MISSION_STATE = "https://api-takumi.mihoyo.com/apihub/wapi/getUserMissionsState?point_sn=myb"
HEADERS_BASE = {
"Host": "bbs-api.miyoushe.com",
"Referer": "https://app.mihoyo.com",
'User-Agent': _conf.device_config.USER_AGENT_ANDROID_OTHER,
"x-rpc-app_version": _conf.device_config.X_RPC_APP_VERSION,
"x-rpc-channel": _conf.device_config.X_RPC_CHANNEL_ANDROID,
"x-rpc-client_type": "2",
"x-rpc-device_id": None,
"x-rpc-device_model": _conf.device_config.X_RPC_DEVICE_MODEL_ANDROID,
"x-rpc-device_name": _conf.device_config.X_RPC_DEVICE_NAME_ANDROID,
"x-rpc-sys_version": _conf.device_config.X_RPC_SYS_VERSION_ANDROID,
"Accept-Encoding": "gzip",
"Connection": "Keep-Alive",
"DS": None
}
HEADERS_MISSION = {
"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_GET_POSTS = {
"Host": "bbs-api.miyoushe.com",
"Accept": "*/*",
"x-rpc-client_type": "1",
"x-rpc-device_id": None,
"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"
}
# 旧的API
HEADERS_OLD = {
"Host": "bbs-api.mihoyo.com",
"Referer": "https://app.mihoyo.com",
'User-Agent': _conf.device_config.USER_AGENT_ANDROID_OTHER,
"x-rpc-app_version": "2.36.1",
"x-rpc-channel": _conf.device_config.X_RPC_CHANNEL_ANDROID,
"x-rpc-client_type": "2",
"x-rpc-device_id": None,
"x-rpc-device_model": _conf.device_config.X_RPC_DEVICE_MODEL_ANDROID,
"x-rpc-device_name": _conf.device_config.X_RPC_DEVICE_NAME_ANDROID,
"x-rpc-sys_version": _conf.device_config.X_RPC_SYS_VERSION_ANDROID,
"Accept-Encoding": "gzip",
"Connection": "Keep-Alive",
"DS": None
}
class BaseMission:
"""
米游币任务基类
"""
NAME = ""
"""米游社分区名字"""
GIDS = 0
FID = 0
SIGN = "continuous_sign"
'''签到任务的 mission_key'''
VIEW = "view_post_0"
'''阅读任务的 mission_key'''
LIKE = "post_up_0"
'''点赞任务的 mission_key'''
SHARE = "share_post_0"
'''分享任务的 mission_key'''
AVAILABLE_GAMES: Set[Type["BaseMission"]] = set()
"""可用的子类"""
def __init__(self, account: UserAccount) -> None:
"""
米游币任务相关
:param account: 账号对象
"""
self.account = account
self.headers = HEADERS_BASE.copy()
self.headers["x-rpc-device_id"] = account.device_id_android
async def sign(self, retry: bool = True) -> Tuple[MissionStatus, Optional[int]]:
"""
签到
:param retry: 是否允许重试
:return: (BaseApiStatus, 签到获得的米游币数量)
"""
content = {"gids": self.GIDS}
try:
async for attempt in get_async_retry(retry):
with attempt:
headers = HEADERS_OLD.copy()
headers["x-rpc-device_id"] = self.account.device_id_android
headers["DS"] = generate_ds(data=content)
async with httpx.AsyncClient() as client:
res = await client.post(
URL_SIGN,
headers=headers,
json=content,
timeout=_conf.preference.timeout,
cookies=self.account.cookies.dict(v2_stoken=True, cookie_type=True)
)
api_result = ApiResultHandler(res.json())
if api_result.login_expired:
logger.info(
f"米游币任务 - 讨论区签到: 用户 {self.account.bbs_uid} 登录失效")
logger.debug(f"网络请求返回: {res.text}")
return MissionStatus(login_expired=True), None
if api_result.invalid_ds:
logger.info(
f"米游币任务 - 讨论区签到: 用户 {self.account.bbs_uid} DS 校验失败")
logger.debug(f"网络请求返回: {res.text}")
return MissionStatus(invalid_ds=True), None
return api_result.data["points"]
except tenacity.RetryError as e:
if is_incorrect_return(e):
logger.exception(f"米游币任务 - 讨论区签到: 服务器没有正确返回")
logger.debug(f"网络请求返回: {res.text}")
return MissionStatus(incorrect_return=True), None
else:
logger.exception("米游币任务 - 讨论区签到: 请求失败")
return MissionStatus(network_error=True), None
async def get_posts(self, retry: bool = True) -> Tuple[BaseApiStatus, Optional[List[str]]]:
"""
获取文章ID列表,若失败返回 `None`
:param retry: 是否允许重试
:return: (BaseApiStatus, 文章ID列表)
"""
post_id_list = []
try:
async for attempt in get_async_retry(retry):
with attempt:
headers = HEADERS_GET_POSTS.copy()
headers["x-rpc-device_id"] = self.account.device_id_ios
async with httpx.AsyncClient() as client:
res = await client.get(
URL_GET_POST.format(self.GIDS),
headers=headers,
timeout=_conf.preference.timeout
)
api_result = ApiResultHandler(res.json())
for post in api_result.data["list"]:
if post["self_operation"]["attitude"] == 0:
post_id_list.append(post['post']['post_id'])
break
return BaseApiStatus(success=True), post_id_list
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 read(self, read_times: int = 5, retry: bool = True) -> MissionStatus:
"""
阅读
:param read_times: 阅读文章数
:param retry: 是否允许重试
"""
count = 0
get_post_status, posts = await self.get_posts(retry)
if not get_post_status:
return MissionStatus(failed_getting_post=True)
while count < read_times:
for post_id in posts:
if count == read_times:
break
try:
async for attempt in get_async_retry(retry):
with attempt:
self.headers["DS"] = generate_ds(platform="android")
async with httpx.AsyncClient() as client:
res = await client.get(
URL_READ.format(post_id),
headers=self.headers,
timeout=_conf.preference.timeout,
cookies=self.account.cookies.dict(v2_stoken=True, cookie_type=True)
)
api_result = ApiResultHandler(res.json())
if api_result.login_expired:
logger.info(
f"米游币任务 - 阅读: 用户 {self.account.bbs_uid} 登录失效")
logger.debug(f"网络请求返回: {res.text}")
return MissionStatus(login_expired=True)
if api_result.invalid_ds:
logger.info(
f"米游币任务 - 阅读: 用户 {self.account.bbs_uid} DS 校验失败")
logger.debug(f"网络请求返回: {res.text}")
return MissionStatus(invalid_ds=True)
if api_result.message == "帖子不存在":
continue
temp = api_result.data.get("post")
if temp is not None and "self_operation" not in temp:
raise ValueError
count += 1
except tenacity.RetryError as e:
if is_incorrect_return(e, ValueError):
logger.exception(f"米游币任务 - 阅读: 服务器没有正确返回")
logger.debug(f"网络请求返回: {res.text}")
return MissionStatus(incorrect_return=True)
else:
logger.exception(f"米游币任务 - 阅读: 请求失败")
return MissionStatus(network_error=True)
if count != read_times:
await asyncio.sleep(_conf.preference.sleep_time)
get_post_status, posts = await self.get_posts(retry)
if not get_post_status:
return MissionStatus(failed_getting_post=True)
return MissionStatus(success=True)
async def like(self, like_times: int = 10, retry: bool = True) -> MissionStatus:
"""
点赞文章
:param like_times: 点赞次数
:param retry: 是否允许重试
"""
count = 0
get_post_status, posts = await self.get_posts(retry)
if not get_post_status:
return MissionStatus(failed_getting_post=True)
while count < like_times:
for post_id in posts:
if count == like_times:
break
try:
async for attempt in get_async_retry(retry):
with attempt:
headers = HEADERS_OLD.copy()
headers["x-rpc-device_id"] = self.account.device_id_android
headers["DS"] = generate_ds(platform="android")
async with httpx.AsyncClient() as client:
res = await client.post(
URL_LIKE, headers=headers,
json={'is_cancel': False, 'post_id': post_id},
timeout=_conf.preference.timeout,
cookies=self.account.cookies.dict(v2_stoken=True, cookie_type=True)
)
api_result = ApiResultHandler(res.json())
if api_result.login_expired:
logger.info(
f"米游币任务 - 点赞: 用户 {self.account.bbs_uid} 登录失效")
logger.debug(f"网络请求返回: {res.text}")
return MissionStatus(login_expired=True)
if api_result.invalid_ds:
logger.info(
f"米游币任务 - 点赞: 用户 {self.account.bbs_uid} DS 校验失败")
logger.debug(f"网络请求返回: {res.text}")
return MissionStatus(invalid_ds=True)
if api_result.message == "帖子不存在":
continue
if api_result.message != "OK":
raise ValueError
count += 1
except tenacity.RetryError as e:
if is_incorrect_return(e, ValueError):
logger.exception(f"米游币任务 - 点赞: 服务器没有正确返回")
logger.debug(f"网络请求返回: {res.text}")
return MissionStatus(incorrect_return=True)
else:
logger.exception(f"米游币任务 - 点赞: 请求失败")
return MissionStatus(network_error=True)
if count != like_times:
await asyncio.sleep(_conf.preference.sleep_time)
get_post_status, posts = await self.get_posts(retry)
if not get_post_status:
return MissionStatus(failed_getting_post=True)
return MissionStatus(success=True)
async def share(self, retry: bool = True):
"""
分享文章
:param retry: 是否允许重试
"""
get_post_status, posts = await self.get_posts(retry)
if not get_post_status or not posts:
return MissionStatus(failed_getting_post=True)
try:
async for attempt in get_async_retry(retry):
with attempt:
headers = HEADERS_OLD.copy()
headers["x-rpc-device_id"] = self.account.device_id_android
headers["DS"] = generate_ds(platform="android")
async with httpx.AsyncClient() as client:
res = await client.get(
URL_SHARE.format(posts[0]),
headers=headers,
timeout=_conf.preference.timeout,
cookies=self.account.cookies.dict(v2_stoken=True, cookie_type=True)
)
api_result = ApiResultHandler(res.json())
if api_result.login_expired:
logger.info(
f"米游币任务 - 分享: 用户 {self.account.bbs_uid} 登录失效")
logger.debug(f"网络请求返回: {res.text}")
return MissionStatus(login_expired=True)
if api_result.invalid_ds:
logger.info(
f"米游币任务 - 分享: 用户 {self.account.bbs_uid} DS 校验失败")
logger.debug(f"网络请求返回: {res.text}")
return MissionStatus(invalid_ds=True)
if api_result.message == "帖子不存在":
continue
if api_result.message != "OK":
raise ValueError
except tenacity.RetryError as e:
if is_incorrect_return(e, ValueError):
logger.exception(f"米游币任务 - 分享: 服务器没有正确返回")
logger.debug(f"网络请求返回: {res.text}")
return MissionStatus(incorrect_return=True)
else:
logger.exception(f"米游币任务 - 分享: 请求失败")
return MissionStatus(network_error=True)
return MissionStatus(success=True)
class GenshinImpactMission(BaseMission):
"""
原神 米游币任务
"""
NAME = "原神"
GIDS = 2
FID = 26
class HonkaiImpact3Mission(BaseMission):
"""
崩坏3 米游币任务
"""
NAME = "崩坏3"
GIDS = 1
FID = 1
class HoukaiGakuen2Mission(BaseMission):
"""
崩坏学园2 米游币任务
"""
NAME = "崩坏学园2"
GIDS = 3
FID = 30
class TearsOfThemisMission(BaseMission):
"""
未定事件簿 米游币任务
"""
NAME = "未定事件簿"
GIDS = 4
FID = 37
class StarRailMission(BaseMission):
"""
崩坏:星穹铁道 米游币任务
"""
NAME = "崩坏:星穹铁道"
GIDS = 5
FID = 52
class BBSMission(BaseMission):
"""
大别野 米游币任务
"""
NAME = "大别野"
GIDS = 5
# TODO: bbs fid暂时未知
BaseMission.AVAILABLE_GAMES.add(GenshinImpactMission)
BaseMission.AVAILABLE_GAMES.add(HonkaiImpact3Mission)
BaseMission.AVAILABLE_GAMES.add(HoukaiGakuen2Mission)
BaseMission.AVAILABLE_GAMES.add(TearsOfThemisMission)
BaseMission.AVAILABLE_GAMES.add(StarRailMission)
BaseMission.AVAILABLE_GAMES.add(BBSMission)
async def get_missions(account: UserAccount, retry: bool = True) -> Tuple[BaseApiStatus, Optional[List[MissionData]]]:
"""
获取米游币任务信息
: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_MISSION, headers=HEADERS_MISSION,
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
mission_list: List[MissionData] = []
for mission in api_result.data["missions"]:
mission_list.append(MissionData.parse_obj(mission))
return BaseApiStatus(success=True), mission_list
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_missions_state(account: UserAccount, retry: bool = True) -> Tuple[BaseApiStatus, Optional[MissionState]]:
"""
获取米游币任务完成情况
:param account: 用户账号
:param retry: 是否允许重试
"""
get_missions_status, missions = await get_missions(account)
if not get_missions_status:
return get_missions_status, None
try:
async for attempt in get_async_retry(retry):
with attempt:
async with httpx.AsyncClient() as client:
res = await client.get(URL_MISSION_STATE, headers=HEADERS_MISSION,
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
state_dict = {}
for mission in missions:
try:
current = list(filter(lambda state: state["mission_key"] == mission.mission_key,
api_result.data["states"]))[0]["happened_times"]
state_dict.setdefault(mission.mission_key, (mission, current))
except IndexError:
state_dict.setdefault(mission.mission_key, (mission, 0))
return BaseApiStatus(success=True), MissionState(state_dict=state_dict,
current_myb=api_result.data["total_points"])
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