home · contact · privacy
Improve todo accounting.
[misc] / todo.py
1 from plomlib import PlomDB, run_server, PlomHandler, PlomException
2 import json
3 from uuid import uuid4
4 from datetime import datetime, timedelta
5 from urllib.parse import parse_qs
6 from jinja2 import Template
7 from urllib.parse import urlparse
8 db_path = '/home/plom/org/todo_new.json'
9 # db_path = '/home/plom/public_repos/misc/todo_new.json'
10 server_port = 8082
11 DATE_FORMAT = '%Y-%m-%d'
12
13 html_head = """
14 <style>
15 body { font-family: monospace; }
16 table.alternating tr:nth-child(even) {
17     background-color: #f2f2f2;
18 }
19 table.alternating tr:nth-child(odd) {
20     background-color: #ffffff;
21 }
22 th, td { text-align: left; vertical_align: top; border-bottom: 1px dotted black; }
23 td details { display: inline }
24 td.input { width: 100%; }
25 td.number { text-align: right; }
26 td.checkbox { width: 0.1em; height: 0.1em; padding: 0em; text-align: center; }
27 tr.week_row td { height: 0.1em; border: 0px; background-color: black; }
28 tr.day_row td { background-color: #f2f2f2 }
29 input { font-family: monospace; padding: 0em; margin: 0em; }
30 input[type="number"] { font-family: monospace; text-align: right; }
31 input[type="text"] { width: 100%; box-sizing: border-box; }
32 </style>
33 <body>
34 tasks: <a href="{{db.prefix}}/tasks">list</a> <a href="{{db.prefix}}/add_task">add</a> | day:
35 <a href="{{db.prefix}}/day?hide_unchosen=0&hide_done=0">choose tasks</a>
36 <a href="{{db.prefix}}/day?hide_unchosen=1&hide_done=1">do tasks</a>
37 | <a href="{{db.prefix}}/calendar">calendar</a>
38 | <a href="{{db.prefix}}/unset_cookie">unset cookie</a>
39 <hr />
40 """
41 form_footer = '\n</form>'
42 form_header_tmpl = """
43 <form action="{{action|e}}" method="POST">
44 """
45 calendar_tmpl = """
46 <p>
47 from: <input name="start" {% if start_date %}value="{{ start_date }}"{% endif %} placeholder="{{ today }}" />
48 to: <input name="end" {% if end_date %}value="{{ end_date }}"{% endif %} placeholder="2030-12-31" />
49 <input type="submit" value="OK" />
50 </p>
51 <table>
52 {% for date, day in days.items() | sort() %}
53 {% if day.weekday == "Mo" %}<tr class="week_row"><td colspan=3></td></tr>{% endif %}
54 <tr class="day_row"><td colspan=3><a href="{{db.prefix}}/day?selected_date={{date}}&hide_unchosen=1">{{ day.weekday }} {{ date }}</a> |{{ '%04.1f' % day.todos_sum|round(2) }}| {{ day.comment|e }}</td></tr>
55 {% for task, todo in day.todos.items() | sort(attribute='1.title', reverse=True)  %}
56 {% if todo.visible %}
57 <tr><td class="checkbox">{% if todo.done %}✓{% else %}&nbsp;&nbsp;{% endif %}</td><td><a href="{{db.prefix}}/todo?task={{ todo.task.id_ }}&date={{ date }}">{%if "cancelled" in todo.tags%}<s>{% endif %}{% if "deadline" in todo.tags %}DEADLINE: {% endif %}{{ todo.title|e }}{%if "cancelled" in todo.tags%}</s>{% endif %}</a></td><td>{{ todo.comment|e }}</td></tr>
58 {% endif %}
59 {% endfor %}
60 {% endfor %}
61 </table>
62 """
63 todo_tmpl = """
64 <input type="hidden" name="task_uuid" value="{{ todo.task.id_ }}" />
65 <input type="hidden" name="date" value="{{ todo.day.date }}" />
66 <table>
67 <tr><th>task</th><td><a href="{{db.prefix}}/task?id={{ todo.task.id_ }}">{{ todo.task.title|e }}</a></td></tr>
68 <tr><th>default weight</th><td>{{ todo.default_weight }}</td></tr>
69 <tr><th>day</th><td>{{ todo.day.date }}</td></tr>
70 <tr><th>day weight</th><td class="input"><input type="number" name="day_weight" step=0.1 size=8 value="{{ todo.day_weight }}" /></td></tr>
71 <tr><th>comment</th><td class="input"><input type="text" name="comment" value="{{todo.comment|e}}" /></td></tr>
72 <tr><th>done</th><td class="input"><input type="checkbox" name="done" {% if todo.done %}checked{% endif %}/></td></tr>
73 <tr><th>day tags</th><td class="input"><input name="day_tags" type="text" value="{{ todo.day_tags_joined|e }}" ></td></tr>
74 </table>
75 <input type="submit" value="update" />
76 """
77 task_tmpl = """
78 <input type="hidden" name="id" value="{{ task.id_ }}" />
79 <table>
80 <tr><th>title</th><td class="input"><input name="title" type="text" value="{{ task.title|e }}" /><details><summary>history</summary><ul>{% for k,v in task.title_history.items() | sort(attribute='0', reverse=True) %}<li>{{ k }}: {{ v|e }}{% endfor %}</ul></details></td></tr>
81 <tr><th>default weight</th><td class="input"><input type="number" name="default_weight" value="{{ task.default_weight }}" step=0.1 size=8 required /><details><summary>history</summary><ul>{% for k,v in task.default_weight_history.items() | sort(attribute='0', reverse=True) %}<li>{{ k }}: {{ v|e }}{% endfor %}</ul></details></td></tr>
82 <tr><th>tags</th><td class="input"><input name="tags" type="text" value="{{ task.tags_joined|e }}" ><details><summary>history</summary><ul>{% for k,v in task.tags_history.items() | sort(attribute='0', reverse=True) %}<li>{{ k }}: {{ v|e }}{% endfor %}</ul></details></td></tr>
83 </table>
84 <input type="submit" value="update" />
85 """
86 day_tmpl = """
87 <p>
88 <input name="hide_unchosen" type="checkbox" {% if db.hide_unchosen %}checked{% endif %} /> hide unchosen <input name="hide_done" type="checkbox" {% if db.hide_done %}checked{% endif %} /> hide done |
89 <a href="{{db.prefix}}/day?selected_date={{prev_date}}">prev</a> <a href="{{db.prefix}}/day?selected_date={{next_date}}">next</a> |
90 <input type="hidden" name="original_selected_date" value="{{ db.selected_date }}" />
91 date: <input name="new_selected_date" value="{{ db.selected_date }}" size=10 /> |
92 {{ db.selected_day.todos_sum|round(2) }} ({{ db.selected_day.todos_sum2|round(2)}}) |
93 comment: <input name="day_comment" value="{{ db.selected_day.comment|e }}">
94 </p>
95
96 <table class="alternating">
97 <tr><th>task</th><th class="checkbox">choose?</th><th class="checkbox">done?</th><th>weight</th><th>day tags</th><th>comment</th></tr>
98 {% for uuid, t in db.tasks.items() | sort(attribute='1.title') %}
99 {% if t.visible and (uuid not in db.selected_day.todos.keys() or db.selected_day.todos[uuid].visible) %}
100 <tr>
101 <input name="t_uuid" value="{{ uuid }}" type="hidden" >
102 <td><details><summary>] <a href="{{db.prefix}}/task?id={{ uuid }}" />{{ t.current_title|e }}</a></summary>tags: {% for tag in t.tags | sort %}<a href="{{db.prefix}}/day?t_and={{tag|e}}">{{ tag }}</a> {% endfor %}</details></td>
103 <td class="checkbox"><input name="choose" type="checkbox" value="{{ uuid }}" {% if uuid in db.selected_day.todos.keys() %}checked{% endif %} ></td>
104 <td class="checkbox"><input name="done" type="checkbox" value="{{ uuid }}" {% if uuid in db.selected_day.todos.keys() and db.selected_day.todos[uuid].done %}checked{% endif %} ></td>
105 <td class="checkbox"><input name="day_weight" type="number" step=0.1 size=8 value="{% if uuid in db.selected_day.todos.keys() and db.selected_day.todos[uuid].day_weight %}{{ db.selected_day.todos[uuid].day_weight }}{% endif %}" placeholder={{ t.current_default_weight }} ></td>
106 <td type="input"><input name="day_tags" type="text" value="{% if uuid in db.selected_day.todos.keys() %}{{ db.selected_day.todos[uuid].day_tags_joined|e }}{% endif %}" ></td>
107 <td type="input"><input name="todo_comment" type="text" value="{% if uuid in db.selected_day.todos.keys() %}{{ db.selected_day.todos[uuid].comment|e }}{% endif %}" ></td>
108 </tr>
109 {% endif %}
110 {% endfor %}
111 </table>
112 <input type="submit" value="OK">
113 """
114 tag_filters_tmpl = """
115 <p style="float: left; margin-right: 1em;">
116 <input type="submit" value="OK">
117 </p>
118 <p>
119 mandatory tags:
120 {% for and_filter in db.t_filter_and %}
121 <select name="t_and">
122 <option></option>
123 {% for tag in db.t_tags | sort %}
124 <option value="{{tag|e}}" {% if and_filter == tag %}selected{% endif %}>{{tag|e}}</option>
125 {% endfor %}
126 </select>
127 {% endfor %}
128 <select name="t_and">
129 <option></option>
130 {% for tag in db.t_tags | sort %}
131 <option value="{{tag|e}}">{{tag|e}}</option>
132 {% endfor %}
133 </select>
134 <br />
135 forbidden tags:
136 {% for not_filter in db.t_filter_not %}
137 <select name="t_not">
138 <option></option>
139 {% for tag in db.t_tags | sort %}
140 <option value="{{tag|e}}" {% if not_filter == tag %}selected{% endif %}>{{tag|e}}</option>
141 {% endfor %}
142 </select>
143 {% endfor %}
144 <select name="t_not">
145 <option></option>
146 {% for tag in db.t_tags | sort %}
147 <option value="{{tag|e}}">{{tag|e}}</option>
148 {% endfor %}
149 </select>
150 </p>
151 """
152 tasks_tmpl = """
153 <table class="alternating">
154 <tr><th>default<br />weight</th><th>task</th><th>tags</th></tr>
155 {% for uuid, t in db.tasks.items() | sort(attribute='1.title') %}
156 {% if t.visible %}
157 <tr>
158 <td class="number">{{ t.default_weight }}</a></td>
159 <td><a href="{{db.prefix}}/task?id={{ uuid }}" />{{ t.title|e }}</a></td>
160 <td>{% for tag in t.tags | sort %}<a href="{{db.prefix}}/tags?t_and={{tag|e}}">{{ tag }}</a> {% endfor %}</td>
161 {% endif %}
162 {% endfor %}
163 </table>
164 """
165
166 class Task:
167
168     def __init__(self, db, title_history=None, tags_history=None, default_weight_history=None):
169         self.db = db
170         self.title_history = title_history if title_history else {}
171         self.tags_history = tags_history if tags_history else {}
172         self.default_weight_history = default_weight_history if default_weight_history else {}
173         self.visible = True
174
175     def _set_with_history(self, history, value):
176         keys = sorted(history.keys())
177         if len(history) == 0 or value != history[keys[-1]]:
178             history[str(datetime.now())[:19]] = value
179
180     def _last_of_history(self, history, default):
181         keys = sorted(history.keys())
182         return default if 0 == len(history) else history[keys[-1]]
183
184     @classmethod
185     def from_dict(cls, db, d):
186         return cls(
187                 db,
188                 d['title_history'],
189                 {k: set(v) for k, v in d['tags_history'].items()},
190                 d['default_weight_history'])
191
192     @property
193     def default_weight(self):
194         return self._last_of_history(self.default_weight_history, 1)
195
196     @default_weight.setter
197     def default_weight(self, default_weight):
198         self._set_with_history(self.default_weight_history, default_weight)
199
200     def default_weight_at(self, queried_date):
201         ret = self.default_weight_history[sorted(self.default_weight_history.keys())[0]]
202         for date_key, default_weight in self.default_weight_history.items():
203             if date_key > f'{queried_date} 23:59:59':
204                 break
205             ret = default_weight
206         return ret
207
208     @property
209     def current_default_weight(self):
210         return self.default_weight_at(self.db.selected_date)
211
212     @property
213     def title(self):
214         return self._last_of_history(self.title_history, '')
215
216     @title.setter
217     def title(self, title):
218         self._set_with_history(self.title_history, title)
219
220     def title_at(self, queried_date):
221         ret = self.title_history[sorted(self.title_history.keys())[0]]
222         for date_key, title in self.title_history.items():
223             if date_key > f'{queried_date} 23:59:59':
224                 break
225             ret = title
226         return ret
227
228     @property
229     def current_title(self):
230         return self.title_at(self.db.selected_date)
231
232     @property
233     def tags(self):
234         return self._last_of_history(self.tags_history, set())
235
236     @tags.setter
237     def tags(self, tags):
238         self._set_with_history(self.tags_history, set(tags))
239
240     @property
241     def tags_joined(self):
242         return ';'.join(sorted(list(self.tags)))
243
244     @tags_joined.setter
245     def tags_joined(self, tags_string):
246         tags = set()
247         for tag in [tag.strip() for tag in tags_string.split(';') if tag.strip() != '']:
248             tags.add(tag)
249         self.tags = tags
250
251     def to_dict(self):
252         return {
253             'title_history': self.title_history,
254             'tags_history': {k: list(v) for k,v in self.tags_history.items()},
255             'default_weight_history': self.default_weight_history}
256
257     @property
258     def id_(self):
259         for k, v in self.db.tasks.items():
260             if v == self:
261                 return k
262
263
264 class Day:
265
266     def __init__(self, db, todos=None, comment=''):
267         self.db = db
268         self.todos = todos if todos else {}
269         self.comment = comment
270         self.archived = True
271
272     @classmethod
273     def from_dict(cls, db, d):
274         todos = {}
275         comment = d['comment'] if 'comment' in d.keys() else ''
276         day = cls(db, todos, comment)
277         for uuid, todo_dict in d['todos'].items():
278             day.add_todo(uuid, todo_dict)
279         return day
280
281     def to_dict(self):
282         d = {'comment': self.comment, 'todos': {}}
283         for task_uuid, todo in self.todos.items():
284             d['todos'][task_uuid] = todo.to_dict()
285         return d
286
287     def add_todo(self, id_, dict_source=None):
288         self.todos[id_] = Todo.from_dict(self, dict_source) if dict_source else Todo(self)
289         return self.todos[id_]
290
291     def _todos_sum(self, include_undone=False):
292         s = 0
293         for todo in [todo for todo in self.todos.values() if todo.done]:
294             s += todo.weight
295         if include_undone:
296             for todo in [todo for todo in self.todos.values() if not todo.done]:
297                 s += todo.day_weight if todo.day_weight else 0
298         return s
299
300     @property
301     def todos_sum(self):
302         return self._todos_sum()
303
304     @property
305     def todos_sum2(self):
306         return self._todos_sum(True)
307
308     @property
309     def date(self):
310         for k, v in self.db.days.items():
311             if v == self:
312                 return k
313
314 class Todo:
315
316     def __init__(self, day, done=False, day_weight=None, comment='', day_tags=None):
317         self.day = day
318         self.done = done
319         self.day_weight = day_weight
320         self.comment = comment
321         self.day_tags = day_tags if day_tags else set()
322
323     @classmethod
324     def from_dict(cls, day, d):
325         return cls(day, d['done'], d['day_weight'], d['comment'], set(d['day_tags']))
326
327     def to_dict(self):
328         return {'done': self.done, 'day_weight': self.day_weight, 'comment': self.comment, 'day_tags': list(self.day_tags)}
329
330     @property
331     def default_weight(self):
332         return self.task.default_weight_at(self.day.date)
333
334     @property
335     def weight(self):
336         if self.day_weight:
337             return self.day_weight
338         else:
339             return self.day_weight if self.day_weight else self.default_weight
340
341     @property
342     def task(self):
343         for k, v in self.day.todos.items():
344             if v == self:
345                 return self.day.db.tasks[k]
346
347     @property
348     def title(self):
349         return self.task.title_at(self.day.date)
350
351     @property
352     def day_tags_joined(self):
353         return ';'.join(sorted(list(self.day_tags)))
354
355     @day_tags_joined.setter
356     def day_tags_joined(self, tags_string):
357         tags = set()
358         for tag in [tag.strip() for tag in tags_string.split(';') if tag.strip() != '']:
359             tags.add(tag)
360         self.day_tags = tags
361
362     @property
363     def tags(self):
364         return self.day_tags | self.task.tags
365
366
367 class TodoDB(PlomDB):
368
369     def __init__(self, prefix, selected_date=None, t_filter_and = None, t_filter_not = None, hide_unchosen=False, hide_done=False):
370         self.prefix = prefix
371         self.selected_date = selected_date if selected_date else str(datetime.now())[:10]
372         self.t_filter_and = t_filter_and if t_filter_and else []
373         self.t_filter_not = t_filter_not if t_filter_not else []
374         self.hide_unchosen = hide_unchosen
375         self.hide_done = hide_done
376         self.days = {}
377         self.tasks = {}
378         self.t_tags = set()
379         super().__init__(db_path)
380
381     def read_db_file(self, f):
382         d = json.load(f)
383         for date, day_dict in d['days'].items():
384             self.days[date] = self.add_day(dict_source=day_dict)
385         for day in self.days.values():
386             for todo in day.todos.values():
387                 for tag in todo.day_tags:
388                     self.t_tags.add(tag)
389         for uuid, t_dict in d['tasks'].items():
390             t = self.add_task(id_=uuid, dict_source=t_dict)
391             for tag in t.tags:
392                 self.t_tags.add(tag)
393         self.set_visibilities()
394
395     def set_visibilities(self):
396         for uuid, t in self.tasks.items():
397             t.visible = len([tag for tag in self.t_filter_and if not tag in t.tags]) == 0\
398                     and len([tag for tag in self.t_filter_not if tag in t.tags]) == 0\
399                     and ((not self.hide_unchosen) or uuid in self.selected_day.todos.keys())
400         for day in self.days.values():
401             for todo in day.todos.values():
402                 todo.visible = len([tag for tag in self.t_filter_and if not tag in todo.day_tags | todo.task.tags ]) == 0\
403                     and len([tag for tag in self.t_filter_not if tag in todo.day_tags | todo.task.tags ]) == 0\
404                     and ((not self.hide_done) or (not todo.done))
405
406     def to_dict(self):
407         d = {
408                 't_filter_and': self.t_filter_and,
409                 't_filter_not': self.t_filter_not,
410                 'tasks': {},
411                 'days': {}
412         }
413         for uuid, t in self.tasks.items():
414              d['tasks'][uuid] = t.to_dict()
415         for date, day in self.days.items():
416             d['days'][date] = day.to_dict()
417         return d
418
419     @property
420     def selected_day(self):
421         if not self.selected_date in self.days.keys():
422             self.days[self.selected_date] = self.add_day()
423         return self.days[self.selected_date]
424
425     def change_selected_days_date(self, new_date):
426         if new_date in self.days.keys():
427             raise PlomException('cannot use same date twice')
428         else:
429             self.days[new_date] = self.selected_day
430             del self.days[self.selected_date]
431             self.selected_date = new_date
432
433     def write(self):
434         dates_to_purge = []
435         for date, day in self.days.items():
436             if len(day.todos) == 0 and len(day.comment) == 0:
437                 dates_to_purge += [date]
438         for date in dates_to_purge:
439             del self.days[date]
440         self.write_text_to_db(json.dumps(self.to_dict()))
441
442     def add_task(self, id_=None, dict_source=None, return_id=False):
443         t = Task.from_dict(self, dict_source) if dict_source else Task(self)
444         id_ = id_ if id_ else str(uuid4())
445         self.tasks[id_] = t
446         if return_id:
447             return id_, t
448         else:
449             return t
450
451     def add_day(self, dict_source=None):
452         return Day.from_dict(self, dict_source) if dict_source else Day(self)
453
454     def show_day(self):
455         current_date = datetime.strptime(self.selected_date, DATE_FORMAT)
456         prev_date = current_date - timedelta(days=1)
457         prev_date_str = prev_date.strftime(DATE_FORMAT)
458         next_date = current_date + timedelta(days=1)
459         next_date_str = next_date.strftime(DATE_FORMAT)
460         return Template(form_header_tmpl + tag_filters_tmpl + day_tmpl + form_footer).render(db=self, action=self.prefix+'/day', prev_date=prev_date_str, next_date=next_date_str)
461
462     def show_calendar(self, start_date_str, end_date_str):
463         self.t_filter_and = ['calendar']
464         self.t_filter_not = ['deleted']
465         self.set_visibilities()
466         days_to_show = {}
467         todays_date = str(datetime.now())[:10]
468         target_start_str = start_date_str if start_date_str else sorted(self.days.keys())[0]
469         target_start = todays_date if target_start_str == 'today' else target_start_str
470         target_end_str = end_date_str if end_date_str else sorted(self.days.keys())[-1]
471         target_end = todays_date if target_end_str == 'today' else target_end_str
472         start_date = datetime.strptime(target_start, DATE_FORMAT)
473         end_date = datetime.strptime(target_end, DATE_FORMAT)
474         for n in range(int((end_date - start_date).days) + 1):
475             current_date_obj = start_date + timedelta(n)
476             current_date = current_date_obj.strftime(DATE_FORMAT)
477             if current_date not in self.days.keys():
478                 days_to_show[current_date] = self.add_day()
479             else:
480                 days_to_show[current_date] = self.days[current_date]
481             days_to_show[current_date].weekday = datetime.strptime(current_date, DATE_FORMAT).strftime('%A')[:2]
482         return Template(form_header_tmpl + calendar_tmpl + form_footer).render(db=self, days=days_to_show, action=self.prefix+'/calendar', today=str(datetime.now())[:10], start_date=start_date_str, end_date=end_date_str)
483
484     def show_todo(self, task_uuid, selected_date):
485         todo = self.days[selected_date].todos[task_uuid]
486         return Template(form_header_tmpl + todo_tmpl + form_footer).render(db=self, todo=todo, action=self.prefix+'/todo')
487
488     def update_todo(self, task_uuid, date, day_weight, done, comment, day_tags_joined):
489         if task_uuid in self.days[date].todos.keys():
490             todo = self.days[date].todos[task_uuid]
491         else:
492             todo = self.days[date].add_todo(task_uuid)
493         todo.day_weight = float(day_weight) if len(day_weight) > 0 else None
494         todo.done = done
495         todo.comment = comment
496         todo.day_tags_joined = day_tags_joined
497
498     def show_task(self, id_):
499         task = self.tasks[id_] if id_ else self.add_task()
500         return Template(form_header_tmpl + task_tmpl + form_footer).render(db=self, task=task, action=self.prefix+'/task')
501
502     def update_task(self, id_, title, default_weight, tags_joined):
503         task = self.tasks[id_] if id_ in self.tasks.keys() else self.add_task(id_)
504         task.title = title
505         task.default_weight = float(default_weight) if len(default_weight) > 0 else None
506         task.tags_joined = tags_joined
507
508     def show_tasks(self):
509         return Template(form_header_tmpl + tag_filters_tmpl + tasks_tmpl + form_footer).render(db=self, action=self.prefix+'/tasks')
510
511
512
513 class TodoHandler(PlomHandler):
514
515     def config_init(self):
516         return {
517             'cookie_name': 'todo_cookie',
518             'prefix': '',
519             'cookie_path': '/'
520         }
521
522     def app_init(self, handler):
523         default_path = '/todo'
524         handler.add_route('GET', default_path, self.show_db)
525         handler.add_route('POST', default_path, self.write_db)
526         return 'todo', {'cookie_name': 'todo_cookie', 'prefix': default_path, 'cookie_path': default_path}
527
528     def do_POST(self):
529         self.try_do(self.config_init)
530         self.try_do(self.write_db)
531
532     def write_db(self):
533         from urllib.parse import urlencode
534         app_config = self.apps['todo'] if hasattr(self, 'apps') else self.config()
535         length = int(self.headers['content-length'])
536         postvars = parse_qs(self.rfile.read(length).decode(), keep_blank_values=1)
537         parsed_url = urlparse(self.path)
538         db = TodoDB(prefix=app_config['prefix'])
539
540         if parsed_url.path == app_config['prefix'] + '/calendar':
541             start = postvars['start'][0] if len(postvars['start'][0]) > 0 else '-'
542             end = postvars['end'][0] if len(postvars['end'][0]) > 0 else '-'
543             homepage = f'{app_config["prefix"]}/calendar?start={start}&end={end}'
544
545         elif parsed_url.path == app_config['prefix'] + '/todo':
546             task_uuid = postvars['task_uuid'][0]
547             date = postvars['date'][0]
548             db.update_todo(task_uuid, date, postvars['day_weight'][0], 'done' in postvars.keys(), postvars['comment'][0], postvars['day_tags'][0])
549             homepage = f'{app_config["prefix"]}/todo?task={task_uuid}&date={date}'
550
551         elif parsed_url.path == app_config['prefix'] + '/task':
552             id_ = postvars['id'][0]
553             db.update_task(id_, postvars['title'][0], postvars['default_weight'][0], postvars['tags'][0])
554             homepage = f'{app_config["prefix"]}/task?id={id_}'
555
556         elif parsed_url.path in {app_config['prefix'] + '/tasks', app_config['prefix'] + '/day'}:
557             data = []
558             for target in postvars['t_and']:
559                 if len(target) > 0 and not target in db.t_filter_and:
560                     db.t_filter_and += [target]
561             if len(db.t_filter_and) == 0:
562                 data += [('t_and', '-')]
563             for target in postvars['t_not']:
564                 if len(target) > 0 and not target in db.t_filter_not:
565                     db.t_filter_not += [target]
566             if len(db.t_filter_not) == 0:
567                 data += [('t_not', '-')]
568             data += [('t_and', f) for f in db.t_filter_and] + [('t_not', f) for f in db.t_filter_not]
569             if parsed_url.path == app_config['prefix'] + '/tasks':
570                 encoded_params = urlencode(data)
571                 homepage = f'{app_config["prefix"]}/tasks?{encoded_params}'
572
573             elif parsed_url.path == app_config['prefix'] + '/day':
574                 db.hide_unchosen = 'hide_unchosen' in postvars.keys()
575                 db.hide_done = 'hide_done' in postvars.keys()
576                 data += [('hide_unchosen', int(db.hide_unchosen))] + [('hide_done', int(db.hide_done))]
577
578                 db.selected_date = postvars['original_selected_date'][0]
579                 new_selected_date = postvars['new_selected_date'][0]
580                 try:
581                     datetime.strptime(new_selected_date, DATE_FORMAT)
582                 except ValueError:
583                     raise PlomException(f'{app_config["prefix"]} bad date string: {new_selected_date}')
584                 if new_selected_date != db.selected_date:
585                     db.change_selected_days_date(new_selected_date)
586                 if 't_uuid' in postvars.keys():
587                     for i, uuid in enumerate(postvars['t_uuid']):
588                         t = db.tasks[uuid]
589                         if uuid in db.selected_day.todos.keys() and ((not 'choose' in postvars) or uuid not in postvars['choose']):
590                             del db.selected_day.todos[uuid]
591                     if 'choose' in postvars.keys():
592                         for i, uuid in enumerate(postvars['t_uuid']):
593                             if uuid in postvars['choose']:
594                                 done = 'done' in postvars and uuid in postvars['done']
595                                 db.update_todo(uuid, db.selected_date, postvars['day_weight'][i], done, postvars['todo_comment'][i], postvars['day_tags'][i])
596                 if 'day_comment' in postvars.keys():
597                     db.selected_day.comment = postvars['day_comment'][0]
598                 data += [('selected_date', db.selected_date)]
599                 encoded_params = urlencode(data)
600                 homepage = f'{app_config["prefix"]}/day?{encoded_params}'
601
602         db.write()
603         self.redirect(homepage)
604
605     def do_GET(self):
606         self.try_do(self.config_init)
607         self.try_do(self.show_db)
608
609     def show_db(self):
610         app_config = self.apps['todo'] if hasattr(self, 'apps') else self.config()
611         cookie_db = self.get_cookie_db(app_config['cookie_name'])
612         parsed_url = urlparse(self.path)
613         params = parse_qs(parsed_url.query)
614         selected_date = None
615         t_filter_and = None
616         t_filter_not = None
617         hide_unchosen = False
618         hide_done = False
619         if parsed_url.path in {app_config['prefix'] + '/day', app_config['prefix'] + '/tasks'}:
620             selected_date = params.get('selected_date', [None])[0]
621             if selected_date is None and 'selected_date' in cookie_db.keys():
622                 selected_date = cookie_db['selected_date']
623             cookie_db['selected_date'] = selected_date
624             t_filter_and = params.get('t_and', None)
625             if t_filter_and is None and 't_and' in cookie_db.keys():
626                 t_filter_and = cookie_db['t_and']
627             elif t_filter_and == ['-']:
628                 t_filter_and = None
629             cookie_db['t_and'] = t_filter_and
630             t_filter_not = params.get('t_not', None)
631             if t_filter_not is None and 't_not' in cookie_db.keys():
632                 t_filter_not = cookie_db['t_not']
633             elif t_filter_not == ['-']:
634                 t_filter_not = None
635             else:
636                 t_filter_not = ['deleted']
637             cookie_db['t_not'] = t_filter_not
638         if parsed_url.path == app_config['prefix'] + '/day':
639             hide_unchosen_params = params.get('hide_unchosen', [])
640             if 0 == len(hide_unchosen_params):
641                 if 'hide_unchosen' in cookie_db.keys():
642                     hide_unchosen = cookie_db['hide_unchosen']
643             else:
644                 hide_unchosen = hide_unchosen_params[0] != '0'
645             cookie_db['hide_unchosen'] = hide_unchosen
646             hide_done_params = params.get('hide_done', [])
647             if 0 == len(hide_done_params):
648                 if 'hide_done' in cookie_db.keys():
649                     hide_done = cookie_db['hide_done']
650             else:
651                 hide_done = hide_done_params[0] != '0'
652             cookie_db['hide_done'] = hide_done
653         db = TodoDB(app_config['prefix'], selected_date, t_filter_and, t_filter_not, hide_unchosen, hide_done)
654         if parsed_url.path == app_config['prefix'] + '/day':
655             page = db.show_day()
656         elif parsed_url.path == app_config['prefix'] + '/todo':
657             todo_date = params.get('date', [None])[0]
658             task_uuid = params.get('task', [None])[0]
659             page = db.show_todo(task_uuid, todo_date)
660         elif parsed_url.path == app_config['prefix'] + '/task':
661             id_ = params.get('id', [None])[0]
662             page = db.show_task(id_)
663         elif parsed_url.path == app_config['prefix'] + '/tasks':
664             page = db.show_tasks()
665         elif parsed_url.path == app_config['prefix'] + '/add_task':
666             page = db.show_task(None)
667         elif parsed_url.path == app_config['prefix'] + '/unset_cookie':
668             page = 'no cookie to unset.'
669             if len(cookie_db) > 0:
670                 self.unset_cookie(app_config['cookie_name'], app_config['cookie_path'])
671                 page = 'cookie unset!'
672         else:
673             start_date = params.get('start', [None])[0]
674             if start_date is None:
675                 if 'calendar_start' in cookie_db.keys():
676                     start_date = cookie_db['calendar_start']
677                 else:
678                     start_date = 'today'
679             elif start_date == '-':
680                 start_date = None
681             cookie_db['calendar_start'] = start_date
682             end_date = params.get('end', [None])[0]
683             if end_date is None and 'calendar_end' in cookie_db.keys():
684                 end_date = cookie_db['calendar_end']
685             elif end_date == '-':
686                 end_date = None
687             cookie_db['calendar_end'] = end_date
688             page = db.show_calendar(start_date, end_date)
689         header = Template(html_head).render(db=db, prefix=app_config['prefix'], date=selected_date)
690         if parsed_url.path != app_config['prefix'] + '/unset_cookie':
691             self.set_cookie(app_config['cookie_name'], app_config['cookie_path'], cookie_db)
692         self.send_HTML(header + page)
693
694
695 if __name__ == "__main__":
696     run_server(server_port, TodoHandler)