-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdata.py
365 lines (313 loc) · 13.4 KB
/
data.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
#!/usr/bin/env python3
# coding=utf-8
import itertools
import uuid
from datetime import datetime, time, timedelta
import icalendar as ic
from loguru import logger
from powerschool import PowerSchool
from utils import *
class Location:
name: str
latitude: float | str
longitude: float | str
def __init__(self, name="", latitude=0, longitute=0) -> None:
self.name = name
self.latitude = latitude
self.longitude = longitute
def __str__(self) -> str:
if self.name == "" and self.latitude == 0 and self.longitude == 0:
return f"Empty Location Instance <{id(self)}>"
else:
return f"[{self.name}]: ({self.latitude}, {self.longitude})"
class Holiday:
name: str
type: str
start: datetime
end: datetime
compensations: list[list[datetime, int]]
def __init__(
self,
name: str,
type: str,
date: list[datetime | int] | list[int | str],
compensations: list[list[datetime, int]] | None,
) -> None:
self.name = name
self.type = type.lower()
self.compensations = compensations if compensations else []
if self.type == "fixed":
if not 0 < len(date) <= 2: # (0,2]
raise ValueError(f"Invalid date list length: {len(date)}, should be 1 or 2")
# TODO: work around to see if there is a solution to resolve the error without exit the program
elif len(date) == 1:
date.append(date[0])
elif self.type == "relative":
raise NotImplementedError("Relative holiday not implemented yet")
ordinal = date[0][:1]
weekNum = date[0][1:]
else:
raise ValueError(
f"Invalid holiday type: {self.name}: type={repr(self.type)}. Holiday should either be 'fixed' or 'relative'."
)
# if the holiday is a single-day holiday
# The start and end time of this holiday would be the same day
self.start, self.end = date[0], date[1]
def __str__(self) -> str:
return f"Holiday - {self.name}:\n Type: {self.type}\n Compensation: {self.compensations}"
class Term:
name: str
uuid: str
start: datetime
end: datetime
duration: int
timetable: list[list[int, int]]
cycle: int
courses: list["Course"]
holidays: list["Holiday"]
def __init__(
self,
name: str,
start: datetime,
end: datetime,
duration: int,
timetable: list[list[int]],
cycle: int,
) -> None:
self.name = name
self.start, self.end = start, end
self.duration = duration
self.timetable = timetable
if cycle <= 0 or not isinstance(cycle, int):
raise ValueError(
f'Invalid global cycle number "{cycle}" for "{self.name}", global cycle number should be positive integer'
)
else:
self.cycle = cycle
self.courses = []
self.holidays = []
self.uuid = str(uuid.uuid4())
def addCourse(self, course: "Course") -> None:
course.setCycle(self.cycle) # set the cycle number of the course instance
self.courses.append(course) # add course instance into the term instance
def addHoliday(self, holiday: Holiday) -> None:
self.holidays.append(holiday)
def isHoliday(self, date: datetime) -> bool:
for holiday in self.holidays:
if holiday.start <= date <= holiday.end:
return True
return False
def __str__(self) -> str:
return f"Term - {self.uuid}:\n Name: {self.name}\n Start: {self.start}\n End: {self.end}\n Class Duration: {self.duration} minutes\n Timetable: {self.timetable}\n Cycle: {self.cycle}"
class Course:
name: str
teacher: str
location: Location
index: list[list[any]]
cycle: int
def __init__(
self,
name: str,
teacher: str,
location: Location,
index: list[list[any]],
cycle: int | None,
) -> None:
self.name = name
self.teacher = teacher
self.location = location
self.index = index
self.cycle = cycle
def setCycle(self, cycle: int) -> None:
if self.cycle == None: # If exceptional cycle is not set
self.cycle = cycle # Apply global setting
else: # If exceptional cycle is set
if self.cycle <= 0:
logger.error(
f'Invalid cycle number "{cycle}" in {self.name}, It should be positive integer. Program will try to use the global cycle setting.'
)
self.cycle = cycle # Rollback to global setting
def getCycleDay(self) -> int:
return self.cycle * 5
def getDecodedIndex(self, term: Term) -> list[list[int]]:
if isinstance(self.index[0], list):
logger.debug("Using traditional index decoder")
return self.__traditionalDecoder(term)
else:
logger.debug("Using ps index decoder")
return PowerSchool.ps2list(self.index, self.getCycleDay())
def __traditionalDecoder(self, term: Term) -> list[list[int]]:
logger.warning("Traditional format is deprecated, it will be removed in future releases")
def decode_component(component: list | str | int, maximum: int):
"""
Decode a component of a schedule.
Parameters:
- component: The component to be decoded, can be an integer, a string, or a list.
- maximum: The maximum value that the component can represent.
Returns:
- Returns a list of decoded numbers corresponding to the input component.
"""
# Define a dictionary for different types of abbreviations, mapping to the corresponding number list
abbrDict = {
"odd": [i for i in range(1, maximum + 1, 2)], # List of odd days
"even": [i for i in range(2, maximum + 1, 2)], # List of even days
"everyday": [i for i in range(1, maximum + 1)], # List of all days
}
# If the component is an integer, check if it is within the valid range
if isinstance(component, int):
if component > self.getCycleDay() or component < 1:
raise ValueError(
f'Invalid schedule file, Error processing "{term.name}.{self.name}.time", {component} is out of range'
)
return [component]
# If the component is a string abbreviation, convert it to the corresponding number list
elif isinstance(component, str):
return abbrDict[component.lower()]
# If the component is a list, process each item in the list
elif isinstance(component, list):
tmp = []
for item in component:
if isinstance(item, int):
tmp.append(item)
elif isinstance(item, str):
tmp.extend(abbrDict[item.lower()])
else:
raise ValueError(
f"Invalid schedule file, Error processing {term.name}.{self.name}.time, {item} can not be indentified"
)
return tmp
# If the component is of an unsupported type, output an error message and exit
else:
raise ValueError(
f"Invalid schedule file, Error processing {term.name}.{self.name}.time, {component} can not be indentified"
)
product: list = []
for timestamp in self.index: # 求decodeTimestamp笛卡尔积
product.extend(
[
list(t)
for t in itertools.product(
[x for x in decode_component(timestamp[0], self.cycle * 5)],
[x - 1 for x in decode_component(timestamp[1], len(term.timetable))],
)
]
)
return product
def eventify(self, term: Term, date: datetime, block: int, reminderSetting: dict) -> ic.Event:
event: ic.Event = ic.Event()
event.add("summary", self.name)
event.add(
"description", f"{self.teacher}\n{self.location.name}"
) # TODO: work around to provide better support for Location and AppleMapLocation
event.add(
"dtstart",
datetime.combine(
date,
time(
term.timetable[block][0],
term.timetable[block][1],
),
),
)
event.add(
"dtend",
datetime.combine(
date,
time(
term.timetable[block][0],
term.timetable[block][1],
),
)
+ timedelta(minutes=term.duration),
)
event.add("dtstamp", datetime.now())
event.add("uid", uuid.uuid4())
if reminderSetting["enabled"] == True:
reminder: ic.Alarm = ic.Alarm()
reminder.add("ACTION", "DISPLAY")
reminder.add("DESCRIPTION", "提醒事项")
reminder.add(
"TRIGGER",
timedelta(
hours=-reminderSetting["before"][0],
minutes=-reminderSetting["before"][1],
),
)
event.add_component(reminder)
return event
@timer
def generateICS(term: Term, config: dict) -> bytes:
ics: ic.Calendar = ic.Calendar()
ics.add("VERSION", "2.0")
ics.add("PRODID", "iScheduler by @Jinyuan")
ics.add("CALSCALE", "GREGORIAN")
ics.add("X-APPLE-CALENDAR-COLOR", parseHexColor(config["color"]))
ics.add("X-WR-CALNAME", f"{config['name']} - {term.name}")
ics.add("X-WR-TIMEZONE", "Asia/Shanghai") # TODO: add time zone support
def isRruleAvailable() -> bool:
if term.holidays:
return True
else:
if config.get("reduceFileSize") == False:
return False
# If there are holidays, the rrule strategy is not gonna work effectively though
if isRruleAvailable():
if config.get("reduceFileSize") == True:
logger.warning(
"Reduce file size mode DOES NOT support holiday and countDayInHoliday functions, attempt to process in normal mode instead..."
)
logger.debug("Using Date Range Strategy")
for course in term.courses: # iterate through all courses
cnt: int = 0 # day counter
timetable: list[list[int]] = course.getDecodedIndex(term)
for date in dateRange(term.start, term.end): # iterate through the term
if date.weekday() < 5: # if the day is a workday
if cnt >= course.getCycleDay(): # if the day counter overflow, reset the counter
cnt = 0
if not term.isHoliday(date): # if the day is both a workday and non-holiday
for timestamp in timetable:
if timestamp[0] - 1 == cnt:
event: ic.Event = course.eventify(term, date, timestamp[1], config["alarm"])
ics.add_component(event)
cnt += 1
else: # workday but holiday
if config.get("countDayInHoliday") == True:
cnt += 1
for holiday in term.holidays:
for compensation in holiday.compensations:
for timestamp in timetable:
if timestamp[0] == compensation[1]:
event = course.eventify(term, compensation[0], timestamp[1], config["alarm"])
ics.add_component(event)
# Else, use rrule strategy to reduce the file size and increase the performance
else:
logger.warning("Tips - Reduce file size mode is enabled, some features may not supported")
logger.debug("Using RRule Strategy")
if term.start.weekday() < 5:
# 如果用户输入的起始日期是工作日,则rrule从 该周 周一起算
initDay: datetime = term.start - timedelta(days=term.start.weekday())
else:
# 如果用户输入的起始日期是双休日,则rrule从 下周 周一起算
initDay: datetime = term.start + timedelta(days=(7 - term.start.weekday()))
for course in term.courses:
timetable = course.getDecodedIndex(term)
for timestamp in timetable:
weekInfo: list[int] = getWeekInfo(timestamp[0])
event: ic.Event = course.eventify(
term,
initDay + timedelta(weeks=weekInfo[1], days=weekInfo[0] - 1),
timestamp[1],
config["alarm"],
)
rrule = ic.vRecur(
freq="weekly",
interval=course.cycle,
byday=day2str(weekInfo[0]),
until=term.end,
) # TODO: work around, try to merge some rrule which are in the same week
logger.debug(f"Adding {course.name} with rrule:{rrule}")
event.add("RRULE", rrule)
ics.add_component(event)
return ics.to_ical()
if __name__ == "__main__":
logger.warning("This module cannot run independently")