1 from plomlib import PlomDB, run_server, PlomHandler, PlomException
4 from datetime import datetime
5 from urllib.parse import parse_qs
6 from jinja2 import Template
7 from urllib.parse import urlparse
8 db_path = '/home/plom/org/todo_new.json'
9 # db_path = '/home/plom/public_repos/misc/todo_new.json'
14 td { border: 1px solid black; }
17 <a href="{{prefix}}/all">all</a> | edit day:
18 <a href="{{prefix}}/day">choose</a>
19 <a href="{{prefix}}/day?hide_unchosen=1">do</a>
20 <a href="{{prefix}}/coming">coming</a>
23 form_footer = '\n</form>'
25 form_header_tmpl = """
26 <form action="{{action|e}}" method="POST">
28 archived_days_tmpl = """
30 {% for date, day in days.items() | sort(reverse=True) %}
32 <tr><td>{{ date }} {{ day.weekday }} ({{ day.todos_sum|round(2) }}) {{ day.comment|e }} <input type="submit" name="edit_{{date}}" value="edit" /></td></tr>
33 {% for task, todo in day.todos.items() | sort(attribute='1.title', reverse=True) %}
34 <tr><td>{{ todo.title }}</td><td>{% if todo.done %}✓{% endif %}</td><td>{{ todo.weight }}</td></tr>
40 selected_day_tmpl = """
41 hiden unchosen: <input name="hide_unchosen" type="checkbox" {% if db.hide_unchosen %}checked{% endif %} /><br />
42 mandatory tags: {% for t_tag in db.t_tags | sort %}
43 <input name="t_filter_and" type="checkbox" value="{{ t_tag }}" {% if t_tag in db.t_filter_and %} checked {% endif %} >{{ t_tag }}
46 forbidden tags: {% for t_tag in db.t_tags | sort %}
47 <input name="t_filter_not" type="checkbox" value="{{ t_tag }}" {% if t_tag in db.t_filter_not %} checked {% endif %} >{{ t_tag }}
50 <tr><th colspan=2></th><th>date</th><td colspan=2><input name="selected_day_date" value="{{ db.selected_day_date }}" size=8 /></td><th>archive?</th><td><input type="checkbox" name="archive_day" /></td><td>{{ db.selected_day.todos_sum|round(2) }} ({{ db.selected_day.todos_sum2|round(2)}})</td><th>comment:</th><td><input name="comment" value="{{ db.selected_day.comment|e }}"></td></tr>
51 <tr><th>default<br />weight</th><th>title</th><th>tags</th><th>choose?</th><th>done?</th><th colspan=2>day<br />weight</th></tr>
52 {% for uuid, t in db.tasks.items() | sort(attribute='1.title', reverse=True) %}
54 <input name="t_uuid" value="{{ uuid }}" type="hidden" >
56 <td><input name="t_default_weight" value="{{ t.default_weight }}" type="number" step=0.1 size=5 required/></td>
57 <td><input name="t_title" value="{{ t.title|e }}"/></td>
58 <td><input name="t_tags" value="{{ t.tags_joined|e }}" >
59 <td><input name="choose" type="checkbox" value="{{ uuid }}" {% if uuid in db.selected_day.todos.keys() %}checked{% endif %} ></td>
60 <td><input name="done" type="checkbox" value="{{ uuid }}" {% if uuid in db.selected_day.todos.keys() and db.selected_day.todos[uuid].done %}checked{% endif %} ></td>
61 <td colspan=2><input name="day_weight" type="number" step=0.1 size=5 value="{% if uuid in db.selected_day.todos.keys() and db.selected_day.todos[uuid].day_weight %}{{ db.selected_day.todos[uuid].day_weight }}{% endif %}" ></td>
66 <input type="submit" value="OK">
71 def __init__(self, db, title_history={}, tags_history={}, default_weight_history={}):
73 self.title_history = title_history.copy()
74 self.tags_history = tags_history.copy()
75 self.default_weight_history = default_weight_history.copy()
78 def _set_with_history(self, history, value):
79 keys = sorted(history.keys())
80 if len(history) == 0 or value != history[keys[-1]]:
81 history[str(datetime.now())[:19]] = value
83 def _last_of_history(self, history, default):
84 keys = sorted(history.keys())
85 return default if 0 == len(history) else history[keys[-1]]
88 def from_dict(cls, db, d):
92 {k: set(v) for k, v in d['tags_history'].items()},
93 d['default_weight_history'])
95 def tags_from_joined_string(self, tags_string):
97 for tag in [tag.strip() for tag in tags_string.split(';') if tag.strip() != '']:
102 def tags_joined(self):
103 return ';'.join(sorted(list(self.tags)))
105 def set_default_weight(self, default_weight):
106 self._set_with_history(self.default_weight_history, default_weight)
109 def default_weight(self):
110 return self._last_of_history(self.default_weight_history, 1)
112 def set_title(self, title):
113 self._set_with_history(self.title_history, title)
117 return self._last_of_history(self.title_history, '')
119 def title_at(self, queried_date):
120 ret = self.title_history[sorted(self.title_history.keys())[0]]
121 for date_key, title in self.title_history.items():
122 if date_key > f'{queried_date} 23:59:59':
127 def set_tags(self, tags):
128 self._set_with_history(self.tags_history, set(tags))
132 return self._last_of_history(self.tags_history, set())
136 'title_history': self.title_history,
137 'tags_history': {k: list(v) for k,v in self.tags_history.items()},
138 'default_weight_history': self.default_weight_history}
143 def __init__(self, db, todos={}, comment=''):
146 self.comment = comment
150 def from_dict(cls, db, d):
152 comment = d['comment'] if 'comment' in d.keys() else ''
153 day = cls(db, todos, comment)
154 for uuid, todo_dict in d['todos'].items():
155 day.add_todo(uuid, todo_dict)
159 d = {'comment': self.comment, 'todos': {}}
160 for task_uuid, todo in self.todos.items():
161 d['todos'][task_uuid] = todo.to_dict()
164 def add_todo(self, id_, dict_source=None):
165 self.todos[id_] = Todo.from_dict(self, dict_source) if dict_source else Todo(self)
167 def _todos_sum(self, include_undone=False):
169 for todo in [todo for todo in self.todos.values() if todo.done]:
172 for todo in [todo for todo in self.todos.values() if not todo.done]:
173 s += todo.day_weight if todo.day_weight else 0
178 return self._todos_sum()
181 def todos_sum2(self):
182 return self._todos_sum(True)
186 def __init__(self, day, done=False, day_weight=None):
189 self.day_weight = day_weight
192 def from_dict(cls, day, d):
193 return cls(day, d['done'], d['day_weight'])
196 return {'done': self.done, 'day_weight': self.day_weight}
201 return self.day_weight
203 task_uuid = [k for k,v in self.day.todos.items() if v == self][0]
204 return self.day_weight if self.day_weight else self.day.db.tasks[task_uuid].default_weight
207 class TodoDB(PlomDB):
209 def __init__(self, prefix, t_filter_and = set(), t_filter_not = set(), hide_unchosen=False):
211 self.t_filter_and = t_filter_and
212 self.t_filter_not = t_filter_not
213 self.hide_unchosen = hide_unchosen
217 super().__init__(db_path)
218 if not hasattr(self, 'selected_day_date'):
221 def read_db_file(self, f):
223 self.selected_day_date = d['selected_day_date']
224 for date, day_dict in d['days'].items():
225 self.days[date] = self.add_day(dict_source=day_dict)
226 self.selected_day.archived = False
227 for uuid, t_dict in d['tasks'].items():
228 t = self.add_task(id_=uuid, dict_source=t_dict)
229 t.visible = len([tag for tag in self.t_filter_and if not tag in t.tags]) == 0\
230 and len([tag for tag in self.t_filter_not if tag in t.tags]) == 0\
231 and ((not self.hide_unchosen) or uuid in self.selected_day.todos)
237 'selected_day_date': self.selected_day_date,
238 't_filter_and': list(self.t_filter_and),
239 't_filter_not': list(self.t_filter_not),
243 for uuid, t in self.tasks.items():
244 d['tasks'][uuid] = t.to_dict()
245 for date, day in self.days.items():
246 d['days'][date] = day.to_dict()
250 def selected_day(self):
251 return self.days[self.selected_day_date]
254 self.write_text_to_db(json.dumps(self.to_dict()))
256 def switch_to_day(self, date=None):
257 if self.selected_day_date in self.days.keys():
258 self.selected_day.archived = True
260 self.selected_day_date = date
262 self.selected_day_date = str(datetime.now())[:10]
263 if not self.selected_day_date in self.days.keys():
264 self.days[self.selected_day_date] = self.add_day()
265 self.selected_day.archived = False
267 def add_task(self, id_=None, dict_source=None, return_id=False):
268 t = Task.from_dict(self, dict_source) if dict_source else Task(self)
269 id_ = id_ if id_ else str(uuid4())
276 def add_day(self, dict_source=None):
277 return Day.from_dict(self, dict_source) if dict_source else Day(self)
281 self.add_task(id_=f'new{i}')
282 for date, day in self.days.items():
283 for task_uuid, todo in day.todos.items():
284 todo.title = self.tasks[task_uuid].title_at(date)
285 return Template(form_header_tmpl + selected_day_tmpl + archived_days_tmpl + form_footer).render(db=self, action=self.prefix+'/all', days=self.days)
287 def show_selected_day(self):
288 return Template(form_header_tmpl + selected_day_tmpl + form_footer).render(db=self, action=self.prefix+'/day')
290 def show_coming(self):
291 from datetime import timedelta
292 todays_date = str(datetime.now())[:10]
293 days_to_show = self.days.copy()
294 for day in days_to_show.values():
296 last_date = sorted(days_to_show.keys())[-1]
297 start_date = datetime.strptime(todays_date, '%Y-%m-%d')
298 end_date = datetime.strptime(last_date, '%Y-%m-%d')
299 for n in range(int((end_date - start_date).days) + 1):
300 current_date_obj = start_date + timedelta(n)
301 current_date = current_date_obj.strftime('%Y-%m-%d')
302 if current_date not in days_to_show.keys():
303 days_to_show[current_date] = self.add_day()
304 days_to_show[current_date].archived = True
305 days_to_show[current_date].weekday = datetime.strptime(current_date, '%Y-%m-%d').strftime('%A')
306 for task_uuid, todo in days_to_show[current_date].todos.items():
307 todo.title = self.tasks[task_uuid].title_at(current_date)
308 return Template(form_header_tmpl + archived_days_tmpl + form_footer).render(db=self, action=self.prefix+'/day', days=days_to_show)
311 class TodoHandler(PlomHandler):
313 def app_init(self, handler):
314 default_path = '/todo'
315 handler.add_route('GET', default_path, self.show_db)
316 handler.add_route('POST', default_path, self.write_db)
317 return 'todo', default_path
320 self.try_do(self.write_db)
323 from urllib.parse import urlencode
324 prefix = self.apps['todo'] if hasattr(self, 'apps') else ''
326 length = int(self.headers['content-length'])
327 postvars = parse_qs(self.rfile.read(length).decode(), keep_blank_values=1)
329 # pp = pprint.PrettyPrinter(indent=4)
330 # pp.pprint(postvars)
331 db.t_filter_and = set()
332 db.t_filter_not = set()
333 if 't_filter_and' in postvars.keys():
334 for target in postvars['t_filter_and']:
335 db.t_filter_and.add(target)
336 if 't_filter_not' in postvars.keys():
337 for target in postvars['t_filter_not']:
338 db.t_filter_not.add(target)
339 if 'hide_unchosen' in postvars.keys():
340 db.hide_unchosen = True
341 if 't_uuid' in postvars.keys():
342 new_postvars_t_uuid = postvars['t_uuid'].copy()
343 for i, uuid in enumerate(postvars['t_uuid']):
344 if len(uuid) < 36 and len(postvars['t_title'][i]) > 0:
345 new_uuid, t = db.add_task(return_id=True)
346 new_postvars_t_uuid[i] = new_uuid
347 for key in [k for k in postvars.keys() if not k == 't_uuid']:
348 if uuid in postvars[key]:
349 uuid_index = postvars[key].index(uuid)
350 postvars[key][uuid_index] = new_uuid
351 postvars['t_uuid'] = new_postvars_t_uuid
352 for i, uuid in enumerate(postvars['t_uuid']):
356 t.set_title(postvars['t_title'][i])
357 t.tags_from_joined_string(postvars['t_tags'][i])
358 t.set_default_weight(float(postvars['t_default_weight'][i]))
359 if uuid in db.selected_day.todos.keys() and ((not 'choose' in postvars) or uuid not in postvars['choose']):
360 del db.selected_day.todos[uuid]
361 if 'choose' in postvars.keys():
362 for i, uuid in enumerate(postvars['t_uuid']):
363 if uuid in postvars['choose']:
364 done = 'done' in postvars and uuid in postvars['done']
365 day_weight = float(postvars['day_weight'][i]) if postvars['day_weight'][i] else None
366 db.selected_day.add_todo(uuid, {'done': done, 'day_weight': day_weight})
368 if 'comment' in postvars.keys():
369 db.selected_day.comment = postvars['comment'][0]
370 if 'selected_day_date' in postvars.keys():
371 new_selected_day_date = postvars['selected_day_date'][0]
373 datetime.strptime(new_selected_day_date, '%Y-%m-%d')
375 raise PlomException(f"{prefix} bad date string: {new_selected_day_date}")
376 if new_selected_day_date != db.selected_day_date:
377 if new_selected_day_date in db.days.keys():
378 raise PlomException('cannot use same date twice')
380 db.days[new_selected_day_date] = db.selected_day
381 del db.days[db.selected_day_date]
382 db.selected_day_date = new_selected_day_date
384 switch_edited_day = None
385 day_edit_prefix = 'edit_'
386 for k in postvars.keys():
387 if k.startswith(day_edit_prefix):
388 switch_edited_day = k[len(day_edit_prefix):]
390 if 'archive_day' in postvars.keys() or switch_edited_day:
391 db.switch_to_day(switch_edited_day)
393 data = [('t_and', f) for f in db.t_filter_and] + [('t_not', f) for f in db.t_filter_not] + [('hide_unchosen', int(db.hide_unchosen))]
394 encoded_params = urlencode(data)
395 parsed_url = urlparse(self.path)
396 if prefix + '/day' == parsed_url.path:
397 homepage = f'{prefix}/day?{encoded_params}'
399 homepage = f'{prefix}/all?{encoded_params}'
400 self.redirect(homepage)
403 self.try_do(self.show_db)
406 prefix = self.apps['todo'] if hasattr(self, 'apps') else ''
407 parsed_url = urlparse(self.path)
408 params = parse_qs(parsed_url.query)
409 t_filter_and = set(params.get('t_and', []))
410 t_filter_not = set(params.get('t_not', ['deleted']))
411 hide_unchosen_params = params.get('hide_unchosen', [])
412 hide_unchosen = len(hide_unchosen_params) > 0 and hide_unchosen_params[0] != '0'
413 db = TodoDB(prefix, t_filter_and, t_filter_not, hide_unchosen)
414 if parsed_url.path == prefix + '/day':
415 page = db.show_selected_day()
416 elif parsed_url.path == prefix + '/coming':
417 page = db.show_coming()
420 header = Template(html_head).render(prefix=prefix)
421 self.send_HTML(header + page)
424 if __name__ == "__main__":
425 run_server(server_port, TodoHandler)