-
Notifications
You must be signed in to change notification settings - Fork 2
/
pupu_api.py
1463 lines (1375 loc) · 57.9 KB
/
pupu_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
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
from asyncio import gather as aio_gather
from asyncio import sleep as aio_sleep
from os import path
from random import randint
from sys import version_info as py_version
from time import time
from typing import Any, Optional, Union # 确保兼容<=Python3.9
from utils import GetScriptConfig, log
import json_codec
from aiohttp import ClientResponse
from aiohttp_retry import JitterRetry, RetryClient
from pupu_types import *
assert py_version >= (3, 9)
server_date_diff = None
server_date_updating = False
class ApiBase(object):
# __slots__ = ("__session", "__receiver")
def __init__(self, device_id: str):
assert device_id
self.__device_id = device_id.upper()
self.__su_id = self.__access_token = self.__user_id = None
self.__receiver = PReceiverInfo("")
self.__init_http()
def __init_http(self):
async def RetryWhenBusy(resp: ClientResponse) -> bool:
obj = await resp.json()
code = obj.get("errcode") or 0
msg = obj.get("errmsg") or ""
if code == -1 and "稍后再试" in msg:
# 系统繁忙,请稍后再试。
return False
return True
self.__session = RetryClient(
raise_for_status=True,
retry_options=JitterRetry(
attempts=3, evaluate_response_callback=RetryWhenBusy
),
)
self.__session._client.headers["Accept"] = "application/json, text/plain, */*"
self.__session._client.headers["Accept-Encoding"] = "gzip;q=1.0, compress;q=0.5"
self.__session._client.headers["Accept-Language"] = (
"zh-Hans-CN;q=1.0, ja-CN;q=0.9, en-CN;q=0.8"
)
self.__session._client.headers["pp-version"] = "2023018200"
self.__session._client.headers["Connection"] = "keep-alive"
async def Release(self):
if self.__session._closed:
return
await self.__session.close()
# Wait 250 ms for the underlying SSL connections to close
await aio_sleep(0.250)
@property
def native_user_agent(self):
if self.__device_id:
id = f";{self.__device_id}"
else:
id = ""
return f"Pupumall/3.6.1;iOS 15.7.1{id}"
@property
def web_user_agent(self):
if self.__device_id:
id = f" D/{self.__device_id}"
else:
id = ""
return f"Mozilla/5.0 (iPhone; CPU iPhone OS 15_7_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148{id}"
@property
def access_token(self):
return self.__access_token
@access_token.setter
def access_token(self, token: Optional[str]):
self.__access_token = token
if token:
self.__session._client.headers["Authorization"] = f"Bearer {token}"
elif "Authorization" in self.__session._client.headers:
del self.__session._client.headers["Authorization"]
@property
def device_id(self):
return self.__device_id
@property
def su_id(self):
return self.__su_id
@su_id.setter
def su_id(self, id: Optional[str]):
self.__su_id = id
if id:
self.__session._client.headers["pp-suid"] = id
elif "pp-suid" in self.__session._client.headers:
del self.__session._client.headers["pp-suid"]
@property
def user_id(self):
return self.__user_id
@user_id.setter
def user_id(self, id: Optional[str]):
self.__user_id = id
if id:
self.__session._client.headers["pp-userid"] = id
elif "pp-userid" in self.__session._client.headers:
del self.__session._client.headers["pp-userid"]
@property
def receiver(self):
return self.__receiver
@receiver.setter
def receiver(self, receiver: PReceiverInfo):
self.__receiver = receiver
if receiver.place_id:
self.__session._client.headers["pp-placeid"] = receiver.place_id
elif "pp-placeid" in self.__session._client.headers:
del self.__session._client.headers["pp-placeid"]
if receiver.store_id:
# 朴朴这里用的下划线
self.__session._client.headers["pp_storeid"] = receiver.store_id
elif "pp_storeid" in self.__session._client.headers:
del self.__session._client.headers["pp_storeid"]
async def GetServerTime(self, force=False):
"""获得与服务器尽可能一致的时间戳"""
global server_date_diff, server_date_updating
while server_date_updating:
await aio_sleep(0)
if server_date_diff is None or force:
try:
server_date_updating = True
result = await self.ComputeServerTimeDiff()
finally:
server_date_updating = False
if isinstance(result, ApiResults.Error):
log(result)
if server_date_diff is None:
return int(time() * 1000)
else:
server_date_diff = result
return int(time() * 1000 + server_date_diff)
@staticmethod
def TryGetServerTime():
"""类似GetServerTime"""
global server_date_diff
if server_date_diff is not None:
return int(time() * 1000 + server_date_diff)
return None
async def ComputeServerTimeDiff(self):
"""计算本地时间与服务器时间的时间差"""
try:
obj = await self._SendRequest(
HttpMethod.kGet,
"https://j1.pupuapi.com/client/base/data",
client=ClientType.kWeb,
headers={
"Origin": "https://ma.pupumall.com",
"Referer": "https://ma.pupumall.com/",
},
)
if obj["errcode"] == 0:
data = obj["data"]
if "server_time" not in data:
raise ValueError("server_time 没了")
server_time = int(data["server_time"])
diff = server_time - int(time() * 1000)
if diff > 1000:
log(f"注意: 本地时间与服务器相差{diff/1000}秒")
return diff
else:
return ApiResults.Error(json=obj)
except Exception:
return ApiResults.Exception()
async def _SendRequest(
self,
method: HttpMethod,
url: str,
client=ClientType.kNative,
headers: Optional[dict] = None,
params: Optional[dict] = None,
data=None,
json=None,
):
"""发起一个HTTP请求"""
req_headers = {}
if client == ClientType.kNative:
req_headers["User-Agent"] = self.native_user_agent
req_headers["pp-os"] = "20" # "0" for wechat
if self.__receiver.place_zip:
req_headers["pp-placezip"] = str(self.__receiver.place_zip)
elif client == ClientType.kWeb:
req_headers["User-Agent"] = self.web_user_agent
req_headers["pp-os"] = "201"
if self.__receiver.city_zip:
req_headers["pp-cityzip"] = str(self.__receiver.city_zip)
else:
raise NotImplementedError
if headers:
req_headers.update(headers)
async with self.__session.request(
ssl=False,
method=method.value,
url=url,
headers=req_headers,
params=params,
data=data,
json=json,
) as response:
# server_date = response.headers.getone("Date", None)
# if server_date:
# from datetime import datetime
# from email.utils import parsedate
# parsedate(server_date)
return await response.json()
class Api(ApiBase):
def __init__(
self,
device_id: str,
refresh_token: str,
access_token: Optional[str],
expires_in: Optional[int],
):
if not (device_id and refresh_token):
raise ValueError("参数没有正确设置")
super().__init__(device_id=device_id)
self.__refresh_token: Optional[str] = refresh_token
self._nickname = self._avatar = None
self.__expires_in = expires_in or 0
self.access_token = access_token
@property
def nickname(self) -> Optional[str]:
return self._nickname
@property
def avatar(self) -> Optional[str]:
return self._avatar
@property
def refresh_token(self):
return self.__refresh_token
@refresh_token.setter
def refresh_token(self, token: Optional[str]):
self.__refresh_token = token
@property
def expires_in(self):
return self.__expires_in
@expires_in.setter
def expires_in(self, v: Optional[int]):
self.__expires_in = v or 0
async def RefreshAccessToken(self):
"""刷新AccessToken 有效期通常只有2小时"""
initial_tasks: list[Any] = [self.GetServerTime()]
if not self.su_id:
initial_tasks.append(self.GetSuID())
current_time = (await aio_gather(*initial_tasks))[0]
if self.access_token and current_time + 360_000 < self.expires_in:
# access_token 有效
return ApiResults.TokenValid()
self.access_token = None
self.user_id = None
try:
if not self.__refresh_token:
raise ValueError("没有配置 refresh_token")
obj = await self._SendRequest(
HttpMethod.kPut,
"https://cauth.pupuapi.com/clientauth/user/refresh_token",
json={"refresh_token": self.__refresh_token},
)
if obj["errcode"] == 0:
data = obj["data"]
self.access_token = data.get("access_token")
self.user_id = data.get("user_id")
# refresh_token 在临期时会更新 我们需要保存新的token 否则很快就得重新登录
prev_refresh_token = self.__refresh_token
self.__refresh_token = data.get("refresh_token") or self.__refresh_token
self.__expires_in = int(data.get("expires_in") or 0)
self._nickname = data.get("nick_name")
return ApiResults.TokenRefreshed(
refresh_token=self.__refresh_token,
access_expires=self.__expires_in,
changed=self.__refresh_token != prev_refresh_token,
)
else:
if obj["errcode"] == 403 or (
obj["errcode"] != 200099 and obj["errcode"] in range(200000, 300000)
):
self.__refresh_token = None
return ApiResults.Error(json=obj)
except Exception:
return ApiResults.Exception()
async def GetSuID(self):
try:
obj = await self._SendRequest(
HttpMethod.kGet,
"https://j1.pupuapi.com/client/caccount/user/suid",
params={"device_id": self.device_id},
)
if obj["errcode"] == 0:
self.su_id = obj["data"]
return ApiResults.SuId(id=self.su_id)
else:
return ApiResults.Error(json=obj)
except Exception:
return ApiResults.Exception()
async def GetUserInfo(self):
"""
获得自己的头像、手机、昵称
"user_id": "xxxx-xx-xx-xx-xxxxxx",
"nick_name": "xxxx",
"sex": 0,
"phone": "13800138000",
"avatar": "https://imgs.static.pupumall.com/NEW_AVATAR_PIC/xxxxx.jpeg",
"zip": 0,
"is_novice": false,
"time_create": 1638444954328,
"invite_code": "xxxx-xx-xx-xx-xxxxxx",
"can_delete": false,
"is_deleted": false
"""
try:
obj = await self._SendRequest(
HttpMethod.kGet, "https://cauth.pupuapi.com/clientauth/user/info"
)
if obj["errcode"] == 0:
data = obj["data"]
self._avatar = data.get("avatar")
self._nickname = data.get("nick_name")
return ApiResults.UserInfo(avatar=self._avatar, nickname=self._nickname)
else:
return ApiResults.Error(json=obj)
except Exception:
return ApiResults.Exception()
async def UpdateReceiver(self, filter: Optional[str] = None):
"""获得收货地址"""
try:
obj = await self._SendRequest(
HttpMethod.kGet, "https://j1.pupuapi.com/client/account/receivers"
)
if obj["errcode"] == 0:
data = obj["data"]
time_last_order: int = -1
info = None
for r in data:
# r["is_in_service"] 意味地址是否可以配送
if (
r.get("is_default")
or int(r.get("time_last_order") or 0) > time_last_order
):
time_last_order = int(r.get("time_last_order") or 0)
place = r["place"]
info = PReceiverInfo(
id=str(r["id"]),
address=r["address"],
room_num=r["building_room_num"],
lng_x=place.get("lng_x") or r["lng_x"],
lat_y=place.get("lat_y") or r["lat_y"],
receiver_name=r["name"],
phone_number=r["mobile"],
store_id=place.get("service_store_id")
or r["service_store_id"],
place_id=place["id"],
city_zip=place.get("store_city_zip") or 0,
)
self.user_id = r.get("user_id") or self.user_id
info.place_zip = int(place.get("zip") or info.city_zip)
building_name = None
room_num = r.get("room_num")
if place.get("have_building", False):
place_building = r.get("place_building")
if (
place_building
and place_building.get("is_deleted", False) == False
):
building_name = place_building.get("building_name")
if building_name and room_num:
info.room_num = f"{building_name} {room_num}"
if filter:
# 配置了地址过滤
if info.address.find(filter) != -1:
# 匹配上了
break
info = None # 不符合筛选条件 需要置空
time_last_order = 0
elif r.get("is_default"):
# 如果是默认地址则直接用(似乎朴朴并没有设置)
break
if not info:
if filter:
raise ValueError(
f"没有符合筛选条件的收货地址, 当前条件`{filter}`"
)
else:
raise ValueError("没有收货地址")
self.receiver = info
return ApiResults.ReceiverInfo(info)
else:
return ApiResults.Error(json=obj)
except Exception:
return ApiResults.Exception()
async def SignIn(self):
"""签到"""
try:
obj = await self._SendRequest(
HttpMethod.kPost,
"https://j1.pupuapi.com/client/game/sign/v2",
params={"city_zip": self.receiver.city_zip, "supplement_id": ""},
client=ClientType.kWeb,
)
if obj["errcode"] == 0:
data = obj["data"]
# 朴分
return ApiResults.SignIn(
coin=data["daily_sign_coin"], explanation=data["reward_explanation"]
)
else:
return ApiResults.Error(json=obj)
except Exception:
return ApiResults.Exception()
async def GetSignPeriodInfo(self):
"""获得本周连续签到的天数"""
try:
obj = await self._SendRequest(
HttpMethod.kGet, "https://j1.pupuapi.com/client/game/sign/period_info"
)
if obj["errcode"] == 0:
data = obj["data"]
return ApiResults.SignPeriodInfo(data["signed_days"])
else:
return ApiResults.Error(json=obj)
except Exception:
return ApiResults.Exception()
async def GetCoinConfig(self):
"""朴分下单抽大奖"""
try:
obj = await self._SendRequest(
HttpMethod.kGet, "https://j1.pupuapi.com/client/coin/unclaimed/config"
)
if obj["errcode"] == 0:
data = obj["data"]
return str(data["lottery_id"])
else:
return ApiResults.Error(json=obj)
except Exception:
return ApiResults.Exception()
async def GetCoinList(self):
"""可领取的朴分IDs"""
try:
obj = await self._SendRequest(
HttpMethod.kGet, "https://j1.pupuapi.com/client/coin/unclaimed/list"
)
if obj["errcode"] == 0:
data = obj["data"]
return [str(item["id"]) for item in data]
else:
return ApiResults.Error(json=obj)
except Exception:
return ApiResults.Exception()
async def DrawCoin(self, id: str):
"""领取朴分"""
try:
obj = await self._SendRequest(
HttpMethod.kPost, f"https://j1.pupuapi.com/client/coin/unclaimed/{id}"
)
# obj["errcode"] == 400000 # 已领取
if obj["errcode"] == 0:
data = obj["data"]
return int(data["coin"])
else:
return ApiResults.Error(json=obj)
except Exception:
return ApiResults.Exception()
async def GetBanner(
self,
link_type: BANNER_LINK_TYPE,
position_types: Optional[list[Union[int, str]]] = None,
):
assert not self.receiver.id_empty
try:
co_req = self._SendRequest(
HttpMethod.kGet,
"https://j1.pupuapi.com/client/marketing/banner/v7",
params={
"position_types": (
",".join(str(p) for p in position_types)
if position_types
else -1
),
"store_id": self.receiver.store_id,
},
)
now, obj = await aio_gather(self.GetServerTime(), co_req)
if obj["errcode"] == 0:
link_ids = set[str]()
banners = []
data = obj["data"]
for item in data:
if (
"link_type" in item
and BANNER_LINK_TYPE(item["link_type"]) == link_type
):
time_open = item.get("time_open") or 0
time_close = item.get("time_close") or (now + 60_000)
if now < time_open or now + 60_000 > time_close:
# 不在效期内 忽略
continue
link_id = item.get("link_id")
if link_id not in link_ids:
# 避免重复
link_ids.add(link_id)
banners.append(
PBanner(
title=item.get("title") or item.get("name"),
link_id=link_id,
)
)
return ApiResults.Banner(banners)
else:
return ApiResults.Error(json=obj)
except Exception:
return ApiResults.Exception()
async def GetLotteryInfo(self, id: str):
"""获取抽奖活动的信息"""
try:
obj = await self._SendRequest(
HttpMethod.kGet,
f"https://j1.pupuapi.com/client/game/custom_lottery/activities/{id}/element_configuration",
client=ClientType.kWeb,
)
if obj["errcode"] == 0:
data = obj["data"]
lottery = PLotteryInfo(
id=id,
name=data["activity_name"], # 开运新年签
type=LOTTERY_TYPE(data["lottery_type"]),
)
for prize in data.get("prize_info") or []:
# 解析奖品
if (
"prize_level" in prize
and "prize_type" in prize
and "prize_name" in prize
):
p = PPrize(
level=prize["prize_level"],
name=prize["prize_name"],
type=RewardType(prize["prize_type"]),
)
lottery.prizes[p.level] = p
task_system_link = data.get("task_system_link") or {}
lottery.task_system_link_id = task_system_link.get("link_id")
if lottery.task_system_link_id:
link_type = BANNER_LINK_TYPE(task_system_link["link_type"])
if link_type != BANNER_LINK_TYPE.USER_TASK:
print(
f"警告: 抽奖任务遇到了不识别的link_type '{link_type.name}'"
)
lottery.task_system_link_id = None
return ApiResults.LotteryInfo(lottery)
else:
# 获取抽奖信息失败
return ApiResults.Error(json=obj)
except Exception:
return ApiResults.Exception()
async def GetUserLotteryInfo(self, lottery: PLotteryInfo):
try:
obj = await self._SendRequest(
HttpMethod.kGet,
f"https://j1.pupuapi.com/client/game/custom_lottery/activities/{lottery.id}/user_chances",
client=ClientType.kWeb,
)
if obj["errcode"] == 0:
num = obj["data"].get("remain_chance_num") or 0
return ApiResults.UserLotteryInfo(remain_chances=num)
else:
return ApiResults.Error(json=obj)
except Exception:
return ApiResults.Exception()
async def GetTaskGroupsData(self, lottery: Union[PLotteryInfo, PCollectCardRule]):
"""获取任务列表"""
task_id = (
lottery.task_system_link_id
if isinstance(lottery, PLotteryInfo)
else lottery.card_get_task_id
)
if not task_id:
return ApiResults.TaskGroupsData([])
try:
tasks: list[PTask] = []
obj = await self._SendRequest(
HttpMethod.kGet,
f"https://j1.pupuapi.com/client/game/task_system/user_tasks/task_groups/{task_id}",
client=ClientType.kWeb,
)
if obj["errcode"] == 0:
data = obj["data"]
hide_type = HideTaskType(data.get("hide_task_type") or 0)
if hide_type != HideTaskType.List:
print(f"检测到非List的任务列表 HideTaskType {hide_type}")
tasks_json: list = data.get("tasks") or []
for task_json in tasks_json:
if "task_status" not in task_json:
continue
try:
base_behavior_event_target_code = int(
task_json.get("base_behavior_event_target_code") or 0
)
page_url = answer_rule = None
link_id = task_json.get("link_id") or ""
link_type = task_json.get("link_type") or 0
page_task_rule = task_json.get("page_task_rule")
if page_task_rule:
# 浏览型任务
page_url = PPageRule(
skim_time=page_task_rule["skim_time"],
activity_id=page_task_rule["activity_id"],
task_type=TaskType(
page_task_rule.get("task_type") or 0
),
action_type=ActionTYPE(page_task_rule["action_type"]),
)
# if page_url.action_type != ActionTYPE.BROWSE:
# continue
elif link_id and (
base_behavior_event_target_code == 2701
or base_behavior_event_target_code == 2702
):
# 2301 ==> CUSTOM_LOTTERY_ASSIST and target_type ==> 302 CUSTOM_LOTTERY
# 2501 ==> WORLD_CUP_BETS
# 2601 ==> CUSTOM_EVENT_TEAM and target_type ==> 310 TEAM_ENTRANCE
# 2801 ==> 开启AppPush权限
# # link_type == 550
# 答题任务
answer_rule = PAnswerRule(
answer_is_done=task_json.get("answer_is_done", True)
)
elif base_behavior_event_target_code == 3001:
# 打卡任务
pass
else:
# 其它任务暂不支持
continue
tasks.append(
PTask(
task_name=task_json["task_name"],
task_id=task_json["task_id"],
task_status=TaskStatus(task_json["task_status"]),
page_rule=page_url,
answer_rule=answer_rule,
link_id=link_id,
target_code=base_behavior_event_target_code,
reward_type=TaskRewardType(
task_json.get("reward_type") or 255
),
)
)
except Exception:
print(f"警告: 解析任务时遇到异常 {ApiResults.Exception()}")
return ApiResults.TaskGroupsData(tasks)
else:
return ApiResults.Error(json=obj)
except Exception:
return ApiResults.Exception()
async def ClockInTask(self, lottery: PLotteryInfo, task: PTask):
"""完成打卡任务"""
if task.target_code != 3001:
return ApiResults.Error(json=None)
try:
obj = await self._SendRequest(
HttpMethod.kPost,
f"https://j1.pupuapi.com/client/game/task_system/user_tasks/task/{lottery.task_system_link_id}/{task.task_id}/clock",
client=ClientType.kWeb,
)
if obj["errcode"] == 0:
# reward_type = obj["data"].get("receive_reward_type")
# 0 : 手动领奖
# 10 : 自动领奖
return ApiResults.TaskCompleted()
else:
return ApiResults.Error(json=obj)
except Exception:
return ApiResults.Exception()
async def PostPageTaskComplete(self, task: PTask):
"""完成浏览任务"""
if not task.page_rule:
return ApiResults.Error(json=None)
# 此任务从何时完成
time_end: int = await self.GetServerTime() - randint(1, 8) * 1000
# 此任务从何时开始
time_from: int = time_end - task.page_rule.skim_time * 1000 - randint(1, 20)
json = {
"activity_id": task.page_rule.activity_id,
"task_type": task.page_rule.task_type,
"action_type": task.page_rule.action_type,
"task_id": task.task_id,
"time_from": time_from,
"time_end": time_end,
}
try:
obj = await self._SendRequest(
HttpMethod.kPost,
"https://j1.pupuapi.com/client/game/task_system/user_tasks/page_task_complete",
json=json,
client=ClientType.kWeb,
)
if obj["errcode"] == 0:
return ApiResults.TaskCompleted()
else:
return ApiResults.Error(json=obj)
except Exception:
return ApiResults.Exception()
async def GetQuestionnaire(self, task: PTask):
"""查询问卷题目"""
try:
obj = await self._SendRequest(
HttpMethod.kGet,
f"https://j1.pupuapi.com/client/user_behavior/questionnaire/papers/{task.link_id}",
client=ClientType.kWeb,
)
if obj["errcode"] == 0:
data = obj["data"]
time_start_answer = data["time_start_answer"]
questions = json_codec.decode(
data["paper_info"].get("questions") or [], list[PQuestion]
)
questionnaire = ApiResults.Questionnaire(
id=data["paper_info"]["id"],
time_start_answer=time_start_answer,
questions=questions,
)
for q in questionnaire.questions:
q.question_id = q.id
return questionnaire
else:
return ApiResults.Error(json=obj)
except Exception:
return ApiResults.Exception()
async def SubmitQuestionnaire(self, questionnaire: ApiResults.Questionnaire):
"""提交问卷"""
try:
obj = await self._SendRequest(
HttpMethod.kPost,
"https://j1.pupuapi.com/client/user_behavior/questionnaire/papers",
json={
"time_start_answer": questionnaire.time_start_answer,
"paper_id": questionnaire.id,
"answer_commits": json_codec.encode(questionnaire.questions),
},
client=ClientType.kWeb,
)
if obj["errcode"] == 0:
return bool(obj.get("data") or False)
else:
return ApiResults.Error(json=obj)
except Exception:
return ApiResults.Exception()
async def GetQuestionnaireAnswerResult(self, task: PTask):
"""查询问题回答结果"""
try:
obj = await self._SendRequest(
HttpMethod.kGet,
f"https://j1.pupuapi.com/client/user_behavior/questionnaire/papers/{task.link_id}/answer_result",
client=ClientType.kWeb,
)
if obj["errcode"] == 0:
result: list[ApiResults.AnswerResult] = []
data = obj["data"]
question_answers = data.get("question_answers") or []
for question in question_answers:
question_id = question["question_id"]
answers = question.get("answer_options") or []
correct = False
standard = ""
for answer in answers:
is_standard = answer.get("is_standard") or False
if is_standard:
standard = answer["name"]
correct = answer.get("selected") == 1
break
result.append(
ApiResults.AnswerResult(
question_id=question_id, standard=standard, result=correct
)
)
return result
else:
return ApiResults.Error(json=obj)
except Exception:
return ApiResults.Exception()
async def GetChanceEntrances(self, lottery: PLotteryInfo):
try:
obj = await self._SendRequest(
HttpMethod.kGet,
f"https://j1.pupuapi.com/client/game/custom_lottery/activities/{lottery.id}/obtain_chance_entrance",
client=ClientType.kWeb,
)
if obj["errcode"] == 0:
data = obj["data"]
coin_balance = int(data.get("coin_balance") or 0)
entrances: list[PChanceEntrance] = []
for item in data.get("chance_obtain_entrance") or []:
if (
"code" in item
and "attend_count" in item
and "limit_count" in item
and "gain_num" in item
and "target_value" in item
):
pitem = PChanceEntrance(
type=CHANCE_OBTAIN_TYPE(item["code"]),
title=item.get("title") or "未知",
attend_count=item["attend_count"],
limit_count=item["limit_count"],
target_value=int(item["target_value"]),
gain_num=int(item["gain_num"]),
)
if pitem.attend_count >= pitem.limit_count:
# 达到限制量 跳过
print(f" {pitem.title} 达到限制 {pitem.limit_count} 跳过")
continue
entrances.append(pitem)
return ApiResults.ChanceEntrances(coin_balance, entrances)
else:
return ApiResults.Error(json=obj)
except Exception:
return ApiResults.Exception()
async def CoinExchange(self, lottery: PLotteryInfo, entrance: PChanceEntrance):
"""开始朴分兑换"""
try:
obj = await self._SendRequest(
HttpMethod.kPost,
f"https://j1.pupuapi.com/client/game/custom_lottery/activities/{lottery.id}/coin_exchange",
params={"lng_x": self.receiver.lng_x, "lat_y": self.receiver.lat_y},
json={},
client=ClientType.kWeb,
)
if obj["errcode"] == 0:
entrance.attend_count += 1
return ApiResults.CoinExchanged(entrance.gain_num)
else:
return ApiResults.Error(json=obj)
except Exception:
return ApiResults.Exception()
async def Lottery(self, lottery: PLotteryInfo):
"""开始抽奖"""
try:
obj = await self._SendRequest(
HttpMethod.kPost,
f"https://j1.pupuapi.com/client/game/custom_lottery/activities/{lottery.id}/lottery",
params={"lng_x": self.receiver.lng_x, "lat_y": self.receiver.lat_y},
json={},
client=ClientType.kWeb,
)
if obj["errcode"] == 0:
prize = lottery.prizes[obj["data"]["prize_level"]]
return ApiResults.LotteryResult(prize)
else:
return ApiResults.Error(json=obj)
except Exception:
return ApiResults.Exception()
async def GetProductCollections(self, page: int, page_size: int = 10):
"""获取商品收藏列表"""
assert not self.receiver.id_empty
try:
obj = await self._SendRequest(
HttpMethod.kGet,
f"https://j1.pupuapi.com/client/user_behavior/product_collection/store/{self.receiver.store_id}/products",
params={"page": page, "size": page_size},
)
if obj["errcode"] == 0:
data = obj["data"]
products = []
# 总共收藏了{total_count}件商品
total_count: int = data.get("count") or 0
for p in data.get("products") or []:
# TODO 若 p["sell_batches"] 不为空,则以该数组的最低价作为当前价格
product = PProduct(
name=p["name"],
price=p["price"],
product_id=p["product_id"],
store_product_id=p["id"],
purchase_type=PURCHASE_TYPE(
p.get("purchase_type") or PURCHASE_TYPE.GENERAL
),
spread_tag=SPREAD_TAG(
p.get("spread_tag") or SPREAD_TAG.NORMAL_PRODUCT
),
stock_quantity=p.get("stock_quantity") or 0,
order_remarks=p.get("order_remarks") or [],
)
if product.spread_tag == SPREAD_TAG.FLASH_SALE_PRODUCT:
flash_sale_info = p.get("flash_sale_info") or {}
progress_rate: float = (
flash_sale_info.get("progress_rate") or 0.0
)
if flash_sale_info and progress_rate < 1.0:
# 限购N件
product.quantity_limit = (
flash_sale_info.get("quantity_each_person_limit") or 1
)
products.append(product)
return ApiResults.ProductCollections(total_count, products)
else:
return ApiResults.Error(json=obj)
except Exception:
return ApiResults.Exception()
async def GetUsableCoupons(self, type: DiscountType, products: list[PProduct]):
"""获得可用的优惠券"""
assert not self.receiver.id_empty
try:
order_items = []
for pi in products:
obj = {
"price": pi.price,
"product_id": pi.product_id,
"batch_id": "",
"discount_type": DiscountType.ABSOLUTE, # TODO
"store_product_id": pi.store_product_id,
"from_module": 0,
"is_gift": False,
"activity_ids": [],
"spread_tag": pi.spread_tag,
"count": pi.selected_count,
"remark": pi.remark,
"gift_belong_to_store_product_ids": [],
}
order_items.append(obj)
json = {
"place_id": self.receiver.place_id,
"place_zip": self.receiver.place_zip,
"receiver_id": self.receiver.id,
"store_id": self.receiver.store_id,
"order_items": order_items,
}
obj = await self._SendRequest(
HttpMethod.kPost,
"https://j1.pupuapi.com/client/account/discount",
params={"discount_type": type},
json=json,
)
if obj["errcode"] == 0:
ids = []
rules = []
data = obj["data"]
if data.get("count"):
best_discount = data.get("best_discount") or {}
id = best_discount.get("id")
rule = best_discount.get("rule") or {}
if id:
# 超时赔付券,券前金额满8减8元;
# content:None|str = rule.get("content")
ids.append(id)
rules.append(
PDiscountRule(