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>
23 form_footer = '\n</form>'
27 {% for date, day in db.old_days.items() | sort(reverse=True) %}
28 <tr><td>{{ date }} ({{ day.todos_sum |round(2) }}) {{ day.comment|e }} <input type="submit" name="edit_{{date}}" value="edit" /></td></tr>
29 {% for task, todo in day.todos.items() | sort(attribute='1.title', reverse=True) %}
30 <tr><td>{{ todo.title }}</td><td>{% if todo.done %}✓{% endif %}</td><td>{{ todo.weight }}</td></tr>
36 selected_day_tmpl = """
37 <form action="{{action|e}}" method="POST">
38 hiden unchosen: <input name="hide_unchosen" type="checkbox" {% if db.hide_unchosen %}checked{% endif %} /><br />
39 mandatory tags: {% for t_tag in db.t_tags | sort %}
40 <input name="t_filter_and" type="checkbox" value="{{ t_tag }}" {% if t_tag in db.t_filter_and %} checked {% endif %} >{{ t_tag }}
43 forbidden tags: {% for t_tag in db.t_tags | sort %}
44 <input name="t_filter_not" type="checkbox" value="{{ t_tag }}" {% if t_tag in db.t_filter_not %} checked {% endif %} >{{ t_tag }}
47 <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>
48 <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>
49 {% for uuid, t in db.tasks.items() | sort(attribute='1.title', reverse=True) %}
51 <input name="t_uuid" value="{{ uuid }}" type="hidden" >
53 <td><input name="t_default_weight" value="{{ t.default_weight }}" type="number" step=0.1 size=5 required/></td>
54 <td><input name="t_title" value="{{ t.title|e }}"/></td>
55 <td><input name="t_tags" value="{{ t.tags_joined|e }}" >
56 <td><input name="choose" type="checkbox" value="{{ uuid }}" {% if uuid in db.selected_day.todos.keys() %}checked{% endif %} ></td>
57 <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>
58 <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>
63 <input type="submit" value="OK">
68 def __init__(self, db, title_history={}, tags_history={}, default_weight_history={}):
70 self.title_history = title_history.copy()
71 self.tags_history = tags_history.copy()
72 self.default_weight_history = default_weight_history.copy()
75 def _set_with_history(self, history, value):
76 keys = sorted(history.keys())
77 if len(history) == 0 or value != history[keys[-1]]:
78 history[str(datetime.now())[:19]] = value
80 def _last_of_history(self, history, default):
81 keys = sorted(history.keys())
82 return default if 0 == len(history) else history[keys[-1]]
85 def from_dict(cls, db, d):
89 {k: set(v) for k, v in d['tags_history'].items()},
90 d['default_weight_history'])
92 def tags_from_joined_string(self, tags_string):
94 for tag in [tag.strip() for tag in tags_string.split(';') if tag.strip() != '']:
99 def tags_joined(self):
100 return ';'.join(sorted(list(self.tags)))
102 def set_default_weight(self, default_weight):
103 self._set_with_history(self.default_weight_history, default_weight)
106 def default_weight(self):
107 return self._last_of_history(self.default_weight_history, 1)
109 def set_title(self, title):
110 self._set_with_history(self.title_history, title)
114 return self._last_of_history(self.title_history, '')
116 def title_at(self, queried_date):
117 ret = self.title_history[sorted(self.title_history.keys())[0]]
118 for date_key, title in self.title_history.items():
119 if date_key > f'{queried_date} 23:59:59':
124 def set_tags(self, tags):
125 self._set_with_history(self.tags_history, set(tags))
129 return self._last_of_history(self.tags_history, set())
133 'title_history': self.title_history,
134 'tags_history': {k: list(v) for k,v in self.tags_history.items()},
135 'default_weight_history': self.default_weight_history}
140 def __init__(self, db, todos={}, comment=''):
143 self.comment = comment
146 def from_dict(cls, db, d):
148 comment = d['comment'] if 'comment' in d.keys() else ''
149 day = cls(db, todos, comment)
150 for uuid, todo_dict in d['todos'].items():
151 day.add_todo(uuid, todo_dict)
155 d = {'comment': self.comment, 'todos': {}}
156 for task_uuid, todo in self.todos.items():
157 d['todos'][task_uuid] = todo.to_dict()
160 def add_todo(self, id_, dict_source=None):
161 self.todos[id_] = Todo.from_dict(self, dict_source) if dict_source else Todo(self)
163 def _todos_sum(self, include_undone=False):
165 for todo in [todo for todo in self.todos.values() if todo.done]:
168 for todo in [todo for todo in self.todos.values() if not todo.done]:
169 s += todo.day_weight if todo.day_weight else 0
174 return self._todos_sum()
177 def todos_sum2(self):
178 return self._todos_sum(True)
182 def __init__(self, day, done=False, day_weight=None):
185 self.day_weight = day_weight
188 def from_dict(cls, day, d):
189 return cls(day, d['done'], d['day_weight'])
192 return {'done': self.done, 'day_weight': self.day_weight}
197 return self.day_weight
199 task_uuid = [k for k,v in self.day.todos.items() if v == self][0]
200 return self.day_weight if self.day_weight else self.day.db.tasks[task_uuid].default_weight
203 class TodoDB(PlomDB):
205 def __init__(self, prefix, t_filter_and = set(), t_filter_not = set(), hide_unchosen=False):
207 self.t_filter_and = t_filter_and
208 self.t_filter_not = t_filter_not
209 self.hide_unchosen = hide_unchosen
214 super().__init__(db_path)
216 def read_db_file(self, f):
218 self.selected_day = self.add_day(d['selected_day'])
219 self.selected_day_date = d['selected_day_date']
220 for uuid, t_dict in d['tasks'].items():
221 t = self.add_task(id_=uuid, dict_source=t_dict)
222 t.visible = len([tag for tag in self.t_filter_and if not tag in t.tags]) == 0\
223 and len([tag for tag in self.t_filter_not if tag in t.tags]) == 0\
224 and ((not self.hide_unchosen) or uuid in self.selected_day.todos)
227 for date, day_dict in d['old_days'].items():
228 self.old_days[date] = self.add_day(dict_source=day_dict) # Day.from_dict(self, day_dict)
232 'selected_day': self.selected_day.to_dict(),
233 'selected_day_date': self.selected_day_date,
234 't_filter_and': list(self.t_filter_and),
235 't_filter_not': list(self.t_filter_not),
239 for uuid, t in self.tasks.items():
240 d['tasks'][uuid] = t.to_dict()
241 for date, day in self.old_days.items():
242 d['old_days'][date] = day.to_dict()
246 self.write_text_to_db(json.dumps(self.to_dict()))
248 def save_selected_day(self):
249 if self.selected_day_date in self.old_days.keys():
250 raise PlomException('cannot use same date twice')
251 self.old_days[self.selected_day_date] = self.selected_day
253 def reset_day(self, date=None):
255 self.selected_day_date = date
256 self.selected_day = self.old_days[date]
257 del self.old_days[date]
259 self.selected_day_date = str(datetime.now())[:10]
260 self.selected_day = self.add_day()
262 def add_task(self, id_=None, dict_source=None, return_id=False):
263 t = Task.from_dict(self, dict_source) if dict_source else Task(self)
264 id_ = id_ if id_ else str(uuid4())
271 def add_day(self, dict_source=None):
272 return Day.from_dict(self, dict_source) if dict_source else Day(self)
276 self.add_task(id_=f'new{i}')
277 for date, day in self.old_days.items():
278 for task_uuid, todo in day.todos.items():
279 todo.title = self.tasks[task_uuid].title_at(date)
280 return Template(selected_day_tmpl + old_days_tmpl + form_footer).render(db=self, action=self.prefix+'/all')
282 def show_selected_day(self):
283 return Template(selected_day_tmpl + form_footer).render(db=self, action=self.prefix+'/day')
286 class TodoHandler(PlomHandler):
288 def app_init(self, handler):
289 default_path = '/todo'
290 handler.add_route('GET', default_path, self.show_db)
291 handler.add_route('POST', default_path, self.write_db)
292 return 'todo', default_path
295 self.try_do(self.write_db)
298 from urllib.parse import urlencode
299 prefix = self.apps['todo'] if hasattr(self, 'apps') else ''
301 length = int(self.headers['content-length'])
302 postvars = parse_qs(self.rfile.read(length).decode(), keep_blank_values=1)
304 # pp = pprint.PrettyPrinter(indent=4)
305 # pp.pprint(postvars)
306 db.t_filter_and = set()
307 db.t_filter_not = set()
308 if 't_filter_and' in postvars.keys():
309 for target in postvars['t_filter_and']:
310 db.t_filter_and.add(target)
311 if 't_filter_not' in postvars.keys():
312 for target in postvars['t_filter_not']:
313 db.t_filter_not.add(target)
314 if 'hide_unchosen' in postvars.keys():
315 db.hide_unchosen = True
316 if 't_uuid' in postvars.keys():
317 new_postvars_t_uuid = postvars['t_uuid'].copy()
318 for i, uuid in enumerate(postvars['t_uuid']):
319 if len(uuid) < 36 and len(postvars['t_title'][i]) > 0:
320 new_uuid, t = db.add_task(return_id=True)
321 new_postvars_t_uuid[i] = new_uuid
322 for key in [k for k in postvars.keys() if not k == 't_uuid']:
323 if uuid in postvars[key]:
324 uuid_index = postvars[key].index(uuid)
325 postvars[key][uuid_index] = new_uuid
326 postvars['t_uuid'] = new_postvars_t_uuid
327 for i, uuid in enumerate(postvars['t_uuid']):
331 t.set_title(postvars['t_title'][i])
332 t.tags_from_joined_string(postvars['t_tags'][i])
333 t.set_default_weight(float(postvars['t_default_weight'][i]))
334 if uuid in db.selected_day.todos.keys() and ((not 'choose' in postvars) or uuid not in postvars['choose']):
335 del db.selected_day.todos[uuid]
336 if 'choose' in postvars.keys():
337 for i, uuid in enumerate(postvars['t_uuid']):
338 if uuid in postvars['choose']:
339 done = 'done' in postvars and uuid in postvars['done']
340 day_weight = float(postvars['day_weight'][i]) if postvars['day_weight'][i] else None
341 db.selected_day.add_todo(uuid, {'done': done, 'day_weight': day_weight})
342 db.selected_day_date = postvars['selected_day_date'][0]
343 db.selected_day.comment = postvars['comment'][0]
344 switch_edited_day = None
345 for date in db.old_days.keys():
346 if f'edit_{date}' in postvars.keys():
347 switch_edited_day = date
349 if 'archive_day' in postvars.keys() or switch_edited_day:
350 db.save_selected_day()
351 if switch_edited_day:
356 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))]
357 encoded_params = urlencode(data)
358 parsed_url = urlparse(self.path)
359 if prefix + '/day' == parsed_url.path:
360 homepage = f'{prefix}/day?{encoded_params}'
362 homepage = f'{prefix}/all?{encoded_params}'
363 self.redirect(homepage)
366 self.try_do(self.show_db)
369 prefix = self.apps['todo'] if hasattr(self, 'apps') else ''
370 parsed_url = urlparse(self.path)
371 params = parse_qs(parsed_url.query)
372 t_filter_and = set(params.get('t_and', []))
373 t_filter_not = set(params.get('t_not', ['deleted']))
374 hide_unchosen_params = params.get('hide_unchosen', [])
375 hide_unchosen = len(hide_unchosen_params) > 0 and hide_unchosen_params[0] != '0'
376 db = TodoDB(prefix, t_filter_and, t_filter_not, hide_unchosen)
377 if parsed_url.path == prefix + '/day':
378 page = db.show_selected_day()
381 header = Template(html_head).render(prefix=prefix)
382 self.send_HTML(header + page)
385 if __name__ == "__main__":
386 run_server(server_port, TodoHandler)