forked from OreosLab/checkinpanel
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ck_epic.py
1544 lines (1429 loc) · 60.2 KB
/
ck_epic.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
"""
:author @luminoleon
cron: 50 1 * * *
new Env('Epic');
"""
import argparse
import asyncio
import base64
import datetime
import hashlib
import hmac
import json
import os
import re
import signal
import sys
import time
import urllib
from getpass import getpass
from json.decoder import JSONDecodeError
from typing import Callable, Dict, List, Optional, Tuple, Union
import requests
import schedule
from pyppeteer import launch, launcher
from pyppeteer.element_handle import ElementHandle
from pyppeteer.frame_manager import Frame
from pyppeteer.network_manager import Request
from notify_mtr import send
from utils import get_data
from utils_env import get_env_str
__version__ = "1.6.8"
NOTIFICATION_TITLE_START = "Epicgames Claimer:启动成功"
NOTIFICATION_TITLE_NEED_LOGIN = "Epicgames Claimer:需要登录"
NOTIFICATION_TITLE_CLAIM_SUCCEED = "Epicgames Claimer:领取成功"
NOTIFICATION_TITLE_ERROR = "EpicGames Claimer:错误"
NOTIFICATION_TITLE_TEST = "EpicGames Claimer:测试"
NOTIFICATION_CONTENT_START = "如果你收到了此消息,表示你可以正常接收来自Epicgames Claimer的通知推送"
NOTIFICATION_CONTENT_NEED_LOGIN = "未登录或登录信息已失效,请检查并尝试重新登录"
NOTIFICATION_CONTENT_CLAIM_SUCCEED = "成功领取到游戏:"
NOTIFICATION_CONTENT_OPEN_BROWSER_FAILED = "打开浏览器失败:"
NOTIFICATION_CONTENT_LOGIN_FAILED = "登录失败:"
NOTIFICATION_CONTENT_CLAIM_FAILED = "领取失败:"
NOTIFICATION_CONTENT_TEST = "测试是否通知推送已被正确设置"
NOTIFICATION_CONTENT_OWNED_ALL = "所有可领取的每周免费游戏已全部在库中"
if "--enable-automation" in launcher.DEFAULT_ARGS:
launcher.DEFAULT_ARGS.remove("--enable-automation")
# Solve the issue of zombie processes
if "SIGCHLD" in dir(signal):
signal.signal(signal.SIGCHLD, signal.SIG_IGN)
def get_current_time() -> str:
current_time_string = str(datetime.datetime.now()).split(".")[0]
return current_time_string
def log(text: str, level: str = "info") -> None:
localtime = get_current_time()
if level == "info":
print("[{} INFO] {}".format(localtime, text))
elif level == "warning":
print("\033[33m[{} WARN] {}\033[0m".format(localtime, text))
elif level == "error":
print("\033[31m[{} ERROR] {}\033[0m".format(localtime, text))
class WeChat:
def __init__(self, corpid, corpsecret, agentid) -> None:
self.corpid = corpid
self.corpsecret = corpsecret
self.agentid = agentid
def get_token(self) -> str:
url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={}&corpsecret={}".format(
self.corpid, self.corpsecret
)
response = requests.get(url)
if response.status_code == 200:
return response.json()["access_token"]
else:
log("Failed to get access_token.", level="error")
return ""
def send_text(self, message, touser="@all") -> str:
url = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token={}".format(
self.get_token()
)
data = {
"touser": touser,
"msgtype": "text",
"agentid": self.agentid,
"text": {"content": message},
"safe": 0,
}
send_msges = bytes(json.dumps(data), "utf-8")
response = requests.post(url, send_msges)
return response
def send_mpnews(self, title, message, media_id, touser="@all") -> str:
url = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token={}".format(
self.get_token()
)
if not message:
message = title
data = {
"touser": touser,
"msgtype": "mpnews",
"agentid": self.agentid,
"mpnews": {
"articles": [
{
"title": title,
"thumb_media_id": media_id,
"content_source_url": "",
"content": message.replace("\n", "<br/>"),
"digest": message,
}
]
},
"safe": 0,
}
send_msges = bytes(json.dumps(data), "utf-8")
response = requests.post(url, send_msges)
return response
class Notifications:
def __init__(
self,
serverchan_sendkey: str = None,
bark_push_url: str = "https://api.day.app/push",
bark_device_key: str = None,
telegram_bot_token: str = None,
telegram_chat_id: str = None,
wechat_qywx_am: str = None,
dingtalk_access_token: str = None,
dingtalk_secret: str = None,
) -> None:
self.serverchan_sendkey = serverchan_sendkey
self.bark_push_url = bark_push_url
self.bark_device_key = bark_device_key
self.telegram_bot_token = telegram_bot_token
self.telegram_chat_id = telegram_chat_id
self.wechat_qywx_am = wechat_qywx_am
self.dingtalk_access_token = dingtalk_access_token
self.dingtalk_secret = dingtalk_secret
def push_serverchan(self, title: str, content: str = None) -> None:
if self.serverchan_sendkey != None:
try:
url = "https://sctapi.ftqq.com/{}.send".format(self.serverchan_sendkey)
data = {"title": title}
if content != None:
data["desp"] = content
requests.post(url, data=data)
except Exception as e:
log("Failed to push to ServerChan: {}".format(e), "error")
def push_bark(self, title: str, content: str = None) -> None:
if self.bark_device_key:
try:
response = requests.post(
url=self.bark_push_url,
headers={
"Content-Type": "application/json; charset=utf-8",
},
data=json.dumps(
{
"body": content,
"device_key": self.bark_device_key,
"title": title,
}
),
)
log(f"Bark Response HTTP Status Code: {response.status_code}")
log(f"Bark Response HTTP Response Body: {response.content}")
except Exception as e:
log("Failed to push to Bark: {}".format(e), "error")
def push_telegram(self, title: str = None, content: str = None) -> None:
if self.telegram_bot_token:
try:
push_text = f"{title}\n\n{content}" if title else content
response = requests.post(
url=f"https://api.telegram.org/bot{self.telegram_bot_token}/sendMessage",
data={"chat_id": self.telegram_chat_id, "text": push_text},
)
log(f"Telegram Response HTTP Status Code: {response.status_code}")
log(f"Telegram Response HTTP Response Body: {response.content}")
except Exception as e:
log("Failed to push to Telegram: {}".format(e), "error")
def push_wechat(self, title: str, content: str = None) -> None:
if self.wechat_qywx_am:
try:
qywx_am_ay = re.split(",", self.wechat_qywx_am)
if 4 < len(qywx_am_ay) > 5:
log("WeChat AM is invalid.", level="error")
return
corpid = qywx_am_ay[0]
corpsecret = qywx_am_ay[1]
touser = qywx_am_ay[2]
agentid = qywx_am_ay[3]
try:
media_id = qywx_am_ay[4]
except:
media_id = None
wx = WeChat(corpid, corpsecret, agentid)
if media_id != None:
response = wx.send_mpnews(title, content, media_id, touser)
else:
message = title + "\n\n" + content
response = wx.send_text(message, touser)
response = response.json()
if response["errmsg"] == "ok":
log("Successfully sent wechat message.")
else:
log(
"Failed to send wechat message. errmsg: {}".format(
response["errmsg"]
),
level="error",
)
except Exception as e:
log("Failed to send wechat message. ExceptErrmsg:{}".format(e), "error")
def _get_dingtalk_timestamp_and_sign(self) -> Tuple[str, str]:
timestamp = str(round(time.time() * 1000))
secret = self.dingtalk_secret
secret_enc = secret.encode("utf-8")
string_to_sign = "{}\n{}".format(timestamp, secret)
string_to_sign_enc = string_to_sign.encode("utf-8")
hmac_code = hmac.new(
secret_enc, string_to_sign_enc, digestmod=hashlib.sha256
).digest()
sign = urllib.parse.quote_plus(base64.b64encode(hmac_code))
return timestamp, sign
def push_dingtalk(self, title: str, content: str) -> None:
if self.dingtalk_access_token:
try:
headers = {"Content-Type": "application/json; charset=utf-8"}
webhook = "https://oapi.dingtalk.com/robot/send"
params = {"access_token": self.dingtalk_access_token}
if self.dingtalk_secret:
(
params["timestamp"],
params["sign"],
) = self._get_dingtalk_timestamp_and_sign()
push_text = f"{title}\n\n{content}" if title else content
data = {"msgtype": "text", "text": {"content": push_text}}
response = requests.post(
url=webhook, headers=headers, params=params, data=json.dumps(data)
)
response_json = response.json()
errcode = response_json["errcode"]
errmsg = response_json["errmsg"]
if errcode == 0:
log("Successfully sent DingTalk message")
else:
log(f"Failed to send Dingtalk message: {errmsg}", level="error")
except Exception as e:
log(f"Failed to send Dingtalk message: {e}", level="error")
def notify(self, title: str, content: str = None) -> None:
self.push_serverchan(title, content)
self.push_bark(title, content)
self.push_telegram(title, content)
self.push_wechat(title, content)
self.push_dingtalk(title, content)
class Item:
def __init__(self, title: str, offer_id: str, namespace: str, type: str) -> None:
self.title = title
self.offer_id = offer_id
self.namespace = namespace
self.type = type
@property
def purchase_url(self) -> str:
url = "https://www.epicgames.com/store/purchase?lang=en-US&namespace={}&offers={}".format(
self.namespace, self.offer_id
)
return url
class Game:
def __init__(self, base_game: Item, dlcs: List[Item] = []) -> None:
self.base_game = base_game
self.dlcs = dlcs
@property
def item_amount(self) -> int:
return len(self.dlcs) + 1
class EpicgamesClaimer:
def __init__(
self,
data_dir: Optional[str] = None,
headless: bool = True,
sandbox: bool = False,
chromium_path: Optional[str] = None,
claimer_notifications: Notifications = None,
timeout: int = 180000,
debug: bool = False,
cookies: str = None,
browser_args: List[str] = [
"--disable-infobars",
"--blink-settings=imagesEnabled=false",
"--no-first-run",
"--disable-gpu",
],
push_when_owned_all=False,
) -> None:
self.data_dir = data_dir
self.headless = headless
self.browser_args = browser_args
self.sandbox = sandbox
if not self.sandbox:
self.browser_args.append("--no-sandbox")
self.chromium_path = chromium_path
if "win" in launcher.current_platform() and self.chromium_path == None:
if os.path.exists("chrome-win32"):
self.chromium_path = "chrome-win32/chrome.exe"
elif os.path.exists("chrome-win"):
self.chromium_path = "chrome-win/chrome.exe"
self._loop = asyncio.get_event_loop()
self.browser_opened = False
self.claimer_notifications = (
claimer_notifications if claimer_notifications != None else Notifications()
)
self.timeout = timeout
self.debug = debug
self.cookies = cookies
self.push_when_owned_all = push_when_owned_all
self.page = None
self.open_browser()
def log(self, text: str, level: str = "info") -> None:
localtime = get_current_time()
if level == "info":
print("[{} INFO] {}".format(localtime, text))
elif level == "warning":
print("\033[33m[{} WARN] {}\033[0m".format(localtime, text))
elif level == "error":
print("\033[31m[{} ERROR] {}\033[0m".format(localtime, text))
elif level == "debug":
if self.debug:
print("[{} DEBUG] {}".format(localtime, text))
async def _headless_stealth_async(self):
original_user_agent = await self.page.evaluate("navigator.userAgent")
user_agent = original_user_agent.replace("Headless", "")
await self.page.evaluateOnNewDocument(
"() => {Object.defineProperty(navigator, 'webdriver', {get: () => false})}"
)
await self.page.evaluateOnNewDocument(
"window.chrome = {'loadTimes': {}, 'csi': {}, 'app': {'isInstalled': false, 'getDetails': {}, 'getIsInstalled': {}, 'installState': {}, 'runningState': {}, 'InstallState': {'DISABLED': 'disabled', 'INSTALLED': 'installed', 'NOT_INSTALLED': 'not_installed'}, 'RunningState': {'CANNOT_RUN': 'cannot_run', 'READY_TO_RUN': 'ready_to_run', 'RUNNING': 'running'}}, 'webstore': {'onDownloadProgress': {'addListener': {}, 'removeListener': {}, 'hasListener': {}, 'hasListeners': {}, 'dispatch': {}}, 'onInstallStageChanged': {'addListener': {}, 'removeListener': {}, 'hasListener': {}, 'hasListeners': {}, 'dispatch': {}}, 'install': {}, 'ErrorCode': {'ABORTED': 'aborted', 'BLACKLISTED': 'blacklisted', 'BLOCKED_BY_POLICY': 'blockedByPolicy', 'ICON_ERROR': 'iconError', 'INSTALL_IN_PROGRESS': 'installInProgress', 'INVALID_ID': 'invalidId', 'INVALID_MANIFEST': 'invalidManifest', 'INVALID_WEBSTORE_RESPONSE': 'invalidWebstoreResponse', 'LAUNCH_FEATURE_DISABLED': 'launchFeatureDisabled', 'LAUNCH_IN_PROGRESS': 'launchInProgress', 'LAUNCH_UNSUPPORTED_EXTENSION_TYPE': 'launchUnsupportedExtensionType', 'MISSING_DEPENDENCIES': 'missingDependencies', 'NOT_PERMITTED': 'notPermitted', 'OTHER_ERROR': 'otherError', 'REQUIREMENT_VIOLATIONS': 'requirementViolations', 'USER_CANCELED': 'userCanceled', 'WEBSTORE_REQUEST_ERROR': 'webstoreRequestError'}, 'InstallStage': {'DOWNLOADING': 'downloading', 'INSTALLING': 'installing'}}}"
)
await self.page.evaluateOnNewDocument(
"() => {Reflect.defineProperty(navigator.connection,'rtt', {get: () => 200, enumerable: true})}"
)
await self.page.evaluateOnNewDocument(
"() => {Object.defineProperty(navigator, 'plugins', {get: () => [{'description': 'Portable Document Format', 'filename': 'internal-pdf-viewer', 'length': 1, 'name': 'Chrome PDF Plugin'}, {'description': '', 'filename': 'mhjfbmdgcfjbbpaeojofohoefgiehjai', 'length': 1, 'name': 'Chromium PDF Viewer'}, {'description': '', 'filename': 'internal-nacl-plugin', 'length': 2, 'name': 'Native Client'}]})}"
)
await self.page.evaluateOnNewDocument(
"() => {const newProto = navigator.__proto__; delete newProto.webdriver; navigator.__proto__ = newProto}"
)
await self.page.evaluateOnNewDocument(
"const getParameter = WebGLRenderingContext.getParameter; WebGLRenderingContext.prototype.getParameter = function(parameter) {if (parameter === 37445) {return 'Intel Open Source Technology Center';}; if (parameter === 37446) {return 'Mesa DRI Intel(R) Ivybridge Mobile ';}; return getParameter(parameter);}"
)
await self.page.evaluateOnNewDocument(
"() => {Reflect.defineProperty(navigator, 'mimeTypes', {get: () => [{type: 'application/pdf', suffixes: 'pdf', description: '', enabledPlugin: Plugin}, {type: 'application/x-google-chrome-pdf', suffixes: 'pdf', description: 'Portable Document Format', enabledPlugin: Plugin}, {type: 'application/x-nacl', suffixes: '', description: 'Native Client Executable', enabledPlugin: Plugin}, {type: 'application/x-pnacl', suffixes: '', description: 'Portable Native Client Executable', enabledPlugin: Plugin}]})}"
)
await self.page.evaluateOnNewDocument(
"() => {const p = {'defaultRequest': null, 'receiver': null}; Reflect.defineProperty(navigator, 'presentation', {get: () => p})}"
)
await self.page.setExtraHTTPHeaders(
{"Accept-Language": "en-GB,en-US;q=0.9,en;q=0.8"}
)
await self.page.setUserAgent(user_agent)
async def _open_browser_async(self) -> None:
if not self.browser_opened:
self.browser = await launch(
options={"args": self.browser_args, "headless": self.headless},
userDataDir=None
if self.data_dir == None
else os.path.abspath(self.data_dir),
executablePath=self.chromium_path,
)
self.page = (await self.browser.pages())[0]
await self.page.setViewport({"width": 1000, "height": 600})
# Async callback functions aren't possible to use (Refer to https://github.com/pyppeteer/pyppeteer/issues/220).
# await self.page.setRequestInterception(True)
# self.page.on('request', self._intercept_request_async)
if self.headless:
await self._headless_stealth_async()
self.browser_opened = True
if self.cookies:
await self._load_cookies_async(self.cookies)
if self.data_dir != None:
cookies_path = os.path.join(self.data_dir, "cookies.json")
if os.path.exists(cookies_path):
await self._load_cookies_async(cookies_path)
os.remove(cookies_path)
# await self._refresh_cookies_async()
async def _refresh_cookies_async(self) -> None:
await self._navigate_async("https://www.epicgames.com/store/en-US/")
async def _intercept_request_async(self, request: Request) -> None:
if request.resourceType in ["image", "media", "font"]:
await request.abort()
else:
await request.continue_()
async def _close_browser_async(self):
if self.browser_opened:
if self.cookies:
await self._save_cookies_async(self.cookies)
await self.browser.close()
self.browser_opened = False
async def _type_async(
self, selector: str, text: str, sleep: Union[int, float] = 0
) -> None:
await self.page.waitForSelector(selector)
await asyncio.sleep(sleep)
await self.page.type(selector, text)
async def _click_async(
self,
selector: str,
sleep: Union[int, float] = 2,
timeout: int = 30000,
frame_index: int = 0,
) -> None:
if frame_index == 0:
await self.page.waitForSelector(selector, options={"timeout": timeout})
await asyncio.sleep(sleep)
await self.page.click(selector)
else:
await self.page.waitForSelector(
"iframe:nth-child({})".format(frame_index), options={"timeout": timeout}
)
frame = self.page.frames[frame_index]
await frame.waitForSelector(selector)
await asyncio.sleep(sleep)
await frame.click(selector)
async def _get_text_async(self, selector: str) -> str:
await self.page.waitForSelector(selector)
return await (
await (await self.page.querySelector(selector)).getProperty("textContent")
).jsonValue()
async def _get_texts_async(self, selector: str) -> List[str]:
texts = []
try:
await self.page.waitForSelector(selector)
for element in await self.page.querySelectorAll(selector):
texts.append(
await (await element.getProperty("textContent")).jsonValue()
)
except:
pass
return texts
async def _get_element_text_async(self, element: ElementHandle) -> str:
return await (await element.getProperty("textContent")).jsonValue()
async def _get_property_async(self, selector: str, property: str) -> str:
await self.page.waitForSelector(selector)
return await self.page.evaluate(
"document.querySelector('{}').getAttribute('{}')".format(selector, property)
)
async def _get_links_async(
self, selector: str, filter_selector: str, filter_value: str
) -> List[str]:
links = []
try:
await self.page.waitForSelector(selector)
elements = await self.page.querySelectorAll(selector)
judgement_texts = await self._get_texts_async(filter_selector)
except:
return []
for element, judgement_text in zip(elements, judgement_texts):
if judgement_text == filter_value:
link = await (await element.getProperty("href")).jsonValue()
links.append(link)
return links
async def _find_async(
self, selectors: Union[str, List[str]], timeout: int = None, frame: Frame = None
) -> Union[bool, int]:
if frame == None:
frame = self.page
if type(selectors) == str:
try:
if timeout == None:
timeout = 1000
await frame.waitForSelector(selectors, options={"timeout": timeout})
return True
except:
return False
elif type(selectors) == list:
if timeout == None:
timeout = 300000
for _ in range(int(timeout / 1000 / len(selectors))):
for i in range(len(selectors)):
if await self._find_async(selectors[i], timeout=1000, frame=frame):
return i
return -1
else:
raise ValueError
async def _try_click_async(
self, selector: str, sleep: Union[int, float] = 2
) -> bool:
try:
await asyncio.sleep(sleep)
await self.page.click(selector)
return True
except:
return False
async def _get_elements_async(
self, selector: str
) -> Union[List[ElementHandle], None]:
try:
await self.page.waitForSelector(selector)
return await self.page.querySelectorAll(selector)
except:
return None
async def _wait_for_element_text_change_async(
self, element: ElementHandle, text: str, timeout: int = 30
) -> None:
if await self._get_element_text_async(element) != text:
return
for _ in range(timeout):
await asyncio.sleep(1)
if await self._get_element_text_async(element) != text:
return
raise TimeoutError(
'Waiting for element "{}" text content change failed: timeout {}s exceeds'.format(
element, timeout
)
)
async def _navigate_async(
self, url: str, timeout: int = 30000, reload: bool = True
) -> None:
if self.page.url == url and not reload:
return
await self.page.goto(url, options={"timeout": timeout})
async def _get_json_async(self, url: str, arguments: Dict[str, str] = None) -> dict:
response_text = await self._get_async(url, arguments)
try:
response_json = json.loads(response_text)
except JSONDecodeError:
response_text_partial = (
response_text if len(response_text) <= 96 else response_text[0:96]
)
raise ValueError(
"Epic Games returnes content that cannot be resolved. Response: {} ...".format(
response_text_partial
)
)
return response_json
async def _login_async(
self,
email: str,
password: str,
verifacation_code: str = None,
interactive: bool = True,
remember_me: bool = True,
) -> None:
self.log("Start to login.", level="debug")
if email == None or email == "":
raise ValueError("Email can't be null.")
if password == None or password == "":
raise ValueError("Password can't be null.")
await self._navigate_async(
"https://www.epicgames.com/store/en-US/", timeout=self.timeout, reload=False
)
await self._click_async("#user", timeout=self.timeout)
await self._click_async("#login-with-epic", timeout=self.timeout)
await self._type_async("#email", email)
await self._type_async("#password", password)
if not remember_me:
await self._click_async("#rememberMe")
await self._click_async("#sign-in[tabindex='0']", timeout=self.timeout)
login_result = await self._find_async(
[
"#talon_frame_login_prod[style*=visible]",
"div.MuiPaper-root[role=alert] h6[class*=subtitle1]",
"input[name=code-input-0]",
"#user",
],
timeout=self.timeout,
)
if login_result == -1:
raise TimeoutError("Chcek login result timeout.")
elif login_result == 0:
raise PermissionError("CAPTCHA is required for unknown reasons.")
elif login_result == 1:
alert_text = await self._get_text_async(
"div.MuiPaper-root[role=alert] h6[class*=subtitle1]"
)
raise PermissionError("From Epic Games: {}".format(alert_text))
elif login_result == 2:
if interactive:
await self._type_async(
"input[name=code-input-0]", input("Verification code: ")
)
else:
await self._type_async("input[name=code-input-0]", verifacation_code)
await self._click_async("#continue[tabindex='0']", timeout=self.timeout)
verify_result = await self._find_async(
["#modal-content div[role*=alert]", "#user"], timeout=self.timeout
)
if verify_result == -1:
raise TimeoutError("Chcek login result timeout.")
elif verify_result == 0:
alert_text = await self._get_text_async(
"#modal-content div[role*=alert]"
)
raise PermissionError("From Epic Games: {}".format(alert_text))
self.log("Login end.", level="debug")
async def _need_login_async(self, use_api: bool = False) -> bool:
need_login = False
if use_api:
page_content_json = await self._get_json_async(
"https://www.epicgames.com/account/v2/ajaxCheckLogin"
)
need_login = page_content_json["needLogin"]
else:
await self._navigate_async(
"https://www.epicgames.com/store/en-US/", timeout=self.timeout
)
if (
await self._get_property_async("#user", "data-component")
) == "SignedIn":
need_login = False
else:
need_login = True
self.log(f"Need Login: {need_login}.", level="debug")
return need_login
async def _get_authentication_method_async(self) -> Optional[str]:
page_content_json = await self._get_json_async(
"https://www.epicgames.com/account/v2/security/settings/ajaxGet"
)
if page_content_json["settings"]["enabled"] == False:
return None
else:
return page_content_json["settings"]["defaultMethod"]
def _quit(self, signum=None, frame=None) -> None:
try:
self.close_browser()
except:
pass
exit(1)
def _screenshot(self, path: str) -> None:
return self._loop.run_until_complete(self.page.screenshot({"path": path}))
async def _post_json_async(
self,
url: str,
data: str,
host: str = "www.epicgames.com",
sleep: Union[int, float] = 2,
):
await asyncio.sleep(sleep)
if not host in self.page.url:
await self._navigate_async("https://{}".format(host))
response = await self.page.evaluate(
"""
xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST", "{}", true);
xmlhttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xmlhttp.send('{}');
xmlhttp.responseText;
""".format(
url, data
)
)
return response
async def _post_async(
self,
url: str,
data: dict,
host: str = "www.epicgames.com",
sleep: Union[int, float] = 2,
) -> str:
await asyncio.sleep(sleep)
if not host in self.page.url:
await self._navigate_async("https://{}".format(host))
evaluate_form = "var form = new FormData();\n"
for key, value in data.items():
evaluate_form += "form.append(`{}`, `{}`);\n".format(key, value)
response = await self.page.evaluate(
evaluate_form
+ """
var form = new FormData();
xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST", `{}`, true);
xmlhttp.send(form);
xmlhttp.responseText;
""".format(
url
)
)
return response
async def _get_account_id_async(self):
if await self._need_login_async():
return None
else:
await self._navigate_async("https://www.epicgames.com/account/personal")
account_id = (
await self._get_text_async("#personalView div.paragraph-container p")
).split(": ")[1]
return account_id
async def _get_async(
self, url: str, arguments: Dict[str, str] = None, sleep: Union[int, float] = 2
):
args = ""
if arguments != None:
args = "?"
for key, value in arguments.items():
args += "{}={}&".format(key, value)
args = args.rstrip("&")
await self._navigate_async(url + args)
response_text = await self._get_text_async("body")
await asyncio.sleep(sleep)
return response_text
async def _get_game_infos_async(self, url_slug: str):
game_infos = {}
response = await self._get_json_async(
"https://store-content.ak.epicgames.com/api/en-US/content/products/{}".format(
url_slug
)
)
game_infos["product_name"] = response["productName"]
game_infos["namespace"] = response["namespace"]
game_infos["pages"] = []
for page in response["pages"]:
game_info_page = {}
if page["offer"]["hasOffer"]:
game_info_page["offer_id"] = page["offer"]["id"]
game_info_page["namespace"] = page["offer"]["namespace"]
game_infos["pages"].append(game_info_page)
return game_infos
def _get_purchase_url(self, namespace: str, offer_id: str):
purchase_url = "https://www.epicgames.com/store/purchase?lang=en-US&namespace={}&offers={}".format(
namespace, offer_id
)
return purchase_url
async def _get_weekly_free_base_games_async(self) -> List[Item]:
response_text = await self._get_async(
"https://store-site-backend-static.ak.epicgames.com/freeGamesPromotions"
)
response_json = json.loads(response_text)
base_games = []
for item in response_json["data"]["Catalog"]["searchStore"]["elements"]:
if {"path": "freegames"} in item["categories"]:
if (
item["price"]["totalPrice"]["discountPrice"] == 0
and item["price"]["totalPrice"]["originalPrice"] != 0
):
if item["offerType"] == "BASE_GAME":
base_game = Item(
item["title"], item["id"], item["namespace"], "BASE_GAME"
)
base_games.append(base_game)
return base_games
async def _get_weekly_free_items_async(
self, user_country: str = "CN"
) -> List[Item]:
try:
user_country = await self._get_user_country_async()
except:
pass
response_text = await self._get_async(
f"https://store-site-backend-static.ak.epicgames.com/freeGamesPromotions?country={user_country}&allowCountries={user_country}"
)
response_json = json.loads(response_text)
items = []
for item in response_json["data"]["Catalog"]["searchStore"]["elements"]:
if item["status"] == "ACTIVE":
if {"path": "freegames"} in item["categories"]:
if item["price"]["totalPrice"]["discountPrice"] == 0:
if item["promotions"] != None:
if (
item["promotions"]["promotionalOffers"] != []
and item["promotions"]["promotionalOffers"] != None
):
items.append(
Item(
item["title"],
item["id"],
item["namespace"],
item["offerType"],
)
)
return items
async def _get_free_dlcs_async(self, namespace: str) -> List[Item]:
args = {
"query": "query searchStoreQuery($namespace: String, $category: String, $freeGame: Boolean, $count: Int){Catalog{searchStore(namespace: $namespace, category: $category, freeGame: $freeGame, count: $count){elements{title id namespace}}}}",
"variables": '{{"namespace": "{}", "category": "digitalextras/book|addons|digitalextras/soundtrack|digitalextras/video", "freeGame": true, "count": 1000}}'.format(
namespace
),
}
response = await self._get_json_async("https://www.epicgames.com/graphql", args)
free_dlcs = []
for item in response["data"]["Catalog"]["searchStore"]["elements"]:
free_dlc = Item(item["title"], item["id"], item["namespace"], "DLC")
free_dlcs.append(free_dlc)
return free_dlcs
async def _get_free_base_game_async(self, namespace: str) -> Optional[Item]:
args = {
"query": "query searchStoreQuery($namespace: String, $category: String, $freeGame: Boolean, $count: Int){Catalog{searchStore(namespace: $namespace, category: $category, freeGame: $freeGame, count: $count){elements{title id namespace}}}}",
"variables": '{{"namespace": "{}", "category": "games/edition/base", "freeGame": true, "count": 1000}}'.format(
namespace
),
}
response = await self._get_json_async("https://www.epicgames.com/graphql", args)
if len(response["data"]["Catalog"]["searchStore"]["elements"]) > 0:
base_game_info = response["data"]["Catalog"]["searchStore"]["elements"][0]
base_game = Item(
base_game_info["title"],
base_game_info["id"],
base_game_info["namespace"],
"BASE_GAME",
)
return base_game
async def _get_weekly_free_games_async(self) -> List[Game]:
free_items = await self._get_weekly_free_items_async()
free_games = []
for item in free_items:
if item.type == "BASE_GAME":
free_dlcs = await self._get_free_dlcs_async(item.namespace)
free_games.append(Game(item, free_dlcs))
elif item.type == "DLC":
free_base_game = await self._get_free_base_game_async(item.namespace)
if free_base_game != None:
free_dlcs = await self._get_free_dlcs_async(
free_base_game.namespace
)
free_games.append(Game(free_base_game, free_dlcs))
else:
free_base_game = await self._get_free_base_game_async(item.namespace)
if free_base_game == None:
free_games.append(Game(item))
else:
free_dlcs = await self._get_free_dlcs_async(
free_base_game.namespace
)
free_games.append(Game(free_base_game, free_dlcs))
return free_games
async def _claim_async(self, item: Item) -> None:
async def findx_async(
items: List[Dict[str, Union[str, bool, int]]], timeout: int
) -> int:
for _ in range(int(timeout / 1000 / (len(items)))):
for i in range(0, len(items)):
if items[i]["exist"]:
if await self._find_async(
items[i]["selector"],
timeout=1000,
frame=self.page.frames[items[i]["frame"]],
):
return i
else:
if not await self._find_async(
items[i]["selector"],
timeout=1000,
frame=self.page.frames[items[i]["frame"]],
):
return i
return -1
await self._navigate_async(item.purchase_url, timeout=self.timeout)
await self._click_async(
"#purchase-app button[class*=confirm]:not([disabled])", timeout=self.timeout
)
await self._try_click_async(
"#purchaseAppContainer div.payment-overlay button.payment-btn--primary"
)
result = await findx_async(
[
{
"selector": "#purchase-app div[class*=alert]",
"exist": True,
"frame": 0,
},
{"selector": "div.MuiDialog-root", "exist": True, "frame": 1},
{"selector": "#purchase-app > div", "exist": False, "frame": 0},
],
timeout=self.timeout,
)
if result == -1:
raise TimeoutError("Timeout when claiming")
elif result == 0:
message = await self._get_text_async(
"#purchase-app div[class*=alert]:not([disabled])"
)
raise PermissionError(message)
elif result == 1:
raise PermissionError("CAPTCHA is required for unknown reasons")
else:
owned = await self._is_owned_async(item.offer_id, item.namespace)
if not owned:
raise RuntimeError(
"An item was mistakenly considered to have been claimed"
)
async def _screenshot_async(self, path: str) -> None:
await self.page.screenshot({"path": path})
def add_quit_signal(self):
signal.signal(signal.SIGINT, self._quit)
signal.signal(signal.SIGTERM, self._quit)
if "SIGBREAK" in dir(signal):
signal.signal(signal.SIGBREAK, self._quit)
if "SIGHUP" in dir(signal):
signal.signal(signal.SIGHUP, self._quit)
async def _is_owned_async(self, offer_id: str, namespace: str) -> bool:
args = {
"query": "query launcherQuery($namespace: String!, $offerId: String!){Launcher{entitledOfferItems(namespace: $namespace, offerId: $offerId){entitledToAllItemsInOffer}}}",
"variables": '{{"namespace": "{}", "offerId": "{}"}}'.format(
namespace, offer_id
),
}
response = await self._get_json_async("https://www.epicgames.com/graphql", args)
try:
owned = response["data"]["Launcher"]["entitledOfferItems"][
"entitledToAllItemsInOffer"
]
except:
raise ValueError("The returned data seems to be incorrect.")
return owned
async def _get_user_country_async(self) -> None:
response = await self._get_json_async(
"https://www.epicgames.com/account/v2/personal/ajaxGet"
)
try:
country = response["userInfo"]["country"]["value"]
except:
raise ValueError("The returned data seems to be incorrect.")
return country
async def _try_get_webpage_content_async(self) -> Optional[str]:
try:
if self.browser_opened:
webpage_content = await self._get_text_async("body")
return webpage_content
except:
pass
def _async_auto_retry(
self,
retries: int,
error_message: str,
error_notification: str,
raise_error: bool = True,
) -> None:
def retry(func: Callable) -> Callable:
async def wrapper(*arg, **kw):