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