-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 Template
+from jinja2 import Environment as JinjaEnv, FileSystemLoader as JinjaFSLoader
+from urllib.parse import urlparse
db_path = '/home/plom/org/todo_new.json'
-# db_path = '/home/plom/public_repos/misc/todo_new.json'
server_port = 8082
-
-tmpl = """
-<style>
-td { border: 1px solid black; }
-</style>
-<body>
-<form action="{{homepage}}" method="POST">
-
-mandatory tags: {% for t_tag in db.t_tags | sort %}
-<input name="t_filter_and" type="checkbox" value="{{ t_tag }}" {% if t_tag in db.t_filter_and %} checked {% endif %} >{{ t_tag }}
-{% endfor %}
-<br />
-forbidden tags: {% for t_tag in db.t_tags | sort %}
-<input name="t_filter_not" type="checkbox" value="{{ t_tag }}" {% if t_tag in db.t_filter_not %} checked {% endif %} >{{ t_tag }}
-{% endfor %}
-<table>
-<tr><th colspan=2></th><th>date</th><td colspan=2><input name="today_date" value="{{ db.today_date }}" size=8 /></td><th>archive?</th><td><input type="checkbox" name="archive_today" /></td><td>{{ db.today.todos_sum|round(2) }}</td><th>comment:</th><td><input name="comment" value="{{ db.today.comment|e }}"></td></tr>
-<tr><th>default<br />weight</th><th>title</th><th>tags</th><th>today?</th><th>done?</th><th colspan=2>day<br />weight</th></tr>
-{% for uuid, t in db.tasks.items() | sort(attribute='1.title', reverse=True) %}
-{% if t.visible %}
-<input name="t_uuid" value="{{ uuid }}" type="hidden" >
-<tr>
-<td><input name="t_default_weight" value="{{ t.default_weight }}" type="number" step=0.1 size=5 required/></td>
-<td><input name="t_title" value="{{ t.title|e }}"/></td>
-<td><input name="t_tags" value="{{ t.tags_joined|e }}" >
-<td><input name="do_today" type="checkbox" value="{{ uuid }}" {% if uuid in db.today.todos.keys() %}checked{% endif %} ></td>
-<td><input name="done" type="checkbox" value="{{ uuid }}" {% if uuid in db.today.todos.keys() and db.today.todos[uuid].done %}checked{% endif %} ></td>
-<td colspan=2><input name="weight" type="number" step=0.1 size=5 value="{% if uuid in db.today.todos.keys() and db.today.todos[uuid].weight %}{{ db.today.todos[uuid].weight }}{% endif %}" ></td>
-</tr>
-{% endif %}
-{% endfor %}
-</table>
-
-<input type="submit" value="OK">
-<table>
-{% for date, day in db.old_days.items() | sort(reverse=True) %}
-<tr><td>{{ date }} ({{ day.todos_sum|round(2) }}) {{ day.comment|e }} <input type="submit" name="edit_{{date}}" value="edit" /></td></tr>
-{% for task, todo in day.todos.items() | sort(attribute='1.title', reverse=True) %}
-<tr><td>{{ todo.title }}</td><td>{% if todo.done %}✓{% endif %}</td><td>{{ todo.weight }}</td></tr>
-{% endfor %}
-{% endfor %}
-</table>
-</form>
-"""
+DATE_FORMAT = '%Y-%m-%d'
+j2env = JinjaEnv(loader=JinjaFSLoader('todo_templates'))
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()
+ def __init__(self, db, title_history=None, tags_history=None, default_weight_history=None, links_history=None):
+ self.db = db
+ self.title_history = title_history if title_history else {}
+ self.tags_history = tags_history if tags_history else {}
+ self.default_weight_history = default_weight_history if default_weight_history else {}
+ self.links_history = links_history if links_history else {}
self.visible = True
def _set_with_history(self, history, value):
def _last_of_history(self, history, default):
keys = sorted(history.keys())
- return default if 0 == len(history) else history[keys[-1]]
+ 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 from_dict(cls, db, d):
+ if 'links_history' in d.keys():
+ return cls(
+ db,
+ d['title_history'],
+ {k: set(v) for k, v in d['tags_history'].items()},
+ d['default_weight_history'],
+ {k: set(v) for k, v in d['links_history'].items()})
+ else:
+ return cls(
+ db,
+ 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)
+ def to_dict(self):
+ return {
+ 'title_history': self.title_history,
+ 'default_weight_history': self.default_weight_history,
+ 'tags_history': {k: list(v) for k,v in self.tags_history.items()},
+ 'links_history': {k: list(v) for k,v in self.links_history.items()},
+ }
@property
- def tags_joined(self):
- return ';'.join(sorted(list(self.tags)))
+ def default_weight(self):
+ return self._last_of_history(self.default_weight_history, 1)
- def set_default_weight(self, default_weight):
+ @default_weight.setter
+ def default_weight(self, default_weight):
self._set_with_history(self.default_weight_history, default_weight)
- @property
- def default_weight(self):
- return self._last_of_history(self.default_weight_history, 1)
+ def default_weight_at(self, queried_date):
+ ret = self.default_weight_history[sorted(self.default_weight_history.keys())[0]]
+ for date_key, default_weight in self.default_weight_history.items():
+ if date_key > f'{queried_date} 23:59:59':
+ break
+ ret = default_weight
+ return ret
- def set_title(self, title):
- self._set_with_history(self.title_history, title)
+ @property
+ def current_default_weight(self):
+ return self.default_weight_at(self.db.selected_date)
@property
def title(self):
return self._last_of_history(self.title_history, '')
+ @title.setter
+ def title(self, title):
+ self._set_with_history(self.title_history, title)
+
def title_at(self, queried_date):
- ret = self.title_history[sorted(self.title_history.keys())[0]]
+ ret = self.title_history[sorted(self.title_history.keys())[0]]
for date_key, title in self.title_history.items():
if date_key > f'{queried_date} 23:59:59':
break
ret = title
return ret
- def set_tags(self, tags):
- self._set_with_history(self.tags_history, set(tags))
+ @property
+ def current_title(self):
+ return self.title_at(self.db.selected_date)
@property
def tags(self):
return self._last_of_history(self.tags_history, set())
- 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}
+ @tags.setter
+ def tags(self, tags):
+ self._set_with_history(self.tags_history, set(tags))
+
+ @property
+ def links(self):
+ return self._last_of_history(self.links_history, set())
+
+ @links.setter
+ def links(self, links):
+ self._set_with_history(self.links_history, set(links))
+
+ @property
+ def id_(self):
+ for k, v in self.db.tasks.items():
+ if v == self:
+ return k
class Day:
- def __init__(self, todos, comment=''):
- self.todos = todos
+ def __init__(self, db, todos=None, comment=''):
+ self.db = db
+ self.todos = todos if todos else {}
self.comment = comment
+ self.archived = True
@classmethod
- def from_dict(cls, d):
+ def from_dict(cls, db, d):
todos = {}
comment = d['comment'] if 'comment' in d.keys() else ''
+ day = cls(db, todos, comment)
for uuid, todo_dict in d['todos'].items():
- todos[uuid] = Todo.from_dict(todo_dict)
- return cls(todos, comment)
-
- @property
- def todos_sum(self):
- s = 0
- for todo in [todo for todo in self.todos.values() if todo.done]:
- s += todo.weight
- return s
+ day.add_todo(uuid, todo_dict)
+ return day
def to_dict(self):
d = {'comment': self.comment, 'todos': {}}
d['todos'][task_uuid] = todo.to_dict()
return d
+ def add_todo(self, id_, dict_source=None):
+ self.todos[id_] = Todo.from_dict(self, dict_source) if dict_source else Todo(self)
+ return self.todos[id_]
+
+ def _todos_sum(self, include_undone=False):
+ s = 0
+ for todo in [todo for todo in self.todos.values() if todo.done]:
+ s += todo.weight
+ if include_undone:
+ for todo in [todo for todo in self.todos.values() if not todo.done]:
+ s += todo.day_weight if todo.day_weight else 0
+ return s
+
+ @property
+ def todos_sum(self):
+ return self._todos_sum()
+
+ @property
+ def todos_sum2(self):
+ return self._todos_sum(True)
+
+ @property
+ def date(self):
+ for k, v in self.db.days.items():
+ if v == self:
+ return k
class Todo:
- def __init__(self, done=False, weight=None):
+ def __init__(self, day, done=False, day_weight=None, comment='', day_tags=None):
+ self.day = day
self.done = done
- self.weight = weight
+ self.day_weight = day_weight
+ self.comment = comment
+ self.day_tags = day_tags if day_tags else set()
@classmethod
- def from_dict(cls, d):
- return cls(d['done'], d['weight'])
+ def from_dict(cls, day, d):
+ return cls(day, d['done'], d['day_weight'], d['comment'], set(d['day_tags']))
def to_dict(self):
- return {'done': self.done, 'weight': self.weight}
+ return {'done': self.done, 'day_weight': self.day_weight, 'comment': self.comment, 'day_tags': list(self.day_tags)}
+
+ @property
+ def default_weight(self):
+ return self.task.default_weight_at(self.day.date)
+
+ @property
+ def weight(self):
+ if self.day_weight:
+ return self.day_weight
+ else:
+ return self.day_weight if self.day_weight else self.default_weight
+
+ @property
+ def task(self):
+ for k, v in self.day.todos.items():
+ if v == self:
+ return self.day.db.tasks[k]
+
+ @property
+ def title(self):
+ return self.task.title_at(self.day.date)
+
+ @property
+ def tags(self):
+ return self.day_tags | self.task.tags
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, prefix, selected_date=None, t_filter_and = None, t_filter_not = None, hide_unchosen=False, hide_done=False):
+ self.prefix = prefix
+ self.selected_date = selected_date if selected_date else str(datetime.now())[:10]
+ self.t_filter_and = t_filter_and if t_filter_and else []
+ self.t_filter_not = t_filter_not if t_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()
super().__init__(db_path)
def read_db_file(self, f):
d = json.load(f)
- self.today = Day.from_dict(d['today'])
- self.today_date = d['today_date']
+ for date, day_dict in d['days'].items():
+ self.days[date] = self.add_day(dict_source=day_dict)
+ for day in self.days.values():
+ for todo in day.todos.values():
+ for tag in todo.day_tags:
+ self.t_tags.add(tag)
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
+ t = self.add_task(id_=uuid, dict_source=t_dict)
for tag in t.tags:
self.t_tags.add(tag)
- for date, day_dict in d['old_days'].items():
- self.old_days[date] = Day.from_dict(day_dict)
+ self.set_visibilities()
+
+ def set_visibilities(self):
+ for uuid, t in self.tasks.items():
+ 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\
+ and ((not self.hide_unchosen) or uuid in self.selected_day.todos.keys())
+ for day in self.days.values():
+ for todo in day.todos.values():
+ todo.visible = len([tag for tag in self.t_filter_and if not tag in todo.day_tags | todo.task.tags ]) == 0\
+ and len([tag for tag in self.t_filter_not if tag in todo.day_tags | todo.task.tags ]) == 0\
+ and ((not self.hide_done) or (not todo.done))
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),
+ # 't_filter_and': self.t_filter_and,
+ # 't_filter_not': self.t_filter_not,
'tasks': {},
- 'old_days': {}
+ 'days': {}
}
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()
return d
+ @property
+ def selected_day(self):
+ if not self.selected_date in self.days.keys():
+ self.days[self.selected_date] = self.add_day()
+ return self.days[self.selected_date]
+
+ def change_selected_days_date(self, new_date):
+ if new_date in self.days.keys():
+ raise PlomException('cannot use same date twice')
+ else:
+ self.days[new_date] = self.selected_day
+ del self.days[self.selected_date]
+ self.selected_date = new_date
+
def write(self):
+ dates_to_purge = []
+ for date, day in self.days.items():
+ if len(day.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 save_today(self):
- if self.today_date in self.old_days.keys():
- raise PlomException('cannot use same date twice')
- for task_uuid, todo in [(task_uuid, todo) for task_uuid, todo in self.today.todos.items()
- if not todo.weight]:
- todo.weight = self.tasks[task_uuid].default_weight
- self.old_days[self.today_date] = self.today
-
- def reset_today(self, date=None):
- if date:
- self.today_date = date
- self.today = self.old_days[date]
- del self.old_days[date]
+ def add_task(self, id_=None, dict_source=None, return_id=False):
+ t = Task.from_dict(self, dict_source) if dict_source else Task(self)
+ id_ = id_ if id_ else str(uuid4())
+ self.tasks[id_] = t
+ if return_id:
+ return id_, t
else:
- self.today_date = str(datetime.now())[:10]
- self.today = Day({})
+ return t
+
+ def add_day(self, dict_source=None):
+ return Day.from_dict(self, dict_source) if dict_source else Day(self)
+
+ def show_day(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 j2env.get_template('day.html').render(db=self, action=self.prefix+'/day', prev_date=prev_date_str, next_date=next_date_str)
+
+ def show_calendar(self, start_date_str, end_date_str):
+ self.t_filter_and = ['calendar']
+ self.t_filter_not = ['deleted']
+ self.set_visibilities()
+ days_to_show = {}
+ todays_date = str(datetime.now())[:10]
+ target_start_str = start_date_str if start_date_str else sorted(self.days.keys())[0]
+ target_start = todays_date if target_start_str == 'today' else target_start_str
+ target_end_str = end_date_str if end_date_str else sorted(self.days.keys())[-1]
+ target_end = todays_date if target_end_str == 'today' else target_end_str
+ start_date = datetime.strptime(target_start, DATE_FORMAT)
+ end_date = datetime.strptime(target_end, DATE_FORMAT)
+ for n in range(int((end_date - start_date).days) + 1):
+ current_date_obj = start_date + timedelta(n)
+ current_date = current_date_obj.strftime(DATE_FORMAT)
+ if current_date not in self.days.keys():
+ days_to_show[current_date] = self.add_day()
+ else:
+ days_to_show[current_date] = self.days[current_date]
+ days_to_show[current_date].weekday = datetime.strptime(current_date, DATE_FORMAT).strftime('%A')[:2]
+ return j2env.get_template('calendar.html').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)
+
+ def show_todo(self, task_uuid, selected_date):
+ todo = self.days[selected_date].todos[task_uuid]
+ return j2env.get_template('todo.html').render(db=self, todo=todo, action=self.prefix+'/todo')
+
+ def update_todo_mini(self, task_uuid, date, day_weight, done):
+ if task_uuid in self.days[date].todos.keys():
+ todo = self.days[date].todos[task_uuid]
+ else:
+ todo = self.days[date].add_todo(task_uuid)
+ todo.day_weight = float(day_weight) if len(day_weight) > 0 else None
+ todo.done = done
+ return todo
+
+ def collect_tags(self, tags_joined, tags_checked):
+ tags = set()
+ for tag in [tag.strip() for tag in tags_joined.split(';') if tag.strip() != '']:
+ tags.add(tag)
+ for tag in tags_checked:
+ tags.add(tag)
+ return tags
+
+ def update_todo(self, task_uuid, date, day_weight, done, comment, day_tags_joined, day_tags_checked):
+ todo = self.update_todo_mini(task_uuid, date, day_weight, done)
+ todo.comment = comment
+ todo.day_tags = self.collect_tags(day_tags_joined, day_tags_checked)
+
+ def show_task(self, id_):
+ task = self.tasks[id_] if id_ else self.add_task()
+ return j2env.get_template('task.html').render(db=self, task=task, action=self.prefix+'/task')
+
+ def update_task(self, id_, title, default_weight, tags_joined, tags_checked, links):
+ task = self.tasks[id_] if id_ in self.tasks.keys() else self.add_task(id_)
+ task.title = title
+ task.default_weight = float(default_weight) if len(default_weight) > 0 else None
+ task.tags = self.collect_tags(tags_joined, tags_checked)
+ task.links = links
+ for link in links:
+ print("DEBUG DEBUG", links)
+ borrowed_links = self.tasks[link].links
+ print("DEBUG DEBUG brorowed1", borrowed_links)
+ borrowed_links.add(id_)
+ print("DEBUG DEBUG brorowed2", borrowed_links)
+ self.tasks[link].links = borrowed_links
+
+ def show_tasks(self):
+ return j2env.get_template('tasks.html').render(db=self, action=self.prefix+'/tasks')
+
class TodoHandler(PlomHandler):
-
+
+ def config_init(self):
+ return {
+ 'cookie_name': 'todo_cookie',
+ 'prefix': '',
+ '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', 'prefix': default_path, 'cookie_path': default_path}
def do_POST(self):
+ self.try_do(self.config_init)
self.try_do(self.write_db)
def write_db(self):
from urllib.parse import urlencode
- db = TodoDB()
+ app_config = self.apps['todo'] if hasattr(self, 'apps') else self.config()
length = int(self.headers['content-length'])
postvars = parse_qs(self.rfile.read(length).decode(), keep_blank_values=1)
+ parsed_url = urlparse(self.path)
+ db = TodoDB(prefix=app_config['prefix'])
+ params_to_encode = []
+ if 't_and' in postvars.keys():
+ for target in postvars['t_and']:
+ if len(target) > 0 and not target in db.t_filter_and:
+ db.t_filter_and += [target]
+ if len(db.t_filter_and) == 0:
+ params_to_encode += [('t_and', '-')]
+ if 't_not' in postvars.keys():
+ for target in postvars['t_not']:
+ if len(target) > 0 and not target in db.t_filter_not:
+ db.t_filter_not += [target]
+ if len(db.t_filter_not) == 0:
+ params_to_encode += [('t_not', '-')]
+ params_to_encode += [('t_and', f) for f in db.t_filter_and] + [('t_not', f) for f in db.t_filter_not]
+
+ def collect_checked(prefix, postvars):
+ tags_checked = []
+ for k in postvars.keys():
+ if k.startswith(prefix):
+ tags_checked += [k[len(prefix):]]
+ return tags_checked
+
+ if parsed_url.path == app_config['prefix'] + '/calendar':
+ start = postvars['start'][0] if len(postvars['start'][0]) > 0 else '-'
+ end = postvars['end'][0] if len(postvars['end'][0]) > 0 else '-'
+ homepage = f'{app_config["prefix"]}/calendar?start={start}&end={end}'
+
+ elif parsed_url.path == app_config['prefix'] + '/todo':
+ task_uuid = postvars['task_uuid'][0]
+ date = postvars['date'][0]
+ db.update_todo(task_uuid, date, postvars['day_weight'][0], 'done' in postvars.keys(), postvars['comment'][0], postvars['joined_day_tags'][0], collect_checked('day_tag_', postvars))
+ homepage = f'{app_config["prefix"]}/todo?task={task_uuid}&date={date}'
+
+ elif parsed_url.path == app_config['prefix'] + '/task':
+ encoded_params = urlencode(params_to_encode)
+ id_ = postvars['id'][0]
+ if 'title' in postvars.keys():
+ db.update_task(id_, postvars['title'][0], postvars['default_weight'][0], postvars['joined_tags'][0], collect_checked('tag_', postvars), collect_checked('link_', postvars))
+ homepage = f'{app_config["prefix"]}/task?id={id_}&{encoded_params}'
+
+ elif parsed_url.path == app_config['prefix'] + '/tasks':
+ encoded_params = urlencode(params_to_encode)
+ homepage = f'{app_config["prefix"]}/tasks?{encoded_params}'
+
+ elif parsed_url.path == app_config['prefix'] + '/day':
+ if 'expect_unchosen_done' in postvars.keys():
+ params_to_encode += [('hide_unchosen', int('hide_unchosen' in postvars.keys()))] + [('hide_done', int('hide_done' in postvars.keys()))]
+ if 'selected_date' in postvars.keys():
+ db.selected_date = postvars['selected_date'][0]
+ if 't_uuid' in postvars.keys():
+ for i, uuid in enumerate(postvars['t_uuid']):
+ t = db.tasks[uuid]
+ if uuid in db.selected_day.todos.keys() and ((not 'choose' in postvars) or uuid not in postvars['choose']):
+ del db.selected_day.todos[uuid]
+ if 'choose' in postvars.keys():
+ for i, uuid in enumerate(postvars['t_uuid']):
+ if uuid in postvars['choose']:
+ done = 'done' in postvars and uuid in postvars['done']
+ db.update_todo_mini(uuid, db.selected_date, postvars['day_weight'][i], done)
+ if 'day_comment' in postvars.keys():
+ db.selected_day.comment = postvars['day_comment'][0]
+ params_to_encode += [('selected_date', db.selected_date)]
+ encoded_params = urlencode(params_to_encode)
+ homepage = f'{app_config["prefix"]}/day?{encoded_params}'
- 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:
- 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']
- weight = float(postvars['weight'][i]) if postvars['weight'][i] else None
- db.today.todos[uuid] = Todo(done, 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:
- db.save_today()
- if switch_edited_day:
- db.reset_today(date)
- else:
- db.reset_today()
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.config_init)
self.try_do(self.show_db)
def show_db(self):
- from jinja2 import Template
- from urllib.parse import urlparse
+ app_config = self.apps['todo'] if hasattr(self, 'apps') else self.config()
+ cookie_db = self.get_cookie_db(app_config['cookie_name'])
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 date, day in db.old_days.items():
- for task_uuid, todo in day.todos.items():
- todo.title = db.tasks[task_uuid].title_at(date)
- page = Template(tmpl).render(db=db)
+ selected_date = None
+ t_filter_and = None
+ t_filter_not = None
+ hide_unchosen = False
+ hide_done = False
+ if parsed_url.path in {app_config['prefix'] + '/day', app_config['prefix'] + '/tasks'}:
+ selected_date = params.get('selected_date', [None])[0]
+ if selected_date is None and 'selected_date' in cookie_db.keys():
+ selected_date = cookie_db['selected_date']
+ cookie_db['selected_date'] = selected_date
+ if parsed_url.path in {app_config['prefix'] + '/day', app_config['prefix'] + '/tasks', app_config['prefix'] + '/task'}:
+ t_filter_and = params.get('t_and', None)
+ if t_filter_and is None and 't_and' in cookie_db.keys():
+ t_filter_and = cookie_db['t_and']
+ elif t_filter_and == ['-']:
+ t_filter_and = None
+ cookie_db['t_and'] = t_filter_and
+ t_filter_not = params.get('t_not', None)
+ if t_filter_not is None:
+ if 't_not' in cookie_db.keys():
+ t_filter_not = cookie_db['t_not']
+ else:
+ t_filter_not = ['deleted']
+ elif t_filter_not == ['-']:
+ t_filter_not = None
+ cookie_db['t_not'] = t_filter_not
+ if parsed_url.path == app_config['prefix'] + '/day':
+ hide_unchosen_params = params.get('hide_unchosen', [])
+ if 0 == len(hide_unchosen_params):
+ if 'hide_unchosen' in cookie_db.keys():
+ hide_unchosen = cookie_db['hide_unchosen']
+ else:
+ hide_unchosen = hide_unchosen_params[0] != '0'
+ cookie_db['hide_unchosen'] = hide_unchosen
+ hide_done_params = params.get('hide_done', [])
+ if 0 == len(hide_done_params):
+ if 'hide_done' in cookie_db.keys():
+ hide_done = cookie_db['hide_done']
+ else:
+ hide_done = hide_done_params[0] != '0'
+ cookie_db['hide_done'] = hide_done
+ db = TodoDB(app_config['prefix'], selected_date, t_filter_and, t_filter_not, hide_unchosen, hide_done)
+ if parsed_url.path == app_config['prefix'] + '/day':
+ page = db.show_day()
+ elif parsed_url.path == app_config['prefix'] + '/todo':
+ todo_date = params.get('date', [None])[0]
+ task_uuid = params.get('task', [None])[0]
+ page = db.show_todo(task_uuid, todo_date)
+ elif parsed_url.path == app_config['prefix'] + '/task':
+ id_ = params.get('id', [None])[0]
+ page = db.show_task(id_)
+ elif parsed_url.path == app_config['prefix'] + '/tasks':
+ page = db.show_tasks()
+ elif parsed_url.path == app_config['prefix'] + '/add_task':
+ page = db.show_task(None)
+ elif parsed_url.path == app_config['prefix'] + '/unset_cookie':
+ page = 'no cookie to unset.'
+ if len(cookie_db) > 0:
+ self.unset_cookie(app_config['cookie_name'], app_config['cookie_path'])
+ page = 'cookie unset!'
+ else:
+ start_date = params.get('start', [None])[0]
+ if start_date is None:
+ if 'calendar_start' in cookie_db.keys():
+ start_date = cookie_db['calendar_start']
+ else:
+ start_date = 'today'
+ elif start_date == '-':
+ start_date = None
+ cookie_db['calendar_start'] = start_date
+ end_date = params.get('end', [None])[0]
+ if end_date is None and 'calendar_end' in cookie_db.keys():
+ end_date = cookie_db['calendar_end']
+ elif end_date == '-':
+ end_date = None
+ cookie_db['calendar_end'] = end_date
+ page = db.show_calendar(start_date, end_date)
+ if parsed_url.path != app_config['prefix'] + '/unset_cookie':
+ self.set_cookie(app_config['cookie_name'], app_config['cookie_path'], cookie_db)
self.send_HTML(page)
-if __name__ == "__main__":
+if __name__ == "__main__":
run_server(server_port, TodoHandler)