summaryrefslogtreecommitdiff
path: root/main.py
blob: cd85abd84762e02950dd1bbf44b5cfc4ce5379d4 (plain)
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
#!./env/bin/python

import yaml, textwrap
from prettytable import PrettyTable
from datetime import datetime, timedelta

with open("infos.yaml", "r") as f:
    _i=yaml.safe_load(f)
    _c=_i["config"]
    _ccal=_c["calendar"]
    _cslot=_c["slots"]
    _cproj=_c["projects"]

#### Parsing
def parse_date(s):
    return datetime.strptime(s, "%d/%m/%Y")
def parse_time(s):
    return datetime.strptime(s, "%H:%M")
#### Dates
def getmonday(d):
    return d - timedelta(days=d.weekday())
def getnextmonday(d):
    return getmonday(d)+timedelta(days=7)
def getnextdayn(d,n):
    return (d+timedelta(days=n))
def getweek(d):
    return d.isocalendar().week
def getdayname(d):
    return d.strftime("%A").lower()
#### Formatting
def gettime(d):
    return d.strftime("%H:%M")
def matchrepeat(d,e):
    _r=events[e]["repeat"]
    if _r["every"] <= 0:
        return False
    delta=timedelta(days=_r["every"])
    current=events[e]["date"]
    while current.date() <= sem["end"].date():
        if _r["until"] is not None and _r["until"].date()<current.date():
            break
        if current.date() == d.date():
            return True
        current+=delta
        continue
    return False
def formatevents(d):
    output=""
    for e in events:
        _e=events[e]
        if (not _e["hidden"]) and (_e["date"].date() == d.date() or matchrepeat(d, e)):
            if len(output)!=0:
                output+="\n\n"
            if _ccal["show_time"] and _e["start"] is not None:
                output+=gettime(_e["start"])+"-"+gettime(_e["end"])+"\n"
            if _ccal["show_room"] and _e["room"] is not None:
                output+="Room: "+_e["room"]+"\n"
            output+=_e["name"]
            if _ccal["show_who"] and _e["who"] is not None:
                output+="\n("+_e["who"]+")"
    return output
def formatday(d):
    return d.strftime("%b %d")
def formatprojects(d):
    output=""
    for pkey in sem["projects"]:
        p=sem["projects"][pkey]
        if d.date() >= p["start"].date() and d.date() <= p["end"].date():
            if len(output)>0:
                output+=","
            output+=p["name"]
    return output
def formatnotes(d):
    output=""
    for e in events:
        _e=events[e]
        if (not _e["hidden"]) and (_e["date"].date() == d.date() or matchrepeat(d, e)):
            if len(output)!=0:
                output+="\n\n"
            if _e["note"] is not None:
                output+= _e["note"]
    return output
#### Other help functions
def add_row(t,row,div):
    total=0
    for e in row[1:]:
        total+=len(e)
    if total > 0 or not _ccal["defrag"]:
        t.add_row(row,divider=div)

#### Load semester
sem={
    "start": parse_date(_i["semester"]["start"]),
    "end": parse_date(_i["semester"]["end"]),
    "slots": {},
    "projects": {}
}
for e in _i["semester"]["slots"]:
    _e=_i["semester"]["slots"][e]
    sem["slots"][e]={}
    for dayname in ["monday","tuesday","wednesday","thursday","friday"]:
        sem["slots"][e][dayname]={
            "start": None,
            "end": None,
            "room": None
        }
        if dayname in _e.keys():
            if "start" in _e[dayname].keys():
                sem["slots"][e][dayname]["start"]=parse_time(_e[dayname]["start"])
                sem["slots"][e][dayname]["end"]=parse_time(_e[dayname]["end"])
            if "room" in _e[dayname].keys():
                sem["slots"][e][dayname]["room"]=_e[dayname]["room"]
if _i["semester"]["projects"] is not None:
    for p in _i["semester"]["projects"]:
        _p=_i["semester"]["projects"][p]
        sem["projects"][p]={}
        sem["projects"][p]["start"]=parse_date(_p["start"])
        sem["projects"][p]["end"]=parse_date(_p["end"])
        sem["projects"][p]["name"]=textwrap.fill(_p["name"])
#### Load events
events={}
for e in _i["events"]:
    _e=_i["events"][e]
    events[e]={
        "type": _e["type"],
        "name": textwrap.fill(_e["name"],_c["name_wrap"]),
        "date": parse_date(_e["date"]),
        "repeat": {
            "every": 0,
            "until": None
        }
    }
    events[e]["hidden"]=_e["hidden"] if "hidden" in _e.keys() else False
    events[e]["who"]=_e["who"] if "who" in _e.keys() else None
    events[e]["start"]=parse_time(_e["start"]) if "start" in _e.keys() else None
    events[e]["end"]=parse_time(_e["end"]) if "end" in _e.keys() else None
    events[e]["room"]=_e["room"] if "room" in _e.keys() else None
    events[e]["note"]=_e["note"] if "note" in _e.keys() else None
    if "repeat" in _e.keys():
        events[e]["repeat"]["every"]=_e["repeat"]["every"]
        events[e]["repeat"]["until"]=parse_date(_e["repeat"]["until"]) if "until" in _e["repeat"].keys() else None
    if _e["type"] in sem["slots"].keys():
        dayname=getdayname(events[e]["date"])
        if events[e]["start"] is None:
            events[e]["start"] = sem["slots"][_e["type"]][dayname]["start"]
        if events[e]["end"] is None:
            events[e]["end"] = sem["slots"][_e["type"]][dayname]["end"]
        if events[e]["room"] is None:
            events[e]["room"] = sem["slots"][_e["type"]][dayname]["room"]

#### Gen semester calendar
if not _ccal["hidden"]:
    d=getmonday(sem["start"])
    w=getweek(d)
    while d<=sem["end"]:
        if _ccal["min_col_width"]>0:
            t = PrettyTable(min_width=_ccal["min_col_width"])
        else:
            t = PrettyTable()
        t.field_names = [_ccal["labels"]["week"].format(w), "Monday", "Tuesday", "Wednesday", "Thursday", "Friday"]
        t.align[t.field_names[0]]="l"
        if _ccal["show_date"]:
            t.add_row(["",
                       formatday(getnextdayn(d, 0)),
                       formatday(getnextdayn(d, 1)),
                       formatday(getnextdayn(d, 2)),
                       formatday(getnextdayn(d, 3)),
                       formatday(getnextdayn(d, 4))],divider=True)
        add_row(t,["",
                   formatevents(getnextdayn(d, 0)),
                   formatevents(getnextdayn(d, 1)),
                   formatevents(getnextdayn(d, 2)),
                   formatevents(getnextdayn(d, 3)),
                   formatevents(getnextdayn(d, 4))],True)
        if _ccal["show_project"]:
            add_row(t,[_ccal["labels"]["project"],
                       formatprojects(getnextdayn(d, 0)),
                       formatprojects(getnextdayn(d, 1)),
                       formatprojects(getnextdayn(d, 2)),
                       formatprojects(getnextdayn(d, 3)),
                       formatprojects(getnextdayn(d, 4))],True)
        if _ccal["show_note"]:
            add_row(t,[_ccal["labels"]["note"],
                       formatnotes(getnextdayn(d, 0)),
                       formatnotes(getnextdayn(d, 1)),
                       formatnotes(getnextdayn(d, 2)),
                       formatnotes(getnextdayn(d, 3)),
                       formatnotes(getnextdayn(d, 4))],False)
        print(t.get_formatted_string(_c["format"]))
        d=getnextmonday(d)
        w+=1
        if d<sem["end"]:
            print("")

#### Gen slots tables
if not _cslot["hidden"]:
    for s in sem["slots"]:
        t = PrettyTable()
        t.field_names = ["Day", "Time", "Room"]
        t.align["Day"]="l"
        for dayname in ["monday","tuesday","wednesday","thursday", "friday"]:
            p=sem["slots"][s][dayname]
            timeStr=gettime(p["start"])+"-"+gettime(p["end"]) if p["start"] is not None else ""
            room=p["room"] if p["room"] is not None else ""
            if timeStr != "" or room != "":
                t.add_row([dayname.capitalize(),timeStr,room])
        if not _cslot["show_room"]:
            t.del_column(t.field_names[-1])
        print(s+":")
        print(t.get_formatted_string(_c["format"]))

#### Gen projects deadline tables
if not _cproj["hidden"]:
    if len(sem["projects"].keys()) > 0:
        t = PrettyTable()
        t.field_names = ["Week", "Day", "Project info"]
        t.align[t.field_names[-1]]="l"
        d=getmonday(sem["start"])
        w=getweek(d)
        while d<=sem["end"]: # This is not optimal but works fine
            for p in sem["projects"].keys():
                start=sem["projects"][p]["start"]
                end=sem["projects"][p]["end"]
                name=sem["projects"][p]["name"]
                if d.date() == start.date():
                    t.add_row([w,formatday(start),_cproj["labels"]["start"].format(name)])
                if d.date() == end.date():
                    t.add_row([w,formatday(end),_cproj["labels"]["end"].format(name)])
            d=getnextdayn(d, 1)
            w=getweek(d)
        if not _cproj["show_week"]:
            t.del_column(t.field_names[0])
        print("Projects deadlines:")
        print(t.get_formatted_string(_c["format"]))