1 from plomlib import PlomDB, run_server, PlomHandler, PlomException
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'
11 DATE_FORMAT = '%Y-%m-%d'
15 body { font-family: monospace; }
16 table.alternating tr:nth-child(even) {
17 background-color: #f2f2f2;
19 table.alternating tr:nth-child(odd) {
20 background-color: #ffffff;
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; }
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>
41 form_footer = '\n</form>'
42 form_header_tmpl = """
43 <form action="{{action|e}}" method="POST">
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" />
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) %}
57 <tr><td class="checkbox">{% if todo.done %}✓{% else %} {% 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>
65 <input type="hidden" name="task_uuid" value="{{ todo.task.id_ }}" />
66 <input type="hidden" name="date" value="{{ todo.day.date }}" />
68 <tr><th>task</th><td><a href="{{db.prefix}}/task?id={{ todo.task.id_ }}">{{ todo.task.title|e }}</a></td></tr>
69 <tr><th>default weight</th><td>{{ todo.default_weight }}</td></tr>
70 <tr><th>day</th><td>{{ todo.day.date }}</td></tr>
71 <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>
72 <tr><th>comment</th><td class="input"><input type="text" name="comment" value="{{todo.comment|e}}" /></td></tr>
73 <tr><th>done</th><td class="input"><input type="checkbox" name="done" {% if todo.done %}checked{% endif %}/></td></tr>
76 {% for tag in db.t_tags | sort %}
77 {% if tag in todo.task.tags %} ✓{% else %}<input type="checkbox" name="day_tag_{{tag|e}}"{% if tag in todo.day_tags %} checked{% endif %}/>{% endif %} {{ tag }}<br />
79 add: <input name="day_tags_joined" type="text" value="" >
83 <input type="submit" value="update" />
87 <input type="hidden" name="id" value="{{ task.id_ }}" />
89 <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>
90 <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>
93 {% for tag in db.t_tags | sort %}
94 <input type="checkbox" name="tag_{{tag|e}}"{% if tag in task.tags %} checked{% endif %}/> {{ tag }}<br />
96 add: <input name="tags_joined" type="text" value="" ><br />
97 <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>
100 <input type="submit" value="update" />
104 <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 |
105 <a href="{{db.prefix}}/day?selected_date={{prev_date}}">prev</a> <a href="{{db.prefix}}/day?selected_date={{next_date}}">next</a> |
106 <input type="hidden" name="original_selected_date" value="{{ db.selected_date }}" />
107 date: <input name="new_selected_date" value="{{ db.selected_date }}" size=10 /> |
108 {{ db.selected_day.todos_sum|round(2) }} ({{ db.selected_day.todos_sum2|round(2)}}) |
109 comment: <input name="day_comment" value="{{ db.selected_day.comment|e }}">
112 <table class="alternating">
113 <tr><th>task</th><th class="checkbox">choose?</th><th class="checkbox">done?</th><th>weight</th><th>edit?</th><th>day tags</th><th>comment</th></tr>
114 {% for uuid, t in db.tasks.items() | sort(attribute='1.title') %}
115 {% if t.visible and (uuid not in db.selected_day.todos.keys() or db.selected_day.todos[uuid].visible) %}
117 <input name="t_uuid" value="{{ uuid }}" type="hidden" >
118 <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>
119 {% if uuid in db.selected_day.todos.keys() %}
120 <td class="checkbox"><input name="choose" type="checkbox" value="{{ uuid }}" checked></td>
121 <td class="checkbox"><input name="done" type="checkbox" value="{{ uuid }}" {% if db.selected_day.todos[uuid].done %}checked{% endif %}></td>
122 <td class="checkbox"><input name="day_weight" type="number" step=0.1 size=8 value="{% if db.selected_day.todos[uuid].day_weight is not none %}{{ db.selected_day.todos[uuid].day_weight }}{% endif %}" placeholder={{ t.current_default_weight }} ></td>
123 <td><a href="{{db.prefix}}/todo?task={{uuid}}&date={{ db.selected_date }}">edit</a></td>
124 <td>{% for tag in db.selected_day.todos[uuid].day_tags | sort %}<a href="{{db.prefix}}/tags?t_and={{tag|e}}">{{ tag }}</a> {% endfor %}</td>
125 <td>{{ db.selected_day.todos[uuid].comment|e }}</td>
127 <td class="checkbox"><input name="choose" type="checkbox" value="{{ uuid }}"</td>
128 <td class="checkbox"><input name="done" type="checkbox" value="{{ uuid }}"></td>
129 <td class="checkbox"><input name="day_weight" type="number" step=0.1 size=8 placeholder={{ t.current_default_weight }} ></td>
138 <input type="submit" value="OK">
140 tag_filters_tmpl = """
141 <p style="float: left; margin-right: 1em;">
142 <input type="submit" value="OK">
146 {% for and_filter in db.t_filter_and %}
147 <select name="t_and">
149 {% for tag in db.t_tags | sort %}
150 <option value="{{tag|e}}" {% if and_filter == tag %}selected{% endif %}>{{tag|e}}</option>
154 <select name="t_and">
156 {% for tag in db.t_tags | sort %}
157 <option value="{{tag|e}}">{{tag|e}}</option>
162 {% for not_filter in db.t_filter_not %}
163 <select name="t_not">
165 {% for tag in db.t_tags | sort %}
166 <option value="{{tag|e}}" {% if not_filter == tag %}selected{% endif %}>{{tag|e}}</option>
170 <select name="t_not">
172 {% for tag in db.t_tags | sort %}
173 <option value="{{tag|e}}">{{tag|e}}</option>
179 <table class="alternating">
180 <tr><th>default<br />weight</th><th>task</th><th>tags</th></tr>
181 {% for uuid, t in db.tasks.items() | sort(attribute='1.title') %}
184 <td class="number">{{ t.default_weight }}</a></td>
185 <td><a href="{{db.prefix}}/task?id={{ uuid }}" />{{ t.title|e }}</a></td>
186 <td>{% for tag in t.tags | sort %}<a href="{{db.prefix}}/tags?t_and={{tag|e}}">{{ tag }}</a> {% endfor %}</td>
194 def __init__(self, db, title_history=None, tags_history=None, default_weight_history=None):
196 self.title_history = title_history if title_history else {}
197 self.tags_history = tags_history if tags_history else {}
198 self.default_weight_history = default_weight_history if default_weight_history else {}
201 def _set_with_history(self, history, value):
202 keys = sorted(history.keys())
203 if len(history) == 0 or value != history[keys[-1]]:
204 history[str(datetime.now())[:19]] = value
206 def _last_of_history(self, history, default):
207 keys = sorted(history.keys())
208 return default if 0 == len(history) else history[keys[-1]]
211 def from_dict(cls, db, d):
215 {k: set(v) for k, v in d['tags_history'].items()},
216 d['default_weight_history'])
219 def default_weight(self):
220 return self._last_of_history(self.default_weight_history, 1)
222 @default_weight.setter
223 def default_weight(self, default_weight):
224 self._set_with_history(self.default_weight_history, default_weight)
226 def default_weight_at(self, queried_date):
227 ret = self.default_weight_history[sorted(self.default_weight_history.keys())[0]]
228 for date_key, default_weight in self.default_weight_history.items():
229 if date_key > f'{queried_date} 23:59:59':
235 def current_default_weight(self):
236 return self.default_weight_at(self.db.selected_date)
240 return self._last_of_history(self.title_history, '')
243 def title(self, title):
244 self._set_with_history(self.title_history, title)
246 def title_at(self, queried_date):
247 ret = self.title_history[sorted(self.title_history.keys())[0]]
248 for date_key, title in self.title_history.items():
249 if date_key > f'{queried_date} 23:59:59':
255 def current_title(self):
256 return self.title_at(self.db.selected_date)
260 return self._last_of_history(self.tags_history, set())
263 def tags(self, tags):
264 self._set_with_history(self.tags_history, set(tags))
267 # def tags_joined(self):
268 # return ';'.join(sorted(list(self.tags)))
270 # @tags_joined.setter
271 # def tags_joined(self, tags_string):
273 # for tag in [tag.strip() for tag in tags_string.split(';') if tag.strip() != '']:
279 'title_history': self.title_history,
280 'tags_history': {k: list(v) for k,v in self.tags_history.items()},
281 'default_weight_history': self.default_weight_history}
285 for k, v in self.db.tasks.items():
292 def __init__(self, db, todos=None, comment=''):
294 self.todos = todos if todos else {}
295 self.comment = comment
299 def from_dict(cls, db, d):
301 comment = d['comment'] if 'comment' in d.keys() else ''
302 day = cls(db, todos, comment)
303 for uuid, todo_dict in d['todos'].items():
304 day.add_todo(uuid, todo_dict)
308 d = {'comment': self.comment, 'todos': {}}
309 for task_uuid, todo in self.todos.items():
310 d['todos'][task_uuid] = todo.to_dict()
313 def add_todo(self, id_, dict_source=None):
314 self.todos[id_] = Todo.from_dict(self, dict_source) if dict_source else Todo(self)
315 return self.todos[id_]
317 def _todos_sum(self, include_undone=False):
319 for todo in [todo for todo in self.todos.values() if todo.done]:
322 for todo in [todo for todo in self.todos.values() if not todo.done]:
323 s += todo.day_weight if todo.day_weight else 0
328 return self._todos_sum()
331 def todos_sum2(self):
332 return self._todos_sum(True)
336 for k, v in self.db.days.items():
342 def __init__(self, day, done=False, day_weight=None, comment='', day_tags=None):
345 self.day_weight = day_weight
346 self.comment = comment
347 self.day_tags = day_tags if day_tags else set()
350 def from_dict(cls, day, d):
351 return cls(day, d['done'], d['day_weight'], d['comment'], set(d['day_tags']))
354 return {'done': self.done, 'day_weight': self.day_weight, 'comment': self.comment, 'day_tags': list(self.day_tags)}
357 def default_weight(self):
358 return self.task.default_weight_at(self.day.date)
363 return self.day_weight
365 return self.day_weight if self.day_weight else self.default_weight
369 for k, v in self.day.todos.items():
371 return self.day.db.tasks[k]
375 return self.task.title_at(self.day.date)
378 # def day_tags_joined(self):
379 # return ';'.join(sorted(list(self.day_tags)))
381 # @day_tags_joined.setter
382 # def day_tags_joined(self, tags_string):
384 # for tag in [tag.strip() for tag in tags_string.split(';') if tag.strip() != '']:
386 # self.day_tags = tags
390 return self.day_tags | self.task.tags
393 class TodoDB(PlomDB):
395 def __init__(self, prefix, selected_date=None, t_filter_and = None, t_filter_not = None, hide_unchosen=False, hide_done=False):
397 self.selected_date = selected_date if selected_date else str(datetime.now())[:10]
398 self.t_filter_and = t_filter_and if t_filter_and else []
399 self.t_filter_not = t_filter_not if t_filter_not else []
400 self.hide_unchosen = hide_unchosen
401 self.hide_done = hide_done
405 super().__init__(db_path)
407 def read_db_file(self, f):
409 for date, day_dict in d['days'].items():
410 self.days[date] = self.add_day(dict_source=day_dict)
411 for day in self.days.values():
412 for todo in day.todos.values():
413 for tag in todo.day_tags:
415 for uuid, t_dict in d['tasks'].items():
416 t = self.add_task(id_=uuid, dict_source=t_dict)
419 self.set_visibilities()
421 def set_visibilities(self):
422 for uuid, t in self.tasks.items():
423 t.visible = len([tag for tag in self.t_filter_and if not tag in t.tags]) == 0\
424 and len([tag for tag in self.t_filter_not if tag in t.tags]) == 0\
425 and ((not self.hide_unchosen) or uuid in self.selected_day.todos.keys())
426 for day in self.days.values():
427 for todo in day.todos.values():
428 todo.visible = len([tag for tag in self.t_filter_and if not tag in todo.day_tags | todo.task.tags ]) == 0\
429 and len([tag for tag in self.t_filter_not if tag in todo.day_tags | todo.task.tags ]) == 0\
430 and ((not self.hide_done) or (not todo.done))
434 't_filter_and': self.t_filter_and,
435 't_filter_not': self.t_filter_not,
439 for uuid, t in self.tasks.items():
440 d['tasks'][uuid] = t.to_dict()
441 for date, day in self.days.items():
442 d['days'][date] = day.to_dict()
446 def selected_day(self):
447 if not self.selected_date in self.days.keys():
448 self.days[self.selected_date] = self.add_day()
449 return self.days[self.selected_date]
451 def change_selected_days_date(self, new_date):
452 if new_date in self.days.keys():
453 raise PlomException('cannot use same date twice')
455 self.days[new_date] = self.selected_day
456 del self.days[self.selected_date]
457 self.selected_date = new_date
461 for date, day in self.days.items():
462 if len(day.todos) == 0 and len(day.comment) == 0:
463 dates_to_purge += [date]
464 for date in dates_to_purge:
466 self.write_text_to_db(json.dumps(self.to_dict()))
468 def add_task(self, id_=None, dict_source=None, return_id=False):
469 t = Task.from_dict(self, dict_source) if dict_source else Task(self)
470 id_ = id_ if id_ else str(uuid4())
477 def add_day(self, dict_source=None):
478 return Day.from_dict(self, dict_source) if dict_source else Day(self)
481 current_date = datetime.strptime(self.selected_date, DATE_FORMAT)
482 prev_date = current_date - timedelta(days=1)
483 prev_date_str = prev_date.strftime(DATE_FORMAT)
484 next_date = current_date + timedelta(days=1)
485 next_date_str = next_date.strftime(DATE_FORMAT)
486 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)
488 def show_calendar(self, start_date_str, end_date_str):
489 self.t_filter_and = ['calendar']
490 self.t_filter_not = ['deleted']
491 self.set_visibilities()
493 todays_date = str(datetime.now())[:10]
494 target_start_str = start_date_str if start_date_str else sorted(self.days.keys())[0]
495 target_start = todays_date if target_start_str == 'today' else target_start_str
496 target_end_str = end_date_str if end_date_str else sorted(self.days.keys())[-1]
497 target_end = todays_date if target_end_str == 'today' else target_end_str
498 start_date = datetime.strptime(target_start, DATE_FORMAT)
499 end_date = datetime.strptime(target_end, DATE_FORMAT)
500 for n in range(int((end_date - start_date).days) + 1):
501 current_date_obj = start_date + timedelta(n)
502 current_date = current_date_obj.strftime(DATE_FORMAT)
503 if current_date not in self.days.keys():
504 days_to_show[current_date] = self.add_day()
506 days_to_show[current_date] = self.days[current_date]
507 days_to_show[current_date].weekday = datetime.strptime(current_date, DATE_FORMAT).strftime('%A')[:2]
508 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)
510 def show_todo(self, task_uuid, selected_date):
511 todo = self.days[selected_date].todos[task_uuid]
512 return Template(form_header_tmpl + todo_tmpl + form_footer).render(db=self, todo=todo, action=self.prefix+'/todo')
514 def update_todo_mini(self, task_uuid, date, day_weight, done):
515 if task_uuid in self.days[date].todos.keys():
516 todo = self.days[date].todos[task_uuid]
518 todo = self.days[date].add_todo(task_uuid)
519 todo.day_weight = float(day_weight) if len(day_weight) > 0 else None
523 def update_todo(self, task_uuid, date, day_weight, done, comment, day_tags_joined, day_tags_checked):
524 todo = self.update_todo_mini(task_uuid, date, day_weight, done)
525 todo.comment = comment
527 for tag in [tag.strip() for tag in day_tags_joined.split(';') if tag.strip() != '']:
529 for tag in day_tags_checked:
531 todo.day_tags = day_tags
533 def show_task(self, id_):
534 task = self.tasks[id_] if id_ else self.add_task()
535 return Template(form_header_tmpl + task_tmpl + form_footer).render(db=self, task=task, action=self.prefix+'/task')
537 def update_task(self, id_, title, default_weight, tags_joined, tags_checked):
538 task = self.tasks[id_] if id_ in self.tasks.keys() else self.add_task(id_)
540 task.default_weight = float(default_weight) if len(default_weight) > 0 else None
542 for tag in [tag.strip() for tag in tags_joined.split(';') if tag.strip() != '']:
544 for tag in tags_checked:
548 def show_tasks(self):
549 return Template(form_header_tmpl + tag_filters_tmpl + tasks_tmpl + form_footer).render(db=self, action=self.prefix+'/tasks')
553 class TodoHandler(PlomHandler):
555 def config_init(self):
557 'cookie_name': 'todo_cookie',
562 def app_init(self, handler):
563 default_path = '/todo'
564 handler.add_route('GET', default_path, self.show_db)
565 handler.add_route('POST', default_path, self.write_db)
566 return 'todo', {'cookie_name': 'todo_cookie', 'prefix': default_path, 'cookie_path': default_path}
569 self.try_do(self.config_init)
570 self.try_do(self.write_db)
573 from urllib.parse import urlencode
574 app_config = self.apps['todo'] if hasattr(self, 'apps') else self.config()
575 length = int(self.headers['content-length'])
576 postvars = parse_qs(self.rfile.read(length).decode(), keep_blank_values=1)
577 parsed_url = urlparse(self.path)
578 db = TodoDB(prefix=app_config['prefix'])
580 if parsed_url.path == app_config['prefix'] + '/calendar':
581 start = postvars['start'][0] if len(postvars['start'][0]) > 0 else '-'
582 end = postvars['end'][0] if len(postvars['end'][0]) > 0 else '-'
583 homepage = f'{app_config["prefix"]}/calendar?start={start}&end={end}'
585 elif parsed_url.path == app_config['prefix'] + '/todo':
586 task_uuid = postvars['task_uuid'][0]
587 date = postvars['date'][0]
590 for k in postvars.keys():
591 if k.startswith(prefix):
592 tags_checked += [k[len(prefix):]]
593 db.update_todo(task_uuid, date, postvars['day_weight'][0], 'done' in postvars.keys(), postvars['comment'][0], postvars['day_tags_joined'][0], tags_checked)
594 homepage = f'{app_config["prefix"]}/todo?task={task_uuid}&date={date}'
596 elif parsed_url.path == app_config['prefix'] + '/task':
597 id_ = postvars['id'][0]
600 for k in postvars.keys():
601 if k.startswith(prefix):
602 tags_checked += [k[len(prefix):]]
603 db.update_task(id_, postvars['title'][0], postvars['default_weight'][0], postvars['tags_joined'][0], tags_checked)
604 homepage = f'{app_config["prefix"]}/task?id={id_}'
606 elif parsed_url.path in {app_config['prefix'] + '/tasks', app_config['prefix'] + '/day'}:
608 for target in postvars['t_and']:
609 if len(target) > 0 and not target in db.t_filter_and:
610 db.t_filter_and += [target]
611 if len(db.t_filter_and) == 0:
612 data += [('t_and', '-')]
613 for target in postvars['t_not']:
614 if len(target) > 0 and not target in db.t_filter_not:
615 db.t_filter_not += [target]
616 if len(db.t_filter_not) == 0:
617 data += [('t_not', '-')]
618 data += [('t_and', f) for f in db.t_filter_and] + [('t_not', f) for f in db.t_filter_not]
619 if parsed_url.path == app_config['prefix'] + '/tasks':
620 encoded_params = urlencode(data)
621 homepage = f'{app_config["prefix"]}/tasks?{encoded_params}'
623 elif parsed_url.path == app_config['prefix'] + '/day':
624 db.hide_unchosen = 'hide_unchosen' in postvars.keys()
625 db.hide_done = 'hide_done' in postvars.keys()
626 data += [('hide_unchosen', int(db.hide_unchosen))] + [('hide_done', int(db.hide_done))]
628 db.selected_date = postvars['original_selected_date'][0]
629 new_selected_date = postvars['new_selected_date'][0]
631 datetime.strptime(new_selected_date, DATE_FORMAT)
633 raise PlomException(f'{app_config["prefix"]} bad date string: {new_selected_date}')
634 if new_selected_date != db.selected_date:
635 db.change_selected_days_date(new_selected_date)
636 if 't_uuid' in postvars.keys():
637 for i, uuid in enumerate(postvars['t_uuid']):
639 if uuid in db.selected_day.todos.keys() and ((not 'choose' in postvars) or uuid not in postvars['choose']):
640 del db.selected_day.todos[uuid]
641 if 'choose' in postvars.keys():
642 for i, uuid in enumerate(postvars['t_uuid']):
643 if uuid in postvars['choose']:
644 done = 'done' in postvars and uuid in postvars['done']
645 db.update_todo_mini(uuid, db.selected_date, postvars['day_weight'][i], done)
646 if 'day_comment' in postvars.keys():
647 db.selected_day.comment = postvars['day_comment'][0]
648 data += [('selected_date', db.selected_date)]
649 encoded_params = urlencode(data)
650 homepage = f'{app_config["prefix"]}/day?{encoded_params}'
653 self.redirect(homepage)
656 self.try_do(self.config_init)
657 self.try_do(self.show_db)
660 app_config = self.apps['todo'] if hasattr(self, 'apps') else self.config()
661 cookie_db = self.get_cookie_db(app_config['cookie_name'])
662 parsed_url = urlparse(self.path)
663 params = parse_qs(parsed_url.query)
667 hide_unchosen = False
669 if parsed_url.path in {app_config['prefix'] + '/day', app_config['prefix'] + '/tasks'}:
670 selected_date = params.get('selected_date', [None])[0]
671 if selected_date is None and 'selected_date' in cookie_db.keys():
672 selected_date = cookie_db['selected_date']
673 cookie_db['selected_date'] = selected_date
674 t_filter_and = params.get('t_and', None)
675 if t_filter_and is None and 't_and' in cookie_db.keys():
676 t_filter_and = cookie_db['t_and']
677 elif t_filter_and == ['-']:
679 cookie_db['t_and'] = t_filter_and
680 t_filter_not = params.get('t_not', None)
681 if t_filter_not is None:
682 if 't_not' in cookie_db.keys():
683 t_filter_not = cookie_db['t_not']
685 t_filter_not = ['deleted']
686 elif t_filter_not == ['-']:
688 cookie_db['t_not'] = t_filter_not
689 if parsed_url.path == app_config['prefix'] + '/day':
690 hide_unchosen_params = params.get('hide_unchosen', [])
691 if 0 == len(hide_unchosen_params):
692 if 'hide_unchosen' in cookie_db.keys():
693 hide_unchosen = cookie_db['hide_unchosen']
695 hide_unchosen = hide_unchosen_params[0] != '0'
696 cookie_db['hide_unchosen'] = hide_unchosen
697 hide_done_params = params.get('hide_done', [])
698 if 0 == len(hide_done_params):
699 if 'hide_done' in cookie_db.keys():
700 hide_done = cookie_db['hide_done']
702 hide_done = hide_done_params[0] != '0'
703 cookie_db['hide_done'] = hide_done
704 db = TodoDB(app_config['prefix'], selected_date, t_filter_and, t_filter_not, hide_unchosen, hide_done)
705 if parsed_url.path == app_config['prefix'] + '/day':
707 elif parsed_url.path == app_config['prefix'] + '/todo':
708 todo_date = params.get('date', [None])[0]
709 task_uuid = params.get('task', [None])[0]
710 page = db.show_todo(task_uuid, todo_date)
711 elif parsed_url.path == app_config['prefix'] + '/task':
712 id_ = params.get('id', [None])[0]
713 page = db.show_task(id_)
714 elif parsed_url.path == app_config['prefix'] + '/tasks':
715 page = db.show_tasks()
716 elif parsed_url.path == app_config['prefix'] + '/add_task':
717 page = db.show_task(None)
718 elif parsed_url.path == app_config['prefix'] + '/unset_cookie':
719 page = 'no cookie to unset.'
720 if len(cookie_db) > 0:
721 self.unset_cookie(app_config['cookie_name'], app_config['cookie_path'])
722 page = 'cookie unset!'
724 start_date = params.get('start', [None])[0]
725 if start_date is None:
726 if 'calendar_start' in cookie_db.keys():
727 start_date = cookie_db['calendar_start']
730 elif start_date == '-':
732 cookie_db['calendar_start'] = start_date
733 end_date = params.get('end', [None])[0]
734 if end_date is None and 'calendar_end' in cookie_db.keys():
735 end_date = cookie_db['calendar_end']
736 elif end_date == '-':
738 cookie_db['calendar_end'] = end_date
739 page = db.show_calendar(start_date, end_date)
740 header = Template(html_head).render(db=db, prefix=app_config['prefix'], date=selected_date)
741 if parsed_url.path != app_config['prefix'] + '/unset_cookie':
742 self.set_cookie(app_config['cookie_name'], app_config['cookie_path'], cookie_db)
743 self.send_HTML(header + page)
746 if __name__ == "__main__":
747 run_server(server_port, TodoHandler)