-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathfxxkstar.py
3280 lines (2885 loc) · 135 KB
/
fxxkstar.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
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import base64
import dataclasses
import datetime
import getpass
import json
import os
import random
import re
import bs4
import hashlib
import requests
import threading
import time
import traceback
import urllib.parse
import zstandard as zstd
from lxml import etree
from bs4 import BeautifulSoup
from concurrent.futures import Future, ThreadPoolExecutor
from dataclasses import dataclass
from typing import List
from collections import Counter
from fontTools.ttLib import TTFont
from Crypto.Cipher import DES
from cryptography.hazmat.primitives import padding
VERSION_NAME = "FxxkStar 0.9"
G_CONFIG = {
# enable verbose mode
'debug': False,
# set language
'language': 'zh-CN',
# chaoxing api path, no '/' at end
'cx_home_path': 'https://i.chaoxing.com', # https://i.mooc.mooc.whu.edu.cn
'cx_mooc1_path': 'https://mooc1.chaoxing.com', # https://mooc1.mooc.whu.edu.cn
'cx_mooc2_path': 'https://mooc2-ans.chaoxing.com', # https://mooc2-ans.mooc.whu.edu.cn
# save state to file
# includes: login state, course list, course info, chapter list, chapter info, media info
'save_state': True,
# If set to False, data will load from cache
'always_request_course_list': True,
'always_request_course_info': True,
# Submit paper automatically if all questions are answered
'auto_submit_work': True,
'video_only_mode': False,
'work_only_mode': False,
'auto_review_mode': False,
# Use OCR instead of glyph table based matching
'experimental_fix_fonts': False,
'save_paper_to_file': False,
# enable test mode
'test': False,
}
G_HEADERS = {
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8",
"Accept-Encoding": "gzip, deflate, br",
"User-Agent": "Mozilla/5.0 (X11; Linux x86_64; rv:106.0) Gecko/20100101 Firefox/106.0",
"Connection": "keep-alive",
"Accept-Language": "zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2",
}
G_STRINGS = {
"alt_insertimage": " - [IMG]",
"antispider_verify": "⚠️ Anti-Spider verify",
"correct_answer": "Correct answer: ",
"course_list_title": "Course List",
"error_please_relogin": "⚠️ Error: Please relogin",
"error_response": "⚠️ Wrong response from server",
"input_chapter_num": "Input chapter number: ",
"input_course_num": "Input course number: ",
"input_if_sync_video_progress": "💬 Sync video progress? (y/n): ",
"input_phone": "Please input your phone number: ",
"input_password": "Please input your password: ",
"login_expired": "⚠️ Login expired, please login again",
"login_wrong_input": "Wrong phone number or password",
"login_reenter": "Please re-enter your phone number and password",
"login_failed": "Login failed ⚠️",
"login_success": "Login success ✅",
"load_course_list_failed": "Load course list failed",
"load_course_list_success": "Load course list success",
"my_answer": "My Answer: ",
"notification": "💬 Notification",
"press_enter_to_continue": "🔞 Press Enter to continue...",
"profile_greeting": "🌈 Hello, {name}",
"profile_student_num": "Student number: {f[0][1]}",
"ready_to_submit_paper": "✅ Ready to submit paper",
"save_state_success": "Save state success",
"score_format": "Score: {score}",
"sign_in_status_unsign": "🔐 Sign in status: Unsigned",
"sign_in_status_success": "✅ Sign in status: Success",
"sign_in_status_signed_by_teacher": "✅ Sign in status: Signed by teacher",
"sign_in_status_personal_leave2": "🔐 Sign in status: Personal leave",
"sign_in_status_absence": "🚫 Sign in status absence",
"sign_in_status_late": "🚫 Sign in status: Late",
"sign_in_status_leave_early": "🚫 Sign in status: Leave early",
"sign_in_status_expired": "🚫 Sign in status: Expired",
"sync_video_progress_started": "Sync video progress started",
"sync_video_progress_ended": "Sync video progress ended",
"tag_eta": "ETA",
"tag_total_progress": "Total Progress",
"unfinished_chapters_title": "Unfinished Chapters",
"welcome_message": "🌠 Welcome to FxxkStar",
}
G_STRINGS_CN = {
"alt_insertimage": " - [图片]",
"antispider_verify": "⚠️ 反蜘蛛验证",
"correct_answer": "正确答案: ",
"course_list_title": "课程列表",
"error_please_relogin": "⚠️ 请重新登录",
"error_response": "⚠️ 错误的响应",
"input_chapter_num": "请输入章节编号: ",
"input_course_num": "请输入课程编号: ",
"input_if_sync_video_progress": "💬 是否同步视频进度? (y/n): ",
"input_phone": "请输入您的手机号码: ",
"input_password": "请输入您的密码: ",
"login_expired": "⚠️ 登录过期,请重新登录",
"login_wrong_input": "手机号或密码错误",
"login_reenter": "请按回车重新键入账号数据",
"login_failed": "登陆失败 ⚠️",
"login_success": "登陆成功 ✅",
"load_course_list_failed": "加载课程列表失败",
"load_course_list_success": "加载课程列表成功",
"my_answer": "我的答案: ",
"notification": "💬 通知",
"press_enter_to_continue": "🔞 请按回车继续...",
"profile_greeting": "🌈 您好, {name}",
"profile_student_num": "学号: {f[0][1]}",
"ready_to_submit_paper": "✅ 准备提交试卷",
"save_state_success": "保存状态成功",
"score_format": "成绩: {score}",
"sign_in_status_unsign": "🔐 签到状态: 未签到",
"sign_in_status_success": "✅ 签到状态: 成功",
"sign_in_status_signed_by_teacher": "✅ 签到状态: 老师代签",
"sign_in_status_personal_leave2": "🔐 签到状态: 个人请假",
"sign_in_status_absence": "🚫 签到状态: 缺勤",
"sign_in_status_late": "🚫 签到状态: 迟到",
"sign_in_status_leave_early": "🚫 签到状态: 早退",
"sign_in_status_expired": "🚫 签到状态: 过期",
"sync_video_progress_started": "同步视频进度开始",
"sync_video_progress_ended": "同步视频进度结束",
"tag_eta": "预计完成时间",
"tag_total_progress": "总进度",
"unfinished_chapters_title": "未完成章节",
"welcome_message": "🌠 欢迎使用 FxxkStar",
}
G_VERBOSE = G_CONFIG['debug']
if G_CONFIG['language'] == 'zh-CN':
G_STRINGS = G_STRINGS_CN
class MyError(Exception):
def __init__(self, code, msg):
self.code = code
self.msg = msg
def __str__(self):
return "{}({})".format(self.msg, self.code)
class MyAgent():
def __init__(self, headers: dict, cookies: dict = {}):
self.cookies = cookies
self.headers = headers
self.headers_cache = headers.copy()
self.headers_dirty = False
self.headers_additional_document = {
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8',
'Sec-Fetch-Dest': 'document',
'Sec-Fetch-Mode': 'navigate',
'Sec-Fetch-Site': 'none',
'Upgrade-Insecure-Requests': '1',
}
self.headers_additional_xhr = {
'Accept': '*/*',
'Sec-Fetch-Dest': 'empty',
'Sec-Fetch-Mode': 'cors',
'Sec-Fetch-Site': 'same-origin',
'X-Requested-With': 'XMLHttpRequest'
}
self.headers_additional_iframe = {
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8',
'Sec-Fetch-Dest': 'iframe',
'Sec-Fetch-Mode': 'navigate',
'Sec-Fetch-Site': 'same-origin',
'Upgrade-Insurance-Requests': '1',
}
def get_cookie_str(self) -> str:
cookie_str = ""
for key, value in self.cookies.items():
cookie_str += key + "=" + value + "; "
if cookie_str.endswith("; "):
cookie_str = cookie_str[:-2]
return cookie_str
def get_cookie_value(self, key: str) -> str:
return self.cookies.get(key, "")
def update_cookie(self, name: str, value: str) -> None:
self.headers_dirty = True
if value == "":
self.cookies.pop(name, "")
else:
self.cookies[name] = value
def update_cookies(self, cookies: dict) -> None:
for key, value in cookies.items():
self.update_cookie(key, value)
def update_cookies_str(self, cookie_str: str) -> None:
for cookie in cookie_str.split(";"):
cookie = cookie.strip()
if cookie == "":
continue
key, value = cookie.split("=")
self.update_cookie(key, value)
def build_headers(self) -> dict:
if self.headers_dirty:
headers = self.headers.copy()
headers['Cookie'] = self.get_cookie_str()
self.headers_cache = headers
self.headers_dirty = False
return headers.copy()
else:
return self.headers_cache.copy()
def build_headers_based_on(self, given_headers: dict, additional_headers: dict = {}) -> dict:
headers = self.build_headers()
headers.update(given_headers)
headers.update(additional_headers)
return headers
class FxxkStar():
def __init__(self, my_agent: MyAgent, saved_state: dict = {}):
self.agent = my_agent
self.uid: str = ""
self.homepage_url: str = ""
self.account_info = {}
self.course_dict = {}
self.course_info = {}
self.chapter_info = {}
self.active_info = {}
if saved_state.__contains__("version") and saved_state['version'] == VERSION_NAME:
if saved_state.get("cookies", None) is not None:
self.agent.update_cookies_str(saved_state['cookies'])
if saved_state.get("uid") is not None:
self.uid = saved_state.get("uid")
if saved_state.get("homepage_url") is not None:
self.homepage_url = saved_state.get("homepage_url")
for prop in ["account_info", "course_dict", "course_info", "chapter_info", "active_info"]:
if saved_state.get(prop) is not None:
self.__setattr__(prop, saved_state.get(prop))
def save_state(self) -> dict:
return {
"version": VERSION_NAME,
"cookies": self.agent.get_cookie_str(),
"uid": self.uid,
"homepage_url": self.homepage_url,
"account_info": self.account_info,
"course_dict": self.course_dict,
"course_info": self.course_info,
"chapter_info": self.chapter_info,
"active_info": self.active_info,
}
def get_agent(self) -> MyAgent:
return self.agent
def check_login(self) -> bool:
if self.uid == "":
_uid = self.agent.get_cookie_value("_uid")
if _uid != "":
self.uid = _uid
else:
return False
return True
@staticmethod
def encrypt_by_DES(message: str, key: str) -> str:
key_bytes = key.encode('utf-8')
des = DES.new(key_bytes, DES.MODE_ECB)
data = message.encode('utf-8')
padder = padding.PKCS7(64).padder()
padded_data = padder.update(data) + padder.finalize()
ciphertext = des.encrypt(padded_data)
return ciphertext.hex()
def sign_in(self, uname: str, password: str):
url = "https://passport2.chaoxing.com/fanyalogin"
data = "fid=-1&uname={0}&password={1}&refer=https%3A%2F%2Fi.chaoxing.com&t=true&forbidotherlogin=0&validate=".format(
uname, self.encrypt_by_DES(password, "u2oh6Vu^"))
headers = self.agent.build_headers_based_on({
'Accept': 'application/json, text/javascript, */*; q=0.01',
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
'Cookie': 'source=""',
'Origin': 'https://passport2.chaoxing.com',
'Referer': 'https://passport2.chaoxing.com/login?fid=&newversion=true&refer=https%3A%2F%2Fi.chaoxing.com',
}, self.agent.headers_additional_xhr)
sign_in_rsp = requests.post(url=url, data=data, headers=headers)
sign_in_json = sign_in_rsp.json()
if sign_in_json['status']:
self.uid = sign_in_rsp.cookies['_uid']
for item in sign_in_rsp.cookies:
self.agent.update_cookie(item.name, item.value)
return True
else:
if 'msg2' in sign_in_json:
msg = sign_in_json['msg2']
if "密码错误" == msg or "用户名或密码错误" == msg:
msg = G_STRINGS['login_wrong_input']
return False
else:
raise MyError(0, msg)
raise MyError(
1, G_STRINGS['login_failed'] + ": " + str(sign_in_json))
def url_302(self, from_url: str, additional_headers: dict = {}, retry=5) -> str:
headers = self.agent.build_headers_based_on(additional_headers)
rsp = None
while retry >= 0:
try:
rsp = requests.get(
url=from_url, headers=headers, allow_redirects=False)
break
except requests.exceptions.ConnectionError as err:
retry -= 1
tag = "[{}] ".format(time.asctime(time.localtime(time.time())))
print(tag, err)
time.sleep(10)
if rsp == None:
raise MyError(1, "url_302: Connection Error")
if rsp.status_code not in [302, 200, 301]:
raise MyError(rsp.status_code,
G_STRINGS['error_response'] + ": url=" + from_url + "\n" + str(rsp.text))
new_url = rsp.headers.get("Location")
if new_url == None:
new_url = from_url
else:
if G_VERBOSE:
print("[INFO] 302 to " + new_url)
if new_url.endswith("/antispiderShowVerify.ac"):
raise MyError(0, G_STRINGS['antispider_verify'])
return new_url
def request(self, url: str, additional_headers: dict = {}, data=None, method="GET", retry=3) -> requests.Response:
headers = self.agent.build_headers_based_on(additional_headers)
rsp = None
while retry >= 0:
try:
if data != None:
rsp = requests.request(
method=method, url=url, headers=headers, data=data)
else:
rsp = requests.request(
method=method, url=url, headers=headers)
break
except requests.exceptions.ConnectionError as err:
retry -= 1
tag = "[{}] ".format(time.asctime(time.localtime(time.time())))
print(tag, err)
time.sleep(10)
if rsp.status_code == 200:
# print(rsp.text)
for item in rsp.cookies:
if item.name in ['actix-session']:
continue
self.agent.update_cookie(item.name, item.value)
return rsp
else:
if G_CONFIG['test']:
with open("temp/error_response.html", "w") as f:
f.write(rsp.text)
raise MyError(rsp.status_code,
G_STRINGS['error_response'] + ": url=" + url + "\n" + str(rsp.text))
def request_document(self, url: str, header_update: dict = {}, data=None, method="GET"):
headers = self.agent.headers_additional_document.copy()
headers.update(header_update)
return self.request(url, headers)
def request_iframe(self, url: str, header_update: dict = {}):
headers = self.agent.headers_additional_iframe.copy()
headers.update(header_update)
return self.request(url, headers, method="GET")
def request_xhr(self, url: str, header_update: dict = {}, data=None, method="GET"):
headers = self.agent.headers_additional_xhr.copy()
headers.update(header_update)
return self.request(url, headers, data, method=method)
@staticmethod
def extract_form_fields(soup):
"Turn a BeautifulSoup form in to a dict of fields and default values"
fields = {}
for input in soup.findAll('input'):
# ignore submit/image with no name attribute
if not input.has_attr('name'):
continue
# single element nome/value fields
if input['type'] in ('text', 'hidden', 'password', 'submit', 'image'):
value = ''
if input.has_attr('value'):
value = input['value']
fields[input['name']] = value
continue
# checkboxes and radios
if input['type'] in ('checkbox', 'radio'):
value = ''
if input.has_attr('checked'):
assert input.get('checked') in ["checked", "true"]
if input.has_attr('value'):
value = input['value']
else:
value = 'on'
fields[input['name']] = value
continue
assert False, 'input type %s not supported' % input['type']
# textareas
for textarea in soup.findAll('textarea'):
fields[textarea['name']] = textarea.string or ''
# select fields
for select in soup.findAll('select'):
value = ''
options = select.findAll('option')
is_multiple = select.has_attr('multiple')
selected_options = [
option for option in options
if option.has_attr('selected')
]
# If no select options, go with the first one
if not selected_options and options:
selected_options = [options[0]]
if not is_multiple:
assert (len(selected_options) < 2)
if len(selected_options) == 1:
value = selected_options[0]['value']
else:
value = [option['value'] for option in selected_options]
fields[select['name']] = value
return fields
@staticmethod
def get_time_millis() -> int:
return int(round(time.time() * 1000))
@staticmethod
def sleep(duration: int, max_duration: int = 0) -> None:
'Sleep for a random amount of milliseconds, up to max_duration'
if duration < max_duration:
time.sleep(random.randint(duration, max_duration) / 1000)
else:
time.sleep(duration / 1000)
@staticmethod
def format_date_like_javascript() -> str:
# format: Fri Feb 07 1997 00:00:00 GMT+0800 (中国标准时间)
t = datetime.datetime.utcnow() + datetime.timedelta(hours=+8)
return t.strftime("%a %b %d %Y %H:%M:%S GMT+0800 (中国标准时间)")
@staticmethod
def bs_get_text_content(el: bs4.Tag) -> str:
contents = el.contents
if not contents:
return ""
text = ""
for con in contents:
if isinstance(con, str):
text += con
return text
def get_homepage_url(self, force_update=False) -> str:
'''
Get the homepage url in 10 minutes
e.g. https://i.chaoxing.com/base?t=1680307200000
'''
def load_homepage_url():
url0 = "https://i.chaoxing.com"
cx_homepage_path = G_CONFIG['cx_home_path']
homepage_url = self.url_302(url0)
if not cx_homepage_path or cx_homepage_path == url0:
if homepage_url.startswith("http://"):
if G_VERBOSE:
print("Rewrite homepage_url to use HTTPS")
homepage_url = "https://" + homepage_url[7:]
homepage_html = self.request_document(homepage_url).text
homepage_soup = BeautifulSoup(homepage_html, "lxml")
if homepage_soup.find("title").string.strip() != "个人空间":
raise MyError(0, G_STRINGS['error_response'] +
": url=" + homepage_url + "\n" + str(homepage_html))
assert homepage_url.startswith("https://i.chaoxing.com/base")
else:
homepage_url = homepage_url.replace(url0, cx_homepage_path)
self.homepage_url = homepage_url
return homepage_url
if self.homepage_url == "" or force_update:
return load_homepage_url()
url_parse = urllib.parse.urlparse(self.homepage_url)
url_param = urllib.parse.parse_qs(url_parse.query)
t = int(url_param.get("t")[0])
if t < self.get_time_millis() - 1000 * 60 * 10:
return load_homepage_url()
else:
return self.homepage_url
def load_notice_count(self) -> int:
url = "https://i.chaoxing.com/base/getNoticeCount"
parms = {"_t": self.format_date_like_javascript()}
resp = self.request_xhr(url, {
"Origin": "https://i.chaoxing.com",
"Referer": self.get_homepage_url(),
}, parms, method="POST")
result = resp.json()
assert result['status'] == True
return result['count']
def load_profile(self) -> dict:
homepage_url = self.get_homepage_url(force_update=True)
self.sleep(500, 700)
# url1 = "https://i.chaoxing.com/base/verify"
# parms1 = {"_t": self.format_date_like_javascript()}
# print("[INFO] load_profile verify")
# result1 = self.request_xhr(url1, {
# "Origin": "https://i.chaoxing.com",
# "Referer": homepage_url,
# }, data=parms1, method="POST").json()
# if result1.get("status", False) != True:
# raise MyError(0, G_STRINGS['error_response'] +
# ": url=" + url1 + "\n" + str(result1))
url2 = "https://i.chaoxing.com/base/settings"
print("[INFO] load_profile settings")
self.request_iframe(url2, {
"Referer": homepage_url,
})
self.sleep(50, 200)
url3 = "https://passport2.chaoxing.com/mooc/accountManage"
print("[INFO] load_profile account")
account_page_html = self.request_iframe(url3, {
"Referer": "https://i.chaoxing.com/",
}).text
if G_CONFIG['test']:
with open("temp/debug-account_page.html", "w") as f:
f.write(account_page_html)
def _parse_profile(account_page_html: str):
soup = BeautifulSoup(account_page_html, "lxml")
title = soup.find("title").string.strip()
assert title == "账号管理"
info_div = soup.find("div", class_="infoDiv")
name = info_div.find(id="messageName").string.strip()
phone = info_div.find(id="messagePhone").string.strip()
sex = info_div.select(".sex .check.checked")[0].get("value", None)
if sex != None:
sex = int(sex)
fid_list_el = info_div.find(id="messageFid").find_all("li")
fid_list = []
for fid_el in fid_list_el:
item_name: str = self.bs_get_text_content(fid_el).strip()
value_el = fid_el.find(class_="xuehao")
if value_el:
item_value: str = value_el.get_text().strip()
if item_value.startswith("学号/工号:"):
item_value = item_value[6:]
fid_list.append([item_name, item_value])
else:
fid_list.append([item_name, None])
return {
"name": name,
"sex": sex,
"phone": phone,
"f": fid_list,
}
self.account_info = _parse_profile(account_page_html)
return self.account_info
def load_course_list(self) -> None:
url = G_CONFIG['cx_mooc2_path'] + "/visit/courses/list?v=" + \
str(self.get_time_millis())
course_html_text = self.request_xhr(url, {
'Accept': 'text/html, */*; q=0.01',
'Referer': G_CONFIG['cx_mooc2_path'] + '/visit/interaction'
}).text
course_HTML = etree.HTML(course_html_text)
list_in_html = course_HTML.xpath("//ul[@class='course-list']/li")
if list_in_html.__len__() == 0:
page_title = course_HTML.xpath("//title/text()")[0].strip()
if page_title == "用户登录":
raise MyError(9, G_STRINGS['login_expired'])
else:
raise MyError(
1, G_STRINGS['load_course_list_failed'] + ": " + course_html_text)
i = 0
course_dict = {}
for course_item in list_in_html:
try:
course_item_name = course_item.xpath(
"./div[2]/h3/a/span/@title")[0]
course_link = course_item.xpath("./div[1]/a[1]/@href")[0]
print(course_item_name, course_link)
i += 1
course_dict[str(i)] = [course_item_name, course_link]
except:
pass
self.course_dict = course_dict
def load_course_info(self, url_course: str) -> dict:
course_info = {}
url_course_page = self.url_302(url_course)
course_info['course_page_url'] = url_course_page
course_HTML_text = self.request_document(url_course_page).text
course_HTML = etree.HTML(course_HTML_text)
try:
course_info['courseid'] = course_HTML.xpath(
"//input[@name='courseid']/@value")[0]
course_info['clazzid'] = course_HTML.xpath(
"//input[@name='clazzid']/@value")[0]
course_info['cfid'] = course_HTML.xpath(
"//input[@name='cfid']/@value")[0]
course_info['bbsid'] = course_HTML.xpath(
"//input[@name='bbsid']/@value")[0]
course_info['cpi'] = course_HTML.xpath(
"//input[@name='cpi']/@value")[0]
except Exception as err:
raise MyError(1, str(err) + "###" + course_HTML_text)
chapters_iframe_url = G_CONFIG['cx_mooc2_path'] + \
"/mycourse/studentcourse?courseid={courseid}&clazzid={clazzid}&cpi={cpi}&ut=s".format(
**course_info)
chapters_HTML_text = self.request_iframe(
chapters_iframe_url, {"Referer": url_course_page}).text
chapters_HTML = etree.HTML(chapters_HTML_text)
mooc1Domain = G_CONFIG['cx_mooc1_path']
enc_search = re.search(r"var enc\s*=\s*[\"'](.*?)[\"']\s*;",
chapters_HTML.xpath("/html/body/script[not(@src)]")[0].text)
enc = enc_search.group(1)
chapter_list = []
chapters_soup = BeautifulSoup(chapters_HTML_text, "lxml")
course_unit_list = chapters_soup.select("div.chapter_unit")
for course_unit in course_unit_list:
catalog_name = course_unit.select(
"div.chapter_item div div.catalog_name span")[0].get("title")
print("# ", catalog_name)
chapter_items = course_unit.select(
"div.catalog_level ul li div.chapter_item")
if len(chapter_items) == 0:
if G_VERBOSE:
print(" * ", catalog_name, " is empty")
for chapter_item in chapter_items:
# parse chapter number
chapter_number_str = chapter_item.select(
"span.catalog_sbar")[0].get_text().strip()
# parse chapter title
chapter_title: str
chapter_title_node = chapter_item.get("title", None)
if chapter_title_node == None:
chapter_title = chapter_item.select(
"div.catalog_name")[0].contents[-1].strip()
else:
chapter_title = chapter_title_node
# parse chapter link
transfer_url: str = ""
course_id = None
chapter_id = None
clazz_id = None
chapter_entrance_node = chapter_item.get("onclick", None)
if chapter_entrance_node == None:
state_node = chapter_item.select(
"div.catalog_state.icon-dingshi")
if len(state_node) > 0:
# chapter is not opened
pass
elif G_CONFIG['debug']:
with open("temp/debug-course-chapters.html", "w") as f:
f.write(chapters_HTML_text)
else:
chapter_entrance = chapter_entrance_node.strip()
# For example: "toOld('000000000', '000000000', '00000000')"
entrance_match = re.match(
r"toOld\('(.*?)',\s*'(.*?)',\s*'(.*?)'\)", chapter_entrance)
if entrance_match == None:
raise MyError(
1, G_STRINGS['error_response'] + ": " + course_HTML_text)
courseid = entrance_match.group(1)
knowledgeId = entrance_match.group(2)
clazzid = entrance_match.group(3)
referUrl = mooc1Domain + "/mycourse/studentstudy?chapterId=" + knowledgeId + \
"&courseId=" + courseid + "&clazzid=" + clazzid + "&enc=" + enc + "&mooc2=1"
transferUrl = mooc1Domain + "/mycourse/transfer?moocId=" + courseid + \
"&clazzid=" + clazzid + "&ut=s&refer=" + \
urllib.parse.quote(referUrl)
transfer_url = transferUrl
course_id = courseid
chapter_id = knowledgeId
clazz_id = clazzid
unfinished_count = 0
task_status_HTML = chapter_item.select("div.catalog_task")[0]
task_count_node: list = task_status_HTML.select(
"input.knowledgeJobCount")
if len(task_count_node) == 1:
unfinished_count = int(task_count_node[0].get("value"))
chapter_info = {
'chapterNumber': chapter_number_str,
'chapterTitle': chapter_title,
'courseid': course_id,
'knowledgeId': chapter_id,
'clazzid': clazz_id,
'transferUrl': transfer_url,
'unfinishedCount': unfinished_count,
}
chapter_list.append(chapter_info)
chapter_mark = unfinished_count if unfinished_count > 3 else [
"🟢", "🟡", "🟠", "🔴"][unfinished_count]
print(" - {} {} {} [{}]".format(chapter_mark,
chapter_number_str, chapter_title, chapter_id))
course_info['chapter_list'] = chapter_list
courseid = course_info['courseid']
self.course_info[courseid] = course_info
print()
return course_info
def get_course_by_index(self, index: int | str) -> dict:
index = str(index)
course_name = self.course_dict[index][0]
course_url = self.course_dict[index][1]
parse_result = urllib.parse.urlparse(course_url)
course_param = urllib.parse.parse_qs(parse_result.query)
course_id = course_param.get("courseid")[0]
clazz_id = course_param.get("clazzid")[0]
course_cpi = course_param.get("cpi")[0]
if G_VERBOSE:
print("[INFO] get_course= [{}]{}".format(course_id, course_name))
print(course_url)
print()
if self.course_info.__contains__(course_id) and G_CONFIG['always_request_course_info'] == False:
return self.course_info[course_id]
else:
return self.load_course_info(course_url)
def load_active_mod(self, course_id: str) -> 'ActiveModule':
'Refresh active list and return an ActiveModule instance'
course_id = str(course_id)
course_info = self.course_info[course_id]
clazz_id = course_info['clazzid']
cpi = course_info['cpi']
mod = ActiveModule(self, course_id, clazz_id, cpi)
info_key = f"{course_id}_{clazz_id}"
if info_key not in self.active_info:
self.active_info[info_key] = {}
self.active_info[info_key]['activeList'] = mod.load_active_list()
return mod
def get_active_cache(self, course_id: str) -> dict:
course_id = str(course_id)
course_info = self.course_info[course_id]
clazz_id = course_info['clazzid']
info_key = f"{course_id}_{clazz_id}"
if info_key not in self.active_info:
self.active_info[info_key] = {}
return self.active_info[info_key]
def read_cardcount(self, chapter_page_url: str,
course_id: str, clazz_id: str, chapter_id: str, course_cpi: str) -> int:
rsp_text = self.request_xhr(
url=G_CONFIG['cx_mooc1_path'] + "/mycourse/studentstudyAjax",
header_update={
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
'Origin': G_CONFIG['cx_mooc1_path'],
'Referer': chapter_page_url,
},
data="courseId={0}&clazzid={1}&chapterId={2}&cpi={3}&verificationcode=&mooc2=1".format(
course_id, clazz_id, chapter_id, course_cpi),
method="POST"
).text
result = etree.HTML(rsp_text).xpath(
"//input[@id='cardcount']/@value")[0]
return int(result)
@staticmethod
def key_chapter(course_id, clazz_id, chapter_id) -> str:
# key to index data in self.chapter_info
return "{}_{}_{}".format(course_id, clazz_id, chapter_id)
def load_chapter(self, chapter_meta: dict) -> list:
# Example for chapter_meta
# Generated by self.load_course_info()
# Located in self.course_list[courseid]['chapter_list'] -> item
# {
# "chapterNumber": "1.1",
# "chapterTitle": "第一课时",
# "courseid": "1111",
# "knowledgeId": "2222",
# "clazzid": "3333",
# "transferUrl": "https://mooc1.chaoxing.com/mycourse/transfer?moocId=1111&clazzid=3333&ut=s&refer=https%3A//mooc1.chaoxing.com/mycourse/studentstudy%3FchapterId%3D2222%26courseId%3D1111%26clazzid%3D3333%26enc%3Dffffffffffffffffffffff%26mooc2%3D1",
# "unfinishedCount": 4
# }
course_id = chapter_meta['courseid']
clazz_id = chapter_meta['clazzid']
chapter_id = chapter_meta['knowledgeId']
transfer_url = chapter_meta['transferUrl']
if (G_VERBOSE):
print("[INFO] load_chapter ==========")
print("|{unfinishedCount}| {chapterNumber} {chapterTitle} {knowledgeId}".format(
**chapter_meta))
print(chapter_meta['transferUrl'])
print()
chapter_page_url = self.url_302(transfer_url, {
"Referer": G_CONFIG['cx_mooc2_path'] + "/"
})
if (G_VERBOSE):
print("got chapter_url: " + chapter_page_url)
parse_result = urllib.parse.urlparse(chapter_page_url)
chapter_param = urllib.parse.parse_qs(parse_result.query)
course_cpi = chapter_param.get('cpi')[0]
chapter_HTML_text = self.request_document(
chapter_page_url, {"Referer": transfer_url}).text
chapter_HTML = etree.HTML(chapter_HTML_text)
ut_enc_search = re.search(r"var utEnc\s*=\s*[\"'](.*?)[\"']\s*;",
chapter_HTML.xpath("/html/head/script[not(@src)]")[0].text)
if ut_enc_search is None:
test1 = etree.tostring(chapter_HTML).decode()
test2 = chapter_HTML.xpath("/html/head/script[not(@src)]")
test3 = chapter_HTML.xpath("/html/head/script[not(@src)]")[0].text
raise MyError(1, "utEnc not found")
ut_enc = ut_enc_search.group(1)
if (G_VERBOSE):
print("utEnc=" + ut_enc)
card_count = self.read_cardcount(
chapter_page_url, course_id, clazz_id, chapter_id, course_cpi)
card_list = []
for num in range(card_count):
try:
cards_url = G_CONFIG['cx_mooc1_path'] + "/knowledge/cards?clazzid={0}&courseid={1}&knowledgeid={2}&num={4}&ut=s&cpi={3}&v=20160407-1".format(
clazz_id, course_id, chapter_id, course_cpi, num)
cards_HTML_text = self.request_iframe(cards_url, {
"Referer": chapter_page_url
}).text
scripts_text = etree.HTML(cards_HTML_text).xpath(
"//script[1]/text()")[0]
pattern = re.compile(r"mArg = ({[\s\S]*)}catch")
datas = re.findall(pattern, scripts_text)[0]
card_args = json.loads(datas.strip()[:-1])
card_info = {
'card_args': card_args,
'card_url': cards_url,
}
card_list.append(card_info)
except Exception as err:
print("[ERROR] {}".format(err))
raise MyError(1, "cards_url=" + cards_url +
"###" + cards_HTML_text)
chapter_info = {
'chapter_page_url': chapter_page_url,
'card_count': card_count,
'ut_enc': ut_enc,
'cards': card_list,
}
key_chapter = self.key_chapter(course_id, clazz_id, chapter_id)
self.chapter_info[key_chapter] = chapter_info
return chapter_info
def get_client_type(self) -> str:
return "app" if ("ChaoXingStudy" in self.agent.headers['User-Agent']) else "pc"
class ActiveModule:
def __init__(self, fxxkstar: FxxkStar, course_id: str, clazz_id: str, course_cpi: str):
self.fxxkstar: FxxkStar = fxxkstar
self.fid: str = self.fxxkstar.get_agent().get_cookie_value("fid")
self.course_id: str = course_id
self.clazz_id: str = clazz_id
self.course_cpi: str = course_cpi
self.referer: str = "https://mobilelearn.chaoxing.com/page/active/stuActiveList" + \
"?courseid={}&clazzid={}&cpi={}&ut=s&fid={}".format(
self.course_id, self.clazz_id, self.course_cpi, self.fid)
self.active_list: List[dict] = []
self.active_list1: List[dict] = []
self.active_list2: List[dict] = []
self.class_obj: dict = {}
def get_active_list(self) -> List[dict]:
if (len(self.active_list) == 0):
self.load_active_list()
return self.active_list.copy()
def get_ongoing_active_list(self) -> List[dict]:
return self.active_list1.copy()
def load_active_list(self) -> List[dict]:
url = "https://mobilelearn.chaoxing.com/v2/apis/active/student/activelist" + \
f"?fid={self.fid}&courseId={self.course_id}&classId={self.clazz_id}&_={self.fxxkstar.get_time_millis()}"
rsp_data = self.fxxkstar.request_xhr(url, { # jquery xhr
"Accept": "application/json, text/plain, */*",
"Referer": self.referer,
}).json()
self.check_response("load_active_list", rsp_data)
data = rsp_data['data']
result_list = data.get('activeList', [])
for item in result_list:
self.active_list.append(item)
if 'status' in item and item['status'] == 1:
self.active_list1.append(item)
else:
self.active_list2.append(item)
reading_duration = data.get('readingDuration', 0)
if reading_duration > 0:
ext = data['ext']
ext_from = ext['_from_']
return self.active_list
def load_class_info(self) -> None:
url = "/v2/apis/class/getClassDetail" + \
f"?fid={self.fid}&courseId={self.course_id}&classId={self.clazz_id}"
rsp_data = self.api_get(url)
self.check_response("load_class_info", rsp_data)
self.class_obj = rsp_data['data']
def load_topic_and_work_url(self) -> List[str]:
url = "/v2/apis/class/getTopicAndWorkUrl?DB_STRATEGY=DEFAULT" + \
f"&fid={self.fid}&courseId={self.course_id}&classId={self.clazz_id}&cpi={self.course_cpi}"
rsp_data = self.api_get(url)
self.check_response("load_topic_and_work_url", rsp_data)
data = rsp_data['data']
topic_icon_url = data['topicUrl']