/
vfs.py
2433 lines (2061 loc) · 99.4 KB
/
vfs.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
# License: LGPL3+
from collections import OrderedDict
from io import BytesIO, StringIO
from lxml import etree
from pathlib import PurePosixPath
from urllib.parse import urlencode, urlsplit, parse_qs
import csv
import json
import logging
# 提供給外部使用的 VFS 界面
class VFS:
def __init__(self, request, strings, edit):
self.logger = logging.getLogger(__name__)
self.request = request
self.strings = strings
self.root = RootDirectory(self)
self._edit = edit
def open(self, path, cwd=None, edit_check=True):
if edit_check and hasattr(self, '_edit'):
self._do_edit()
if cwd == None:
work = self.root
else:
work = cwd
path = PurePosixPath(path)
for item in path.parts:
if item.find('/') >= 0:
continue
work = work.access(item)
if not work.ready:
work.fetch()
return work
def is_root(self, node):
return node is self.root
def is_regular(self, node):
return isinstance(node, Regular)
def is_directory(self, node):
return isinstance(node, Directory)
def is_internal_link(self, node):
return isinstance(node, InternalLink)
def is_external_link(self, node):
return isinstance(node, ExternalLink)
def _do_edit(self):
s = self.strings
# add_courses
for semester, sn in self._edit['add_courses']:
path = PurePosixPath('/', s['dir_root_courses'], semester)
node = self.open(path, edit_check=False)
course = WebCourseDirectory(self, node, semester, sn)
course.fetch()
assert course.ready == True
node.add(course.name, course)
node.add(sn, InternalLink(self, node, course.name))
# delete_files
for path in self._edit['delete_files']:
node = self.open(path, edit_check=False)
if node is self.root:
raise ValueError('不可以刪除根資料夾')
node.parent.unlink(PurePosixPath(path).name)
# 完成。下次 open 不會再進來了
del self._edit
# 把 JSON 裡的多行字串轉成陣列
class OrderedDictWithLineBreak(OrderedDict):
def __setitem__(self, key, value, **kwargs):
if isinstance(value, str) and value.find('\n') >= 0:
value = ['(多行字串)'] + value.replace('\r', '').split('\n')
super().__setitem__(key, value, **kwargs)
# 產生普通資料檔的檔案名稱
def format_dirname(sn, title):
return '{:08} {}'.format(int(sn), title.strip().rstrip('.'))
def format_filename(sn, title, extension):
return '{}.{}'.format(format_dirname(sn, title), extension)
# 把網址轉成 ceiba_dl.Request 可以接受的格式
def url_to_path_and_args(url):
components = urlsplit(url)
path = components.path
query_string = components.query
args = parse_qs(query_string, keep_blank_values=True)
for key, value in args.items():
if isinstance(value, list):
assert len(value) == 1
args[key] = value[0]
return (path, args)
# lxml 遇到沒有文字時回傳 None,但空字串比較好操作
def element_get_text(element):
return '' if element.text == None else element.text
# 從雙欄表格中取得資料的輔助工具
def row_get_value(row, expected_keys, value_mappings,
free_form=False, return_object=False):
assert len(row) == 2
assert row[0].tag == 'th'
assert row[1].tag == 'td'
assert row[0].text in expected_keys
for source, mapped in value_mappings.items():
assert isinstance(source, tuple)
if row[1].text in source:
return mapped
if free_form:
if return_object:
return row[1]
else:
return element_get_text(row[1])
else:
assert False
# 在真正開始爬網頁前先檢查功能是否開啟
def ceiba_function_enabled(request, course_sn, function, path):
frame_path = '/modules/index.php'
frame_args = {'csn': course_sn, 'default_fun': function}
request.web(frame_path, args=frame_args)
return len(request.web(path).xpath('//table')) > 0
# 基本的檔案型別:普通檔案、目錄、內部連結、外部連結
class File:
def __init__(self, vfs, parent):
self.parent = parent
self.vfs = vfs
self.local = True
self._ready = False
def fetch(self):
raise NotImplementedError('繼承的類別沒有實作 fetch 方法')
def read(self, output, progress_callback=lambda *x: None):
raise NotImplementedError('繼承的類別沒有實作 read 方法')
@property
def ready(self):
return self._ready
@ready.setter
def ready(self, value):
if value == True:
self._ready = True
else:
raise ValueError('不可以將 ready 重設為 False 或任何其他數值')
class Regular(File):
def __init__(self, vfs, parent):
super().__init__(vfs, parent)
def read(self, output, progress_callback=lambda *x: None):
progress_callback(False, None, None, None)
if not self.ready:
self.fetch()
output.write(self._content.encode())
progress_callback(True, None, None, None)
def size(self):
return len(self._content.encode())
class Directory(File):
def __init__(self, vfs, parent):
super().__init__(vfs, parent)
self._children = list()
def read(self, output, **kwargs):
if not self.ready:
self.fetch()
output.write(str(self._children).encode() + b'\n')
def list(self):
if not self.ready:
self.fetch()
return self._children
def add(self, name, node, ignore_duplicate=False):
assert node.parent is self
assert node.vfs is self.vfs
name = name.replace('/', '_').strip()
if name in map(lambda x: x[0], self._children):
if ignore_duplicate:
return
else:
raise FileExistsError('檔案 {} 已經存在了'.format(name))
self._children.append((name, node))
def access(self, name):
if name == '.':
return self
elif name == '..':
return self.parent
else:
if not self.ready:
self.fetch()
for child in self._children:
if child[0] == name:
return child[1]
raise FileNotFoundError('在目前的目錄下找不到 {} 檔案'.format(name))
def unlink(self, name):
for index, child in enumerate(self._children):
if child[0] == name:
del self._children[index]
return
raise FileNotFoundError('在目前的目錄下找不到 {} 檔案'.format(name))
class InternalLink(File):
def __init__(self, vfs, parent, path):
super().__init__(vfs, parent)
self.path = path
self.ready = True
def access(self, name):
return self.vfs.open(self.path, cwd=self.parent).access(name)
def read(self, *args, **kwargs):
return self.vfs.open(self.path, cwd=self.parent).read(*args, **kwargs)
def read_link(self):
return self.path
class ExternalLink(File):
def __init__(self, vfs, parent, url):
super().__init__(vfs, parent)
self.url = url
self.ready = True
def read(self, output, **kwargs):
output.write(self.url.encode() + b'\n')
def read_link(self):
return self.url
# 其他衍生的檔案型別
class RootDirectory(Directory):
def __init__(self, vfs):
super().__init__(vfs, self)
s = self.vfs.strings
self.add(s['dir_root_courses'], RootCoursesDirectory(self.vfs, self))
self.add(s['dir_root_students'], RootStudentsDirectory(self.vfs, self))
self.add(s['dir_root_teachers'], RootTeachersDirectory(self.vfs, self))
self.ready = True
class RootCoursesDirectory(Directory):
def __init__(self, vfs, parent):
super().__init__(vfs, parent)
def fetch(self):
s = self.vfs.strings
result = self.vfs.request.api({'mode': 'semester'})
for semester in result['semester']:
name = semester['semester']
if 'now' in semester:
assert semester['now'] == 1
self.add(s['link_semester_current'],
InternalLink(self.vfs, self, name))
self.add(name, SemesterDirectory(self.vfs, self, name))
self.ready = True
class RootStudentsDirectory(Directory):
def __init__(self, vfs, parent):
super().__init__(vfs, parent)
self.ready = True
class RootTeachersDirectory(Directory):
def __init__(self, vfs, parent):
super().__init__(vfs, parent)
self.ready = True
class SemesterDirectory(Directory):
def __init__(self, vfs, parent, semester):
super().__init__(vfs, parent)
self._semester = semester
def fetch(self):
result = self.vfs.request.api(
{'mode': 'semester', 'semester': self._semester})
result_keys = ['student_id', 'student_cname', 'semester', 'grid', 'calendar']
assert set(result.keys()) == set(result_keys)
days = '一二三四五六日'
slots = '01234@56789XABC'
courses = dict()
class Course(dict):
def __init__(self):
super().__init__(self)
self['sn'] = None
self['time'] = list()
self['class_no'] = ''
for course in result['calendar']:
name = course['crs_cname']
sn = course['course_sn']
day = days[course['day']]
slot = list(course['slot'])
assert isinstance(name, str)
assert isinstance(sn, str)
assert slot == sorted(slot, key=lambda x: slots.index(x))
if name in courses:
assert sn == courses[name]['sn']
else:
courses[name] = Course()
courses[name]['sn'] = sn
courses[name]['time'].append((day, slot))
courses[name]['class_no'] = ''
for ceiba_course in result['grid']:
class_no = ceiba_course['class_no']
sn = ceiba_course['course_sn']
name = ceiba_course['crs_cname']
semester = ceiba_course['semester']
assert semester == self._semester
if class_no == 0 and sn == 0 and name == 'Calendar':
continue
assert isinstance(class_no, str)
if name in courses:
assert sn == courses[name]['sn']
else:
courses[name] = Course()
courses[name]['sn'] = sn
courses[name]['class_no'] = class_no
for name, course in courses.items():
self.add(name, CourseDirectory(self.vfs, self, self._semester,
name, course['sn'], course['time'], course['class_no']))
for name, course in courses.items():
if course['sn'] != '':
self.add(course['sn'], InternalLink(self.vfs, self, name))
self.ready = True
class CourseDirectory(Directory):
def __init__(self, vfs, parent, semester, name, sn, time, class_no):
super().__init__(vfs, parent)
self._semester = semester
self._name = name
self._sn = sn
self._time = time
self._class_no = class_no
def fetch(self):
# 填入課程基本資料
s = self.vfs.strings
metadata = JSONFile(self.vfs, self)
self.add(s['file_course_metadata'], metadata)
metadata.add(s['attr_course_metadata_name'], self._name, 'crs_cname')
metadata.add(s['attr_course_metadata_class_no'], self._class_no, 'class_no')
if len(self._sn) > 0:
metadata.add(s['attr_course_metadata_sn'], self._sn, 'course_sn')
if len(self._time) > 0:
metadata.add(s['attr_course_metadata_time'], self._time, ['day', 'slot'])
# 沒有 CEIBA 代號的現在可以離開了
if len(self._sn) == 0:
metadata.finish()
self.ready = True
return
# CEIBA 規定要先呼叫過 semester 才能用 course
self.vfs.request.api({'mode': 'semester', 'semester': self._semester})
# 一定要傳 class_no 才能拿到完整的課程內容
result = self.vfs.request.api(
{'mode': 'course',
'semester': self._semester,
'course_sn': self._sn,
'class_no': self._class_no})
result_keys = [
'lang', 'course_info', 'teacher_info', 'contents', 'content_files']
optional_keys = [
'bulletin', 'board', 'course_grade', 'homeworks']
assert set(result.keys()) - set(optional_keys) == set(result_keys)
# lang
if result['lang'] == 'big5':
lang = s['value_course_metadata_lang_big5']
elif result['lang'] == 'eng':
lang = s['value_course_metadata_lang_eng']
else:
assert False, '無法識別的課程語言 {}'.format(result['lang'])
metadata.add(s['attr_course_metadata_lang'], lang, 'lang')
# course_info
for day in range(1, 7):
day_attr = 'day{}'.format(day)
if day_attr in result['course_info']:
del result['course_info'][day_attr]
course_info_keys = [ 'course_req', 'dpt_cou', 'mark', 'place' ]
assert set(result['course_info'].keys()) == set(course_info_keys)
metadata.add(s['attr_course_metadata_code'], result['course_info']['dpt_cou'], 'dpt_cou')
metadata.add(s['attr_course_metadata_place'], result['course_info']['place'], 'place')
if len(result['course_info']['mark']) > 0:
metadata.add(s['attr_course_metadata_mark'], result['course_info']['mark'], 'mark')
if len(result['course_info']['course_req']) > 0:
evaluation = list()
for req in result['course_info']['course_req']:
req_keys = ['item', 'percent', 'notes']
assert set(req.keys()) == set(req_keys)
req_data = OrderedDictWithLineBreak()
req_data[s['attr_course_metadata_evaluation_item']] = req['item']
req_data[s['attr_course_metadata_evaluation_percent']] = req['percent']
req_data[s['attr_course_metadata_evaluation_notes']] = req['notes']
evaluation.append(req_data)
metadata.add(s['attr_course_metadata_evaluation'], evaluation, 'course_req')
metadata.finish()
# bulletin
if 'bulletin' in result:
self.add(s['dir_course_bulletin'], CourseBulletinDirectory(
self.vfs, self, self._sn, result['bulletin']))
# contents + content_files
self.add(s['dir_course_contents'], CourseContentsDirectory(
self.vfs, self, self._sn, result['contents'], result['content_files']))
# board
if 'board' in result:
assert result['board'] == '1'
self.add(s['dir_course_boards'], CourseBoardsDirectory(
self.vfs, self, self._semester, self._sn))
# homeworks
if 'homeworks' in result:
self.add(s['dir_course_homeworks'], CourseHomeworksDirectory(
self.vfs, self, self._sn, result['homeworks']))
# course_grade
if 'course_grade' in result:
self.add(s['dir_course_grades'], CourseGradesDirectory(
self.vfs, self, self._sn, result['course_grade']))
# 資源分享
if ceiba_function_enabled(self.vfs.request, self._sn,
'share', '/modules/share/share.php'):
self.add(s['dir_course_share'], CourseShareDirectory(
self.vfs, self, self._sn))
# 投票區
if ceiba_function_enabled(self.vfs.request, self._sn,
'vote', '/modules/vote/vote.php'):
self.add(s['dir_course_vote'], CourseVoteDirectory(
self.vfs, self, self._sn))
self.ready = True
class WebCourseDirectory(Directory):
def __init__(self, vfs, parent, semester, sn):
super().__init__(vfs, parent)
self._semester = semester
self._sn = sn
def fetch(self):
s = self.vfs.strings
frame_path = '/modules/index.php'
frame_args = {'csn': self._sn, 'default_fun': 'info'}
info_path = '/modules/info/info.php'
self.vfs.request.web(frame_path, args=frame_args)
info_page = self.vfs.request.web(info_path)
info_basic_rows = info_page.xpath('//div[@id="sect_cont"]/table[1]/tr')
metadata = JSONFile(self.vfs, self)
# name
info_basic_name = row_get_value(info_basic_rows[0],
['課程名稱', 'Course Name'], {}, free_form=True)
metadata.add(s['attr_course_metadata_name'], info_basic_name, info_path)
self._name = info_basic_name
info_basic_semester = row_get_value(info_basic_rows[1],
['開課學期', 'Semester'], {}, free_form=True)
if info_basic_semester != self._semester:
self.vfs.logger.warning(
'手動加入的課程 {} ({})開課學期是 {},卻被放在 {} 資料夾' \
.format(self._sn, self._name, info_basic_semester, self._semester))
# class_no
info_basic_class_no = row_get_value(info_basic_rows[4],
['班次', 'Class'], {}, free_form=True)
metadata.add(s['attr_course_metadata_class_no'],
info_basic_class_no, info_path)
# sn
metadata.add(s['attr_course_metadata_sn'], self._sn, '設定檔')
# time
info_basic_time = row_get_value(info_basic_rows[5],
['上課時間', 'Time'], {}, free_form=True)
metadata.add(s['attr_course_metadata_time'], info_basic_time, info_path)
# code
info_basic_code = row_get_value(info_basic_rows[3],
['課號', 'Course No.'], {}, free_form=True)
metadata.add(s['attr_course_metadata_code'], info_basic_code, info_path)
# place
info_basic_place = row_get_value(info_basic_rows[6],
['上課地點', 'Classroom'], {}, free_form=True)
metadata.add(s['attr_course_metadata_place'], info_basic_place, info_path)
metadata.finish()
self.add(s['file_course_metadata'], metadata)
# homeworks
if ceiba_function_enabled(self.vfs.request, self._sn,
'hw', '/modules/hw/hw.php'):
self.add(s['dir_course_homeworks'], CourseHomeworksDirectory(
self.vfs, self, self._sn, [], api=False))
# course_grade
if ceiba_function_enabled(self.vfs.request, self._sn,
'grade', '/modules/grade/grade.php'):
self.add(s['dir_course_grades'], CourseGradesDirectory(
self.vfs, self, self._sn, []))
# 資源分享
if ceiba_function_enabled(self.vfs.request, self._sn,
'share', '/modules/share/share.php'):
self.add(s['dir_course_share'], CourseShareDirectory(
self.vfs, self, self._sn))
# 投票區
if ceiba_function_enabled(self.vfs.request, self._sn,
'vote', '/modules/vote/vote.php'):
self.add(s['dir_course_vote'], CourseVoteDirectory(
self.vfs, self, self._sn))
self.ready = True
@property
def name(self):
return self._name
class CourseBulletinDirectory(Directory):
def __init__(self, vfs, parent, course_sn, bulletin):
super().__init__(vfs, parent)
self._course_sn = course_sn
self._bulletin = bulletin
def fetch(self):
s = self.vfs.strings
anno_keys = ['sn', 'subject', 'post_time', 'b_link', 'attach', 'content']
attachments_directory_created = False
for anno in self._bulletin:
assert set(anno.keys()) == set(anno_keys)
anno_node = JSONFile(self.vfs, self)
anno_node.add(s['attr_course_bulletin_sn'], anno['sn'], 'sn')
anno_node.add(s['attr_course_bulletin_subject'], anno['subject'], 'subject')
anno_node.add(s['attr_course_bulletin_date'], anno['post_time'], 'post_time')
anno_node.add(s['attr_course_bulletin_url'], anno['b_link'], 'b_link')
anno_node.add(s['attr_course_bulletin_attachment'], anno['attach'], 'attach')
anno_node.add(s['attr_course_bulletin_content'], anno['content'], 'content')
anno_node.finish()
anno_filename = format_filename(anno['sn'], anno['subject'], 'json')
self.add(anno_filename, anno_node)
if len(anno['attach']) > 0:
if not attachments_directory_created:
att_dir = Directory(self.vfs, self)
attachments_directory_created = True
att_dir.add(anno['attach'], DownloadFile(
self.vfs, att_dir, '/course/{}/bulletin/{}'.format(
self._course_sn, anno['attach'])),
ignore_duplicate=True)
if attachments_directory_created:
att_dir.ready = True
self.add(s['dir_course_bulletin_attachments'], att_dir)
self.ready = True
class CourseContentsDirectory(Directory):
def __init__(self, vfs, parent, course_sn, contents, content_files):
super().__init__(vfs, parent)
self._course_sn = course_sn
self._contents = contents
self._content_files = content_files
def fetch(self):
s = self.vfs.strings
content_keys = ['syl_sn', 'unit', 'notes', 'subject']
content_file_keys = ['syl_sn', 'file_name']
all_contents = OrderedDict()
for content in self._contents:
if isinstance(content, list):
assert len(content) == 4
assert len(self._contents) == 1
break
assert set(content.keys()) == set(content_keys)
content_node = JSONFile(self.vfs, self)
content_node.add(s['attr_course_contents_sn'], content['syl_sn'], 'syl_sn')
content_node.add(s['attr_course_contents_week'], content['unit'], 'unit')
content_node.add(s['attr_course_contents_date'], content['notes'], 'notes')
content_node.add(s['attr_course_contents_subject'], content['subject'], 'subject')
content_node.add(s['attr_course_contents_files'], list(), 'file_name')
all_contents[content['syl_sn']] = content_node
for content_file in self._content_files:
assert set(content_file.keys()) == set(content_file_keys)
all_contents[content_file['syl_sn']].append(
s['attr_course_contents_files'], content_file['file_name'])
for sn, content_node in all_contents.items():
content_filename = format_filename(sn,
content_node.get(s['attr_course_contents_week']), 'json')
content_node.finish()
self.add(content_filename, content_node)
if len(self._content_files) > 0:
files_dir = Directory(self.vfs, self)
for content_file in self._content_files:
files_dir.add(content_file['file_name'], DownloadFile(
self.vfs, files_dir, '/course/{}/content/{}'.format(
self._course_sn, content_file['file_name'])),
ignore_duplicate=True)
files_dir.ready = True
self.add(s['dir_course_contents_files'], files_dir)
self.ready = True
class CourseBoardsDirectory(Directory):
def __init__(self, vfs, parent, semester, course_sn):
super().__init__(vfs, parent)
self._semester = semester
self._course_sn = course_sn
def fetch(self):
# CEIBA 規定要先呼叫過 semester 才能用 read_board
self.vfs.request.api({'mode': 'semester', 'semester': self._semester})
result = self.vfs.request.api(
{'mode': 'read_board',
'semester': self._semester,
'course_sn': self._course_sn,
'board': '0'})
board_keys = ['sn', 'caption']
for board in result:
assert set(board.keys()) == set(board_keys)
posts_dir = CourseBoardsThreadDirectory(self.vfs, self,
self._semester, self._course_sn, board)
posts_dirname = format_dirname(board['sn'], board['caption'])
self.add(posts_dirname, posts_dir)
self.ready = True
class CourseBoardsThreadDirectory(Directory):
def __init__(self, vfs, parent, semester, course_sn, board):
super().__init__(vfs, parent)
self._semester = semester
self._course_sn = course_sn
self._board = board
def fetch(self):
from html import escape
s = self.vfs.strings
board_metadata = JSONFile(self.vfs, self)
board_metadata.add(s['attr_course_boards_metadata_sn'],
self._board['sn'], 'sn')
board_metadata.add(s['attr_course_boards_metadata_caption'],
self._board['caption'], 'caption')
board_metadata.finish()
self.add(s['file_course_boards_metadata'], board_metadata)
# CEIBA 規定要先呼叫過 semester 才能用 read_board_post
self.vfs.request.api({'mode': 'semester', 'semester': self._semester})
result = self.vfs.request.api(
{'mode': 'read_board_post',
'semester': self._semester,
'course_sn': self._course_sn,
'board': self._board['sn']})
post_keys = ['sn', 'parent', 'subject', 'post_time', 'attach', 'file_path',
'content', 'author', 'cauthor', 'count_rep', 'latest_rep']
threads = OrderedDict()
thread_subjects = dict()
for post in result:
assert set(post.keys()) == set(post_keys)
if post['parent'] == '0':
assert post['sn'] not in thread_subjects
if post['sn'] in threads:
threads[post['sn']].append(post)
else:
threads[post['sn']] = [ post ]
thread_subjects[post['sn']] = post['subject']
else:
if post['parent'] in threads:
threads[post['parent']].append(post)
else:
threads[post['parent']] = [ post ]
for sn, thread in threads.items():
thread_dir = Directory(self.vfs, self)
thread_attachments = list()
for post in thread:
post_node = JSONFile(self.vfs, thread_dir)
post_node.add(s['attr_course_boards_thread_sn'], post['sn'], 'sn')
if post['parent'] != '0':
post_node.add(s['attr_course_boards_thread_parent'],
post['parent'], 'parent')
post_node.add(s['attr_course_boards_thread_subject'],
post['subject'], 'subject')
post_node.add(s['attr_course_boards_thread_post_time'],
post['post_time'], 'post_time')
if post['attach'] != '' or post['file_path'] != '':
assert post['attach'] != ''
extension = post['attach'].rsplit('.', maxsplit=1)[1]
post_node.add(s['attr_course_boards_thread_attach'],
post['attach'], 'attach')
if post['file_path'] != '':
assert post['file_path'] == post['sn'] + '.' + extension
thread_attachments.append(
(post['sn'], post['attach'], post['file_path']))
post_node.add(s['attr_course_boards_thread_author'],
post['author'], 'author')
post_node.add(s['attr_course_boards_thread_cauthor'],
post['cauthor'], 'cauthor')
post_node.add(s['attr_course_boards_thread_count_rep'],
post['count_rep'], 'count_rep')
post_node.add(s['attr_course_boards_thread_latest_rep'],
post['latest_rep'], 'latest_rep')
post_node.finish()
content = '\n'.join([
'<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"',
' "http://www.w3.org/TR/html4/loose.dtd">',
'<html>',
' <head>',
' <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">',
' <title>{}</title>'.format(escape(post['subject'])),
' </head>',
' <body>',
' <p>',
' {}'.format(post['content']),
' </p>',
' </body>',
'</html>' ]) + '\n'
post_content = StringFile(self.vfs, thread_dir, content)
post_node_filename = format_filename(
post['sn'], post['subject'], 'json')
post_content_filename = format_filename(
post['sn'], post['subject'], 'html')
thread_dir.add(post_node_filename, post_node)
thread_dir.add(post_content_filename, post_content)
if len(thread_attachments):
files_dir = Directory(self.vfs, thread_dir)
for attachment in thread_attachments:
attachment_filename = format_dirname(
attachment[0], attachment[1])
attachment_path = '/course/{}/board/{}'.format(
self._course_sn, attachment[2])
files_dir.add(attachment_filename, DownloadFile(
self.vfs, files_dir, attachment_path))
files_dir.ready = True
thread_dir.add(s['dir_course_boards_thread_files'], files_dir)
thread_dir.ready = True
thread_dirname = format_dirname(sn, thread_subjects[sn])
self.add(thread_dirname, thread_dir)
self.ready = True
class CourseHomeworksDirectory(Directory):
def __init__(self, vfs, parent, course_sn, homeworks, api=True):
super().__init__(vfs, parent)
self._course_sn = course_sn
self._homeworks = homeworks
self._api = api
def fetch(self):
if self._api:
for homework in self._homeworks:
self.add(format_dirname(homework['sn'], homework['name']),
CourseHomeworksHomeworkDirectory(self.vfs, self,
self._course_sn, homework, homework['sn']))
else:
frame_path = '/modules/index.php'
frame_args = {'csn': self._course_sn, 'default_fun': 'hw'}
hw_list_path = '/modules/hw/hw.php'
self.vfs.request.web(frame_path, args=frame_args)
hw_list_page = self.vfs.request.web(hw_list_path)
assert len(hw_list_page.xpath('//table')) > 0
hw_list_rows_all = hw_list_page.xpath('//div[@id="sect_cont"]/table/tr')
hw_list_rows = hw_list_rows_all[1:]
hw_header_row = hw_list_rows_all[0]
assert hw_header_row[0].text in ['名稱', 'Title']
for row in hw_list_rows:
assert row[0].tag == 'td'
assert len(row[0]) == 1
assert row[0][0].tag == 'a'
assert row[0][0].get('href')
args = url_to_path_and_args(row[0][0].get('href'))[1]
sn = args['hw_sn']
if len(row[0][0]) >= 1:
assert len(row[0][0]) == 1
assert row[0][0][0].tag == 'font'
name = element_get_text(row[0][0][0])
else:
name = element_get_text(row[0][0])
self.add(format_dirname(sn, name),
CourseHomeworksHomeworkDirectory(self.vfs, self,
self._course_sn, {}, sn))
self.ready = True
class CourseHomeworksHomeworkDirectory(Directory):
def __init__(self, vfs, parent, course_sn, hw, hw_sn):
super().__init__(vfs, parent)
self._course_sn = course_sn
self._hw = hw
self._hw_sn = hw_sn
if self._hw:
assert self._hw['sn'] == self._hw_sn
def fetch(self):
import ast
s = self.vfs.strings
hw_keys = ['sn', 'name', 'description', 'file_path', 'url',
'pub_date', 'pub_hour', 'end_date', 'end_hour', 'is_subm', 'hw_scores']
hw_score_keys = ['course_sn', 'hw_sn', 'hand_time', 'file_path',
'sw', 'ranking_grade', 'score', 'evaluation']
# 課程主頁面
frame_path = '/modules/index.php'
frame_args = {'csn': self._course_sn, 'default_fun': 'hw'}
# 作業列表
hw_list_path = '/modules/hw/hw.php'
# 作業內容
hw_show_path = '/modules/hw/hw_show.php'
hw_show_args = {'hw_sn': self._hw_sn}
# 作業評語
hw_eval_path = '/modules/hw/hw_eval.php'
hw_eval_args = {'hw_sn': self._hw_sn, 'all': '1'}
# 作業觀摩
hw_view_path = '/modules/hw/hw_view.php'
hw_view_args = {'hw_sn': self._hw_sn, 'all': '1'}
# 按照順序爬網頁
self.vfs.request.web(frame_path, args=frame_args)
self.vfs.request.web(hw_list_path)
hw_show_page = self.vfs.request.web(hw_show_path, args=hw_show_args)
hw_eval_page = self.vfs.request.web(hw_eval_path, args=hw_eval_args)
hw_view_page = self.vfs.request.web(hw_view_path, args=hw_view_args)
def make_date_hour(date, hour):
assert len(date) == 10
assert date[0:4].isnumeric()
assert date[5:7].isnumeric()
assert date[8:10].isnumeric()
assert date[4] == '-' and date[7] == '-'
assert len(hour) == 2
assert hour.isnumeric()
return date + ' ' + hour
def use_unicode_private_areas(s):
for c in s:
if ord(c) >= 0xe000 and ord(c) <= 0xf8ff:
return True
return False
hw_show_rows = hw_show_page.xpath('//div[@id="sect_cont"]/table/tr')
assert len(hw_show_rows) >= 9
# 0
hw_show_name = row_get_value(hw_show_rows[0],
['名稱', 'Title'], {}, free_form=True)
# 1
hw_show_description_element = row_get_value(hw_show_rows[1],
['作業說明', 'Description'], {}, free_form=True, return_object=True)
assert list(map(lambda x: x.tag, hw_show_description_element)) == \
['br'] * len(hw_show_description_element)
hw_show_description = ''.join(hw_show_description_element.itertext()) \
.rstrip('\xa0')
hw_show_description_cannot_be_decoded_with_default_encoding = \
use_unicode_private_areas(hw_show_description)
if hw_show_description_cannot_be_decoded_with_default_encoding:
self.vfs.logger.warning(
'作業 {} 的說明文字中有 Unicode 私人使用區的字元' \
.format(hw_show_name))
self.vfs.logger.warning(
'這很可能是因為預設編碼無法解讀日文所造成的錯誤')
self.vfs.logger.warning(
'準備使用 big5-hkscs 編碼重新讀取網頁')
hw_show_page = self.vfs.request.web(
hw_show_path, args=hw_show_args, encoding='big5-hkscs')
hw_show_rows = hw_show_page.xpath(
'//div[@id="sect_cont"]/table/tr')
hw_show_description_element = row_get_value(hw_show_rows[1],
['作業說明', 'Description'], {},
free_form=True, return_object=True)
hw_show_description = ''.join(
hw_show_description_element.itertext()).rstrip('\xa0')
assert not use_unicode_private_areas(hw_show_description)
# 2
hw_show_download_file_path_element = row_get_value(hw_show_rows[2],
['相關檔案', 'Related File'], {}, free_form=True, return_object=True)
if len(hw_show_download_file_path_element) > 0:
assert len(hw_show_download_file_path_element) == 2
assert hw_show_download_file_path_element[0].tag == 'a'
assert hw_show_download_file_path_element[0].text in ['檔案', 'File']
assert hw_show_download_file_path_element[0].get('href')
assert hw_show_download_file_path_element[1].tag == 'br'
hw_show_download_file_path_full = url_to_path_and_args(
hw_show_download_file_path_element[0].get('href'))[0]
hw_show_download_file_dir, hw_show_download_file_path = \
hw_show_download_file_path_full.rsplit('/', maxsplit=1)
assert hw_show_download_file_dir == '/course/{}/hw' \
.format(self._course_sn)
else:
assert hw_show_download_file_path_element.text.isspace()
hw_show_download_file_path = ''
# 3
hw_show_url_element = row_get_value(hw_show_rows[3],
['相關網址', 'Related URL'], {}, free_form=True, return_object=True)
if len(hw_show_url_element) > 0:
assert len(hw_show_url_element) == 2
assert hw_show_url_element[0].tag == 'a'
assert hw_show_url_element[0].get('href')
assert hw_show_url_element[1].tag == 'br'
hw_show_url = hw_show_url_element[0].get('href')
assert hw_show_url == hw_show_url_element[0].text
else:
assert hw_show_url_element.text.isspace()
hw_show_url = ''
# 4
hw_show_type = row_get_value(hw_show_rows[4], ['成員', 'Type'],
{('個人', 'individual'):
s['value_course_homeworks_homework_type_individual'],
('小組', 'group'):
s['value_course_homeworks_homework_type_group']})
# 5
hw_show_method = row_get_value(hw_show_rows[5],
['繳交方法', 'Submission Method'],
{('線上繳交', 'submit online'):
s['value_course_homeworks_homework_method_online'],
('紙本繳交', 'printed copy'):
s['value_course_homeworks_homework_method_printed']},
free_form=True)
# 6
hw_show_percentage = row_get_value(hw_show_rows[6],
['成績比重', 'Submission Method'], {}, free_form=True)
# 7
hw_show_end = row_get_value(hw_show_rows[7],
['繳交期限', 'Due Date'],
{('無限期', 'Indefinite Duration'):
s['value_course_homeworks_homework_end_2030_12_31_24']},
free_form=True)
# 8
hw_show_is_subm = row_get_value(hw_show_rows[8],
['逾期繳交', 'Accept late submission after the due date'],
{('可以', 'Yes'):
s['attr_course_homeworks_homework_is_subm_yes'],