-
Notifications
You must be signed in to change notification settings - Fork 3
/
api.py
690 lines (541 loc) · 20.1 KB
/
api.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
import csv
import base64
import bs4
import orjson
from aiohttp import ContentTypeError
import config
import const
from handlers.base import Errors
from services.cache import CacheService
from services.service import client_session
from services.utils import timeout_handle, ReturnType
def get_optional_str(obj):
"""
This function is designed for situations where the academic system might return None or indicate the absence of a value for results that are not yet available.
While .get("key", "") function can handle cases where the value does not exist, this function should be used when the return value is None.
"""
if obj is None:
return ""
return obj
@timeout_handle
async def get_validate_pic() -> ReturnType:
async with client_session.post(const.VALIDATE_URL) as resp:
if not resp.ok:
return Errors.RemoteServer, None
res = await resp.json()
if res is None:
return Errors.RemoteServer, None
if "src" not in res or res["src"] is None:
return Errors.RemoteServer, None
return Errors.Success, {
"picture": res["src"],
"src": "",
}
@timeout_handle
async def get_student_info(session_key: str) -> ReturnType:
"""
Get student info from index page
<div style="display: none;" id="userInfo">Base64 encoded string</div>
:param session_key:
:return: student info dict
"""
data = {
"session_key": session_key
}
async with client_session.post(const.INDEX_URL, data=data) as resp:
if not resp.ok:
return Errors.RemoteServer, None
res = await resp.text()
i = res.find("id=\"userInfo\">") + 14
j = res.find("<", i)
tmp = orjson.loads(base64.b64decode(res[i:j]).decode("utf-8"))
data["pId"] = tmp["childId"]
async with client_session.post(f"{const.MAIN_URL}/B0410S_StdSemeView_select0410.action", data=data) as resp:
if not resp.ok:
return Errors.RemoteServer, None
res = await resp.json(loads=orjson.loads)
if not res["data"]:
res = {"data": {"seat": "-1", "clsNo": "000-1"}}
return Errors.Success, {
"studentId": tmp["childId"],
"name": tmp["name"],
"seat_number": res["data"]["seat"],
"class_number": res["data"]["clsNo"][3:],
}
@timeout_handle
async def get_exam_stats(session_key: str, item_id: str, std_seme_id: str) -> ReturnType:
"""
Get specific exam statistics data such as rank, score sum of all subjects, score average.
If the statistics info has not been published, data will be empty.
:param session_key: connection session key
:param item_id: the exam id from StdSemeView function
:param std_seme_id: semester id
:return:
"""
data = {
"session_key": session_key,
"itemId": item_id,
"stdSemeId": std_seme_id,
}
async with client_session.post(f"{const.MAIN_URL}/A0410S_ItemScoreStat_select.action", data=data) as resp:
if not resp.ok:
return Errors.RemoteServer, None
res = await resp.json(loads=orjson.loads)
# stats not publish
if len(res["dataRows"]) == 0:
return Errors.Success, {
"class_rank": "",
"class_cnt": "",
"group_rank": "",
"group_cnt": "",
"all_rank": "",
"all_cnt": "",
"score_sum": "",
"average": "",
}
r = res["dataRows"][0]
return Errors.Success, {
"class_rank": r.get("orderC", ""),
"class_cnt": r.get("pnmC", ""),
"group_rank": r.get("orderS", ""),
"group_cnt": r.get("pnmS", ""),
"all_rank": r.get("orderG", ""),
"all_cnt": r.get("pnmG", ""),
"score_sum": r.get("scoreT", ""),
"average": r.get("scoreV", ""),
}
@timeout_handle
async def get_all_semester_info(session_key: str, std_id: str) -> ReturnType:
"""
Get all semester info including semester id, grade, semester year.
Semester id is a necessary parameter in many data queries.
:param session_key: connection session key
:param std_id: student id from student info
:return: data for semester info
:rtype: list[dict]
"""
data = {
"session_key": session_key,
"stdId": std_id,
"statusM": 15,
}
async with client_session.post(f"{const.MAIN_URL}/A0410S_StdSemeView_select.action", data=data) as resp:
if not resp.ok:
return Errors.RemoteServer, None
res = await resp.json(loads=orjson.loads)
return Errors.Success, [{
"stdSemeId": obj["id"],
"syear": obj["syear"],
"seme": obj["seme"],
"grade": obj["grade"],
} for obj in res["dataRows"]]
@timeout_handle
async def get_school_year_data(session_key: str, year: int = None, seme: int = None) -> ReturnType:
"""
Get school year data
If year and seme is null, you will get all year data
:param session_key: connection session key
:param year: query year
:param seme: query semester
:return: data for a given year and semester
:rtype: list[dict]
"""
data = {
"session_key": session_key
}
if year:
data["syear"] = year
if seme:
data["seme"] = seme
async with client_session.post(f"{const.MAIN_URL}/A0410S_Item_select.action", data=data) as resp:
if not resp.ok:
return Errors.RemoteServer, None
res = await resp.json(loads=orjson.loads)
return Errors.Success, [{
"itemId": obj["id"],
"year": obj["syear"],
"semester": obj["seme"],
"exam_name": obj["name"],
} for obj in res["dataRows"]]
@timeout_handle
async def get_single_exam_scores(session_key: str, item_id: str, std_seme_id: str) -> ReturnType:
"""
Get single exam scores data
Have subject name, exam name, subject score, class average for subject
:param session_key: the connection session key
:param item_id: the exam id from StdSemeView function
:param std_seme_id: semester id
:return: List of score data
:rtype: list[dict]
"""
data = {
"session_key": session_key,
"itemId": item_id,
"stdSemeId": std_seme_id,
}
async with client_session.post(f"{const.MAIN_URL}/A0410S_OpenItemScoreView_selectA0410s.action", data=data) as resp:
if not resp.ok:
return Errors.RemoteServer, None
res = await resp.json(loads=orjson.loads)
scores = [{
"subject": score_obj["subjId"],
"exam_name": score_obj["itemId"],
"score": get_optional_str(score_obj.get("score", "")),
"class_average": get_optional_str(score_obj.get("yl", "")),
"is_participated": score_obj["noExamMark"],
} for score_obj in res["dataRows"]]
return Errors.Success, scores
@timeout_handle
async def get_term_scores(session_key: str, student_id: str) -> ReturnType:
"""
:param session_key: the connection session key
:param student_id: student id from student info
:return: List of all year term data
:rtype: list[dict]
"""
data = {
"session_key": session_key,
"stdId": student_id,
"statusM": 15,
"queryKind": "a0410s",
}
async with client_session.post(f"{const.MAIN_URL}/A0410S_StdSemeView_select.action", data=data) as resp:
if not resp.ok:
return Errors.RemoteServer, None
res = await resp.json(loads=orjson.loads)
scores = [{
"stdSemeId": score_obj["id"],
"score": get_optional_str(score_obj.get("sco6", "")),
"all_score": get_optional_str(score_obj.get("scoreT", "")),
"deserved_credits": get_optional_str(score_obj.get("credSum", "")),
"observed_credits": get_optional_str(score_obj.get("credTot", "")),
"total_observed_credits_sum": get_optional_str(score_obj.get("credAdd", "")),
} for score_obj in res["dataRows"]]
return Errors.Success, scores
@timeout_handle
async def get_term_scores_ranking(session_key: str, std_seme_id: str) -> ReturnType:
"""
Get single term ranking data
:param session_key: the connection session key
:param std_seme_id: semester id
:return: List of all term subject scores
:rtype: dict
"""
data = {
"session_key": session_key,
"pId": std_seme_id,
}
async with client_session.post(f"{const.MAIN_URL}/A0410S_OpenStdView_selectA0410s.action", data=data) as resp:
if not resp.ok:
return Errors.RemoteServer, None
res = await resp.json(loads=orjson.loads)
ranking = {
"class_rank": "",
"group_rank": "",
"all_rank": "",
}
if res["dataRows"]:
ranking["class_rank"] = get_optional_str(res["dataRows"][0].get("orderCQ", ""))
ranking["group_rank"] = get_optional_str(res["dataRows"][0].get("orderSQ", ""))
ranking["all_rank"] = get_optional_str(res["dataRows"][0].get("orderGQ", ""))
return Errors.Success, ranking
@timeout_handle
async def get_subject_term_scores(session_key: str, std_seme_id: str) -> ReturnType:
"""
Get single term all subject scores
:param session_key: the connection session key
:param std_seme_id: semester id
:return: List of all term subject scores
:rtype: list[dict]
"""
data = {
"session_key": session_key,
"pId": std_seme_id,
}
async with client_session.post(f"{const.MAIN_URL}/A0410S_OpenStdView_selectA0410s.action", data=data) as resp:
if not resp.ok:
return Errors.RemoteServer, None
res = await resp.json(loads=orjson.loads)
scores = [{
"subject": score_obj["subjId"],
"course_type": score_obj["courseType"],
"credits": score_obj["credits"],
"pass": score_obj["passYn"] == "是",
"score": get_optional_str(score_obj.get("score", "")),
"score_original": get_optional_str(score_obj.get("scoreSrc", "")),
"score_examed": get_optional_str(score_obj.get("scoreExam", "")),
"score_retake": get_optional_str(score_obj.get("scoreRem", "")),
"class_average": get_optional_str(score_obj.get("yl", "")),
"class_rank": get_optional_str(score_obj.get("orderC", "")),
"group_rank": get_optional_str(score_obj.get("orderS", "")),
"all_rank": get_optional_str(score_obj.get("orderG", "")),
} for score_obj in res["dataRows"]]
return Errors.Success, scores
def _get_rewards(reward_obj) -> tuple[int, int, int, int, int, int]:
c1 = reward_obj["reward1"]
c2 = reward_obj["reward2"]
c3 = reward_obj["reward3"]
c4 = reward_obj["reward4"]
c5 = reward_obj["reward5"]
c6 = reward_obj["reward6"]
return c1, c2, c3, c4, c5, c6
@timeout_handle
async def get_rewards_record(session_key: str) -> ReturnType:
"""
Get all reward record
:param session_key: the connection session key
:return: List of all reward record
:rtype: list[dict]
"""
data = {
"session_key": session_key,
}
async with client_session.post(f"{const.MAIN_URL}/B0305S_Reward_select.action", data=data) as resp:
if not resp.ok:
return Errors.RemoteServer, None
res = await resp.json(loads=orjson.loads)
rewards = [{
"syear": obj["syear"],
"seme": obj["seme"],
"fact": obj["fact"],
"desc": get_optional_str(obj.get("rewardArticleId", "")),
"rewards": _get_rewards(obj),
"cancel": get_optional_str(obj.get("cancelYn", "")),
"cancel_date": obj["cancelDt"],
} for obj in res["dataRows"]]
return Errors.Success, rewards
def _get_absences(absence_obj):
return [
absence_obj["morn"],
absence_obj["raiseFlag"],
absence_obj["lesson1"],
absence_obj["lesson2"],
absence_obj["lesson3"],
absence_obj["lesson4"],
absence_obj["rest"],
absence_obj["lesson5"],
absence_obj["lesson6"],
absence_obj["lesson7"],
absence_obj["lesson8"],
]
@timeout_handle
async def get_absence_record(session_key: str) -> ReturnType:
"""
Get all absence records
:param session_key: the connection session key
:return:
:rtype: list[dict]
"""
data = {
"session_key": session_key,
"rows": 365 * 3,
}
async with client_session.post(f"{const.MAIN_URL}/B0209S_Absence_select.action", data=data) as resp:
if not resp.ok:
return Errors.RemoteServer, None
res = await resp.json(loads=orjson.loads)
absences = [{
"syear": obj["syear"],
"seme": obj["seme"],
"date": obj["absenceDt"],
"absences": _get_absences(obj),
} for obj in res["dataRows"]]
return Errors.Success, absences
@timeout_handle
async def update_password(session_key: str, original_password: str, new_password: str,
confirm_new_password: str) -> ReturnType:
"""
Update password by using 180 days check password api(180天密碼重設).
:param session_key: the connection session key
:param original_password: original password
:param new_password: new password
:param confirm_new_password: new password repeat
:return:
"""
data = {
"session_key": session_key,
"oldpd": original_password,
"newpd": new_password,
"agnpd": confirm_new_password
}
async with client_session.post(f"{const.MAIN_URL}/changecheck.action", data=data) as resp:
if not resp.ok:
return Errors.RemoteServer, None
res = await resp.json(loads=orjson.loads)
if res["parameterMap"] and res["parameterMap"]["status"] == 200 and res["message"] is None:
res["message"] = "S"
return Errors.Success, res["message"]
def _get_credits_type(t) -> str:
if t == "C1":
return "all_credit"
elif t == "C2":
return "graduation_credit"
elif t == "C4":
return "required_courses_credit"
elif t == "C9":
return "elective_courses_credit"
@timeout_handle
async def get_graduation_credits(session_key: str, std_seme_id: str) -> ReturnType:
"""
Get all information regarding course credit types for graduation credits.
:param session_key: the connection session key
:param std_seme_id: semester id
:return:
"""
data = {
"session_key": session_key,
"stdSemeId": std_seme_id,
"pId": 2,
}
async with client_session.post(f"{const.MAIN_URL}/A0410S_GradCredit_select.action", data=data) as resp:
if not resp.ok:
return Errors.RemoteServer, None
res = await resp.json(loads=orjson.loads)
graduation_credits = {
_get_credits_type(obj["areaM"]): {
"required_credits": obj["credSum"],
"observed_credits": obj["credits"],
} for obj in res["dataRows"]}
return Errors.Success, graduation_credits
@timeout_handle
async def get_single_exam_scores_and_stats_from_report(session_key: str, syear: int, seme: int, item_id: int):
"""
Get the exam score and statistics through the report API.
:param session_key: the connection session key
:param syear: semester year
:param seme: first semester (1) / second semester (2)
:param item_id: the exam id from StdSemeView function
:return: a dict contain subjects score and stats
"""
data = {
"session_key": session_key,
"syse": f"{syear}{seme}",
"syear": syear,
"seme": seme,
"item": item_id,
"item2": item_id,
"format": "CSV",
"headSign": False,
"mail": 5,
"showWhat": "on",
"showOrd": "on",
"showOrd2": "on",
"raDt": "",
}
async with client_session.post(f"{const.MAIN_URL}/A0492R1.action", data=data) as resp:
if not resp.ok:
return Errors.RemoteServer, None
res = await resp.text(encoding='utf-8')
res = res.split('\n')
reader = csv.reader(res, delimiter=',')
is_end = False
stats = {
"score_sum": None,
"average": None,
"class_rank": None,
"class_cnt": None,
"group_rank": None,
"group_cnt": None,
"all_rank": None,
"all_cnt": None,
}
subjects = []
for idx, row in enumerate(reader):
row = list(filter(lambda s: s != '', row))
if '應修學分' in row:
stats["score_sum"] = row[3]
stats["average"] = row[5]
elif '全班名次' in row:
stats["class_rank"], stats["class_cnt"] = row[1].split('/') # class rank
stats["group_rank"], stats["group_cnt"] = row[3].split('/') # group rank
stats["all_rank"], stats["all_cnt"] = row[5].split('/')
is_end = True
elif idx > 19 and not is_end:
subjects.append({
"subject": row[0].replace('\u3000', ''),
"score": row[2].replace('#', ''),
"class_rank": row[4],
"group_rank": row[5],
"class_average": row[6]
})
if len(row) > 7: # contain two subject
subjects.append({
"subject": row[0 + 7].replace('\u3000', ''),
"score": row[2 + 7].replace('#', ''),
"class_rank": row[4 + 7],
"group_rank": row[5 + 7],
"class_average": row[6 + 7]
})
return Errors.Success, {
"stats": stats,
"scores": subjects,
}
@timeout_handle
async def forget_password(account: str, username: str, idnumber: str, birth: str) -> ReturnType:
"""
Send forget password request to school server.
:param account:
:param username:
:param idnumber: Identity Number
:param birth:
:return:
"""
data = f"act={account},name={username},idno={idnumber},schNo={config.SCHNO},typs=s,birth={birth}"
async with client_session.post(f"{const.MAIN_URL}/Fta.action?a={data}", data=data) as resp:
if not resp.ok:
return Errors.RemoteServer, None
try:
res = await resp.json(loads=orjson.loads)
except ContentTypeError:
return Errors.RemoteServerBlock, None
err = Errors.General
if m := res["parameterMap"]:
if m.get("status") == "200":
err = Errors.Success
elif m["msg"] == "無此帳號":
err = Errors.NotExist
elif m["msg"].find("空白") != -1:
err = Errors.WrongParam
return err, None
def _parse_tr(section_tr: bs4.Tag, section_number: int, curriculum: dict[int, str]):
for (weekday, course_td) in enumerate(section_tr.select("td")[2:]):
teacher_texts = []
for a in course_td.select('a'):
if a is not None:
teacher_texts.append(a.text.strip())
course_name = ""
for t in course_td.text.strip().split("\n"):
if t in teacher_texts or t == "":
continue
for name in teacher_texts:
t = t.replace(name, '')
course_name += t
course_name = course_name.strip().replace(u'\xa0', '') # remove html nbsp
if course_name == "":
continue
curriculum[(weekday + 1) * 10 + (section_number + 1)] = course_name
@timeout_handle
async def get_curriculum(class_number: int) -> ReturnType:
cache_res = CacheService.inst.get(class_number)
if cache_res is not None:
return Errors.Success, cache_res
year = 101
if str(class_number).endswith("18"):
year = 106
elif str(class_number).endswith("19"):
year = 108
url = f"http://w3.tnfsh.tn.edu.tw/deanofstudies/course/C{year}{class_number}.HTML"
async with client_session.get(url) as resp:
if not resp.ok:
return Errors.RemoteServer, None
html = await resp.content.read()
soup = bs4.BeautifulSoup(html, "html.parser")
soup.encoding = "utf-8"
curriculum = {}
for i in range(2, 6):
_parse_tr(soup.select_one(f'tr[style="mso-yfti-irow:{i}"]'), i - 2, curriculum)
for i in range(7, 10):
_parse_tr(soup.select_one(f'tr[style="mso-yfti-irow:{i}"]'), i - 3, curriculum)
_parse_tr(soup.select_one('tr[style="mso-yfti-irow:10;mso-yfti-lastrow:yes"]'), 10 - 3, curriculum)
CacheService.inst.set(class_number, curriculum)
return Errors.Success, curriculum