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 Environment as JinjaEnv, FileSystemLoader as JinjaFSLoader
7 from urllib.parse import urlparse
8 from os.path import split as path_split
9 db_path = '/home/plom/org/todo_new.json'
11 DATE_FORMAT = '%Y-%m-%d'
12 j2env = JinjaEnv(loader=JinjaFSLoader('todo_templates'))
16 def today_date(with_time=False):
17 length = 19 if with_time else 10
18 return str(datetime.now())[:length]
22 class AttributeWithHistory:
24 def __init__(self, default_if_empty, history=None, then_date='2000-01-01', set_check=None, alt_get=None):
25 self.default = default_if_empty
26 self.then_date = then_date
27 self.history = history if history else {}
28 self.set_check = set_check
29 self.alt_get = alt_get
34 keys = sorted(self.history.keys())
35 if len(self.history) == 0 or value != self.history[keys[-1]]:
36 self.history[today_date(with_time=True)] = value
38 def at(self, queried_date):
40 ret = self.alt_get('at', queried_date)
43 if 0 == len(self.history):
45 ret = self.history[sorted(self.history.keys())[0]]
46 for date_key, item in self.history.items():
47 if date_key > f'{queried_date} 23:59:59':
55 ret = self.alt_get('now')
58 keys = sorted(self.history.keys())
59 return self.default if 0 == len(self.history) else self.history[keys[-1]]
64 ret = self.alt_get('then')
67 return self.at(self.then_date)
78 default_effort_history=None,
79 subtask_ids_history=None,
83 self.title = AttributeWithHistory('', title_history, self.db.selected_date)
84 self.tags = AttributeWithHistory(set(), tags_history, self.db.selected_date)
85 self.default_effort = AttributeWithHistory(0.0, default_effort_history, self.db.selected_date, alt_get=self.subtasks_sum_maker())
86 self.subtask_ids = AttributeWithHistory(set(), subtask_ids_history, self.db.selected_date, set_check=self.subtask_loop_checker())
87 self.comment = comment
92 def from_dict(cls, db, d, id_):
97 {k: set(v) for k, v in d['tags_history'].items()},
98 d['default_effort_history'],
99 {k: set(v) for k, v in d['subtasks_history'].items()},
105 'title_history': self.title.history,
106 'default_effort_history': self.default_effort.history,
107 'tags_history': {k: list(v) for k, v in self.tags.history.items()},
108 'subtasks_history': {k: list(v) for k, v in self.subtask_ids.history.items()},
109 'comment': self.comment,
115 for id_ in self.subtask_ids.now:
116 subtasks += [self.db.tasks[id_]]
119 def subtask_loop_checker(self):
120 def f(subtask_ids_now):
121 loop_msg = "can't set subtask, would create loop"
122 for id_ in subtask_ids_now:
124 raise PlomException(loop_msg)
125 elif id_ in self.db.tasks.keys():
126 subtask = self.db.tasks[id_]
127 f(subtask.subtask_ids.now)
130 def subtasks_sum_maker(self):
131 def f(f_name, queried_date=None):
132 subtask_ids_to_check = getattr(self.subtask_ids, f_name)
134 subtasks = [self.db.tasks[id_] for id_ in subtask_ids_to_check(queried_date)]
136 subtasks = [self.db.tasks[id_] for id_ in subtask_ids_to_check]
137 if len(self.subtasks) > 0:
139 for subtask in self.subtasks:
141 to_add = getattr(subtask.default_effort, f_name)
142 summe += to_add(queried_date)
144 summe += getattr(subtask.default_effort, f_name)
149 def matches(self, search):
153 return search in self.title.now or search in self.comment or search in '$'.join(self.tags.now)
158 def __init__(self, db, date, comment=''):
161 self.comment = comment
163 self.linked_todos_as_list = []
167 def from_dict(cls, db, d, date=None):
168 comment = d['comment'] if 'comment' in d.keys() else ''
169 day = cls(db, date, comment)
170 for id_ in d['linked_todos']:
171 day.linked_todos_as_list += [db.todos[id_]]
175 d = {'comment': self.comment, 'linked_todos': []}
176 for todo_id in self.linked_todos.keys():
177 d['linked_todos'] += [todo_id]
181 def linked_todos(self):
183 for todo in self.linked_todos_as_list:
184 linked_todos[todo.id_] = todo
187 def _todos_sum(self, include_undone=False):
189 for todo in [todo for todo in self.linked_todos.values()
190 if self.date in todo.efforts.keys()]:
191 day_effort = todo.efforts[self.date]
193 s += day_effort if day_effort else todo.task.default_effort.at(self.date)
195 s += day_effort if day_effort else 0
200 return self._todos_sum()
219 self._efforts = efforts if efforts else {}
220 self.comment = comment
221 self.day_tags = day_tags if day_tags else set()
222 self.importance = importance
223 self.child_ids = child_ids if child_ids else []
228 def from_dict(cls, db, d, id_):
243 'task': self.task.id_,
245 'comment': self.comment,
246 'day_tags': list(self.day_tags),
247 'importance': self.importance,
248 'efforts': self.efforts,
249 'children': self.child_ids}
253 return self.parents[0] if len(self.parents) > 0 else None
257 return self.task.title.at(self.earliest_date)
261 return [self.db.todos[id_] for id_ in self.child_ids]
264 def children(self, children):
265 self.child_ids = [child.id_ for child in children]
268 def default_effort(self):
269 return self.task.default_effort.at(self.earliest_date)
273 if len(self.children) > 0:
274 for child in self.children:
282 def done(self, doneness):
283 self._done = doneness
289 for date in self._efforts.keys():
291 for child in self.children:
293 for date, effort in child.efforts.items():
294 if not date in efforts.keys():
296 if effort is not None:
299 to_add = child.task.default_effort.at(date)
300 if to_add is not None:
301 if efforts[date] is not None:
302 efforts[date] += to_add
304 efforts[date] = to_add
310 def efforts(self, efforts_dict):
311 self._efforts = efforts_dict
314 def all_days_effort(self):
316 for effort in self.efforts.values():
317 total += effort if effort else 0
319 total = max(total, self.task.default_effort.at(self.latest_date))
322 def matches(self, search):
326 return search in self.comment or search in '$'.join(self.tags) or search in self.title
328 def is_effort_removable(self, date):
329 if not date in self.efforts.keys():
331 if self.efforts[date]:
333 if self.done and date == self.latest_date:
341 path = f'{self.parent.path}{self.parent.title}:'
346 return self.day_tags | self.task.tags.now
349 def day_effort(self):
350 return self.efforts[self.db.selected_date]
354 return self.db.days[self.earliest_date]
357 def sorted_effort_dates(self):
358 dates = list(self.efforts.keys())
363 def earliest_date(self):
364 return self.sorted_effort_dates[0]
367 def latest_date(self):
368 return self.sorted_effort_dates[-1]
371 class TodoDB(PlomDB):
381 self.selected_date = selected_date if selected_date else today_date()
382 self.t_filter_and = t_filter_and if t_filter_and else []
383 self.t_filter_not = t_filter_not if t_filter_not else []
384 self.hide_unchosen = hide_unchosen
385 self.hide_done = hide_done
391 super().__init__(db_path)
395 def read_db_file(self, f):
397 for id_, t_dict in d['tasks'].items():
398 t = self.add_task(id_=id_, dict_source=t_dict)
399 for tag in t.tags.now:
401 for id_, todo_dict in d['todos'].items():
402 todo = self.add_todo(todo_dict, id_)
403 self.todos[id_] = todo
404 for tag in todo.day_tags:
406 for date, day_dict in d['days'].items():
407 self.add_day(dict_source=day_dict, date=date)
408 for todo in self.todos.values():
409 for child in todo.children:
410 child.parents += [todo]
411 for date in todo.efforts.keys():
412 if not date in self.days.keys():
414 if not todo in self.days[date].linked_todos_as_list:
415 self.days[date].linked_todos_as_list += [todo]
416 self.set_visibilities()
419 d = {'tasks': {}, 'days': {}, 'todos': {}}
420 for uuid, t in self.tasks.items():
421 d['tasks'][uuid] = t.to_dict()
422 for date, day in self.days.items():
423 d['days'][date] = day.to_dict()
424 for todo in day.todos.values():
425 d['todos'][todo.id_] = todo.to_dict()
426 for id_, todo in self.todos.items():
427 d['todos'][id_] = todo.to_dict()
432 for date, day in self.days.items():
433 if len(day.linked_todos) == 0 and len(day.comment) == 0:
434 dates_to_purge += [date]
435 for date in dates_to_purge:
437 self.write_text_to_db(json.dumps(self.to_dict()))
442 def selected_day(self):
443 if not self.selected_date in self.days.keys():
444 self.days[self.selected_date] = self.add_day(date=self.selected_date)
445 return self.days[self.selected_date]
447 # table manipulations
449 def add_day(self, date, dict_source=None):
450 day = Day.from_dict(self, dict_source, date) if dict_source else Day(self, date)
451 self.days[date] = day
454 def add_task(self, id_=None, dict_source=None):
455 id_ = id_ if id_ else str(uuid4())
456 t = Task.from_dict(self, dict_source, id_) if dict_source else Task(self, id_)
460 def update_task(self, id_, title, default_effort, tags, subtask_ids, comment):
461 task = self.tasks[id_] if id_ in self.tasks.keys() else self.add_task(id_)
462 task.title.set(title)
463 task.default_effort.set(default_effort)
465 task.subtask_ids.set(subtask_ids)
466 task.comment = comment
468 def add_todo(self, todo_dict=None, id_=None, task=None, efforts=None):
469 id_ = id_ if id_ else str(uuid4())
471 todo = Todo.from_dict(self, todo_dict, id_)
472 elif task and efforts:
473 todo = Todo(self, id_, task, efforts=efforts)
475 for child_task in task.subtasks:
476 children += [self.add_todo(task=child_task, efforts=efforts)]
477 todo.child_ids = [child.id_ for child in children]
478 self.todos[id_] = todo
481 def _update_todo_shared(self, id_, done, comment, importance):
482 todo = self.todos[id_]
484 todo.comment = comment
485 todo.importance = importance
488 def update_todo_for_day(self, id_, date, effort, done, comment, importance):
489 todo = self._update_todo_shared(id_, done, comment, importance)
490 todo.efforts[date] = effort
492 def update_todo(self, id_, efforts, done, comment, tags, importance, children):
493 todo = self._update_todo_shared(id_, done, comment, importance)
494 if len(efforts) == 0 and not todo.children:
495 raise PlomException('todo must have at least one effort!')
496 todo.children = children
497 todo.efforts = efforts
498 for date in todo.efforts:
499 if not date in self.days.keys():
500 self.add_day(date=date)
501 if not self in self.days[date].linked_todos_as_list:
502 self.days[date].linked_todos_as_list += [todo]
505 def delete_todo(self, id_):
506 todo = self.todos[id_]
508 for date in todo.efforts.keys():
509 dates_to_delete += [date]
510 for date in dates_to_delete:
511 self.delete_effort(todo, date, force=True)
512 for parent in todo.parents:
513 parent.child_ids.remove(todo.id_)
516 def delete_effort(self, todo, date, force=False):
517 if (not force) and len(todo.efforts) == 1:
518 raise PlomException('todo must retain at least one effort!')
519 self.days[date].linked_todos_as_list.remove(todo)
520 del todo.efforts[date]
524 def show_calendar(self, start_date_str, end_date_str):
525 self.t_filter_and = ['calendar']
526 self.t_filter_not = ['deleted']
527 self.set_visibilities()
528 start_date_obj, end_date_obj = self.get_limit_days_from_date_strings(start_date_str, end_date_str)
530 for n in range(int((end_date_obj - start_date_obj).days) + 1):
531 date_obj = start_date_obj + timedelta(n)
532 date_str = date_obj.strftime(DATE_FORMAT)
533 if date_str not in self.days.keys():
534 days_to_show[date_str] = self.add_day(date_str)
536 days_to_show[date_str] = self.days[date_str]
537 days_to_show[date_str].month_title = date_obj.strftime('%B') if date_obj.day == 1 else None
538 days_to_show[date_str].weekday = datetime.strptime(date_str, DATE_FORMAT).strftime('%A')[:2]
540 return j2env.get_template('calendar.html').render(
541 selected_date=self.selected_date,
543 start_date=start_date_str,
544 end_date=end_date_str)
546 def show_do_todos(self, sort_order=None):
547 prev_date_str, next_date_str = self.neighbor_dates()
548 todos = [t for t in self.selected_day.linked_todos_as_list
551 if sort_order == 'title':
552 todos.sort(key=lambda t: t.task.title.then)
553 elif sort_order == 'done':
554 todos.sort(key=lambda t: t.day_effort if t.day_effort else t.default_effort if t.done else 0, reverse=True)
555 elif sort_order == 'default_effort':
556 todos.sort(key=lambda t: t.default_effort, reverse=True)
557 elif sort_order == 'importance':
558 todos.sort(key=lambda t: t.importance, reverse=True)
559 return j2env.get_template('do_todos.html').render(
560 day=self.selected_day,
562 filter_and=self.t_filter_and,
563 filter_not=self.t_filter_not,
564 prev_date=prev_date_str,
565 next_date=next_date_str,
568 hide_done=self.hide_done)
570 def show_todo(self, id_, return_to, search, start_date, end_date):
571 todo = self.todos[id_]
572 start_day, end_day = self.get_limit_days_from_date_strings(start_date, end_date)
573 if start_day < datetime.now() - timedelta(days=2):
574 end_day = start_day + timedelta(days=3)
575 end_date = end_day.strftime(DATE_FORMAT)
577 for n in range(int((end_day - start_day).days) + 1):
578 day = start_day + timedelta(n)
579 legal_dates += [day.strftime(DATE_FORMAT)]
580 filtered_todos = [t for t in self.todos.values()
583 and (len(search) == 0 or t.matches(search))]
584 date_filtered_todos = []
585 for date in legal_dates:
586 for filtered_todo in filtered_todos:
587 if filtered_todo in date_filtered_todos:
589 if date in filtered_todo.efforts.keys():
590 date_filtered_todos += [filtered_todo]
591 return j2env.get_template('todo.html').render(
592 filter_and=self.t_filter_and,
593 filter_not=self.t_filter_not,
596 filtered_todos=date_filtered_todos,
597 child_todos=todo.children,
599 start_date=start_date,
602 def show_task(self, id_, return_to='', search=''):
603 task = self.tasks[id_] if id_ else self.add_task()
604 selected = task.id_ in self.selected_day.todos.keys()
605 filtered_tasks = [t for t in self.tasks.values()
608 and (t not in task.subtasks)
609 and (len(search) == 0 or t.matches(search))]
610 return j2env.get_template('task.html').render(
613 filter_and=self.t_filter_and,
614 filter_not=self.t_filter_not,
615 filtered_tasks=filtered_tasks,
619 def show_tasks(self, expand_uuid):
622 for uuid in self.tasks[expand_uuid].subtask_ids.now:
623 expanded_tasks[uuid] = self.tasks[uuid]
624 return j2env.get_template('tasks.html').render(
626 filter_and=self.t_filter_and,
627 filter_not=self.t_filter_not,
628 expand_uuid=expand_uuid,
629 expanded_tasks=expanded_tasks)
631 def show_pick_tasks(self, search, hide_chosen_tasks, sort_order=None):
632 prev_date_str, next_date_str = self.neighbor_dates()
634 chosen_todos = self.selected_day.linked_todos_as_list
637 for todo in self.todos.values():
639 or (not todo.visible)\
640 or (not todo.matches(search))\
641 or todo.earliest_date >= self.selected_date:
643 relevant_todos += [todo]
646 chosen_tasks = [todo.task for todo in self.selected_day.linked_todos_as_list]
647 for uuid, task in self.tasks.items():
648 if (not task.visible)\
649 or (not task.matches(search))\
650 or (hide_chosen_tasks and task in chosen_tasks):
654 if sort_order == 'title':
655 chosen_todos.sort(key=lambda t: t.title)
656 relevant_todos.sort(key=lambda t: t.title)
657 tasks.sort(key=lambda t: t.title.then)
658 elif sort_order == 'effort':
659 chosen_todos.sort(key=lambda t:
660 t.day_effort if t.day_effort else (t.default_effort if t.done else 0),
662 relevant_todos.sort(key=lambda t: t.all_days_effort, reverse=True)
663 tasks.sort(key=lambda t: t.default_effort.then, reverse=True)
665 return j2env.get_template('pick_tasks.html').render(
668 chosen_todos=chosen_todos,
669 filter_and=self.t_filter_and,
670 filter_not=self.t_filter_not,
671 day=self.selected_day,
672 prev_date=prev_date_str,
673 next_date=next_date_str,
675 hide_chosen_tasks=hide_chosen_tasks,
676 relevant_todos=relevant_todos,
681 def set_visibilities(self):
682 for uuid, t in self.tasks.items():
683 t.visible = len([tag for tag in self.t_filter_and if not tag in t.tags.now]) == 0\
684 and len([tag for tag in self.t_filter_not if tag in t.tags.now]) == 0\
685 and ((not self.hide_unchosen) or uuid in self.selected_day.todos.keys())
686 for todo in self.todos.values():
687 todo.visible = len([tag for tag in self.t_filter_and if not tag in todo.day_tags | todo.task.tags.now ]) == 0\
688 and len([tag for tag in self.t_filter_not if tag in todo.day_tags | todo.task.tags.now ]) == 0\
689 and ((not self.hide_done) or (not todo.done))
691 def get_limit_days_from_date_strings(self, start_date_str, end_date_str):
692 todays_date_obj = datetime.strptime(today_date(), DATE_FORMAT)
693 yesterdays_date_obj = todays_date_obj - timedelta(1)
694 def get_day_limit_obj(index, day_limit_string):
695 date_obj = datetime.strptime(sorted(self.days.keys())[index], DATE_FORMAT)
696 if day_limit_string and len(day_limit_string) > 0:
697 if day_limit_string in {'today', 'yesterday'}:
698 date_obj = todays_date_obj if day_limit_string == 'today' else yesterdays_date_obj
700 date_obj = datetime.strptime(day_limit_string, DATE_FORMAT)
702 start_date_obj = get_day_limit_obj(0, start_date_str)
703 end_date_obj = get_day_limit_obj(-1, end_date_str)
704 return start_date_obj, end_date_obj
706 def neighbor_dates(self):
707 current_date = datetime.strptime(self.selected_date, DATE_FORMAT)
708 prev_date = current_date - timedelta(days=1)
709 prev_date_str = prev_date.strftime(DATE_FORMAT)
710 next_date = current_date + timedelta(days=1)
711 next_date_str = next_date.strftime(DATE_FORMAT)
712 return prev_date_str, next_date_str
718 def __init__(self, parsed_url_query, cookie_db):
719 self.params = parse_qs(parsed_url_query)
720 self.cookie_db = cookie_db
722 def get(self, key, default=None):
723 boolean = bool == type(default)
724 param = self.params.get(key, [default])[0]
729 def get_cookied(self, key, default=None):
730 param = self.get(key, default)
733 if key in self.cookie_db.keys():
734 del self.cookie_db[key]
735 if param is None and key in self.cookie_db.keys():
736 param = self.cookie_db[key]
737 if param is not None:
738 self.cookie_db[key] = param
741 def get_cookied_chain(self, key, default=None):
742 params = self.params.get(key, default)
745 if key in self.cookie_db.keys():
746 del self.cookie_db[key]
747 if params is None and key in self.cookie_db.keys():
748 params = self.cookie_db[key]
749 if params is not None:
750 self.cookie_db[key] = params
754 class PostvarsParser:
756 def __init__(self, postvars):
757 self.postvars = postvars
760 return key in self.postvars.keys()
762 def get(self, key, on_empty=None):
763 return self.get_at_index(key, 0, on_empty)
765 def get_at_index(self, key, i, on_empty=None):
766 if self.has(key) and len(self.postvars[key][i]) > 0:
767 return self.postvars[key][i]
770 def get_float_if_possible(self, key):
777 def get_all(self, key, on_empty=None):
778 if self.has(key) and len(self.postvars[key]) > 0:
779 return self.postvars[key]
782 def get_defined_tags(self, joined_key, key_prefix):
785 for k in self.postvars.keys():
786 if k.startswith(key_prefix):
787 tags_checked += [k[len(key_prefix):]]
788 tags_joined = self.get(joined_key, '')
789 for tag in [tag.strip() for tag in tags_joined.split(';') if tag.strip() != '']:
791 for tag in tags_checked:
795 def set(self, key, value):
796 self.postvars[key] = [value]
799 class TodoHandler(PlomHandler):
801 def config_init(self):
803 'cookie_name': 'todo_cookie',
808 def app_init(self, handler):
809 default_path = '/todo'
810 handler.add_route('GET', default_path, self.show_db)
811 handler.add_route('POST', default_path, self.write_db)
812 return 'todo', {'cookie_name': 'todo_cookie', 'prefix': default_path, 'cookie_path': default_path}
815 self.try_do(self.write_db)
818 from urllib.parse import urlencode
819 config = self.apps['todo'] if hasattr(self, 'apps') else self.config_init()
820 parsed_url = urlparse(self.path)
821 site = path_split(parsed_url.path)[1]
822 length = int(self.headers['content-length'])
823 postvars = PostvarsParser(parse_qs(self.rfile.read(length).decode(), keep_blank_values=1))
825 db = TodoDB(prefix=config['prefix'])
827 # if we do encounter a filter post, we repost it (and if empty, the emptying command '-')
828 for param_name, filter_db_name in {('t_and', 't_filter_and'), ('t_not', 't_filter_not')}:
829 filter_db = getattr(db, filter_db_name)
830 if postvars.has(param_name):
831 for target in postvars.get_all(param_name, []):
832 if len(target) > 0 and not target in filter_db:
833 filter_db += [target]
834 if len(filter_db) == 0:
835 redir_params += [(param_name, '-')]
836 redir_params += [(param_name, f) for f in filter_db]
837 if site in {'calendar', 'todo'}:
838 redir_params += [('end', postvars.get('end', '-'))]
839 redir_params += [('start', postvars.get('start', '-'))]
840 if site in {'todo', 'task', 'pick_tasks'}:
841 redir_params += [('search', postvars.get('search', ''))]
842 redir_params += [('search', postvars.get('search', ''))]
843 redir_params += [('search', postvars.get('search', ''))]
844 if postvars.has('filter'):
845 postvars.set('return_to', '')
848 todo_id = postvars.get('todo_id')
849 redir_params += [('id', todo_id)]
850 old_todo = db.todos[todo_id] if todo_id in db.todos.keys() else None
852 for i, date in enumerate(postvars.get_all('effort_date', [])):
856 datetime.strptime(date, DATE_FORMAT)
858 raise PlomException(f'bad date string')
860 if not (old_todo and old_todo.children):
861 efforts[date] = postvars.get_at_index('effort', i, None)
862 if postvars.has('delete'):
863 has_day_effort = len([e for e in efforts.values() if e is not None]) > 0
864 if postvars.has('done')\
865 or postvars.get('comment')\
866 or len(postvars.get_defined_tags('joined_day_tags', 'day_tag_')) > 0\
868 raise PlomException('will not remove todo of preserve-worthy values')
869 db.delete_todo(todo_id)
870 if not postvars.get('return_to'):
871 postvars.set('return_to', 'calendar')
872 elif postvars.has('update'):
873 if postvars.has('delete_effort'):
874 for date in postvars.get_all('delete_effort'):
875 db.delete_effort(old_todo, date)
877 children = [db.todos[id_] for id_ in postvars.get_all('adopt_child', [])]
878 db.update_todo(id_=todo_id,
880 done=postvars.has('done'),
881 comment=postvars.get('comment', ''),
882 tags=postvars.get_defined_tags('joined_day_tags', 'day_tag_'),
883 importance=float(postvars.get('importance')),
887 task_id = postvars.get('task_id')
888 if postvars.has('update'):
891 title=postvars.get('title', ''),
892 default_effort=postvars.get_float_if_possible('default_effort'),
893 tags=postvars.get_defined_tags('joined_tags', 'tag_'),
894 subtask_ids=postvars.get_all('subtask', []),
895 comment=postvars.get('comment', ''))
896 redir_params += [('id', task_id)]
898 elif 'pick_tasks' == site:
899 redir_params += [('hide_chosen_tasks', int(postvars.has('hide_chosen_tasks')))]
900 if postvars.has('update'):
901 db.selected_date = postvars.get('date')
904 for todo in db.selected_day.linked_todos_as_list:
905 if todo.visible and not todo.id_ in postvars.get_all('chosen_todo', []):
906 if len(todo.comment) > 0\
907 or len(todo.day_tags) > 0\
908 or not todo.is_effort_removable(db.selected_date):
909 raise PlomException('will not remove effort of preserve-worthy values')
910 if len(todo.efforts) > 1:
911 todos_to_shrink += [todo]
913 todos_to_delete += [todo]
914 for todo in todos_to_shrink:
915 db.delete_effort(todo, db.selected_date)
916 for todo in todos_to_delete:
917 db.delete_todo(todo.id_)
918 for id_ in postvars.get_all('choose_task', []):
919 db.add_todo(task=db.tasks[id_], efforts={db.selected_date: None})
920 for id_ in postvars.get_all('choose_todo', []):
921 db.todos[id_].efforts[db.selected_date] = None
923 elif 'do_todos' == site:
924 redir_params += [('hide_done', int(postvars.has('hide_done')))]
925 if postvars.has('update'):
926 db.selected_date = postvars.get('date')
927 redir_params += [('date', db.selected_date)]
928 db.selected_day.comment = postvars.get('day_comment', '')
929 for i, todo_id in enumerate(postvars.get_all('todo_id')):
930 old_todo = None if not todo_id in db.todos.keys() else db.todos[todo_id]
931 done = todo_id in postvars.get_all('done', [])
932 day_effort_input = postvars.get_at_index('effort', i, '')
933 day_effort = float(day_effort_input) if len(day_effort_input) > 0 else None
934 comment = postvars.get_at_index('effort_comment', i, '')
935 importance = float(postvars.get_at_index('importance', i))
937 and old_todo.done == done\
938 and old_todo.day_effort == day_effort\
939 and comment == old_todo.comment\
940 and old_todo.importance == importance:
942 db.update_todo_for_day(
950 homepage = postvars.get('return_to')
952 encoded_params = urlencode(redir_params)
953 homepage = f'{site}?{encoded_params}'
955 self.redirect(homepage)
958 self.try_do(self.show_db)
961 config = self.apps['todo'] if hasattr(self, 'apps') else self.config_init()
962 parsed_url = urlparse(self.path)
963 site = path_split(parsed_url.path)[1]
964 cookie_db = self.get_cookie_db(config['cookie_name'])
965 params = ParamsParser(parsed_url.query, cookie_db)
967 selected_date = t_filter_and = t_filter_not = None
968 hide_unchosen = hide_done = False
969 return_to = params.get('return_to', '')
970 if site in {'do_todos', 'pick_tasks', 'calendar'}:
971 selected_date = params.get_cookied('date')
972 if site in {'do_todos', 'pick_tasks', 'task', 'todo'}:
973 t_filter_and = params.get_cookied_chain('t_and')
974 t_filter_not = params.get_cookied_chain('t_not')
975 if 'do_todos' == site:
976 hide_done = params.get('hide_done', False)
977 db = TodoDB(config['prefix'], selected_date, t_filter_and, t_filter_not, hide_unchosen, hide_done)
978 if site in {'todo', 'task'}:
979 id_ = params.get('id')
980 if site in {'todo', 'task', 'pick_tasks'}:
981 search = params.get('search', '')
982 if site in {'do_todos', 'pick_tasks'}:
983 sort_order = params.get_cookied('sort')
984 if site in {'calendar', 'todo'}:
985 start_date = params.get_cookied('start')
986 end_date = params.get_cookied('end')
987 if 'do_todos' == site:
988 page = db.show_do_todos(sort_order)
989 elif 'pick_tasks' == site:
990 hide_chosen_tasks = params.get('hide_chosen_tasks', False)
991 page = db.show_pick_tasks(search, hide_chosen_tasks, sort_order)
993 page = db.show_todo(id_, return_to, search, start_date, end_date)
995 page = db.show_task(id_, return_to, search)
996 elif 'tasks' == site:
997 expand_uuid = params.get('expand_uuid')
998 page = db.show_tasks(expand_uuid)
999 elif 'add_task' == site:
1000 page = db.show_task(None)
1001 elif 'unset_cookie' == site:
1002 page = 'no cookie to unset.'
1003 if len(cookie_db) > 0:
1004 self.unset_cookie(config['cookie_name'], config['cookie_path'])
1005 page = 'cookie unset!'
1007 page = db.show_calendar(start_date, end_date)
1009 if 'unset_cookie' != site:
1010 self.set_cookie(config['cookie_name'], config['cookie_path'], cookie_db)
1011 self.send_HTML(page)
1014 if __name__ == "__main__":
1015 run_server(server_port, TodoHandler)