-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtimetable.py
executable file
·1090 lines (840 loc) · 35.4 KB
/
timetable.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
# -*- coding: iso-8859-1 -*-
# Skapat av Christian Davén 2004
import calendar
import error
from i18n import *
# -----------------------------------------------------------
class CourseList:
"Lista med kurser"
def __init__(self):
self.courses = []
def clear(self):
self.courses = []
def clearDaisyCourses(self):
for course in self.getAllDaisyCourseIDs():
self.removeCourse(course)
def clearTimeEditCourses(self):
for course in self.getAllTimeEditCourseIDs():
self.removeCourse(course)
def isEmpty(self):
return self.courses == []
def addCourse(self, idorcourse, name = "", id = "", group = ""):
"""
Lägger till en kurs eller skriver över befintlig om samma id
Det kan alltså finnas flera kurser med samma kod,
men inte med samma kurs/moment-id.
"""
if isinstance(idorcourse, Course):
if self.hasCourse(idorcourse):
self.courses.remove(idorcourse)
self.courses.append(idorcourse)
else:
if self.hasCourse(idorcourse):
self.courses.remove(self.getCourse(idorcourse))
self.courses.append(Course(idorcourse, name, id, group))
def removeCourse(self, id):
"Tar bort en kurs ur listan"
self.courses.remove(self.getCourse(id))
def hasCourse(self, course):
for c in self.courses:
if c == course: return True
return False
def getCourse(self, id):
"Returnerar en kurs definierad av id (kurskod eller Daisy-id)"
for course in self.courses:
if course == id: return course
raise ValueError("The course " + str(id) + " does not exist")
def getCourseByCode(self, code):
"Returnerar en kurs definierad av kurskod"
for course in self.courses:
if course.hasCode(code): return course
raise ValueError("The course " + str(id) + " does not exist")
def getCourseName(self, code):
"Returnerar namnet (ev. användardefinierat) på en kurs"
return self.getCourse(code).name
def setCourseName(self, code, name):
self.getCourse(code).name = name
def getCourseGroup(self, code):
"Returnerar vald grupp för aktuell kurs"
return self.getCourse(code).group
def setCourseGroup(self, code, group):
self.getCourse(code).group = group
def getCourseID(self, code):
"Returnerar kurs-id på en kurs"
return self.getCourse(code).id
def setCourseID(self, code, id):
self.getCourse(code).id = id
def getAllDaisyCourses(self):
courses = []
map(courses.append, map(self.getCourse, self.getAllDaisyCourseIDs()))
return courses
def getAllTimeEditCourses(self):
courses = []
map(courses.append, map(self.getCourse, self.getAllTimeEditCourseIDs()))
return courses
def getAllDaisyCourseIDs(self):
ids = []
for course in self.courses:
if course.isDaisy(): ids.append(course.id)
return ids
def getAllTimeEditCourseIDs(self):
ids = []
for course in self.courses:
if course.isTimeEdit(): ids.append(course.id)
return ids
def getAllPersistent(self):
courses = []
courses += self.getAllTimeEditCourses()
courses += self.getAllDaisyCourses()
return courses
def getAllMatchingName(self, name):
courses = []
name = name.lower()
for course in self.courses:
if name in course.name.lower():
courses.append(course)
return courses
def getAllMatchingCode(self, code):
courses = []
code = code.upper()
for course in self.courses:
if code in course.code:
courses.append(course)
return courses
def pickle(self):
import StringIO
import pickle
string = StringIO.StringIO()
pickle.dump(self.getAllPersistent(), string)
return string.getvalue()
def unpickle(self, data):
import StringIO
import pickle
string = StringIO.StringIO(data)
self.courses = pickle.load(string)
# -----------------------------------------------------------
class CachedCourseList(CourseList):
"Lista med kurser som hämtats från ITU:s webbplats"
filename = "daisycourses"
def __init__(self):
CourseList.__init__(self)
self.readFromFile()
def readFromFile(self):
import os.path
import time
try:
self.unpickle(file(self.filename).read())
if self.isOldList(calendar.Date(time.localtime(os.path.getctime(self.filename)))):
self.courses = []
else:
# omvandlar gamla heltalsgrupper till strängar
# bör tas bort till version 2.4
courses = []
for course in self.courses:
if isinstance(course.group, int):
course.group = str(course.group)
if course.group == "0": course.group = ""
courses.append(course)
self.courses = courses
except (IOError, EOFError):
self.courses = []
def isEmpty(self):
return self.courses == []
def isOldList(self, date):
diff = calendar.Date() - date
monthtoday = calendar.Date().getMonth()
monththen = date.getMonth()
if (monthtoday > 9 and monththen < 10) or diff > 90:
return True
elif (monthtoday > 2 and monththen < 3) or diff > 90:
return True
return False
def save(self):
file(self.filename, "w+").write(self.pickle())
def setCourses(self, courselist):
self.courses = courselist
# -----------------------------------------------------------
class TimeTable:
"Ett schema (dvs en samling schemalagda händelser)"
def __init__(self):
self.eventlist = EventList(self)
self.courselist = CourseList()
self.groups = {}
self.updated = None
def clear(self):
self.eventlist.clear()
self.courselist.clear()
self.updated = None
def importVCalendarData(self, input, courses = []):
"Importerar händelser från vCalendar-data"
import vcalendar
events = vcalendar.Reader().read(input)
if events:
# tar också bort de händelser som inte längre
# finns på servern, mha EventCleaner.
cleaner = EventCleaner()
cleaner.reset()
course = None
if len(courses) == 1:
course = courses[0]
self.eventlist.addEvents(events, course)
cleaner.sweep(self, courses)
self.updated = calendar.Date()
def getAllChosenEvents(self):
events = []
for event in self.eventlist.getAll():
if event.isGroupChosen():
events.append(event)
return events
def getAllGroups(self, course):
"Returnerar alla möjliga grupper för en viss kurs"
groups = []
events = self.getAllEventsForCourse(course)
for event in events:
if event.group and event.group not in groups:
groups.append(event.group)
return groups
def getEventsForDate(self, date):
events = []
for event in self.eventlist.getAll():
if event.date == date and event.isGroupChosen():
events.append(event)
return events
def getEventsForDateRange(self, fromdate, todate):
date = calendar.Date(fromdate)
events = []
while date <= todate:
events.extend(self.getEventsForDate(date))
date += 1
return events
def removeOrphanEvents(self):
"Tar bort alla händelser vars kurs inte längre finns i kurslistan"
remove = []
for event in self.eventlist.getAll():
if not self.hasCourse(event.course):
self.removeEvent(event.getID())
def addSubscriptionGroup(self, name, members):
if not isinstance(name, unicode):
name = unicode(name, "latin_1")
if isinstance(members, str):
members = members.split("|")
self.groups[name] = subscription.Group(name, members)
def getAllSubscriptionGroupNames(self):
names = self.groups.keys()
names.sort()
return names
def getSubscriptionGroup(self, name):
return self.groups[name]
def removeSubscriptionGroup(self, name):
try:
del self.groups[name]
except KeyError:
pass
def load(self, filename = ""):
"Läser in schemat från en INI-liknande fil"
import configfileparser
import settings
import os.path
self.clear()
if not filename:
filename = settings.timetablefile
if not os.path.exists(filename):
return # ger inget felmeddelande
config = configfileparser.ConfigParserX()
try:
config.readfp(file(filename))
except IOError:
raise error.ReadError("Could not read from " + str(filename))
# läser först in inställningarna och kurserna ...
for section in config.sections():
if section == "main":
self.updated = calendar.Date(config.get(section, "updated"))
elif section == "courses":
pairs = config.items(section)
for pair in pairs:
code = pair[0]
data = pair[1].split("|")
self.addCourse(code, name=data[0], id=data[1], group=data[2])
elif section == "groups":
pairs = config.items(section)
for pair in pairs:
name = pair[0]
members = pair[1].split("|")
self.addSubscriptionGroup(name, members)
# ... och därefter alla händelser som beror på de inlästa kurserna
for section in config.sections():
if section != "main" and section != "courses" and section != "settings" and section != "groups":
event = Event(self)
event.setID(section)
event.location = config.get(section, "location")
event.date = calendar.Date(config.get(section, "date"))
event.begin = calendar.Time(config.get(section, "begin"))
event.end = calendar.Time(config.get(section, "end"))
event.course = self.getCourseByCode(config.get(section, "course"))
event.type = config.get(section, "type")
event.group = config.getstrorempty(section, "group")
event.seriesno = config.getintorzero(section, "seriesno")
event.active = config.getboolean(section, "active")
self.addEvent(event)
def save(self, filename = ""):
"Sparar schemat till en INI-liknande fil"
import configfileparser
if not filename:
import settings
filename = settings.timetablefile
config = configfileparser.ConfigParserX()
if not self.isEmpty():
config.add_section("main")
config.set("main", "updated", str(self.updated))
for event in self.eventlist.getAllPersistent():
config.add_section(event.getID())
config.set(event.getID(), "date", str(event.date))
config.set(event.getID(), "begin", str(event.begin))
config.set(event.getID(), "end", str(event.end))
config.set(event.getID(), "location", event.location)
config.set(event.getID(), "course", event.course.code)
config.set(event.getID(), "type", event.type)
if event.group: config.set(event.getID(), "group", event.group)
if event.seriesno: config.set(event.getID(), "seriesno", event.seriesno)
if not event.active: config.set(event.getID(), "active", "false")
if self.hasCourses():
config.add_section("courses")
for course in self.getAllPersistentCourses():
value = course.name + "|" + str(course.id) + "|" + course.group
config.set("courses", course.code, value)
if self.groups:
config.add_section("groups")
for name in self.getAllSubscriptionGroupNames():
config.set("groups", name, str(self.getSubscriptionGroup(name)))
try:
config.write(file(filename, "w+"))
except IOError:
raise error.WriteError("Could not write to " + str(filename))
# -- delegeringar till EventList
def isEmpty(self):
return self.eventlist.isEmpty()
def addEvent(self, event):
self.eventlist.addEvent(event)
def getAllEvents(self):
return self.eventlist.getAll()
def getAllDaisyEvents(self):
return self.eventlist.getAllDaisyEvents()
def getAllTimeEditEvents(self):
return self.eventlist.getAllTimeEditEvents()
def getEvent(self, id):
return self.eventlist.getEvent(id)
def getAllEventsForCourse(self, course):
return self.eventlist.getAllEventsForCourse(course)
def removeCourseEvents(self, course):
self.eventlist.removeCourseEvents(course)
def removeEvent(self, id):
self.eventlist.removeEvent(id)
# -- delegeringar till CourseList
def hasCourses(self):
return not self.courselist.isEmpty()
def clearCourses(self):
self.courselist.clear()
def clearDaisyCourses(self):
self.courselist.clearDaisyCourses()
def clearTimeEditCourses(self):
self.courselist.clearTimeEditCourses()
def addCourse(self, codeorcourse, name = "", id = 0, group = ""):
self.courselist.addCourse(codeorcourse, name, id, group)
def removeCourse(self, code):
self.courselist.removeCourse(code)
def hasCourse(self, course):
return self.courselist.hasCourse(course)
def getCourse(self, code):
return self.courselist.getCourse(code)
def getCourseByCode(self, code):
return self.courselist.getCourseByCode(code)
def getCourseName(self, code):
return self.courselist.getCourseName(code)
def setCourseName(self, code, name):
self.courselist.setCourseName(code, name)
def getCourseGroup(self, code):
return self.courselist.getCourseGroup(code)
def setCourseGroup(self, code, group):
self.courselist.setCourseGroup(code, group)
def getCourseID(self, code):
return self.courselist.getCourseID(code)
def setCourseID(self, code, id):
self.courselist.setCourseID(code, id)
def getAllDaisyCourses(self):
return self.courselist.getAllDaisyCourses()
def getAllTimeEditCourses(self):
return self.courselist.getAllTimeEditCourses()
def getAllDaisyCourseIDs(self):
return self.courselist.getAllDaisyCourseIDs()
def getAllTimeEditCourseIDs(self):
return self.courselist.getAllTimeEditCourseIDs()
def getAllPersistentCourses(self):
return self.courselist.getAllPersistent()
def getAllCoursesMatchingName(self, name):
return self.courselist.getAllMatchingName(name)
def pickleCourses(self):
return self.courselist.pickle()
def unpickleCourses(self, data):
self.courselist.unpickle(data)
# -----------------------------------------------------------
class Course:
"En kurs"
def __init__(self, code, name, id = "", group = "", term = ""):
if not isinstance(code, unicode):
code = unicode(code, "latin_1")
if not isinstance(name, unicode):
name = unicode(name, "latin_1")
self.code = code # kurskod
self.name = name # kursnamn eller beteckning
self.id = id # Daisys kurs-id eller TimeEdits kurskod
if not id:
self.id = code
self.term = term # starttermin för kursen (endast Daisy)
group = str(group)
if group == "0": group = ""
self.group = group
def __eq__(self, other):
"Jämför kurskod för TimeEdit-kurser (=id) eller Daisy-id"
if isinstance(other, Course):
other = other.id
return self.id == other
def hasCode(self, code):
return self.code == code
def __ne__(self, other):
return not self == other
def __str__(self):
return unicode(self).encode("latin_1")
def __unicode__(self):
if self.name: return self.name
else: return self.code
def __repr__(self):
return self.code + self.name + str(self.id) + self.group
def isDaisy(self):
return not self.isTimeEdit()
def isTimeEdit(self):
val = False
if self.code == self.id: val = True
return val
def getTerm(self):
"Returnerar terminen för kursen, ex. 'VT05'"
if self.term == "": return "?"
term = "HT"
if self.term[-1] == "1": term = "VT"
return term + self.term[2:4]
# -----------------------------------------------------------
class Event:
"En schemalagd händelse"
cachedcourselist = CachedCourseList() # behövs för att kolla upp Daisy-kurser
def __init__(self, timetable, data = None):
"""
Tar emot strängrepresentationer för de fält som Daisy anger
och gör om till bättre lämpade typer samt tolkar
beskrivningsdatat till grupp, kurskod och händelsetyp.
"""
self.__id = "" # händelsens id, privat variabel då tolkningen beror på den
self.date = None # datum för händelse
self.begin = None # tid då händelse börjar
self.end = None # tid då händelse slutar
self.location = None # plats för händelsen
self.course = None # händelsens kurs
self.type = "" # händelsens typ (ex. föreläsning, lektion, laboration, seminarium etc)
self.group = "" # händelsens gruppnummer (vissa lektioner etc är indelade i grupper)
self.seriesno = 0 # händelsetypens löpnummer (ex. (föreläsning) 7, (lektion) 3)
self.parser = None
self.active = True # händelsen är aktiv, dvs. ej "borttagen"
self.flag = None # används för att se om en händelse inte har uppdaterats
# vid synkronisering, dvs. om den egentligen är borttagen
self.timetable = timetable
if not data:
# om data är None sätts inte instansens värden här
return
else:
self.copyFromDict(data)
def __repr__(self):
"Returnerar en exakt beskrivning av aktuell händelse"
return str(self.__id) + str(self.date) + str(self.begin) + str(self.end) +\
str(self.location) + unicode(self.course) + str(self.type) + self.group + str(self.seriesno)
def __str__(self):
return unicode(self).encode("latin_1")
def __unicode__(self):
"Returnerar en beskrivning av aktuell händelse, ex. 'Kursnamn Ö7 grp 3 (401)'"
description = self.getDescriptionWithoutLocation()
if self.location: description += " (" + self._manipulateLocation(self.location) + ")"
return description
def __eq__(self, other):
if self.getID() == other.getID() and\
self.date == other.date and\
self.begin == other.begin and\
self.end == other.end and\
self.location == other.location and\
self.type == other.type and\
self.group == other.group and\
self.seriesno == other.seriesno and\
self.course == other.course: return True
else:
return False
def __ne__(self, other):
return False == self.__eq__(other)
def copyDetails(self, other):
"Kopierar tid, plats och datum från annan aktivitet"
self.begin = other.begin
self.end = other.end
self.location = other.location
self.date = other.date
def getNiceString(self):
string = "[" + self.begin.getNiceString() + "-" + self.end.getNiceString() + "] " + unicode(self)
if not self.active:
string = U_("inactivated")
return string
def setID(self, id):
self.__id = id
if id.endswith("timeedit.evolvera.se"):
# även tidsstämpel för när schemat genererades inkluderas
# i TimeEdits "id"
try:
self.__id = id.split("-")[1]
except IndexError:
pass
def getID(self):
return self.__id
def setParser(self, id):
self.parser = None
if id.startswith("DAISYKTH"):
import daisy
self.parser = daisy.SummaryParser()
elif id.endswith("timeedit.evolvera.se"):
import timeedit
self.parser = timeedit.SummaryParser()
def _parseSummary(self, summary):
data = self.parser.parse(summary)
self.type = data["type"]
self.group = data["group"]
self.seriesno = data["seriesno"]
if not self.location:
# om inte copyFromDict redan satt lokalen,
# som den gör för Daisy-aktiviteter
self.location = data["location"]
try:
if not self.course:
# om inte copyFromDict redan satt kursen,
# som den gör om kursen anges explicit
self.course = self.timetable.getCourseByCode(data["course"])
except ValueError:
"Testar alternativa sätt att hitta rätt kurs för aktivitet"
if self.__id.startswith("DAISYKTH"):
course = self._findDaisyCourse(data["course"])
if course: self.course = course
else: raise
elif self.__id.endswith("timeedit.evolvera.se"):
course = self._findTimeEditCourse(data["course"])
if course: self.course = course
else: raise
def _findDaisyCourse(self, name):
"""
Hittar en Daisy-kurs via dess ursprungliga namn;
om flera kurser har samma namn hämtas den (om någon)
som redan finns i kurslistan.
"""
if self.cachedcourselist.isEmpty():
self.cachedcourselist.readFromFile()
for course in self.cachedcourselist.getAllMatchingName(name):
if self.timetable.hasCourse(course):
return self.timetable.getCourseByCode(course.code)
return None
def _findTimeEditCourse(self, codes):
"Hittar en TimeEdit-kurs genom att prova alla i en lista"
for code in codes.split(","):
if self.timetable.hasCourse(code):
return self.timetable.getCourseByCode(code)
return None
def copyFromDict(self, other):
keys = other.keys()
if "id" in keys:
self.setID(other["id"])
self.setParser(other["id"])
if "course" in keys: self.course = other["course"]
if "date" in keys: self.date = calendar.Date(other["date"])
if "begin" in keys: self.begin = calendar.Time(other["begin"])
if "end" in keys: self.end = calendar.Time(other["end"])
if "type" in keys: self.type = other["type"]
if "group" in keys: self.group = other["group"]
if "seriesno" in keys: self.seriesno = other["seriesno"]
if "active" in keys: self.active = other["active"]
if "location" in keys: self.location = other["location"]
if "summary" in keys and self.parser: self._parseSummary(other["summary"])
def _manipulateLocation(self, location):
"""
Tar bort Daisy-prefixen Hörsal och Övningssal för
kurser på Valhallavägen samt möjliggör översättning
av språkspecifika ord som Sal, Aulan etc.
"""
location = location.replace(u"Övningssal ", "")
location = location.replace(u"Hörsal ", "")
location = location.replace(u"Sal", U_("Room"))
location = location.replace(u"Aulan", U_("Great Hall"))
return location
def getDescriptionWithoutLocation(self):
description = ""
if self.course:
description = self.course.name + " "
if self.type == u"Föreläsning": description += U_("Lect")
elif self.type == u"Övning": description += U_("Tut")
elif self.type == u"Lektion": description += U_("Lesson")
elif self.type == u"Seminarium": description += U_("Sem")
elif self.type == u"Laboration": description += U_("Lab")
elif self.type == u"Kontrollskrivning": description += U_("Quiz")
elif self.type == u"Salsskrivning": description += U_("Exam")
elif self.type == u"Tentamen": description += U_("Exam")
elif self.type == u"Workshop": description += U_("WS")
elif self.type == u"Introduktion": description += U_("Intro")
elif self.type == u"Information": description += U_("Info")
elif self.type == "": description += "???"
else: description += self.type
if self.seriesno: description += str(self.seriesno)
if self.group: description += " " + U_("grp") + " " + self.group
return description
def isGroupChosen(self):
"""
Om händelsens grupp är tom är den inte gruppindelad och ska visas.
Om vald grupp är tom ska alla grupper visas.
Om vald grupp är lika med händelsens grupp ska den visas.
"""
val = False
if not self.group or not self.course.group or self.group == self.course.group:
val = True
return val
def toggleActive(self):
if self.active: self.active = False
else: self.active = True
# -----------------------------------------------------------
class EventList:
def __init__(self, timetable, list = None):
self.events = {}
self.timetable = timetable
if list:
self.addEvents(list)
def clear(self):
self.events = {}
def isEmpty(self):
return self.events == {}
def getAll(self):
return self.events.values()
def getAllPersistent(self):
"""
Returnerar alla aktiviteter som hör till det
aktuella schemat; dvs. som inte är "prenumererade"
"""
events = []
for event in self.getAll():
if not isinstance(event, subscription.SubscribedEvent):
events.append(event)
return events
def getAllDaisyEvents(self):
events = []
for event in self.events:
if event.course.isDaisy(): events.append(event)
return events
def getAllTimeEditEvents(self):
events = []
for event in self.events:
if event.course.isTimeEdit(): events.append(event)
return events
def getAllEventsForCourse(self, course):
"Returnerar alla händelser för en viss kurs, utan hänsyn till gruppval"
events = []
coursefound = False
for event in self.getAll():
if event.course == course:
coursefound = True
events.append(event)
if not coursefound:
raise ValueError("The course " + str(course) + " does not exist")
return events
def removeCourseEvents(self, course):
"Tar bort alla händelser för en viss kurs"
try:
remove = self.getAllEventsForCourse(course)
for event in remove:
self.removeEvent(event.getID())
except ValueError:
return # redan borttaget
def hasEvent(self, id):
return id in self.events.keys()
def _add(self, event):
"""
Lägger till en aktivitet. ID är en unik nyckel i listan.
Nya aktiviteter med ID som redan existerar skriver
_inte_ över existerande aktiviteter.
"""
if self.hasEvent(event.getID()):
# kopierar tid, plats och datum från ny aktivitet
# till existerande
self.getEvent(event.getID()).copyDetails(event)
else:
# aktiviteten är ny, lägg bara till
self.events[event.getID()] = event
return self.getEvent(event.getID())
def addEvent(self, event, course = None):
if not isinstance(event, Event):
try:
if course:
# en kurs är angiven explicit, ex. i webb-gränssnittet
# eller för "prenumererade" händelser från webben
event["course"] = course
event = Event(self.timetable, event)
except ValueError, e:
# när en händelse skapas som inte hör till någon
# känd kurs avbryts inte all inläsning utan just
# den händelsen ignoreras
import sys
sys.stderr.write("\n" + str(e) + "\n")
return
EventCleaner().mark(self._add(event))
def addEvents(self, list, course = None):
for event in list:
self.addEvent(event, course)
def removeEvent(self, id):
try:
del self.events[id]
except KeyError:
raise ValueError("The event " + str(id) + " does not exist")
def getEvent(self, id):
try:
return self.events[id]
except KeyError:
raise ValueError("The event " + str(id) + " does not exist")
# -----------------------------------------------------------
class EventCleaner:
"""
Rensar borttagna händelser enligt Mark-Sweep-algoritmen.
Varje uppdaterad händelse som hämtats från schemaservern
markeras. De som sedan inte markerats tas bort.
"""
__shared_state = {}
okflag = False
def __init__(self):
self.__dict__ = self.__shared_state
def reset(self):
self.okflag = not self.okflag
def mark(self, event):
event.flag = self.okflag
def sweep(self, timetable, courses = []):
"Tar endast bort angivna kurshändelser"
events = timetable.getAllEvents()
if courses:
events = []
for course in courses:
events.extend(timetable.getAllEventsForCourse(course))
for event in events:
if not isinstance(event, subscription.SubscribedEvent)\
and not event.flag == self.okflag:
timetable.removeEvent(event.getID())
# -----------------------------------------------------------
class VCalendarExporter:
def __init__(self, encoding = "latin_1"):
self.encoding = encoding
def export(self, filename, timetable, fromdate, todate):
"Exporterar data till fil"
events = timetable.getEventsForDateRange(fromdate, todate)
activeevents = []
for event in events:
if event.active: activeevents.append(event)
self.write(activeevents, filename)
def write(self, events, filename):
import vcalendar
data = vcalendar.Writer(self.encoding).write(events)
try:
file(filename, "w+").writelines(data)
except IOError:
raise error.WriteError("Could not write to " + str(filename))
# -----------------------------------------------------------
class HTMLExporter:
def generate(self, timetable, fromdate, todate):
self.timetable = timetable
self.html = """<!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.1//EN'
'http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd'>
<html xmlns='http://www.w3.org/1999/xhtml'><head>
<title>""" + U_("TimeTable") + """</title>
<meta name='generator' content='KTH TimeTable' />
<link rel='stylesheet' type='text/css' href='timetable-html.css' />
</head><body><h1>""" + U_("TimeTable") + "</h1>"
date = fromdate.getLastMonday()
while date <= todate:
self.formatWeek(date)
date += 7
self.html += "</body></html>"
return self.html.encode("latin_1")
def export(self, filename, timetable, fromdate, todate):