-
Notifications
You must be signed in to change notification settings - Fork 58
Expand file tree
/
Copy pathapi.py
More file actions
1046 lines (1002 loc) · 36.9 KB
/
api.py
File metadata and controls
1046 lines (1002 loc) · 36.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import json
import time
from base64 import urlsafe_b64decode, urlsafe_b64encode
from random import choice, randint
from typing import Any, Dict
import requests
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad
from requests.adapters import HTTPAdapter, Retry
def create_retry_session(baseurl) -> requests.Session:
retry = Retry(total=5, backoff_factor=1, status_forcelist=[429, 500, 502, 503, 504], allowed_methods=["GET", "POST"])
session = requests.Session()
session.mount("https://", HTTPAdapter(max_retries=retry))
session.headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3",
"Referer": f"{baseurl}/",
"Accept": "application/json, text/plain, */*",
"Accept-Language": "zh-CN,zh;q=0.5",
"Accept-Encoding": "gzip, deflate, br",
"Dnt": "1",
"Sec-Gpc": "1",
"Sec-Fetch-Dest": "script",
"Sec-Fetch-Mode": "no-cors",
"Sec-Fetch-Site": "same-site",
"Te": "trailers",
}
return session
def handle_response(response: requests.Response) -> Dict[str, Any]:
"""
处理接口响应
:param response: 接口响应
:return: 处理后的结果
"""
if response.status_code != 200:
if response.status_code == 403:
raise PermissionError("Token 无效,不允许同时登录,请重试")
if response.status_code == 401:
raise PermissionError("Token 无效,请检查账号信息")
print(f"请求失败:{response.status_code} {response.text}")
return {}
try:
response_data = response.json()
except json.JSONDecodeError:
print(f"响应内容不是有效的 JSON:{response.text}")
return {}
return response_data
class WeBanAPI:
def __init__(self, tenant_code: str | None = None, account: str | None = None, password: str | None = None, user: Dict[str, str] | None = None, timeout: int | tuple = (9.05, 15), session: requests.Session | None = None):
self.account = account
self.password = password
self.tenant_code = tenant_code
self.baseurl = "https://weiban.mycourse.cn"
self.timeout = timeout # 连接超时和读取超时
self.session = session or create_retry_session(self.baseurl)
self.user = user or {"userId": "", "token": ""}
self.session.headers["X-Token"] = self.user["token"]
@staticmethod
def get_timestamp(int_len: int = 10, frac_len: int = 3) -> str:
"""
获取当前时间戳,单位为毫秒,保留三位小数
:param int_len: 整数部分长度
:param frac_len: 小数部分长度
:return:
1234567890.123
"""
t = str(time.time_ns())
return f"{t[:int_len]}.{t[int_len:int_len+frac_len]}" if frac_len else t[:int_len]
@staticmethod
def encrypt(data) -> str:
"""
AES加密
:param data: json 字符串
:return: base64 编码的加密字符串
"""
key = urlsafe_b64decode("d2JzNTEyAAAAAAAAAAAAAA==") # wbs512
return urlsafe_b64encode(AES.new(key, AES.MODE_ECB).encrypt(pad(data.encode(), AES.block_size))).decode()
def set_tenant_code(self, tenant_code: str):
"""
设置学校代码
:param tenant_code: 学校代码
:return:
"""
self.tenant_code = tenant_code
def get_tenant_list_with_letter(self) -> Dict[str, Any]:
"""
获取学校代码和名称列表
:return:
{
"code": "0",
"data": [
{
"index": "a",
"list": [
{ "code": "0000010", "name": "安全教育" }
]
}
],
"detailCode": "0"
}
"""
url = f"{self.baseurl}/pharos/login/getTenantListWithLetter.do"
params = {"timestamp": self.get_timestamp()}
response = self.session.post(url, params=params, timeout=self.timeout)
return handle_response(response)
def get_tenant_config(self, tenant_code: str | None = None) -> Dict[str, Any]:
"""
获取学校配置
:return:
{
"code": "0",
"data": {
"code": "0000010",
"name": "安全教育",
"userNamePrompt": "请输入学号",
"passwordPrompt": "请输入学号",
"forgetPasswordUserNamePrompt": "",
"displayPop": 2,
"popPrompt": "",
"loginType": "1",
"forgetPassword": 2,
"customerTitle": "安全微伴",
"customerLoginTips": "安全教育"
},
"detailCode": "0"
}
"""
url = f"{self.baseurl}/pharos/login/getTenantConfig.do"
params = {"timestamp": self.get_timestamp()}
data = {"tenantCode": tenant_code or self.tenant_code}
response = self.session.post(url, params=params, data=data, timeout=self.timeout)
return handle_response(response)
def get_simple_config(self, tenant_code: str | None = None) -> Dict[str, Any]:
"""
获取简单配置
:param tenant_code: 学校代码
:return:
"""
url = f"{self.baseurl}/pharos/tenantconfig/getSimpleConfig.do"
params = {"timestamp": self.get_timestamp()}
data = {"tenantCode": tenant_code or self.tenant_code, "userId": self.user["userId"]}
response = self.session.post(url, params=params, data=data, timeout=self.timeout)
return handle_response(response)
def get_help(self, tenant_code: str | None = None) -> Dict[str, Any]:
"""
获取帮助文件
:return:
{
"code": "0",
"data": {
"helpFileUrl": ""
},
"detailCode": "0"
}
"""
url = f"{self.baseurl}/pharos/login/getHelp.do"
params = {"timestamp": self.get_timestamp()}
data = {"tenantCode": tenant_code or self.tenant_code}
response = self.session.post(url, params=params, data=data, timeout=self.timeout)
return handle_response(response)
def rand_letter_image(self, verify_time: str | None) -> bytes:
"""
获取验证码图片
:return:
images bytes
"""
url = f"{self.baseurl}/pharos/login/randLetterImage.do"
params = {"time": verify_time or self.get_timestamp(frac_len=0)}
response = self.session.get(url, params=params, timeout=self.timeout)
return response.content
def login(self, verify_code: str, verify_time: int | None) -> Dict[str, Any]:
"""
登录
:param verify_code: 验证码
:param verify_time: 验证码时间戳
:return:
{
"code": "0",
"data": {
"token": "${uuid}",
"userId": "${uuid}",
"userName": "",
"realName": "",
"userNameLabel": "学号",
"uniqueValue": "",
"isBind": "1",
"tenantCode": "0000010",
"batchCode": "",
"gender": 1,
"openid": "",
"switchGoods": 1,
"switchDanger": 1,
"switchNetCase": 1,
"preBanner": "https://h.mycourse.cn/pharosfile/resources/images/projectbanner/pre.png",
"normalBanner": "https://h.mycourse.cn/pharosfile/resources/images/projectbanner/normal.png",
"specialBanner": "https://h.mycourse.cn/pharosfile/resources/images/projectbanner/special.png",
"militaryBanner": "https://h.mycourse.cn/pharosfile/resources/images/projectbanner/military.png",
"isLoginFromWechat": 2,
"tenantName": "安全教育",
"tenantType": 1,
"loginSide": 1,
"popForcedCompleted": 2,
"showGender": 2,
"showOrg": 2,
"orgLabel": "院系",
"nickName": "",
"imageUrl": "https://resource.mycourse.cn/mercury/resources/mercury/wb/images/portrait.jpg",
"defensePower": 60,
"knowledgePower": 60,
"safetyIndex": 99
},
"detailCode": "0"
}
"""
url = f"{self.baseurl}/pharos/login/login.do"
params = {"timestamp": self.get_timestamp()}
data = {
"keyNumber": self.account,
"password": self.password,
"tenantCode": self.tenant_code,
"time": verify_time or int(self.get_timestamp(frac_len=0)),
"verifyCode": verify_code,
}
encrypt_data = self.encrypt(json.dumps(data, separators=(",", ":")))
response = self.session.post(url, params=params, data={"data": encrypt_data}, timeout=self.timeout)
if response.json().get("data", {}).get("token", None):
self.user = response.json()["data"]
self.session.headers["X-Token"] = self.user["token"]
self.password = None
return handle_response(response)
def list_completion(self) -> Dict[str, Any]:
"""
获取模块
:return:
{
"code": "0",
"data": [
{
"module": "labProject",
"showable": 2
},
{
"module": "fireTrainingProject",
"showable": 2
},
{
"module": "trainingActivity",
"showable": 2
},
{
"module": "virtualTrainingPlace",
"showable": 2
},
{
"module": "notice",
"showable": 0,
"completion": {
"marked": 2,
"finished": 2,
"grey": 1,
"active": 2,
"message": "无通知"
}
},
{
"module": "forcePassword",
"showable": 2
}
],
"detailCode": "0"
}
"""
url = f"{self.baseurl}/pharos/index/listCompletion.do"
params = {"timestamp": self.get_timestamp()}
data = {"tenantCode": self.tenant_code, "userId": self.user["userId"]}
response = self.session.post(url, params=params, data=data, timeout=self.timeout)
return handle_response(response)
def lab_index(self) -> Dict[str, Any]:
"""
获取实验室模块信息
:return:
{
"code": "0",
"data": {
"current": {
"projectName": "2025级硕士生实验室安全教育",
"projectImageUrl": "https://weibanstatic.mycourse.cn/pharos/resource/10000024/image/project/20250707/ae93f8d9-80b6-4047-97a6-aa344794d2ee.jpg",
"endTime": "2025-10-12",
"progressPet": 2,
"userProjectId": "${uuid}",
"projectCategory": 9,
"projectAttribute": 3,
"existedCertificate": 2
},
"projects": [{
"projectName": "2025级硕士生实验室安全教育",
"projectImageUrl": "https://weibanstatic.mycourse.cn/pharos/resource/10000024/image/project/20250707/ae93f8d9-80b6-4047-97a6-aa344794d2ee.jpg",
"endTime": "2025-10-12",
"progressPet": 2,
"userProjectId": "${uuid}",
"projectCategory": 9,
"projectAttribute": 3,
"existedCertificate": 2
}],
"ebookState": 1,
"labCardState": 2,
"ebookIsMust": 2
},
"detailCode": "0"
}
"""
url = f"{self.baseurl}/pharos/lab/index.do"
params = {"timestamp": self.get_timestamp(10, 1)}
data = {"tenantCode": self.tenant_code, "userId": self.user["userId"]}
response = self.session.post(url, params=params, data=data, timeout=self.timeout)
return handle_response(response)
def list_study_task(self) -> Dict[str, Any]:
"""
获取学习任务列表
:return:
{
"code": "0",
"data": {
"studyTaskList": [
{
"projectId": "${uuid}",
"projectName": "2025年春季安全教育",
"projectImageUrl": "",
"endTime": "2025-05-31",
"finished": 2,
"progressPet": 5,
"exceedPet": 46,
"assessment": "完成进度达到100%视为完成",
"userProjectId": "${uuid}",
"projectMode": 1,
"projectCategory": 9,
"projectAttribute": 1,
"studyState": 5,
"studyStateLabel": "未完成",
"certificateAcquired": 2,
"completion": {
"marked": 1,
"finished": 2,
"grey": 2,
"active": 1,
"message": ""
}
}
],
"indexShowType": 2
},
"detailCode": "0"
}
"""
url = f"{self.baseurl}/pharos/index/listStudyTask.do"
params = {"timestamp": self.get_timestamp()}
data = {"tenantCode": self.tenant_code, "userId": self.user["userId"]}
response = self.session.post(url, params=params, data=data, timeout=self.timeout)
return handle_response(response)
def list_my_project(self, ended: int = 2) -> Dict[str, Any]:
"""
获取我的项目列表,和 list_study_task 几乎相同
:param ended: 1:进行中 2:已结束
:return:
{
"code": "0",
"data": [
{
"projectId": "${uuid}",
"projectName": "2025年春季安全教育",
"projectImageUrl": "",
"endTime": "2025-05-31",
"finished": 2,
"progressPet": 5,
"exceedPet": 46,
"assessment": "完成进度达到100%视为完成",
"userProjectId": "${uuid}",
"projectMode": 1,
"projectCategory": 9,
"projectAttribute": 1,
"studyState": 5,
"studyStateLabel": "未完成",
"certificateAcquired": 2
}
],
"detailCode": "0"
}
"""
url = f"{self.baseurl}/pharos/index/listMyProject.do"
params = {"timestamp": self.get_timestamp()}
data = {"tenantCode": self.tenant_code, "userId": self.user["userId"], "ended": ended}
response = self.session.post(url, params=params, data=data, timeout=self.timeout)
return handle_response(response)
def show_progress(self, user_project_id: str) -> Dict[str, Any]:
"""
获取学习任务进度
:param user_project_id: 用户项目ID
:return:
{
"code": "0",
"data": {
"name": "2025年春季安全教育",
"pushNum": 0,
"pushFinishedNum": 0,
"optionalNum": 0,
"optionalFinishedNum": 0,
"requiredNum": 100,
"requiredFinishedNum": 6,
"examNum": 1,
"examFinishedNum": 0,
"examAssessmentNum": 1,
"endTime": "2025-05-31 00:00:00",
"ended": 2,
"lastDays": 31,
"progressPet": 5,
"finished": 2,
"imageUrl": "",
"studyRank": 0,
"assessment": "完成进度达到100%视为完成",
"assessmentRemark": "(完成课程占进度条的80%,考试通过占进度条的20%)",
"existedExam": 1,
"existedOptionalCourse": 2
},
"detailCode": "0"
}
"""
url = f"{self.baseurl}/pharos/project/showProgress.do"
params = {"timestamp": self.get_timestamp()}
data = {
"tenantCode": self.tenant_code,
"userId": self.user["userId"],
"userProjectId": user_project_id,
}
response = self.session.post(url, params=params, data=data, timeout=self.timeout)
return handle_response(response)
def list_category(self, user_project_id: str, choose_type: int = 3) -> Dict[str, Any]:
"""
获取课程分类列表
:param user_project_id: 用户项目ID
:param choose_type: PushCourse(1,"推送课"),OptionalCourse(2,"自选课"),RequiredCourse(3,"必修课")
:return:
{
"code": "0",
"data": [
{
"categoryCode": "101001001",
"categoryName": "国家安全各个方面",
"categoryRemark": "国家安全是国家的基本利益,是一个国家处于没有危险的客观状态。本系列从保密、反间谍、反邪教、国情教育等方面介绍了国家安全知识。",
"totalNum": 11,
"finishedNum": 6,
"categoryImageUrl": "https://jxstatic.mycourse.cn/image/category/20210929/8557a267-c38d-4eb3-81c6-d4d55637c068.jpg"
}
]
}
"""
url = f"{self.baseurl}/pharos/usercourse/listCategory.do"
params = {"timestamp": self.get_timestamp()}
data = {
"tenantCode": self.tenant_code,
"userId": self.user["userId"],
"userProjectId": user_project_id,
"chooseType": choose_type,
}
response = self.session.post(url, params=params, data=data, timeout=self.timeout)
return handle_response(response)
def list_course(self, user_project_id: str, category_code: str, choose_type: int = 3) -> Dict[str, Any]:
"""
获取课程列表
:param user_project_id: 用户项目ID
:param category_code: 课程分类代码
:param choose_type: PushCourse(1,"推送课"),OptionalCourse(2,"自选课"),RequiredCourse(3,"必修课")
:return:
{
"code": "0",
"data": [
{
"userCourseId": "${uuid}",
"resourceId": "${uuid}",
"resourceName": "扫黑除恶应知应会知识(上)",
"finished": 2,
"isPraise": 2,
"isShare": 2,
"praiseNum": 36844,
"shareNum": 0,
"shared": 2,
"source": 1,
"imageUrl": "https://jxstatic.mycourse.cn/image/microlecture/20200101/33e72c5e-f4a8-4e06-b253-6c907da76963.png",
"categoryName": "国家安全各个方面"
}
]
}
"""
url = f"{self.baseurl}/pharos/usercourse/listCourse.do"
params = {"timestamp": self.get_timestamp()}
data = {
"tenantCode": self.tenant_code,
"userId": self.user["userId"],
"userProjectId": user_project_id,
"chooseType": choose_type,
"categoryCode": category_code,
}
response = self.session.post(url, params=params, data=data, timeout=self.timeout)
return handle_response(response)
def study(self, course_id: str, user_project_id: str) -> Dict[str, Any]:
"""
开始学习课程
:param course_id: 课程ID
:param user_project_id: 用户项目ID
:return:
{
"code":"0",
"detailCode":"0"
}
"""
url = f"{self.baseurl}/pharos/usercourse/study.do"
params = {"timestamp": self.get_timestamp()}
data = {
"tenantCode": self.tenant_code,
"userId": self.user["userId"],
"courseId": course_id,
"userProjectId": user_project_id,
}
response = self.session.post(url, params=params, data=data, timeout=self.timeout)
return handle_response(response)
def get_course_url(self, course_id: str, user_project_id: str) -> Dict[str, Any]:
"""
获取课程链接
:param course_id: 课程ID
:param user_project_id: 用户项目ID
:return:
{
"code":"0",
"data":"https://mcwk.mycourse.cn/course/A11072/A11072.html?userCourseId=&tenantCode=&type=1&csComm=true&csCapt=true",
"detailCode":"0"
}
"""
url = f"{self.baseurl}/pharos/usercourse/getCourseUrl.do"
params = {"timestamp": self.get_timestamp()}
data = {
"tenantCode": self.tenant_code,
"userId": self.user["userId"],
"courseId": course_id,
"userProjectId": user_project_id,
}
response = self.session.post(url, params=params, data=data, timeout=self.timeout)
return handle_response(response)
def invoke_captcha(self, user_course_id: str, user_project_id: str) -> Dict[str, Any]:
"""
通过验证码获取完成 token
:param user_course_id: 用户课程ID
:param user_project_id: 用户项目ID
:return:
{"code":"0",data:{"methodToken",""}}
"""
fetch_url = f"{self.baseurl}/pharos/usercourse/getCaptcha.do"
check_url = f"{self.baseurl}/pharos/usercourse/checkCaptcha.do"
params = {
"userCourseId": user_course_id,
"userProjectId": user_project_id,
"userId": self.user["userId"],
"tenantCode": self.tenant_code,
}
response = self.session.get(fetch_url, params=params, timeout=self.timeout) # {"captcha":{"num":3,"questionId":"${uuid}","imageUrl":"${url}"}}
params["questionId"] = handle_response(response).get("captcha", {}).get("questionId", "")
coordinates = [{"x": x + randint(-5, 5), "y": y + randint(-5, 5)} for x, y in [(207, 436), (67, 424), (141, 427)]]
data = {"coordinateXYs": json.dumps(coordinates, separators=(",", ":"))}
time.sleep(3)
response = self.session.post(check_url, params=params, data=data, timeout=self.timeout)
return handle_response(response)
def finish_by_token(self, user_course_id: str, token: str | None = None, course_type: str | None = "weiban") -> str:
"""
通过 userCourseId 或验证码 token 完成课程
:param user_course_id: 用户课程 ID
:param token: 用户课程 ID 或验证码 token
:param course_type: 课程类型 weiban, lyra, open, moon
:return:
jQuery341002461326005930642_1747119073594({"msg":"ok","code":"0","detailCode":"0"})
"""
url = f"{self.baseurl}/pharos/usercourse/v2/{token or user_course_id}.do"
params = {
"callback": f"jQuery3210{''.join(choice('123456789') for _ in range(15))}_{int(self.get_timestamp(13,0))}",
"userCourseId": user_course_id,
"tenantCode": self.tenant_code,
"_": int(self.get_timestamp(13, 0)),
}
if course_type == "open":
url = f"https://open.mycourse.cn/proteus/usercourse/finish.do"
elif course_type == "moon":
url = f"https://moon.mycourse.cn/moonapi/api/study/activity/microCourse/v1/finishedCourse"
response = self.session.get(url, params=params, timeout=self.timeout)
return response.text
def finish_lyra(self, user_activity_id: str) -> Dict[str, Any]:
"""
完成安全实训
:param user_activity_id: 用户活动 ID
:return:
{"msg":"ok","code":"0","detailCode":"0"}
"""
url = f"https://lyra.mycourse.cn/lyraapi/study/course/finish.api"
data = {"userActivityId": user_activity_id}
response = self.session.post(url, data=data, timeout=self.timeout)
return handle_response(response)
def exam_list_plan(self, user_project_id: str) -> Dict[str, Any]:
"""
获取考试计划列表
:param user_project_id: 用户课程 ID
:return:
{
"code": "0",
"data": [
{
"id": "${uuid}",
"examPlanId": "${uuid}",
"examPlanName": "结课考试",
"answerNum": 3,
"answerTime": 60,
"passScore": 80,
"isRetake": 2,
"examType": 2,
"isAssessment": 1,
"startTime": "2025-03-01 00:00:00",
"endTime": "2025-04-31 23:59:59",
"examFinishNum": 1,
"examOddNum": 2,
"examScore": 100,
"examTimeState": 2,
"displayState": 1,
"prompt": ""
}
],
"detailCode": "0"
}
"""
url = f"{self.baseurl}/pharos/exam/listPlan.do"
params = {"timestamp": self.get_timestamp()}
data = {
"tenantCode": self.tenant_code,
"userId": self.user["userId"],
"userProjectId": user_project_id,
}
response = self.session.post(url, params=params, data=data, timeout=self.timeout)
return handle_response(response)
def exam_before_paper(self, user_exam_plan_id: str) -> Dict[str, Any]:
"""
获取是否有未提交的答案
:param user_exam_plan_id: 用户考试计划 ID
:return:
{
"code": "0",
"data": {
"isExistedNotSubmit": false
},
"detailCode": "0"
}
"""
url = f"{self.baseurl}/pharos/exam/beforePaper.do"
params = {"timestamp": self.get_timestamp()}
data = {
"tenantCode": self.tenant_code,
"userId": self.user["userId"],
"userExamPlanId": user_exam_plan_id,
}
response = self.session.post(url, params=params, data=data, timeout=self.timeout)
return handle_response(response)
def exam_prepare_paper(self, user_exam_plan_id: str) -> Dict[str, Any]:
"""
准备考试
:param user_exam_plan_id: 用户考试计划 ID
:return:
{
"code": "0",
"data": {
"realName": "张三",
"userIDLabel": "学号:",
"questionNum": 50,
"paperScore": 100,
"answerTime": 60
},
"detailCode": "0"
}
"""
url = f"{self.baseurl}/pharos/exam/preparePaper.do"
params = {"timestamp": self.get_timestamp()}
data = {
"tenantCode": self.tenant_code,
"userId": self.user["userId"],
"userExamPlanId": user_exam_plan_id,
}
response = self.session.post(url, params=params, data=data, timeout=self.timeout)
return handle_response(response)
def exam_check_verify_code(self, user_exam_plan_id: str, verfy_code: str, verify_time: int | None) -> Dict[str, Any]:
"""
检查考试验证码
:param user_exam_plan_id: 用户考试计划 ID
:param verfy_code: 验证码
:param verify_time: 验证码 13 位时间戳
:return:
{
"code": "0",
"detailCode": "0"
}
"""
url = f"{self.baseurl}/pharos/exam/checkVerifyCode.do"
params = {"timestamp": self.get_timestamp()}
data = {
"tenantCode": self.tenant_code,
"userId": self.user["userId"],
"time": verify_time or int(self.get_timestamp(frac_len=0)),
"userExamPlanId": user_exam_plan_id,
"verifyCode": verfy_code,
}
response = self.session.post(url, params=params, data=data, timeout=self.timeout)
return handle_response(response)
def exam_start_paper(self, user_exam_plan_id: str) -> Dict[str, Any]:
"""
开始考试
:param user_exam_plan_id: 用户考试计划 ID
:return:
{
"code": "0",
"data": {
"answerTime": 60,
"questionList": [
{
"id": "${uuid}",
"title": "小玲有辆最高时速40公里每小时的电动自行车,按照这个时速上路,如果遇到事故,极有可能被认定为( )追责。",
"type": 1,
"typeLabel": "单选题",
"score": 2,
"sequence": 0,
"isRight": 0,
"optionList": [
{
"id": "${uuid}",
"questionId": "${uuid}",
"content": "机动车",
"sequence": 1,
"selected": 2,
"attachmentList": []
},
{
"id": "${uuid}",
"questionId": "${uuid}",
"content": "非机动车",
"sequence": 2,
"selected": 2,
"attachmentList": []
},
{
"id": "${uuid}",
"questionId": "${uuid}",
"content": "行人",
"sequence": 3,
"selected": 2,
"attachmentList": []
},
{
"id": "${uuid}",
"questionId": "${uuid}",
"content": "残疾人用车",
"sequence": 4,
"selected": 2,
"attachmentList": []
}
],
"attachmentList": []
}
]
},
"detailCode": "0"
}
"""
url = f"{self.baseurl}/pharos/exam/startPaper.do"
params = {"timestamp": self.get_timestamp()}
data = {
"tenantCode": self.tenant_code,
"userId": self.user["userId"],
"userExamPlanId": user_exam_plan_id,
}
response = self.session.post(url, params=params, data=data, timeout=self.timeout)
return handle_response(response)
def exam_record_question(self, user_exam_plan_id: str, question_id: str, use_time: int, answer_ids: list | None, exam_plan_id: str) -> Dict[str, Any]:
"""
记录考试答案
:param user_exam_plan_id: 用户考试计划 ID
:param question_id: 题目 ID
:param use_time: 本题用时,单位为秒
:param answer_ids: 答案 ID, 列表形式
:param exam_plan_id: 考试计划 ID
:return:
{
"code": "0",
"detailCode": "0"
}
"""
url = f"{self.baseurl}/pharos/exam/recordQuestion.do"
params = {"timestamp": self.get_timestamp()}
data = {
"tenantCode": self.tenant_code,
"userId": self.user["userId"],
"userExamPlanId": user_exam_plan_id,
"questionId": question_id,
"useTime": use_time,
"examPlanId": exam_plan_id,
}
if answer_ids:
data["answerIds"] = ",".join(answer_ids)
response = self.session.post(url, params=params, data=data, timeout=self.timeout)
return handle_response(response)
def exam_submit_paper(self, user_exam_plan_id: str) -> Dict[str, Any]:
"""
提交考试
:param user_exam_plan_id: 用户考试计划 ID
:return:
{
"code": "0",
"data": {
"score": 100,
"redpacketInfo": {
"redpacketName": "",
"redpacketComment": "",
"redpacketMoney": 0.0,
"isSendRedpacket": 2
},
"ebookInfo": { "displayBook": 2 }
},
"detailCode": "0"
}
"""
url = f"{self.baseurl}/pharos/exam/submitPaper.do"
params = {"timestamp": self.get_timestamp()}
data = {
"tenantCode": self.tenant_code,
"userId": self.user["userId"],
"userExamPlanId": user_exam_plan_id,
}
response = self.session.post(url, params=params, data=data, timeout=self.timeout)
return handle_response(response)
def exam_fresh_paper(self, user_exam_plan_id: str) -> Dict[str, Any]:
"""
重置考试题目
:param user_exam_plan_id: 用户考试计划 ID
:return:
{
"code": "0",
"data": {
"answerTime": 56,
"questionList": [
{
"id": "536a43c6-c6f4-4fbf-97f5-a64e53cb813c",
"title": "昏厥的病人不能随意搬动,但可适当挪动头部来保持病人呼吸通畅。",
"type": 1,
"typeLabel": "单选题",
"score": 2,
"sequence": 0,
"isRight": 0,
"optionList": [
{
"id": "afab5aea-2cab-46c2-b3cc-6009c6b6de55",
"questionId": "536a43c6-c6f4-4fbf-97f5-a64e53cb813c",
"content": "对。",
"sequence": 1,
"selected": 1,
"attachmentList": []
},
{
"id": "2913e6b8-51a8-4716-a2d9-9d019ef900da",
"questionId": "536a43c6-c6f4-4fbf-97f5-a64e53cb813c",
"content": "错。",
"sequence": 2,
"selected": 2,
"attachmentList": []
}
],
"attachmentList": []
}
]
},
"detailCode": "0"
}
"""
url = f"{self.baseurl}/pharos/exam/freshPaper.do"
params = {"timestamp": self.get_timestamp()}
data = {
"tenantCode": self.tenant_code,
"userId": self.user["userId"],
"userExamPlanId": user_exam_plan_id,
}
response = self.session.post(url, params=params, data=data, timeout=self.timeout)
return handle_response(response)
def exam_review_paper(self, user_exam_id: str, is_retake: int = 2) -> Dict[str, Any]:
"""
查看考试结果
:param user_exam_id: 用户考试 ID
:param is_retake: 是否重考,1:是,2:否
:return:
{
"code": "0",
"data": {
"submitTime": "2025-05-19 01:59:37",
"score": 100,
"useTime": 526,
"questions": [
{
"title": "题目",
"type": 1,
"typeLabel": "单选题",
"score": 2,
"sequence": 0,
"analysis": "",
"isRight": 1,
"optionList": [
{
"content": "正确。",
"sequence": 1,
"selected": 1,
"isCorrect": 1,
"attachmentList": []
},
{
"content": "错误。",
"sequence": 2,
"selected": 2,
"isCorrect": 2,
"attachmentList": []
}
],
"attachmentList": []
}
]
},
"detailCode": "0"
}
"""
url = f"{self.baseurl}/pharos/exam/reviewPaper.do"
params = {"timestamp": self.get_timestamp()}
data = {
"tenantCode": self.tenant_code,
"userId": self.user["userId"],
"userExamId": user_exam_id,
"isRetake": is_retake,
}
response = self.session.post(url, params=params, data=data, timeout=self.timeout)
return handle_response(response)
def exam_list_history(self, exam_plan_id: str, exam_type: int) -> Dict[str, Any]:
"""
获取考试历史记录
:param exam_plan_id: 考试计划 ID
:param exam_type: 考试类型
:return:
{
"code": "0",
"data": [
{
"id": "${uuid}",
"examPlanId": "${uuid}",
"examPlanName": "结课考试",
"answerNum": 5,