-
Notifications
You must be signed in to change notification settings - Fork 2
/
calendargenerator.py
764 lines (622 loc) · 24.4 KB
/
calendargenerator.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
#!/usr/bin/env python3
# -.- encoding: utf-8 -.-
import re
import datetime
import time
from dateutil import rrule
import icalendar as ical
import pytz
import calendar
import locale
import hashlib
import string
import os
import json
import sys
import urllib.parse
TIMEZONE = 'Europe/Berlin'
DEFAULT_DURATION = 3 # 3h
MAX_NEXT_UP_REPEATED = 3
MAX_NEXT_UP_REPEATED_DAYS = 4 * 7
MAX_NEXT_UP_DAYS = 31 * 3
MAX_IN_BEFORE_REPEATED = 1
MAX_IN_BEFORE_DAYS = 31
T_CATEGORY = "category"
T_EVENT = "date"
T_INVALID_EVENT = "invalid date"
T_ROW_DIVIDER = "row divider"
T_REST = "rest"
LANG_DE = "de_DE.UTF-8"
LANG_EN = "en_US.UTF-8"
LANG_FR = "fr_CA.UTF-8"
tz = pytz.timezone('Europe/Berlin')
entry = re.compile(r"^\|\s*(.*?)\s*\|\|\s*(.*?)\s*\|\|\s*(.*?)\s*$")
single_date = re.compile(r"^(\d+)\.(\d+)\.(\d+)$")
single_date_time = re.compile(r"^(\d+)\.(\d+)\.(\d+)\s+(\d+)[:\.](\d+)$")
single_date_time_range = re.compile(r"^(\d+)\.(\d+)\.(\d+)\s+(\d+)[:\.](\d+)\s*\-\s*(\d+)[:\.](\d+)$")
date_range = re.compile(r"^(\d+)\.(\d+)\.(\d+)\s*\-\s*(\d+)\.(\d+)\.(\d+)$")
date_range_time = re.compile(r"^(\d+)\.(\d+)\.(\d+)\s+(\d+)[:\.](\d+)\s*\-\s*(\d+)\.(\d+)\.(\d+)\s+(\d+)[:\.](\d+)$")
weekday_time = re.compile(r"^([a-zA-Z0-9/]+),?\s*(\d+)[:\.](\d+)$")
weekday_time_range = re.compile(r"^([a-zA-Z0-9/]+),?\s*(\d+)[:\.](\d+)\s*\-\s*(\d+)[:\.](\d+)$")
mediawiki_intern_link = re.compile(r"(\[\[([^|\]]+)\|?(.*?)\]\])")
mediawiki_extern_link = re.compile(r"(\[([^\ ]+)\s+(.*?)\])")
mediawiki_bold = re.compile(r"'''(.*?)'''")
mediawiki_emph = re.compile(r"''(.*?)''")
category_re = re.compile(r"^==([^=]+)==$")
divider_re = re.compile(r"^\|-$")
dow_regex = re.compile(r"^(\w+)(|/(\d+))$")
dow_index = {
"mo": 0,
"mon": 0,
"di": 1,
"tue": 1,
"mi": 2,
"wed": 2,
"do": 3,
"thu": 3,
"fr": 4,
"fri": 4,
"sa": 5,
"sat": 5,
"so": 6,
"sun": 6}
dow_list = ["Mo", "Di", "Mi", "Do", "Fr", "Sa", "So"]
def simple_name(name):
name = name.lower()
ok = string.digits + string.ascii_lowercase
new_name = []
for char in name:
if char in ok:
new_name.append(char)
return "".join(new_name)
def day_of_week_str(day_of_week, lang=LANG_EN):
locale.setlocale(locale.LC_ALL, lang)
return calendar.day_abbr[day_of_week].title()
def short_lang(lang):
return lang.split("_")[0]
def to_in_lang(lang):
slang = short_lang(lang)
if slang == "en":
return "to"
elif slang == "de":
return "bis"
elif slang == "fr":
return u"à"
return "--"
def make_extern(intern_url):
intern_url = intern_url.replace(" ", "_")
return "https://stratum0.org/wiki/%s" % urllib.parse.quote(intern_url)
def date2datetime(date):
return tz.localize(datetime.datetime(date.year, date.month, date.day, 0, 0))
class InvalidDateEntryException(Exception):
pass
class DatePrinter(object):
def __init__(self, name, category, start_date, end_date):
self.name = name
self.rule = None
self.start_date = start_date
self.end_date = end_date
self.category = category
if self.end_date <= self.start_date:
raise InvalidDateEntryException
def getIcal(self):
event = ical.Event()
event.add('uid', hashlib.md5(self.name.encode("utf8") + str(self.start_date).encode("utf8")).hexdigest() + "@stratum0.org")
event.add('summary', self.getPlainName().encode("utf8"))
url = self.getURL()
if url:
event.add('url', url.encode("utf8"))
event.add('dtstart', self.start_date)
event.add('dtend', self.end_date)
return event
def getJson(self):
result = {}
result["id"] = hashlib.md5(self.getPlainName().encode("utf8")).hexdigest()
result["title"] = self.getDetailPlain()
result["url"] = self.getURL()
result["class"] = "event-%s" % simple_name(self.category)
result["start"] = int(time.mktime(self.start_date.timetuple()) * 1000)
result["end"] = int(time.mktime(self.end_date.timetuple()) * 1000) - 1
return result
def getMediawikiRow(self):
return ("| %s || %s ||" % (self.getMediawikiName(), self.getDateString()))
def getDateString(self):
raise Exception("not implemented")
def getDateRangeString(self):
raise Exception("not implemented")
def getMediawikiEntry(self, lang=LANG_DE):
raise Exception("not implemented")
def getDetailPlain(self, lang=LANG_DE):
raise Exception("not implemented")
def getMediawikiName(self):
return self.name
def getPlainName(self):
def fix_intern(match):
_, url, name = match.groups()
if name:
return name
return url
name = mediawiki_intern_link.sub(fix_intern, self.name)
name = mediawiki_extern_link.sub(r"\3", name)
name = mediawiki_bold.sub(r"\1", name)
name = mediawiki_emph.sub(r"\1", name)
return name
def getURL(self):
urls_intern = mediawiki_intern_link.findall(self.name)
urls_extern = mediawiki_extern_link.findall(self.name)
extern_url = None
intern_url = None
if urls_extern:
extern_url = urls_extern[0]
if urls_intern:
intern_url = urls_intern[0]
if extern_url and intern_url:
if self.name.index(extern_url[0]) < self.name.index(intern_url[0]):
intern_url = None
else:
extern_url = None
if intern_url:
if intern_url[1]:
return make_extern(intern_url[1])
return make_extern(intern_url[2])
if extern_url:
return extern_url[1]
return None
def start_datetime(self):
if type(self.start_date) is datetime.date:
return date2datetime(self.start_date)
return self.start_date
def end_datetime(self):
if type(self.end_date) is datetime.date:
return date2datetime(self.end_date)
return self.end_date
def __lt__(self, other):
if isinstance(other, datetime.datetime):
return self.start_datetime() < other
if self.start_datetime() >= other.start_datetime() and self.end_datetime() < other.end_datetime():
return True
if self.start_datetime() == other.start_datetime():
if self.end_datetime() == other.end_datetime():
return self.name < other.name
return self.end_datetime() < other.end_datetime()
return self.start_datetime() < other.start_datetime()
def __le__(self, other):
if isinstance(other, datetime.datetime):
return self.start_datetime() <= other
return self < other or self == other
def __eq__(self, other):
return self.start_datetime() == other.start_datetime() and self.end_datetime() == other.end_datetime() and self.name == other.name
def __gt__(self, other):
if isinstance(other, datetime.datetime):
return self.end_datetime() > other
if self.start_datetime() <= other.start_datetime() and self.end_datetime() > other.end_datetime():
return True
if self.start_datetime() == other.start_datetime():
if self.end_datetime() == other.end_datetime():
return self.name > other.name
return self.end_datetime() > other.end_datetime()
return self.start_datetime() > other.start_datetime()
def __ge__(self, other):
if isinstance(other, datetime.datetime):
return self.end_datetime() >= other
return self > other or self == other
class SingleDate(DatePrinter):
def __init__(self, name, category, values):
day, month, year = map(int, values)
date = datetime.date(year, month, day)
date_end = date + datetime.timedelta(days=1)
DatePrinter.__init__(self, name, category, date, date_end)
def getDetailPlain(self, lang=LANG_DE):
dow = day_of_week_str(self.start_date.weekday(), lang)
return "%s, %02d.%02d.: %s" % (dow, self.start_date.day, self.start_date.month, self.getPlainName())
def getMediawikiEntry(self, lang=LANG_DE):
dow = day_of_week_str(self.start_date.weekday(), lang)
return "* %s, %02d.%02d.: %s" % (dow, self.start_date.day, self.start_date.month, self.getMediawikiName())
def getDateString(self):
return "%02d.%02d.%02d" % (self.start_date.day, self.start_date.month, self.start_date.year)
class SingleDateTime(DatePrinter):
def __init__(self, name, category, values):
day, month, year, hour, minute = map(int, values)
date = tz.localize(datetime.datetime(year, month, day, hour, minute))
date_end = date + datetime.timedelta(hours=DEFAULT_DURATION)
DatePrinter.__init__(self, name, category, date, date_end)
def getDetailPlain(self, lang=LANG_DE):
dow = day_of_week_str(self.start_date.weekday(), lang)
return "%s, %02d.%02d. %02d:%02d: %s" % (dow, self.start_date.day, self.start_date.month, self.start_date.hour, self.start_date.minute, self.getPlainName())
def getMediawikiEntry(self, lang=LANG_DE):
dow = day_of_week_str(self.start_date.weekday(), lang)
return "* %s, %02d.%02d. %02d:%02d: %s" % (dow, self.start_date.day, self.start_date.month, self.start_date.hour, self.start_date.minute, self.getMediawikiName())
def getDateString(self):
return "%02d.%02d.%02d %02d:%02d" % (self.start_date.day, self.start_date.month, self.start_date.year, self.start_date.hour, self.start_date.minute)
class SingleDateTimeRange(DatePrinter):
def __init__(self, name, category, values):
day, month, year, hour, minute, hour2, minute2 = map(int, values)
date = tz.localize(datetime.datetime(year, month, day, hour, minute))
date_end = tz.localize(datetime.datetime(year, month, day, hour2, minute2))
if date_end < date:
date_end += datetime.timedelta(days=1)
DatePrinter.__init__(self, name, category, date, date_end)
def getDetailPlain(self, lang=LANG_DE):
dow = day_of_week_str(self.start_date.weekday(), lang)
return "%s, %02d.%02d. %02d:%02d - %02d:%02d: %s" % (dow, self.start_date.day, self.start_date.month, self.start_date.hour, self.start_date.minute, self.end_date.hour, self.end_date.minute, self.getPlainName())
def getMediawikiEntry(self, lang=LANG_DE):
dow = day_of_week_str(self.start_date.weekday(), lang)
return "* %s, %02d.%02d. %02d:%02d - %02d:%02d: %s" % (dow, self.start_date.day, self.start_date.month, self.start_date.hour, self.start_date.minute, self.end_date.hour, self.end_date.minute, self.getMediawikiName())
def getDateString(self):
return "%02d.%02d.%02d %02d:%02d - %02d:%02d" % (self.start_date.day, self.start_date.month, self.start_date.year, self.start_date.hour, self.start_date.minute, self.end_date.hour, self.end_date.minute)
class DateRange(DatePrinter):
def __init__(self, name, category, values):
day, month, year, day2, month2, year2 = map(int, values)
date = datetime.date(year, month, day)
date_end = datetime.date(year2, month2, day2) + datetime.timedelta(days=1)
self.end_date2 = datetime.date(year2, month2, day2)
DatePrinter.__init__(self, name, category, date, date_end)
def getDetailPlain(self, lang=LANG_DE):
dow = day_of_week_str(self.start_date.weekday(), lang)
dow2 = day_of_week_str(self.end_date2.weekday(), lang)
to = to_in_lang(lang)
return "%s, %02d.%02d. %s %s, %02d.%02d.: %s" % (dow, self.start_date.day, self.start_date.month, to, dow2, self.end_date2.day, self.end_date2.month, self.getPlainName())
def getMediawikiEntry(self, lang=LANG_DE):
dow = day_of_week_str(self.start_date.weekday(), lang)
dow2 = day_of_week_str(self.end_date2.weekday(), lang)
to = to_in_lang(lang)
return "* %s, %02d.%02d. %s %s, %02d.%02d.: %s" % (dow, self.start_date.day, self.start_date.month, to, dow2, self.end_date2.day, self.end_date2.month, self.getMediawikiName())
def getDateString(self):
return "%02d.%02d.%02d - %02d.%02d.%02d" % (self.start_date.day, self.start_date.month, self.start_date.year, self.end_date2.day, self.end_date2.month, self.end_date2.year)
class DateTimeRange(DatePrinter):
def __init__(self, name, category, values):
day, month, year, hour, minute, day2, month2, year2, hour2, minute2 = map(int, values)
date = tz.localize(datetime.datetime(year, month, day, hour, minute))
date_end = tz.localize(datetime.datetime(year2, month2, day2, hour2, minute2))
DatePrinter.__init__(self, name, category, date, date_end)
def getDetailPlain(self, lang=LANG_DE):
dow = day_of_week_str(self.start_date.weekday(), lang)
dow2 = day_of_week_str(self.end_date.weekday(), lang)
to = to_in_lang(lang)
return "%s, %02d.%02d. %02d:%02d %s %s, %02d.%02d. %02d:%02d: %s" % (dow, self.start_date.day, self.start_date.month, self.start_date.hour, self.start_date.minute, to, dow2, self.end_date.day, self.end_date.month, self.end_date.hour, self.end_date.minute, self.getPlainName())
def getMediawikiEntry(self, lang=LANG_DE):
dow = day_of_week_str(self.start_date.weekday(), lang)
dow2 = day_of_week_str(self.end_date.weekday(), lang)
to = to_in_lang(lang)
return "* %s, %02d.%02d. %02d:%02d %s %s, %02d.%02d. %02d:%02d: %s" % (dow, self.start_date.day, self.start_date.month, self.start_date.hour, self.start_date.minute, to, dow2, self.end_date.day, self.end_date.month, self.end_date.hour, self.end_date.minute, self.getMediawikiName())
def getDateString(self):
return "%02d.%02d.%02d %02d:%02d - %02d.%02d.%02d %02d:%02d" % (self.start_date.day, self.start_date.month, self.start_date.year, self.start_date.hour, self.start_date.minute, self.end_date.day, self.end_date.month, self.end_date.year, self.end_date.hour, self.end_date.minute)
class Generator:
def __init__(self):
self.entries = []
def getIcal(self):
if not self.entries:
return None
first = self.entries[0]
event = first.getIcal()
interval = first.rule._interval
until = first.rule._until
event.add('rrule', {'FREQ': ['WEEKLY'], 'INTERVAL': [interval], 'UNTIL': [until]})
return event
def getMediawikiRow(self):
first = self.entries[0]
return ("| %s || %s || %s" % (first.getMediawikiName(), self.getDateString(), self.getDateRangeString())).strip()
def getDateString(self):
first = self.entries[0]
interval = first.rule._interval
if interval > 1:
interval = "/%d" % interval
else:
interval = ""
return "%s%s, %s" % (dow_list[first.start_date.weekday()], interval, first.getDateString())
def getDateRangeString(self):
first = self.entries[0]
start = first.start_date
end = first.rule._until
return "%02d.%02d.%04d - %02d.%02d.%04d" % (start.day, start.month, start.year, end.day, end.month, end.year)
def __lt__(self, other):
return self.entries[-1] < other
def start_datetime(self):
return self.entries[0].start_datetime()
def end_datetime(self):
return self.entries[-1].end_datetime()
class WeekdayTimeRangeGenerator(Generator):
def __init__(self, name, category, values, rep):
Generator.__init__(self)
self.category = category
nonetime = False
self.entries = []
rep = date_range.match(rep)
if not rep:
return
kind, hour, minute, hour2, minute2 = values
if hour:
hour = int(hour)
if minute:
minute = int(minute)
if hour2:
hour2 = int(hour2)
else:
hour2 = (hour + DEFAULT_DURATION) % 24
nonetime = True
if minute2:
minute2 = int(minute2)
else:
minute2 = minute
dow = dow_regex.match(kind)
if not dow:
return
wd, _, interval = dow.groups()
if interval:
interval = int(interval)
else:
interval = 1
if wd.lower() not in dow_index:
return
wd = dow_index[wd.lower()]
day, month, year, day2, month2, year2 = map(int, rep.groups())
start = tz.localize(datetime.datetime(year, month, day, hour, minute))
start2 = tz.localize(datetime.datetime(year, month, day, hour2, minute2))
if start2 < start:
start2 += datetime.timedelta(days=1)
delta = start2 - start
stop = tz.localize(datetime.datetime(year2, month2, day2, 23, 59))
rule = rrule.rrule(rrule.WEEKLY, interval=interval, byweekday=wd, dtstart=start, until=stop)
for event in rule:
event_end = event + delta
if nonetime:
self.entries.append(RepSingleDateTime(name, category, (event.day, event.month, event.year, event.hour, event.minute), rule))
else:
if event_end.day != event.day:
self.entries.append(RepDateTimeRange(name, category, (event.day, event.month, event.year, event.hour, event.minute, event_end.day, event_end.month, event_end.year, event_end.hour, event_end.minute), rule))
else:
self.entries.append(RepSingleDateTimeRange(name, category, (event.day, event.month, event.year, event.hour, event.minute, event_end.hour, event_end.minute), rule))
class RepSingleDateTime(SingleDateTime):
def __init__(self, name, category, values, rule):
SingleDateTime.__init__(self, name, category, values)
self.rule = rule
def getDateString(self):
return "%02d:%02d" % (self.start_date.hour, self.start_date.minute)
class RepSingleDateTimeRange(SingleDateTimeRange):
def __init__(self, name, category, values, rule):
SingleDateTimeRange.__init__(self, name, category, values)
self.rule = rule
def getDateString(self):
return "%02d:%02d - %02d:%02d" % (self.start_date.hour, self.start_date.minute, self.end_date.hour, self.end_date.minute)
class RepDateTimeRange(DateTimeRange):
def __init__(self, name, category, values, rule):
DateTimeRange.__init__(self, name, category, values)
self.rule = rule
class WeekdayTimeGenerator(WeekdayTimeRangeGenerator):
def __init__(self, name, category, values, rep):
values = values + (None, None)
WeekdayTimeRangeGenerator.__init__(self, name, category, values, rep)
tests = [(single_date, SingleDate),
(single_date_time, SingleDateTime),
(single_date_time_range, SingleDateTimeRange),
(date_range, DateRange),
(date_range_time, DateTimeRange),
(weekday_time, WeekdayTimeGenerator),
(weekday_time_range, WeekdayTimeRangeGenerator)]
def analyze_date(name, category, date, rep):
for regex, dateClass in tests:
try:
rg = regex.match(date)
if rg:
if issubclass(dateClass, Generator):
return dateClass(name, category, rg.groups(), rep)
else:
return dateClass(name, category, rg.groups())
except InvalidDateEntryException:
sys.stderr.write("InvalidDate: %s %s %s %s\n" % (name, category, date, rep))
sys.stderr.flush()
return
def tokenize_wiki_page(content):
result = []
category = None
for line in content.splitlines(False):
line = line.strip()
dateinfo = entry.match(line)
if not dateinfo:
new_cat = category_re.match(line)
if new_cat:
category = new_cat.group(1).strip()
result.append((T_CATEGORY, category))
continue
divider = divider_re.match(line)
if divider:
result.append((T_ROW_DIVIDER, None))
continue
result.append((T_REST, line))
continue
name, date, rep = dateinfo.groups()
obj = analyze_date(name, category, date, rep)
if obj:
result.append((T_EVENT, obj))
else:
result.append((T_INVALID_EVENT, line))
return result
def parse_wiki_page(content):
result = []
category = None
for token, value in tokenize_wiki_page(content):
if token == T_EVENT:
result.append(value)
return result
def parse_wiki_page_ordered(pagedata):
ordered_categories = []
category = None
events = {}
for token, value in tokenize_wiki_page(pagedata):
if token == T_CATEGORY:
category = value
if category not in ordered_categories:
ordered_categories.append(category)
events[category] = []
elif token == T_EVENT:
events[category].append(value)
return ordered_categories, events
def move_to_archive(events_text, archive_text, threshold_date):
n = 0
events_categories, _ = parse_wiki_page_ordered(events_text)
archive_categories, archive_events = parse_wiki_page_ordered(archive_text)
archive_final_categories = list(events_categories)
for category in archive_categories:
if category not in archive_final_categories:
archive_final_categories.append(category)
flatend = []
skip_divider = False
for token, value in tokenize_wiki_page(events_text):
if token == T_EVENT:
if value < threshold_date:
if value.category not in archive_events:
archive_events[value.category] = []
archive_events[value.category].append(value)
n += 1
skip_divider = True
continue
elif token in (T_CATEGORY, T_REST, T_INVALID_EVENT):
skip_divider = False
elif token == T_ROW_DIVIDER and skip_divider:
skip_divider = False
continue
flatend.append((token, value))
archive_flatend = [(T_REST, u"= Termine Archiv =")]
for category in archive_final_categories:
if category in archive_events and archive_events[category]:
archive_flatend.append((T_CATEGORY, category))
archive_flatend.append((T_REST, u"{| class=\"prettytable\""))
archive_flatend.append((T_REST, u"! Event !! Termin !! Im Zeitraum"))
for event in sorted(archive_events[category]):
archive_flatend.append((T_ROW_DIVIDER, None))
archive_flatend.append((T_EVENT, event))
archive_flatend.append((T_REST, u"|}\n"))
new_events = render_page(flatend)
new_archive = render_page(archive_flatend)
return new_events, new_archive, n
def render_page(flatend):
r = u""
for token, value in flatend:
if token == T_REST:
r += u"%s\n" % value
elif token == T_CATEGORY:
r += u"== %s ==\n" % value
elif token == T_ROW_DIVIDER:
r += u"|-\n"
elif token == T_EVENT:
r += u"%s\n" % value.getMediawikiRow()
elif token == T_INVALID_EVENT:
r += u"%s\n" % value
print(str(token), repr(value))
else:
print(str(token), repr(value))
return r.strip()
def expand_dates(dates):
result = []
for date in dates:
if issubclass(date.__class__, Generator):
result.extend(date.entries)
else:
result.append(date)
return result
def next_up(entries, now_):
repeated_events = {}
now = now_ - datetime.timedelta(hours=1)
far_far_away = now + datetime.timedelta(days=MAX_NEXT_UP_REPEATED_DAYS)
far_far_far_away = now + datetime.timedelta(days=MAX_NEXT_UP_DAYS)
result = []
for entry in sorted(entries):
if entry.end_datetime() > now:
# detect repeating events by name
eventid = entry.getPlainName()
if eventid not in repeated_events:
repeated_events[eventid] = 0
repeated_events[eventid] += 1
if repeated_events[eventid] > MAX_NEXT_UP_REPEATED:
continue
# repeated events only in the near future
if repeated_events[eventid] > 1 and entry.start_datetime() > far_far_away:
continue
# restrict all events to not so fare future
if entry.start_datetime() > far_far_far_away:
continue
result.append(entry)
return result
def in_before(entries, now_):
repeated_events = {}
now = now_ - datetime.timedelta(hours=1)
lowest = now_ - datetime.timedelta(days=MAX_IN_BEFORE_DAYS)
result = []
for entry in sorted(entries, reverse=True):
if entry.end_datetime() < now and entry.end_datetime() > lowest:
# detect repeating events by nameyy
eventid = entry.getPlainName()
if eventid not in repeated_events:
repeated_events[eventid] = 0
repeated_events[eventid] += 1
if repeated_events[eventid] > MAX_IN_BEFORE_REPEATED:
continue
result.append(entry)
return result
def generate_wiki_section(entries, templatefile, lang=LANG_DE, now=None):
if now is None:
now = datetime.datetime.utcnow().replace(tzinfo=pytz.utc).astimezone(tz)
result = open(templatefile).read()
next_dates = []
for i in next_up(entries, now):
next_dates.append(i.getMediawikiEntry(lang=lang))
next_dates = "\n".join(next_dates)
prev_dates = []
for i in in_before(entries, now):
prev_dates.append(i.getMediawikiEntry(lang=lang))
prev_dates = "\n".join(prev_dates)
result = result.format(next_dates=next_dates, prev_dates=prev_dates)
return result.strip()
def write_if_changed(filename, content):
if not os.path.exists(filename) or content != open(filename).read():
f = open(filename, "w")
f.write(content)
f.close()
def generate_ical(entries, filename):
cal = ical.Calendar()
timezone = ical.cal.Timezone()
timezone.add('TZID', TIMEZONE)
timezone.add('x-lic-location', TIMEZONE)
tzs = ical.TimezoneStandard()
tzs.add('tzname', 'MEZ')
tzs.add('dtstart', datetime.datetime(1996, 10, 27, 3, 0, 0))
tzs.add('rrule', {'freq': 'yearly', 'bymonth': 10, 'byday': '-1su'})
tzs.add('TZOFFSETFROM', datetime.timedelta(hours=2))
tzs.add('TZOFFSETTO', datetime.timedelta(hours=1))
tzd = ical.TimezoneDaylight()
tzd.add('tzname', 'MESZ')
tzd.add('dtstart', datetime.datetime(1981, 3, 29, 2, 0, 0))
tzd.add('rrule', {'freq': 'yearly', 'bymonth': 3, 'byday': '-1su'})
tzd.add('TZOFFSETFROM', datetime.timedelta(hours=1))
tzd.add('TZOFFSETTO', datetime.timedelta(hours=2))
timezone.add_component(tzs)
timezone.add_component(tzd)
cal.add_component(timezone)
cal.add('version', '2.0')
cal.add('prodid', '-//willenbot')
cal.add('x-wr-calname', 'Stratum 0')
for entry in entries:
component = entry.getIcal()
if component:
cal.add_component(component)
# note: to_ical() returns bytes, but this is not documented.
write_if_changed(filename, cal.to_ical().decode("utf8"))
def generate_json_css(entries, jsonfile, cssfile):
e = []
css = []
for entry in entries:
data = entry.getJson()
group = data["class"]
if group not in css:
css.append(group)
e.append(data)
result = {
"success": 1,
"result": e}
write_if_changed(jsonfile, json.dumps(result))
css_content = ""
for group in css:
(r, g, b) = hashlib.md5(group.encode("utf8")).hexdigest()[:3]
color = r + "f" + g + "f" + b + "f"
css_content += ".{name},.dh-{name} {{background-color:#{color};}}\n".format(name=group, color=color)
write_if_changed(cssfile, css_content)