X-Git-Url: https://plomlompom.com/repos/new_day?a=blobdiff_plain;f=todo.py;h=11b0149028966effd5f551d1fbc0f36819838faf;hb=38b9ce0ba2b5af072554999bc5836ffe455f06db;hp=08fb8b82f6e3921ce6d75c3e86428d31c6398902;hpb=2960beb644986049fd975eac8e348ca61ab122b8;p=misc diff --git a/todo.py b/todo.py index 08fb8b8..11b0149 100644 --- a/todo.py +++ b/todo.py @@ -1,314 +1,1049 @@ -from plomlib import PlomDB, run_server, PlomHandler, PlomException +from plomlib import PlomDB, run_server, PlomHandler, PlomException import json from uuid import uuid4 -from datetime import datetime +from datetime import datetime, timedelta from urllib.parse import parse_qs +from jinja2 import Environment as JinjaEnv, FileSystemLoader as JinjaFSLoader +from urllib.parse import urlparse +from os.path import split as path_split db_path = '/home/plom/org/todo_new.json' -# db_path = '/home/plom/public_repos/misc/todo_new.json' server_port = 8082 +DATE_FORMAT = '%Y-%m-%d' +j2env = JinjaEnv(loader=JinjaFSLoader('todo_templates')) -tmpl = """ - -
- -""" -class Task: - def __init__(self, title_history={}, tags_history={}, default_weight_history={}): - self.title_history = title_history.copy() - self.tags_history = tags_history.copy() - self.default_weight_history = default_weight_history.copy() - self.visible = True +def today_date(with_time=False): + length = 19 if with_time else 10 + return str(datetime.now())[:length] - def _set_with_history(self, history, value): - keys = sorted(history.keys()) - if len(history) == 0 or value != history[keys[-1]]: - history[str(datetime.now())[:19]] = value - def _last_of_history(self, history, default): - keys = sorted(history.keys()) - return default if 0 == len(history) else history[keys[-1]] - @classmethod - def from_dict(cls, d): - return cls( - d['title_history'], - {k: set(v) for k, v in d['tags_history'].items()}, - d['default_weight_history']) - - def tags_from_joined_string(self, tags_string): - tags = set() - for tag in [tag.strip() for tag in tags_string.split(';') if tag.strip() != '']: - tags.add(tag) - self.set_tags(tags) +class AttributeWithHistory: - @property - def tags_joined(self): - return ';'.join(sorted(list(self.tags))) + def __init__(self, default_if_empty, history=None, then_date='2000-01-01', set_check=None, alt_get=None): + self.default = default_if_empty + self.then_date = then_date + self.history = history if history else {} + self.set_check = set_check + self.alt_get = alt_get - def set_default_weight(self, default_weight): - self._set_with_history(self.default_weight_history, default_weight) + def set(self, value): + if self.set_check: + self.set_check(value) + keys = sorted(self.history.keys()) + if len(self.history) == 0 or value != self.history[keys[-1]]: + self.history[today_date(with_time=True)] = value - @property - def default_weight(self): - return self._last_of_history(self.default_weight_history, 1) + def at(self, queried_date): + if self.alt_get: + ret = self.alt_get('at', queried_date) + if ret is not None: + return ret + if 0 == len(self.history): + return self.default + ret = self.history[sorted(self.history.keys())[0]] + for date_key, item in self.history.items(): + if date_key > f'{queried_date} 23:59:59': + break + ret = item + return ret - def set_title(self, title): - self._set_with_history(self.title_history, title) + @property + def now(self): + if self.alt_get: + ret = self.alt_get('now') + if ret is not None: + return ret + keys = sorted(self.history.keys()) + return self.default if 0 == len(self.history) else self.history[keys[-1]] @property - def title(self): - return self._last_of_history(self.title_history, '') + def then(self): + if self.alt_get: + ret = self.alt_get('then') + if ret is not None: + return ret + return self.at(self.then_date) - def set_tags(self, tags): - self._set_with_history(self.tags_history, set(tags)) - @property - def tags(self): - return self._last_of_history(self.tags_history, set()) + +class Task: + + def __init__(self, + db, + id_, + title_history=None, + tags_history=None, + default_effort_history=None, + subtask_ids_history=None, + comment=''): + self.db = db + self.id_ = id_ + self.title = AttributeWithHistory('', title_history, self.db.selected_date) + self.tags = AttributeWithHistory(set(), tags_history, self.db.selected_date) + self.default_effort = AttributeWithHistory(0.0, default_effort_history, self.db.selected_date, alt_get=self.subtasks_sum_maker()) + self.subtask_ids = AttributeWithHistory(set(), subtask_ids_history, self.db.selected_date, set_check=self.subtask_loop_checker()) + self.comment = comment + + self.visible = True + self.parents = [] + + @classmethod + def from_dict(cls, db, d, id_): + t = cls( + db, + id_, + d['title_history'], + {k: set(v) for k, v in d['tags_history'].items()}, + d['default_effort_history'], + {k: set(v) for k, v in d['subtasks_history'].items()}, + d['comment']) + return t def to_dict(self): return { - 'title_history': self.title_history, - 'tags_history': {k: list(v) for k,v in self.tags_history.items()}, - 'default_weight_history': self.default_weight_history} + 'title_history': self.title.history, + 'default_effort_history': self.default_effort.history, + 'tags_history': {k: list(v) for k, v in self.tags.history.items()}, + 'subtasks_history': {k: list(v) for k, v in self.subtask_ids.history.items()}, + 'comment': self.comment, + } + + @property + def subtasks(self): + subtasks = [] + for id_ in self.subtask_ids.now: + if len(id_) == 0: + continue + subtasks += [self.db.tasks[id_]] + return subtasks + + def subtask_loop_checker(self): + def f(subtask_ids_now): + loop_msg = "can't set subtask, would create loop" + for id_ in subtask_ids_now: + if id_ == self.id_: + raise PlomException(loop_msg) + elif id_ in self.db.tasks.keys(): + subtask = self.db.tasks[id_] + f(subtask.subtask_ids.now) + return f + + def subtasks_sum_maker(self): + def f(f_name, queried_date=None): + subtask_ids_to_check = getattr(self.subtask_ids, f_name) + if queried_date: + subtasks = [self.db.tasks[id_] for id_ in subtask_ids_to_check(queried_date)] + else: + subtasks = [self.db.tasks[id_] for id_ in subtask_ids_to_check] + if len(self.subtasks) > 0: + summe = 0 + for subtask in self.subtasks: + if queried_date: + to_add = getattr(subtask.default_effort, f_name) + summe += to_add(queried_date) + else: + summe += getattr(subtask.default_effort, f_name) + return summe + return None + return f + + def matches(self, search): + if search is None: + return False + else: + return search in self.title.now or search in self.comment or search in '$'.join(self.tags.now) class Day: - def __init__(self, todos, comment=''): - self.todos = todos + def __init__(self, db, date, comment=''): + self.date = date + self.db = db self.comment = comment + self.linked_todos_as_list = [] @classmethod - def from_dict(cls, d): - todos = {} + def from_dict(cls, db, d, date=None): comment = d['comment'] if 'comment' in d.keys() else '' - for uuid, todo_dict in d['todos'].items(): - todos[uuid] = Todo.from_dict(todo_dict) - return cls(todos, comment) + day = cls(db, date, comment) + return day + + def to_dict(self): + d = {'comment': self.comment} + return d @property - def todos_sum(self): + def linked_todos(self): + linked_todos = {} + for todo in self.linked_todos_as_list: + linked_todos[todo.id_] = todo + return linked_todos + + def _todos_sum(self, include_undone=False): s = 0 - for todo in [todo for todo in self.todos.values() if (todo.done or todo.day_weight)]: - s += todo.weight + for todo in [todo for todo in self.linked_todos.values() + if self.date in todo.efforts.keys()]: + day_effort = todo.efforts[self.date] + if todo.done: + s += day_effort if day_effort else todo.task.default_effort.at(self.date) + elif include_undone: + s += day_effort if day_effort else 0 return s - def to_dict(self): - d = {'comment': self.comment, 'todos': {}} - for task_uuid, todo in self.todos.items(): - d['todos'][task_uuid] = todo.to_dict() - return d + @property + def todos_sum(self): + return self._todos_sum() class Todo: - def __init__(self, done=False, day_weight=None): - self.done = done - self.day_weight = day_weight + def __init__(self, + db, + id_, + task, + done=False, + comment='', + day_tags=None, + importance=1.0, + efforts=None, + child_ids=None): + self.id_ = id_ + self.db = db + self.task = task + self._done = done + self._efforts = efforts if efforts else {} + self.comment = comment + self.day_tags = day_tags if day_tags else set() + self.importance = importance + self.child_ids = child_ids if child_ids else [] + + self.parents = [] @classmethod - def from_dict(cls, d): - return cls(d['done'], d['day_weight']) + def from_dict(cls, db, d, id_): + todo = cls( + db, + id_, + db.tasks[d['task']], + d['done'], + d['comment'], + set(d['day_tags']), + d['importance'], + d['efforts'], + d['children']) + return todo def to_dict(self): - return {'done': self.done, 'day_weight': self.day_weight} + return { + 'task': self.task.id_, + 'done': self.done, + 'comment': self.comment, + 'day_tags': list(self.day_tags), + 'importance': self.importance, + 'efforts': self.efforts, + 'children': self.child_ids} + + @property + def parent(self): + return self.parents[0] if len(self.parents) > 0 else None + + @property + def title(self): + return self.task.title.at(self.earliest_date) + + @property + def dated_title(self): + return f'{self.earliest_date}:{self.title}' + + @property + def children(self): + return [self.db.todos[id_] for id_ in self.child_ids] + + @children.setter + def children(self, children): + self.child_ids = [child.id_ for child in children] + + @property + def default_effort(self): + return self.task.default_effort.at(self.earliest_date) + + @property + def done(self): + if len(self.children) > 0: + for child in self.children: + if not child.done: + return False + return True + else: + return self._done + + @done.setter + def done(self, doneness): + self._done = doneness + + @property + def efforts(self): + if self.children: + efforts = {} + for date in self._efforts.keys(): + efforts[date] = None + for child in self.children: + to_add = None + for date, effort in child.efforts.items(): + if not date in efforts.keys(): + efforts[date] = None + if effort is not None: + to_add = effort / len(child.parents) + elif child.done: + to_add = child.task.default_effort.at(date) / len(child.parents) + if to_add is not None: + if efforts[date] is not None: + efforts[date] += to_add + else: + efforts[date] = to_add + return efforts + else: + return self._efforts + + @efforts.setter + def efforts(self, efforts_dict): + self._efforts = efforts_dict + + @property + def all_days_effort(self): + total = 0 + for effort in self.efforts.values(): + total += effort if effort else 0 + if self.done: + total = max(total, self.task.default_effort.at(self.latest_date)) + return total + + def matches(self, search): + if search is None: + return False + else: + return search in self.comment or search in '$'.join(self.tags) or search in self.title + + def is_effort_removable(self, date): + if not date in self.efforts.keys(): + return False + if self.efforts[date]: + return False + if self.done and date == self.latest_date: + return False + return True + + @property + def tags(self): + return self.day_tags | self.task.tags.now + + @property + def day_effort(self): + return self.efforts[self.db.selected_date] + + @property + def day(self): + return self.db.days[self.earliest_date] + + @property + def sorted_effort_dates(self): + dates = list(self.efforts.keys()) + dates.sort() + return dates + + @property + def earliest_date(self): + return self.sorted_effort_dates[0] + + @property + def latest_date(self): + return self.sorted_effort_dates[-1] class TodoDB(PlomDB): - def __init__(self, t_filter_and = set(), t_filter_not = set()): - self.t_filter_and = t_filter_and - self.t_filter_not = t_filter_not - self.old_days = {} + def __init__(self, + selected_date=None, + tag_filter_and = None, + tag_filter_not = None, + hide_unchosen=False, + hide_done=False): + self.selected_date = selected_date if selected_date else today_date() + self.tag_filter_and = tag_filter_and if tag_filter_and else [] + self.tag_filter_not = tag_filter_not if tag_filter_not else [] + self.hide_unchosen = hide_unchosen + self.hide_done = hide_done + + self.days = {} self.tasks = {} - self.reset_today() - self.t_tags = set() + self.t_tags = set() + self.todos = {} super().__init__(db_path) + # savefile I/O + def read_db_file(self, f): d = json.load(f) - self.today = Day.from_dict(d['today']) - self.today_date = d['today_date'] - for uuid, t_dict in d['tasks'].items(): - t = Task.from_dict(t_dict) - self.tasks[uuid] = t - t.visible = len([tag for tag in self.t_filter_and if not tag in t.tags]) == 0\ - and len([tag for tag in self.t_filter_not if tag in t.tags]) == 0 - for tag in t.tags: + + for id_, t_dict in d['tasks'].items(): + t = self.add_task(id_=id_, dict_source=t_dict) + for tag in t.tags.now: self.t_tags.add(tag) - for date, day_dict in d['old_days'].items(): - self.old_days[date] = Day.from_dict(day_dict) + for task in self.tasks.values(): + for child in task.subtasks: + child.parents += [task] + + for id_, todo_dict in d['todos'].items(): + todo = self.add_todo(todo_dict, id_, link_into_day=False) + for tag in todo.day_tags: + self.t_tags.add(tag) + for todo in self.todos.values(): + for child in todo.children: + child.parents += [todo] + + for date, day_dict in d['days'].items(): + self.add_day(dict_source=day_dict, date=date) + for todo in self.todos.values(): + for date in todo.efforts.keys(): + if not date in self.days.keys(): + self.add_day(date) + # if not todo in self.days[date].linked_todos_as_list: + # self.days[date].linked_todos_as_list += [todo] + self.days[date].linked_todos_as_list += [todo] + + self.set_visibilities() def to_dict(self): - d = { - 'today': self.today.to_dict(), - 'today_date': self.today_date, - 't_filter_and': list(self.t_filter_and), - 't_filter_not': list(self.t_filter_not), - 'tasks': {}, - 'old_days': {} - } + d = {'tasks': {}, 'days': {}, 'todos': {}} for uuid, t in self.tasks.items(): d['tasks'][uuid] = t.to_dict() - for date, day in self.old_days.items(): - d['old_days'][date] = day.to_dict() + for date, day in self.days.items(): + d['days'][date] = day.to_dict() + for id_, todo in self.todos.items(): + d['todos'][id_] = todo.to_dict() return d def write(self): + dates_to_purge = [] + for date, day in self.days.items(): + if len(day.linked_todos) == 0 and len(day.comment) == 0: + dates_to_purge += [date] + for date in dates_to_purge: + del self.days[date] self.write_text_to_db(json.dumps(self.to_dict())) - def reset_today(self, date=None): - if date: - self.today_date = date - self.today = self.old_days[date] - del self.old_days[date] + # properties + + @property + def selected_day(self): + if not self.selected_date in self.days.keys(): + self.days[self.selected_date] = self.add_day(date=self.selected_date) + return self.days[self.selected_date] + + # table manipulations + + def add_day(self, date, dict_source=None): + day = Day.from_dict(self, dict_source, date) if dict_source else Day(self, date) + self.days[date] = day + return day + + def add_task(self, id_=None, dict_source=None): + id_ = id_ if id_ else str(uuid4()) + t = Task.from_dict(self, dict_source, id_) if dict_source else Task(self, id_) + self.tasks[id_] = t + return t + + def update_task(self, id_, title, default_effort, tags, subtask_ids, comment): + task = self.tasks[id_] if id_ in self.tasks.keys() else self.add_task(id_) + task.title.set(title) + task.default_effort.set(default_effort) + task.tags.set(tags) + task.subtask_ids.set(subtask_ids) + task.comment = comment + return task + + def add_todo(self, todo_dict=None, id_=None, task=None, efforts=None, link_into_day=True): + id_ = id_ if id_ else str(uuid4()) + if todo_dict: + todo = Todo.from_dict(self, todo_dict, id_) + elif task and efforts: + todo = Todo(self, id_, task, efforts=efforts) + children = [] + for child_task in task.subtasks: + # if Todo expects chuldren, adopt any compatibles found in DB.selected_date + # before creating new child Todos + child_todo = None + if list(efforts.keys())[0] == self.selected_date: + adoptable_todos = [t for t in self.selected_day.linked_todos_as_list + if t.task.id_ == child_task.id_] + if len(adoptable_todos) > 0: + child_todo = adoptable_todos[0] + if not child_todo: + child_todo = self.add_todo(task=child_task, + efforts=efforts, link_into_day=link_into_day) + children += [child_todo] + todo.child_ids = [child.id_ for child in children] + self.todos[id_] = todo + if link_into_day: + self.selected_day.linked_todos_as_list += [todo] + return todo + + def _update_todo_shared(self, id_, done, comment, importance): + todo = self.todos[id_] + todo.done = done + todo.comment = comment + todo.importance = importance + return todo + + def update_todo_for_day(self, id_, date, effort, done, comment, importance): + todo = self._update_todo_shared(id_, done, comment, importance) + todo.efforts[date] = effort + + def update_todo(self, id_, efforts, done, comment, tags, importance, children): + todo = self._update_todo_shared(id_, done, comment, importance) + if len(efforts) == 0 and not todo.children: + raise PlomException('todo must have at least one effort!') + todo.children = children + todo.efforts = efforts + for date in todo.efforts.keys(): + if not date in self.days.keys(): + self.add_day(date=date) + if not self in self.days[date].linked_todos_as_list: + self.days[date].linked_todos_as_list += [todo] + todo.day_tags = tags + + def delete_todo(self, id_): + todo = self.todos[id_] + dates_to_delete = [] + for date in todo.efforts.keys(): + dates_to_delete += [date] + for date in dates_to_delete: + self.delete_effort(todo, date, force=True) + for parent in todo.parents: + parent.child_ids.remove(todo.id_) + del self.todos[id_] + + def delete_task(self, id_): + del self.tasks[id_] + + def delete_effort(self, todo, date, force=False): + if (not force) and len(todo.efforts) == 1: + raise PlomException('todo must retain at least one effort!') + self.days[date].linked_todos_as_list.remove(todo) + del todo.efforts[date] + + # views + + def show_message(self, message): + return j2env.get_template('message.html').render(message=message) + + def show_calendar(self, start_date_str, end_date_str): + self.tag_filter_and = ['calendar'] + self.tag_filter_not = ['deleted'] + self.set_visibilities() + start_date_obj, end_date_obj = self.get_limit_days_from_date_strings(start_date_str, end_date_str) + days_to_show = {} + for n in range(int((end_date_obj - start_date_obj).days) + 1): + date_obj = start_date_obj + timedelta(n) + date_str = date_obj.strftime(DATE_FORMAT) + if date_str not in self.days.keys(): + days_to_show[date_str] = self.add_day(date_str) + else: + days_to_show[date_str] = self.days[date_str] + days_to_show[date_str].month_title = date_obj.strftime('%B') if date_obj.day == 1 else None + days_to_show[date_str].weekday = datetime.strptime(date_str, DATE_FORMAT).strftime('%A')[:2] + + return j2env.get_template('calendar.html').render( + selected_date=self.selected_date, + days=days_to_show, + start_date=start_date_str, + end_date=end_date_str) + + def show_do_todos(self, sort_order=None): + prev_date_str, next_date_str = self.neighbor_dates() + todos = [t for t in self.selected_day.linked_todos_as_list + if t.visible + and not t.children] + if sort_order == 'title': + todos.sort(key=lambda t: t.task.title.then) + elif sort_order == 'done': + todos.sort(key=lambda t: t.day_effort if t.day_effort else t.default_effort if t.done else 0, reverse=True) + elif sort_order == 'default_effort': + todos.sort(key=lambda t: t.default_effort, reverse=True) + elif sort_order == 'importance': + todos.sort(key=lambda t: t.importance, reverse=True) + return j2env.get_template('do_todos.html').render( + day=self.selected_day, + tags=self.t_tags, + filter_and=self.tag_filter_and, + filter_not=self.tag_filter_not, + prev_date=prev_date_str, + next_date=next_date_str, + todos=todos, + sort=sort_order, + hide_done=self.hide_done) + + def show_todo(self, id_, search, start_date, end_date): + todo = self.todos[id_] + filtered_tasks = [t for t in self.tasks.values() + if t != todo.task] + filtered_todos = [t for t in self.todos.values() + if t != todo] + + # if going into the past, only allow 3-day ranges + start_day, end_day = self.get_limit_days_from_date_strings(start_date, end_date) + if start_day < datetime.now() - timedelta(days=2): + end_day = start_day + timedelta(days=3) + end_date = end_day.strftime(DATE_FORMAT) + legal_dates = [] + for n in range(int((end_day - start_day).days) + 1): + day = start_day + timedelta(n) + legal_dates += [day.strftime(DATE_FORMAT)] + date_filtered_todos = [] + for date in legal_dates: + for filtered_todo in filtered_todos: + if filtered_todo in date_filtered_todos: + continue + if date in filtered_todo.efforts.keys(): + date_filtered_todos += [filtered_todo] + + return j2env.get_template('todo.html').render( + tags=self.t_tags, + todo=todo, + filtered_todos=date_filtered_todos, + filtered_tasks=filtered_tasks, + child_todos=todo.children, + start_date=start_date, + end_date=end_date) + + def show_task(self, id_): + task = self.tasks[id_] if id_ else self.add_task() + if not id_: + task.default_effort.set(1.0) + filtered_tasks = [t for t in self.tasks.values() + if t != task + and (t not in task.subtasks)] + return j2env.get_template('task.html').render( + selected_date=self.selected_date, + tags=self.t_tags, + filtered_tasks=filtered_tasks, + task=task) + + def show_tasks(self, expand_uuid): + expanded_tasks = {} + if expand_uuid: + for uuid in self.tasks[expand_uuid].subtask_ids.now: + expanded_tasks[uuid] = self.tasks[uuid] + return j2env.get_template('tasks.html').render( + db=self, + filter_and=self.tag_filter_and, + filter_not=self.tag_filter_not, + expand_uuid=expand_uuid, + expanded_tasks=expanded_tasks) + + def show_pick_tasks(self, search, hide_chosen_tasks, sort_order=None): + prev_date_str, next_date_str = self.neighbor_dates() + + chosen_todos = self.selected_day.linked_todos_as_list + + relevant_todos = [] + for todo in self.todos.values(): + if todo.done\ + or (not todo.visible)\ + or (not todo.matches(search))\ + or todo.earliest_date >= self.selected_date: + continue + relevant_todos += [todo] + + filtered_tasks = [] + chosen_tasks = [todo.task for todo in self.selected_day.linked_todos_as_list] + for uuid, task in self.tasks.items(): + if (not task.visible)\ + or (not task.matches(search))\ + or (hide_chosen_tasks and task in chosen_tasks): + continue + filtered_tasks += [task] + + if sort_order == 'title': + chosen_todos.sort(key=lambda t: t.title) + relevant_todos.sort(key=lambda t: t.dated_title) + tasks.sort(key=lambda t: t.title.then) + elif sort_order == 'effort': + chosen_todos.sort(key=lambda t: + t.day_effort if t.day_effort else (t.default_effort if t.done else 0), + reverse=True) + relevant_todos.sort(key=lambda t: t.all_days_effort, reverse=True) + filtered_tasks.sort(key=lambda t: t.default_effort.then, reverse=True) + + return j2env.get_template('pick_tasks.html').render( + sort=sort_order, + tags=self.t_tags, + chosen_todos=chosen_todos, + filter_and=self.tag_filter_and, + filter_not=self.tag_filter_not, + day=self.selected_day, + prev_date=prev_date_str, + next_date=next_date_str, + all_tasks=[t for t in self.tasks.values()], + filtered_tasks=filtered_tasks, + hide_chosen_tasks=hide_chosen_tasks, + relevant_todos=relevant_todos, + search=search) + + # helpers + + def set_visibilities(self): + for uuid, t in self.tasks.items(): + t.visible = len([tag for tag in self.tag_filter_and if not tag in t.tags.now]) == 0\ + and len([tag for tag in self.tag_filter_not if tag in t.tags.now]) == 0\ + and ((not self.hide_unchosen) or uuid in self.selected_day.todos.keys()) + for todo in self.todos.values(): + todo.visible = len([tag for tag in self.tag_filter_and if not tag in todo.day_tags | todo.task.tags.now ]) == 0\ + and len([tag for tag in self.tag_filter_not if tag in todo.day_tags | todo.task.tags.now ]) == 0\ + and ((not self.hide_done) or (not todo.done)) + + def get_limit_days_from_date_strings(self, start_date_str, end_date_str): + todays_date_obj = datetime.strptime(today_date(), DATE_FORMAT) + yesterdays_date_obj = todays_date_obj - timedelta(1) + def get_day_limit_obj(index, day_limit_string): + date_obj = datetime.strptime(sorted(self.days.keys())[index], DATE_FORMAT) + if day_limit_string and len(day_limit_string) > 0: + if day_limit_string in {'today', 'yesterday'}: + date_obj = todays_date_obj if day_limit_string == 'today' else yesterdays_date_obj + else: + date_obj = datetime.strptime(day_limit_string, DATE_FORMAT) + return date_obj + start_date_obj = get_day_limit_obj(0, start_date_str) + end_date_obj = get_day_limit_obj(-1, end_date_str) + return start_date_obj, end_date_obj + + def neighbor_dates(self): + current_date = datetime.strptime(self.selected_date, DATE_FORMAT) + prev_date = current_date - timedelta(days=1) + prev_date_str = prev_date.strftime(DATE_FORMAT) + next_date = current_date + timedelta(days=1) + next_date_str = next_date.strftime(DATE_FORMAT) + return prev_date_str, next_date_str + + + +class ParamsParser: + + def __init__(self, parsed_url_query, cookie_db): + self.params = parse_qs(parsed_url_query) + self.cookie_db = cookie_db + + def get(self, key, default=None): + boolean = bool == type(default) + param = self.params.get(key, [default])[0] + if boolean: + param = param != '0' + return param + + def cookie_key_from_params_key(self, prefix, key): + return f'{prefix}:{key}' if prefix else key + + def get_cookied(self, key, default=None, prefix=None): + cookie_key = self.cookie_key_from_params_key(prefix, key) + param = self.get(key, default) + if param == '-': + param = None + if cookie_key in self.cookie_db.keys(): + del self.cookie_db[cookie_key] + if param is None and cookie_key in self.cookie_db.keys(): + param = self.cookie_db[cookie_key] + if param is not None: + self.cookie_db[cookie_key] = param + return param + + def get_cookied_chain(self, key, default=None, prefix=None): + cookie_key = self.cookie_key_from_params_key(prefix, key) + params = self.params.get(key, default) + if params == ['-']: + params = None + if cookie_key in self.cookie_db.keys(): + del self.cookie_db[cookie_key] + if params is None and cookie_key in self.cookie_db.keys(): + params = self.cookie_db[cookie_key] + if params is not None: + self.cookie_db[cookie_key] = params + return params + + +class PostvarsParser: + + def __init__(self, postvars): + self.postvars = postvars + + def has(self, key): + return key in self.postvars.keys() + + def get(self, key, on_empty=None, float_if_possible=False): + return self.get_at_index(key, 0, on_empty, float_if_possible) + + def get_at_index(self, key, i, on_empty=None, float_if_possible=False): + if self.has(key) and len(self.postvars[key][i]) > 0: + val = self.postvars[key][i] else: - self.today_date = str(datetime.now())[:10] - self.today = Day({}) + val = on_empty + if float_if_possible and val is not None: + return float(val) + else: + return val + + def get_all(self, key, on_empty=None): + if self.has(key) and len(self.postvars[key]) > 0: + return [v for v in self.postvars[key] if len(v) > 0] + return on_empty + + def set(self, key, value): + self.postvars[key] = [value] class TodoHandler(PlomHandler): - + + def config_init(self): + return { + 'cookie_name': 'todo_cookie', + 'cookie_path': '/' + } + def app_init(self, handler): default_path = '/todo' - handler.add_route('GET', default_path, self.show_db) - handler.add_route('POST', default_path, self.write_db) - return 'todo', default_path + handler.add_route('GET', default_path, self.show_db) + handler.add_route('POST', default_path, self.write_db) + return 'todo', {'cookie_name': 'todo_cookie', 'cookie_path': default_path} def do_POST(self): self.try_do(self.write_db) def write_db(self): from urllib.parse import urlencode - db = TodoDB() + config = self.apps['todo'] if hasattr(self, 'apps') else self.config_init() + parsed_url = urlparse(self.path) + site = path_split(parsed_url.path)[1] length = int(self.headers['content-length']) - postvars = parse_qs(self.rfile.read(length).decode(), keep_blank_values=1) - - import pprint - pp = pprint.PrettyPrinter(indent=4) - pp.pprint(postvars) - - db.t_filter_and = set() - db.t_filter_not = set() - if 't_filter_and' in postvars.keys(): - for target in postvars['t_filter_and']: - db.t_filter_and.add(target) - if 't_filter_not' in postvars.keys(): - for target in postvars['t_filter_not']: - db.t_filter_not.add(target) - if 't_uuid' in postvars.keys(): - new_postvars_t_uuid = postvars['t_uuid'].copy() - for i, uuid in enumerate(postvars['t_uuid']): - if len(uuid) < 36 and len(postvars['t_title'][i]) > 0: - t = Task() - new_uuid = str(uuid4()) - db.tasks[new_uuid] = t - new_postvars_t_uuid[i] = new_uuid - for key in [k for k in postvars.keys() if not k == 't_uuid']: - if uuid in postvars[key]: - uuid_index = postvars[key].index(uuid) - postvars[key][uuid_index] = new_uuid - postvars['t_uuid'] = new_postvars_t_uuid - for i, uuid in enumerate(postvars['t_uuid']): - if len(uuid) < 36: + postvars = PostvarsParser(parse_qs(self.rfile.read(length).decode(), keep_blank_values=1)) + + db = TodoDB() + redir_params = [] + # if we do encounter a filter post, we repost it (and if empty, the emptying command '-') + for param_name, filter_db_name in {('and_tag', 'tag_filter_and'), ('not_tag', 'tag_filter_not')}: + filter_db = getattr(db, filter_db_name) + if postvars.has(param_name): + for target in postvars.get_all(param_name, []): + if len(target) > 0 and not target in filter_db: + filter_db += [target] + if len(filter_db) == 0: + redir_params += [(param_name, '-')] + redir_params += [(param_name, f) for f in filter_db] + if site in {'calendar', 'todo'}: + redir_params += [('end', postvars.get('end', '-'))] + redir_params += [('start', postvars.get('start', '-'))] + if site in {'todo', 'pick_tasks'}: + redir_params += [('search', postvars.get('search', ''))] + redir_params += [('search', postvars.get('search', ''))] + redir_params += [('search', postvars.get('search', ''))] + if postvars.has('filter'): + postvars.set('return_to', '') + + if 'todo' == site: + todo_id = postvars.get('todo_id') + redir_params += [('id', todo_id)] + old_todo = db.todos[todo_id] if todo_id in db.todos.keys() else None + efforts = {} + latest_date = db.selected_date + for i, date in enumerate(postvars.get_all('effort_date', [])): + if '' == date: continue - t = db.tasks[uuid] - t.set_title(postvars['t_title'][i]) - t.tags_from_joined_string(postvars['t_tags'][i]) - t.set_default_weight(float(postvars['t_default_weight'][i])) - if uuid in db.today.todos.keys() and ((not 'do_today' in postvars) or uuid not in postvars['do_today']): - del db.today.todos[uuid] - if 'do_today' in postvars.keys(): - for i, uuid in enumerate(postvars['t_uuid']): - if uuid in postvars['do_today']: - done = 'done' in postvars and uuid in postvars['done'] - day_weight = float(postvars['day_weight'][i]) if postvars['day_weight'][i] else None - db.today.todos[uuid] = Todo(done, day_weight) - db.today_date = postvars['today_date'][0] - db.today.comment = postvars['comment'][0] - switch_edited_day = None - for date in db.old_days.keys(): - if f'edit_{date}' in postvars.keys(): - switch_edited_day = date - break - if 'archive_today' in postvars.keys() or switch_edited_day: - if db.today_date in db.old_days.keys(): - raise PlomException('cannot use same date twice') - db.old_days[db.today_date] = db.today - if switch_edited_day: - db.reset_today(date) - else: - db.reset_today() + try: + datetime.strptime(date, DATE_FORMAT) + except ValueError: + raise PlomException(f'bad date string') + latest_date = date + efforts[date] = None + if not (old_todo and old_todo.children): + efforts[date] = postvars.get_at_index('effort', i, on_empty=None, + float_if_possible=True) + if postvars.has('delete'): + has_day_effort = len([e for e in efforts.values() if e is not None]) > 0 + if postvars.has('done')\ + or postvars.get('comment')\ + or postvars.get_all('tag', [])\ + or has_day_effort: + raise PlomException('will not remove todo of preserve-worthy values') + db.delete_todo(todo_id) + postvars.set('return_to', 'calendar') + elif postvars.has('update'): + if postvars.has('delete_effort'): + for date in postvars.get_all('delete_effort'): + db.delete_effort(old_todo, date) + del efforts[date] + children = [db.todos[id_] for id_ in postvars.get_all('adopt_child', []) + if id_ in db.todos.keys()] + for child in children: + if not todo_id in [t.id_ for t in child.parents]: + child.parents += [db.todos[todo_id]] + tasks_to_birth = [db.tasks[id_] for id_ in postvars.get_all('birth_child', [])] + for task in tasks_to_birth: + children += [db.add_todo(task=task, efforts={latest_date: None})] + db.update_todo(id_=todo_id, + efforts=efforts, + done=postvars.has('done'), + comment=postvars.get('comment', ''), + tags=postvars.get_all('tag', []), + importance=float(postvars.get('importance')), + children=children) + + elif 'task' == site: + task_id = postvars.get('task_id') + if postvars.has('delete') and task_id in db.tasks.keys(): + if [t for t in db.todos.values() if task_id == t.task.id_]: + raise PlomException('will not remove Task describing existing Todos') + if postvars.get('title', '')\ + or postvars.get_all('tag', [])\ + or postvars.get_all('subtask', [])\ + or postvars.get('comment', ''): + raise PlomException('will not remove Task of preserve-worthy values') + db.delete_task(task_id) + elif postvars.has('update'): + task = db.update_task( + id_=task_id, + title=postvars.get('title', ''), + default_effort=postvars.get('default_effort', float_if_possible=True), + tags=postvars.get_all('tag', []), + subtask_ids=postvars.get_all('subtask', []), + comment=postvars.get('comment', '')) + if postvars.has('add_as_todo'): + db.add_todo(task=task, efforts={postvars.get('selected_date'): None}) + redir_params += [('id', task_id)] + + elif 'pick_tasks' == site: + redir_params += [('hide_chosen_tasks', int(postvars.has('hide_chosen_tasks')))] + if postvars.has('update'): + db.selected_date = postvars.get('date') + todos_to_shrink = [] + todos_to_delete = [] + for todo in db.selected_day.linked_todos_as_list: + if todo.visible and not todo.id_ in postvars.get_all('chosen_todo', []): + if len(todo.comment) > 0\ + or len(todo.day_tags) > 0\ + or not todo.is_effort_removable(db.selected_date): + raise PlomException('will not remove effort of preserve-worthy values') + if len(todo.efforts) > 1: + todos_to_shrink += [todo] + else: + todos_to_delete += [todo] + for todo in todos_to_shrink: + db.delete_effort(todo, db.selected_date) + for todo in todos_to_delete: + db.delete_todo(todo.id_) + for id_ in postvars.get_all('choose_task', []): + db.add_todo(task=db.tasks[id_], efforts={db.selected_date: None}) + for id_ in postvars.get_all('choose_todo', []): + db.todos[id_].efforts[db.selected_date] = None + + elif 'do_todos' == site: + redir_params += [('hide_done', int(postvars.has('hide_done')))] + if postvars.has('update'): + db.selected_date = postvars.get('date') + redir_params += [('date', db.selected_date)] + db.selected_day.comment = postvars.get('day_comment', '') + for i, todo_id in enumerate(postvars.get_all('todo_id', [])): + old_todo = db.todos[todo_id] + done = todo_id in postvars.get_all('done', []) + day_effort_input = postvars.get_at_index('effort', i, '') + day_effort = float(day_effort_input) if len(day_effort_input) > 0 else None + comment = postvars.get_at_index('effort_comment', i, '') + if (day_effort is not None) and (not done) and day_effort < 0 and 0 == len(comment): + if len(old_todo.efforts) > 1: + db.delete_effort(old_todo, db.selected_date) + else: + db.delete_todo(todo_id) + continue + importance = float(postvars.get_at_index('importance', i)) + if old_todo\ + and old_todo.done == done\ + and old_todo.day_effort == day_effort\ + and comment == old_todo.comment\ + and old_todo.importance == importance: + continue + db.update_todo_for_day( + todo_id, + db.selected_date, + day_effort, + done, + comment, + importance) + + homepage = postvars.get('return_to') + if not homepage: + encoded_params = urlencode(redir_params) + homepage = f'{site}?{encoded_params}' db.write() - homepage = self.apps['todo'] if hasattr(self, 'apps') else self.homepage - data = [('t_and', f) for f in db.t_filter_and] + [('t_not', f) for f in db.t_filter_not] - encoded_params = urlencode(data) - homepage += '?' + encoded_params self.redirect(homepage) def do_GET(self): self.try_do(self.show_db) def show_db(self): - from jinja2 import Template - from urllib.parse import urlparse + config = self.apps['todo'] if hasattr(self, 'apps') else self.config_init() parsed_url = urlparse(self.path) - params = parse_qs(parsed_url.query) - t_filter_and = set(params.get('t_and', [])) - t_filter_not = set(params.get('t_not', ['deleted'])) - db = TodoDB(t_filter_and, t_filter_not) - for i in range(10): - db.tasks[f'new{i}'] = Task() - for task_uuid, todo in db.today.todos.items(): - todo.weight = todo.day_weight if todo.day_weight else db.tasks[task_uuid].default_weight - for date, day in db.old_days.items(): - for task_uuid, todo in day.todos.items(): - todo.title = db.tasks[task_uuid].title - todo.weight = todo.day_weight if todo.day_weight else db.tasks[task_uuid].default_weight - page = Template(tmpl).render(db=db) + site = path_split(parsed_url.path)[1] + cookie_db = self.get_cookie_db(config['cookie_name']) + params = ParamsParser(parsed_url.query, cookie_db) + + selected_date = tag_filter_and = tag_filter_not = None + hide_unchosen = hide_done = False + return_to = params.get('return_to', '') + if site in {'do_todos', 'pick_tasks', 'calendar', 'task'}: + selected_date = params.get_cookied('date') + if site in {'do_todos', 'pick_tasks'}: + tag_filter_and = params.get_cookied_chain('and_tag', prefix=site) + tag_filter_not = params.get_cookied_chain('not_tag', prefix=site) + if 'do_todos' == site: + hide_done = params.get('hide_done', False) + db = TodoDB(selected_date, tag_filter_and, tag_filter_not, hide_unchosen, hide_done) + if site in {'todo', 'task'}: + id_ = params.get('id') + if site in {'todo', 'pick_tasks'}: + search = params.get('search', '') + if site in {'do_todos', 'pick_tasks'}: + sort_order = params.get_cookied('sort', prefix=site) + if site in {'', 'calendar', 'todo'}: + start_date = params.get_cookied('start', prefix=site) + end_date = params.get_cookied('end', prefix=site) + if 'reset_cookie' == site: + cookie_db = { # sensible defaults + params.cookie_key_from_params_key('pick_tasks', 'and_tag'): ['default'], + params.cookie_key_from_params_key('pick_tasks', 'not_tag'): ['ignore'], + params.cookie_key_from_params_key('todo', 'and_tag'): ['default'], + params.cookie_key_from_params_key('todo', 'not_tag'): ['ignore'], + params.cookie_key_from_params_key('todo', 'start'): 'yesterday', + params.cookie_key_from_params_key('todo', 'end'): 'today'} + page = db.show_message('cookie unset!') + elif 'do_todos' == site: + page = db.show_do_todos(sort_order) + elif 'pick_tasks' == site: + hide_chosen_tasks = params.get('hide_chosen_tasks', False) + page = db.show_pick_tasks(search, hide_chosen_tasks, sort_order) + elif site == 'todo': + page = db.show_todo(id_, search, start_date, end_date) + elif 'task' == site: + page = db.show_task(id_) + elif 'tasks' == site: + expand_uuid = params.get('expand_uuid') + page = db.show_tasks(expand_uuid) + elif 'add_task' == site: + page = db.show_task(None) + else: # 'calendar' == site + page = db.show_calendar(start_date, end_date) + + self.set_cookie(config['cookie_name'], config['cookie_path'], cookie_db) self.send_HTML(page) -if __name__ == "__main__": +if __name__ == "__main__": run_server(server_port, TodoHandler)