home · contact · privacy
To lewdger.py, add in-transaction line mirroring.
[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 db_path = '/home/plom/org/todo_new.json'
7 # db_path = '/home/plom/public_repos/misc/todo_new.json'
8 server_port = 8082
9
10 tmpl = """
11 <style>
12 td { border: 1px solid black; }
13 </style>
14 <body>
15 <form action="{{homepage}}" method="POST">
16
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 }}
19 {% endfor %}
20 <br />
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 }}
23 {% endfor %}
24 <table>
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) %}
28 {% if t.visible %}
29 <input name="t_uuid" value="{{ uuid }}" type="hidden" >
30 <tr>
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>
37 </tr>
38 {% endif %}
39 {% endfor %}
40 </table>
41
42 <input type="submit" value="OK">
43 <table>
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>
48 {% endfor %}
49 {% endfor %}
50 </table>
51 </form>
52 """
53
54 class Task:
55
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()
60         self.visible = True
61
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
66
67     def _last_of_history(self, history, default):
68         keys = sorted(history.keys())
69         return default if 0 == len(history) else history[keys[-1]] 
70
71     @classmethod
72     def from_dict(cls, d):
73         return cls(
74                 d['title_history'],
75                 {k: set(v) for k, v in d['tags_history'].items()},
76                 d['default_weight_history'])
77
78     def tags_from_joined_string(self, tags_string):
79         tags = set()
80         for tag in [tag.strip() for tag in tags_string.split(';') if tag.strip() != '']:
81             tags.add(tag)
82         self.set_tags(tags)
83
84     @property
85     def tags_joined(self):
86         return ';'.join(sorted(list(self.tags)))
87
88     def set_default_weight(self, default_weight):
89         self._set_with_history(self.default_weight_history, default_weight)
90
91     @property
92     def default_weight(self):
93         return self._last_of_history(self.default_weight_history, 1)
94
95     def set_title(self, title):
96         self._set_with_history(self.title_history, title)
97
98     @property
99     def title(self):
100         return self._last_of_history(self.title_history, '')
101
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':
106                 break
107             ret = title
108         return ret
109
110     def set_tags(self, tags):
111         self._set_with_history(self.tags_history, set(tags))
112
113     @property
114     def tags(self):
115         return self._last_of_history(self.tags_history, set())
116
117     def to_dict(self):
118         return {
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}
122
123
124 class Day:
125
126     def __init__(self, todos, comment=''):
127         self.todos = todos 
128         self.comment = comment
129
130     @classmethod
131     def from_dict(cls, d):
132         todos = {}
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)
137
138     @property
139     def todos_sum(self):
140         s = 0
141         for todo in [todo for todo in self.todos.values() if todo.done]:
142             s += todo.weight
143         return s
144
145     def to_dict(self):
146         d = {'comment': self.comment, 'todos': {}}
147         for task_uuid, todo in self.todos.items():
148             d['todos'][task_uuid] = todo.to_dict()
149         return d
150
151
152 class Todo:
153
154     def __init__(self, done=False, weight=None):
155         self.done = done
156         self.weight = weight
157
158     @classmethod
159     def from_dict(cls, d):
160         return cls(d['done'], d['weight'])
161
162     def to_dict(self):
163         return {'done': self.done, 'weight': self.weight}
164
165
166 class TodoDB(PlomDB):
167
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
171         self.old_days = {}
172         self.tasks = {}
173         self.reset_today()
174         self.t_tags = set() 
175         super().__init__(db_path)
176
177     def read_db_file(self, f):
178         d = json.load(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)
183             self.tasks[uuid] = t
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
186             for tag in t.tags:
187                 self.t_tags.add(tag)
188         for date, day_dict in d['old_days'].items():
189             self.old_days[date] = Day.from_dict(day_dict)
190
191     def to_dict(self):
192         d = {
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),
197                 'tasks': {},
198                 'old_days': {}
199         }
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()
204         return d
205
206     def write(self):
207         self.write_text_to_db(json.dumps(self.to_dict()))
208
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()
213                                 if not todo.weight]:
214             todo.weight = self.tasks[task_uuid].default_weight
215         self.old_days[self.today_date] = self.today
216
217     def reset_today(self, date=None):
218         if date:
219             self.today_date = date 
220             self.today = self.old_days[date]
221             del self.old_days[date]
222         else:
223             self.today_date = str(datetime.now())[:10]
224             self.today = Day({})
225
226
227 class TodoHandler(PlomHandler):
228     
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 
234
235     def do_POST(self):
236         self.try_do(self.write_db)
237
238     def write_db(self):
239         from urllib.parse import urlencode
240         db = TodoDB()
241         length = int(self.headers['content-length'])
242         postvars = parse_qs(self.rfile.read(length).decode(), keep_blank_values=1)
243
244         import pprint
245         pp = pprint.PrettyPrinter(indent=4)
246         pp.pprint(postvars)
247
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:
260                         t = Task() 
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']):
270                 if len(uuid) < 36:
271                     continue
272                 t = db.tasks[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
290                 break
291         if 'archive_today' in postvars.keys() or switch_edited_day:
292             db.save_today()
293             if switch_edited_day:
294                 db.reset_today(date) 
295             else:
296                 db.reset_today()
297         db.write()
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)
303
304     def do_GET(self):
305         self.try_do(self.show_db)
306
307     def show_db(self):
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)
315         for i in range(10):
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)
321         self.send_HTML(page)
322
323
324 if __name__ == "__main__":  
325     run_server(server_port, TodoHandler)