forked from nikosavola/fk-tiedotin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.py
70 lines (54 loc) · 2.81 KB
/
utils.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
from datetime import date, timedelta
from functools import partial
from itertools import groupby
from tinydb import TinyDB
# Define categories for entries and current week.
# To make a newsletter for a specific week (eg week 1), last possible occasion
# to do it is on Monday of that specific week (week 1). On Tuesday newsletter is made for the
# following week (week 2). timedelta correction below takes into account this and a fact
# that datetime library consideres week 1 to be the year's first week that starts from Monday,
# which differs from finnish convention. Correction is different every year.
week = (date.today()+timedelta(days=6)).strftime('%W')
categories = ["Opinnot", "Killan tapahtumat", "Muut tapahtumat", "Yleistä"]
categories_en = ["Studies", "Guild's events", "Other events", "General"]
# Database logic.
def save_entry(entry, isEnglish=False, addWeeks=0):
"""Save entry to database."""
for i in range(addWeeks+1):
week_number = str(int(week)+i).zfill(2)
if isEnglish:
path = 'data/week'+week_number+'-en.json'
else:
path = 'data/week'+week_number+'.json'
db = TinyDB(path, ensure_ascii=False, sort_keys=True, indent=4, separators=(',', ': '))
db.insert(entry)
def all_entries(isEnglish=False):
"""Return all events from database for this week."""
if isEnglish:
path = 'data/week'+week+'-en.json'
else:
path = 'data/week'+week+'.json'
db = TinyDB(path, ensure_ascii=False, sort_keys=True, indent=4, separators=(',', ': '))
return db.all()
# Functions for grouping and sorting database entries.
def category_sort(x, cats):
"""Return index of database entry's category from a given list."""
return cats.index(x['category'])
def date_sort(x):
"""Return date of database-entry."""
return date(x['date'][2], x['date'][1], x['date'][0])
def in_current_week(x):
"""Test whether entry's date is on current week."""
return int((date(x['date'][2], x['date'][1], x['date'][0]) - timedelta(days=1)).strftime('%U')) + 1 == int(week)
def grouper(entries, cats):
"""Return tuple, which consists of string and another tuple, which consist of two lists.
First entries are grouped by category and sorted by date. Then they are sorted even
further to events that happen this week and events that happen later in the future.
"""
category_and_events = []
for k, g in groupby(entries, key=partial(category_sort, cats=cats)):
events_sorted = sorted(list(g), key=date_sort)
this_week = [e for e in events_sorted if in_current_week(e)]
following_week = [e for e in events_sorted if not in_current_week(e)]
category_and_events.append((cats[k], (this_week, following_week)))
return category_and_events