1 from plomlib import PlomDB, run_server, PlomHandler, PlomException
4 from datetime import datetime
5 from urllib.parse import parse_qs
6 db_path = '/home/plom/org/todo_new.json'
7 # db_path = '/home/plom/public_repos/misc/todo_new.json'
12 td { border: 1px solid black; }
15 <form action="{{homepage}}" method="POST">
17 mandatory tags: {% for t_tag in db.t_tags | sort %}
18 <input name="t_filter_and" type="checkbox" value="{{ t_tag }}" {% if t_tag in db.t_filter_and %} checked {% endif %} >{{ t_tag }}
21 forbidden tags: {% for t_tag in db.t_tags | sort %}
22 <input name="t_filter_not" type="checkbox" value="{{ t_tag }}" {% if t_tag in db.t_filter_not %} checked {% endif %} >{{ t_tag }}
25 <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>
26 <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>
27 {% for uuid, t in db.tasks.items() | sort(attribute='1.title', reverse=True) %}
29 <input name="t_uuid" value="{{ uuid }}" type="hidden" >
31 <td><input name="t_default_weight" value="{{ t.default_weight }}" type="number" step=0.1 size=5 required/></td>
32 <td><input name="t_title" value="{{ t.title|e }}"/></td>
33 <td><input name="t_tags" value="{{ t.tags_joined|e }}" >
34 <td><input name="do_today" type="checkbox" value="{{ uuid }}" {% if uuid in db.today.todos.keys() %}checked{% endif %} ></td>
35 <td><input name="done" type="checkbox" value="{{ uuid }}" {% if uuid in db.today.todos.keys() and db.today.todos[uuid].done %}checked{% endif %} ></td>
36 <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>
42 <input type="submit" value="OK">
44 {% for date, day in db.old_days.items() | sort(reverse=True) %}
45 <tr><td>{{ date }} ({{ day.todos_sum|round(2) }}) {{ day.comment|e }} <input type="submit" name="edit_{{date}}" value="edit" /></td></tr>
46 {% for task, todo in day.todos.items() | sort(attribute='1.title', reverse=True) %}
47 <tr><td>{{ todo.title }}</td><td>{% if todo.done %}✓{% endif %}</td><td>{{ todo.weight }}</td></tr>
56 def __init__(self, title_history={}, tags_history={}, default_weight_history={}):
57 self.title_history = title_history.copy()
58 self.tags_history = tags_history.copy()
59 self.default_weight_history = default_weight_history.copy()
62 def _set_with_history(self, history, value):
63 keys = sorted(history.keys())
64 if len(history) == 0 or value != history[keys[-1]]:
65 history[str(datetime.now())[:19]] = value
67 def _last_of_history(self, history, default):
68 keys = sorted(history.keys())
69 return default if 0 == len(history) else history[keys[-1]]
72 def from_dict(cls, d):
75 {k: set(v) for k, v in d['tags_history'].items()},
76 d['default_weight_history'])
78 def tags_from_joined_string(self, tags_string):
80 for tag in [tag.strip() for tag in tags_string.split(';') if tag.strip() != '']:
85 def tags_joined(self):
86 return ';'.join(sorted(list(self.tags)))
88 def set_default_weight(self, default_weight):
89 self._set_with_history(self.default_weight_history, default_weight)
92 def default_weight(self):
93 return self._last_of_history(self.default_weight_history, 1)
95 def set_title(self, title):
96 self._set_with_history(self.title_history, title)
100 return self._last_of_history(self.title_history, '')
102 def title_at(self, queried_date):
103 ret = self.title_history[sorted(self.title_history.keys())[0]]
104 for date_key, title in self.title_history.items():
105 if date_key > f'{queried_date} 23:59:59':
110 def set_tags(self, tags):
111 self._set_with_history(self.tags_history, set(tags))
115 return self._last_of_history(self.tags_history, set())
119 'title_history': self.title_history,
120 'tags_history': {k: list(v) for k,v in self.tags_history.items()},
121 'default_weight_history': self.default_weight_history}
126 def __init__(self, todos, comment=''):
128 self.comment = comment
131 def from_dict(cls, d):
133 comment = d['comment'] if 'comment' in d.keys() else ''
134 for uuid, todo_dict in d['todos'].items():
135 todos[uuid] = Todo.from_dict(todo_dict)
136 return cls(todos, comment)
141 for todo in [todo for todo in self.todos.values() if todo.done]:
146 d = {'comment': self.comment, 'todos': {}}
147 for task_uuid, todo in self.todos.items():
148 d['todos'][task_uuid] = todo.to_dict()
154 def __init__(self, done=False, weight=None):
159 def from_dict(cls, d):
160 return cls(d['done'], d['weight'])
163 return {'done': self.done, 'weight': self.weight}
166 class TodoDB(PlomDB):
168 def __init__(self, t_filter_and = set(), t_filter_not = set()):
169 self.t_filter_and = t_filter_and
170 self.t_filter_not = t_filter_not
175 super().__init__(db_path)
177 def read_db_file(self, f):
179 self.today = Day.from_dict(d['today'])
180 self.today_date = d['today_date']
181 for uuid, t_dict in d['tasks'].items():
182 t = Task.from_dict(t_dict)
184 t.visible = len([tag for tag in self.t_filter_and if not tag in t.tags]) == 0\
185 and len([tag for tag in self.t_filter_not if tag in t.tags]) == 0
188 for date, day_dict in d['old_days'].items():
189 self.old_days[date] = Day.from_dict(day_dict)
193 'today': self.today.to_dict(),
194 'today_date': self.today_date,
195 't_filter_and': list(self.t_filter_and),
196 't_filter_not': list(self.t_filter_not),
200 for uuid, t in self.tasks.items():
201 d['tasks'][uuid] = t.to_dict()
202 for date, day in self.old_days.items():
203 d['old_days'][date] = day.to_dict()
207 self.write_text_to_db(json.dumps(self.to_dict()))
209 def save_today(self):
210 if self.today_date in self.old_days.keys():
211 raise PlomException('cannot use same date twice')
212 for task_uuid, todo in [(task_uuid, todo) for task_uuid, todo in self.today.todos.items()
214 todo.weight = self.tasks[task_uuid].default_weight
215 self.old_days[self.today_date] = self.today
217 def reset_today(self, date=None):
219 self.today_date = date
220 self.today = self.old_days[date]
221 del self.old_days[date]
223 self.today_date = str(datetime.now())[:10]
227 class TodoHandler(PlomHandler):
229 def app_init(self, handler):
230 default_path = '/todo'
231 handler.add_route('GET', default_path, self.show_db)
232 handler.add_route('POST', default_path, self.write_db)
233 return 'todo', default_path
236 self.try_do(self.write_db)
239 from urllib.parse import urlencode
241 length = int(self.headers['content-length'])
242 postvars = parse_qs(self.rfile.read(length).decode(), keep_blank_values=1)
245 pp = pprint.PrettyPrinter(indent=4)
248 db.t_filter_and = set()
249 db.t_filter_not = set()
250 if 't_filter_and' in postvars.keys():
251 for target in postvars['t_filter_and']:
252 db.t_filter_and.add(target)
253 if 't_filter_not' in postvars.keys():
254 for target in postvars['t_filter_not']:
255 db.t_filter_not.add(target)
256 if 't_uuid' in postvars.keys():
257 new_postvars_t_uuid = postvars['t_uuid'].copy()
258 for i, uuid in enumerate(postvars['t_uuid']):
259 if len(uuid) < 36 and len(postvars['t_title'][i]) > 0:
261 new_uuid = str(uuid4())
262 db.tasks[new_uuid] = t
263 new_postvars_t_uuid[i] = new_uuid
264 for key in [k for k in postvars.keys() if not k == 't_uuid']:
265 if uuid in postvars[key]:
266 uuid_index = postvars[key].index(uuid)
267 postvars[key][uuid_index] = new_uuid
268 postvars['t_uuid'] = new_postvars_t_uuid
269 for i, uuid in enumerate(postvars['t_uuid']):
273 t.set_title(postvars['t_title'][i])
274 t.tags_from_joined_string(postvars['t_tags'][i])
275 t.set_default_weight(float(postvars['t_default_weight'][i]))
276 if uuid in db.today.todos.keys() and ((not 'do_today' in postvars) or uuid not in postvars['do_today']):
277 del db.today.todos[uuid]
278 if 'do_today' in postvars.keys():
279 for i, uuid in enumerate(postvars['t_uuid']):
280 if uuid in postvars['do_today']:
281 done = 'done' in postvars and uuid in postvars['done']
282 weight = float(postvars['weight'][i]) if postvars['weight'][i] else None
283 db.today.todos[uuid] = Todo(done, weight)
284 db.today_date = postvars['today_date'][0]
285 db.today.comment = postvars['comment'][0]
286 switch_edited_day = None
287 for date in db.old_days.keys():
288 if f'edit_{date}' in postvars.keys():
289 switch_edited_day = date
291 if 'archive_today' in postvars.keys() or switch_edited_day:
293 if switch_edited_day:
298 homepage = self.apps['todo'] if hasattr(self, 'apps') else self.homepage
299 data = [('t_and', f) for f in db.t_filter_and] + [('t_not', f) for f in db.t_filter_not]
300 encoded_params = urlencode(data)
301 homepage += '?' + encoded_params
302 self.redirect(homepage)
305 self.try_do(self.show_db)
308 from jinja2 import Template
309 from urllib.parse import urlparse
310 parsed_url = urlparse(self.path)
311 params = parse_qs(parsed_url.query)
312 t_filter_and = set(params.get('t_and', []))
313 t_filter_not = set(params.get('t_not', ['deleted']))
314 db = TodoDB(t_filter_and, t_filter_not)
316 db.tasks[f'new{i}'] = Task()
317 for date, day in db.old_days.items():
318 for task_uuid, todo in day.todos.items():
319 todo.title = db.tasks[task_uuid].title_at(date)
320 page = Template(tmpl).render(db=db)
324 if __name__ == "__main__":
325 run_server(server_port, TodoHandler)