home · contact · privacy
444923218121b91d648f2ba87052ea3801dd838a
[misc] / todo.py
1 from plomlib import PlomDB, run_server, PlomHandler, PlomException 
2 import json
3 from uuid import uuid4
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'
10 server_port = 8082
11
12 html_head = """
13 <style>
14 td { border: 1px solid black; }
15 </style>
16 <body>
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 <hr />
21 """
22
23 form_footer = '\n</form>'
24
25 old_days_tmpl = """
26 <table>
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>
31 {% endfor %}
32 {% endfor %}
33 </table>
34 """
35
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 }}
41 {% endfor %}
42 <br />
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 }}
45 {% endfor %}
46 <table>
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) %}
50 {% if t.visible %}
51 <input name="t_uuid" value="{{ uuid }}" type="hidden" >
52 <tr>
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>
59 </tr>
60 {% endif %}
61 {% endfor %}
62 </table>
63 <input type="submit" value="OK">
64 """
65
66 class Task:
67
68     def __init__(self, db, title_history={}, tags_history={}, default_weight_history={}):
69         self.db = db
70         self.title_history = title_history.copy()
71         self.tags_history = tags_history.copy()
72         self.default_weight_history = default_weight_history.copy()
73         self.visible = True
74
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
79
80     def _last_of_history(self, history, default):
81         keys = sorted(history.keys())
82         return default if 0 == len(history) else history[keys[-1]] 
83
84     @classmethod
85     def from_dict(cls, db, d):
86         return cls(
87                 db,
88                 d['title_history'],
89                 {k: set(v) for k, v in d['tags_history'].items()},
90                 d['default_weight_history'])
91
92     def tags_from_joined_string(self, tags_string):
93         tags = set()
94         for tag in [tag.strip() for tag in tags_string.split(';') if tag.strip() != '']:
95             tags.add(tag)
96         self.set_tags(tags)
97
98     @property
99     def tags_joined(self):
100         return ';'.join(sorted(list(self.tags)))
101
102     def set_default_weight(self, default_weight):
103         self._set_with_history(self.default_weight_history, default_weight)
104
105     @property
106     def default_weight(self):
107         return self._last_of_history(self.default_weight_history, 1)
108
109     def set_title(self, title):
110         self._set_with_history(self.title_history, title)
111
112     @property
113     def title(self):
114         return self._last_of_history(self.title_history, '')
115
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':
120                 break
121             ret = title
122         return ret
123
124     def set_tags(self, tags):
125         self._set_with_history(self.tags_history, set(tags))
126
127     @property
128     def tags(self):
129         return self._last_of_history(self.tags_history, set())
130
131     def to_dict(self):
132         return {
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}
136
137
138 class Day:
139
140     def __init__(self, db, todos={}, comment=''):
141         self.db = db
142         self.todos = todos 
143         self.comment = comment
144
145     @classmethod
146     def from_dict(cls, db, d):
147         todos = {}
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)
152         return day
153
154     def to_dict(self):
155         d = {'comment': self.comment, 'todos': {}}
156         for task_uuid, todo in self.todos.items():
157             d['todos'][task_uuid] = todo.to_dict()
158         return d
159
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)
162
163     def _todos_sum(self, include_undone=False):
164         s = 0
165         for todo in [todo for todo in self.todos.values() if todo.done]:
166             s += todo.weight
167         if include_undone:
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
170         return s
171
172     @property
173     def todos_sum(self):
174         return self._todos_sum()
175
176     @property
177     def todos_sum2(self):
178         return self._todos_sum(True)
179
180 class Todo:
181
182     def __init__(self, day, done=False, day_weight=None):
183         self.day = day 
184         self.done = done
185         self.day_weight = day_weight
186
187     @classmethod
188     def from_dict(cls, day, d):
189         return cls(day, d['done'], d['day_weight'])
190
191     def to_dict(self):
192         return {'done': self.done, 'day_weight': self.day_weight}
193
194     @property
195     def weight(self):
196         if self.day_weight:
197             return self.day_weight
198         else:
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
201
202
203 class TodoDB(PlomDB):
204
205     def __init__(self, prefix, t_filter_and = set(), t_filter_not = set(), hide_unchosen=False):
206         self.prefix = prefix
207         self.t_filter_and = t_filter_and
208         self.t_filter_not = t_filter_not
209         self.hide_unchosen = hide_unchosen 
210         self.old_days = {}
211         self.tasks = {}
212         self.reset_day()
213         self.t_tags = set() 
214         super().__init__(db_path)
215
216     def read_db_file(self, f):
217         d = json.load(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)
225             for tag in t.tags:
226                 self.t_tags.add(tag)
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)
229
230     def to_dict(self):
231         d = {
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),
236                 'tasks': {},
237                 'old_days': {}
238         }
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()
243         return d
244
245     def write(self):
246         self.write_text_to_db(json.dumps(self.to_dict()))
247
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
252
253     def reset_day(self, date=None):
254         if date:
255             self.selected_day_date = date 
256             self.selected_day = self.old_days[date]
257             del self.old_days[date]
258         else:
259             self.selected_day_date = str(datetime.now())[:10]
260             self.selected_day = self.add_day()
261
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())
265         self.tasks[id_] = t
266         if return_id:
267             return id_, t
268         else: 
269             return t
270
271     def add_day(self, dict_source=None):
272         return Day.from_dict(self, dict_source) if dict_source else Day(self)
273
274     def show_all(self):
275         for i in range(10):
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')
281
282     def show_selected_day(self):
283         return Template(selected_day_tmpl + form_footer).render(db=self, action=self.prefix+'/day')
284
285
286 class TodoHandler(PlomHandler):
287     
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 
293
294     def do_POST(self):
295         self.try_do(self.write_db)
296
297     def write_db(self):
298         from urllib.parse import urlencode
299         prefix = self.apps['todo'] if hasattr(self, 'apps') else '' 
300         db = TodoDB(prefix)
301         length = int(self.headers['content-length'])
302         postvars = parse_qs(self.rfile.read(length).decode(), keep_blank_values=1)
303         # import pprint
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']):
328                 if len(uuid) < 36:
329                     continue
330                 t = db.tasks[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
348                 break
349         if 'archive_day' in postvars.keys() or switch_edited_day:
350             db.save_selected_day()
351             if switch_edited_day:
352                 db.reset_day(date) 
353             else:
354                 db.reset_day()
355         db.write()
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}'
361         else:
362             homepage = f'{prefix}/all?{encoded_params}'
363         self.redirect(homepage)
364
365     def do_GET(self):
366         self.try_do(self.show_db)
367
368     def show_db(self):
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()
379         else:
380             page = db.show_all()
381         header = Template(html_head).render(prefix=prefix)
382         self.send_HTML(header + page)
383
384
385 if __name__ == "__main__":  
386     run_server(server_port, TodoHandler)