home · contact · privacy
Allow creation of new Todos rather than just adoption from Todo edit view.
[plomtask] / plomtask / http.py
1 """Web server stuff."""
2 from typing import Any
3 from base64 import b64encode, b64decode
4 from http.server import BaseHTTPRequestHandler
5 from http.server import HTTPServer
6 from urllib.parse import urlparse, parse_qs
7 from os.path import split as path_split
8 from jinja2 import Environment as JinjaEnv, FileSystemLoader as JinjaFSLoader
9 from plomtask.dating import date_in_n_days
10 from plomtask.days import Day
11 from plomtask.exceptions import HandledException, BadFormatException, \
12         NotFoundException
13 from plomtask.db import DatabaseConnection, DatabaseFile
14 from plomtask.processes import Process, ProcessStep
15 from plomtask.conditions import Condition
16 from plomtask.todos import Todo
17
18 TEMPLATES_DIR = 'templates'
19
20
21 class TaskServer(HTTPServer):
22     """Variant of HTTPServer that knows .jinja as Jinja Environment."""
23
24     def __init__(self, db_file: DatabaseFile,
25                  *args: Any, **kwargs: Any) -> None:
26         super().__init__(*args, **kwargs)
27         self.db = db_file
28         self.jinja = JinjaEnv(loader=JinjaFSLoader(TEMPLATES_DIR))
29
30
31 class InputsParser:
32     """Wrapper for validating and retrieving dict-like HTTP inputs."""
33
34     def __init__(self, dict_: dict[str, list[str]],
35                  strictness: bool = True) -> None:
36         self.inputs = dict_
37         self.strict = strictness
38
39     def get_str(self, key: str, default: str = '',
40                 ignore_strict: bool = False) -> str:
41         """Retrieve single/first string value of key, or default."""
42         if key not in self.inputs.keys() or 0 == len(self.inputs[key]):
43             if self.strict and not ignore_strict:
44                 raise BadFormatException(f'no value found for key {key}')
45             return default
46         return self.inputs[key][0]
47
48     def get_int(self, key: str) -> int:
49         """Retrieve single/first value of key as int, error if empty."""
50         val = self.get_int_or_none(key)
51         if val is None:
52             raise BadFormatException(f'unexpected empty value for: {key}')
53         return val
54
55     def get_int_or_none(self, key: str) -> int | None:
56         """Retrieve single/first value of key as int, return None if empty."""
57         val = self.get_str(key, ignore_strict=True)
58         if val == '':
59             return None
60         try:
61             return int(val)
62         except ValueError as e:
63             msg = f'cannot int form field value for key {key}: {val}'
64             raise BadFormatException(msg) from e
65
66     def get_float(self, key: str) -> float:
67         """Retrieve float value of key from self.postvars."""
68         val = self.get_str(key)
69         try:
70             return float(val)
71         except ValueError as e:
72             msg = f'cannot float form field value for key {key}: {val}'
73             raise BadFormatException(msg) from e
74
75     def get_all_str(self, key: str) -> list[str]:
76         """Retrieve list of string values at key."""
77         if key not in self.inputs.keys():
78             return []
79         return self.inputs[key]
80
81     def get_all_int(self, key: str) -> list[int]:
82         """Retrieve list of int values at key."""
83         all_str = self.get_all_str(key)
84         try:
85             return [int(s) for s in all_str if len(s) > 0]
86         except ValueError as e:
87             msg = f'cannot int a form field value for key {key} in: {all_str}'
88             raise BadFormatException(msg) from e
89
90
91 class TaskHandler(BaseHTTPRequestHandler):
92     """Handles single HTTP request."""
93     server: TaskServer
94
95     def do_GET(self) -> None:
96         """Handle any GET request."""
97         try:
98             self._init_handling()
99             if hasattr(self, f'do_GET_{self.site}'):
100                 template = f'{self.site}.html'
101                 ctx = getattr(self, f'do_GET_{self.site}')()
102                 html = self.server.jinja.get_template(template).render(**ctx)
103                 self._send_html(html)
104             elif '' == self.site:
105                 self._redirect('/day')
106             else:
107                 raise NotFoundException(f'Unknown page: /{self.site}')
108         except HandledException as error:
109             self._send_msg(error, code=error.http_code)
110         finally:
111             self.conn.close()
112
113     def do_GET_calendar(self) -> dict[str, object]:
114         """Show Days from ?start= to ?end=."""
115         start = self.params.get_str('start')
116         end = self.params.get_str('end')
117         if not end:
118             end = date_in_n_days(60)
119         ret = Day.by_date_range_with_limits(self.conn, (start, end), 'id')
120         days, start, end = ret
121         days = Day.with_filled_gaps(days, start, end)
122         for day in days:
123             day.collect_calendarized_todos(self.conn)
124         today = date_in_n_days(0)
125         return {'start': start, 'end': end, 'days': days, 'today': today}
126
127     def do_GET_day(self) -> dict[str, object]:
128         """Show single Day of ?date=."""
129         date = self.params.get_str('date', date_in_n_days(0))
130         todays_todos = Todo.by_date(self.conn, date)
131         conditions_present = []
132         enablers_for = {}
133         disablers_for = {}
134         for todo in todays_todos:
135             for condition in todo.conditions + todo.blockers:
136                 if condition not in conditions_present:
137                     conditions_present += [condition]
138                     enablers_for[condition.id_] = [p for p in
139                                                    Process.all(self.conn)
140                                                    if condition in p.enables]
141                     disablers_for[condition.id_] = [p for p in
142                                                     Process.all(self.conn)
143                                                     if condition in p.disables]
144         seen_todos: set[int] = set()
145         top_nodes = [t.get_step_tree(seen_todos)
146                      for t in todays_todos if not t.parents]
147         return {'day': Day.by_id(self.conn, date, create=True),
148                 'top_nodes': top_nodes,
149                 'enablers_for': enablers_for,
150                 'disablers_for': disablers_for,
151                 'conditions_present': conditions_present,
152                 'processes': Process.all(self.conn)}
153
154     def do_GET_todo(self) -> dict[str, object]:
155         """Show single Todo of ?id=."""
156         id_ = self.params.get_int('id')
157         todo = Todo.by_id(self.conn, id_)
158         return {'todo': todo,
159                 'process_candidates': Process.all(self.conn),
160                 'todo_candidates': Todo.by_date(self.conn, todo.date),
161                 'condition_candidates': Condition.all(self.conn)}
162
163     def do_GET_todos(self) -> dict[str, object]:
164         """Show Todos from ?start= to ?end=, of ?process=, ?comment= pattern"""
165         sort_by = self.params.get_str('sort_by')
166         start = self.params.get_str('start')
167         end = self.params.get_str('end')
168         process_id = self.params.get_int_or_none('process_id')
169         comment_pattern = self.params.get_str('comment_pattern')
170         todos = []
171         ret = Todo.by_date_range_with_limits(self.conn, (start, end))
172         todos_by_date_range, start, end = ret
173         todos = [t for t in todos_by_date_range
174                  if comment_pattern in t.comment
175                  and ((not process_id) or t.process.id_ == process_id)]
176         if sort_by == 'doneness':
177             todos.sort(key=lambda t: t.is_done)
178         elif sort_by == '-doneness':
179             todos.sort(key=lambda t: t.is_done, reverse=True)
180         elif sort_by == 'title':
181             todos.sort(key=lambda t: t.title_then)
182         elif sort_by == '-title':
183             todos.sort(key=lambda t: t.title_then, reverse=True)
184         elif sort_by == 'comment':
185             todos.sort(key=lambda t: t.comment)
186         elif sort_by == '-comment':
187             todos.sort(key=lambda t: t.comment, reverse=True)
188         elif sort_by == '-date':
189             todos.sort(key=lambda t: t.date, reverse=True)
190         else:
191             todos.sort(key=lambda t: t.date)
192         return {'start': start, 'end': end, 'process_id': process_id,
193                 'comment_pattern': comment_pattern, 'todos': todos,
194                 'all_processes': Process.all(self.conn), 'sort_by': sort_by}
195
196     def do_GET_conditions(self) -> dict[str, object]:
197         """Show all Conditions."""
198         pattern = self.params.get_str('pattern')
199         conditions = Condition.matching(self.conn, pattern)
200         sort_by = self.params.get_str('sort_by')
201         if sort_by == 'is_active':
202             conditions.sort(key=lambda c: c.is_active)
203         elif sort_by == '-is_active':
204             conditions.sort(key=lambda c: c.is_active, reverse=True)
205         elif sort_by == '-title':
206             conditions.sort(key=lambda c: c.title.newest, reverse=True)
207         else:
208             conditions.sort(key=lambda c: c.title.newest)
209         return {'conditions': conditions,
210                 'sort_by': sort_by,
211                 'pattern': pattern}
212
213     def do_GET_condition(self) -> dict[str, object]:
214         """Show Condition of ?id=."""
215         id_ = self.params.get_int_or_none('id')
216         c = Condition.by_id(self.conn, id_, create=True)
217         ps = Process.all(self.conn)
218         return {'condition': c, 'is_new': c.id_ is None,
219                 'enabled_processes': [p for p in ps if c in p.conditions],
220                 'disabled_processes': [p for p in ps if c in p.blockers],
221                 'enabling_processes': [p for p in ps if c in p.enables],
222                 'disabling_processes': [p for p in ps if c in p.disables]}
223
224     def do_GET_condition_titles(self) -> dict[str, object]:
225         """Show title history of Condition of ?id=."""
226         id_ = self.params.get_int_or_none('id')
227         condition = Condition.by_id(self.conn, id_)
228         return {'condition': condition}
229
230     def do_GET_condition_descriptions(self) -> dict[str, object]:
231         """Show description historys of Condition of ?id=."""
232         id_ = self.params.get_int_or_none('id')
233         condition = Condition.by_id(self.conn, id_)
234         return {'condition': condition}
235
236     def do_GET_process(self) -> dict[str, object]:
237         """Show Process of ?id=."""
238         id_ = self.params.get_int_or_none('id')
239         process = Process.by_id(self.conn, id_, create=True)
240         title_64 = self.params.get_str('title_b64')
241         if title_64:
242             title = b64decode(title_64.encode()).decode()
243             process.title.set(title)
244         owners = process.used_as_step_by(self.conn)
245         for step_id in self.params.get_all_int('step_to'):
246             owners += [Process.by_id(self.conn, step_id)]
247         preset_top_step = None
248         for process_id in self.params.get_all_int('has_step'):
249             preset_top_step = process_id
250         return {'process': process, 'is_new': process.id_ is None,
251                 'preset_top_step': preset_top_step,
252                 'steps': process.get_steps(self.conn), 'owners': owners,
253                 'n_todos': len(Todo.by_process_id(self.conn, process.id_)),
254                 'process_candidates': Process.all(self.conn),
255                 'condition_candidates': Condition.all(self.conn)}
256
257     def do_GET_process_titles(self) -> dict[str, object]:
258         """Show title history of Process of ?id=."""
259         id_ = self.params.get_int_or_none('id')
260         process = Process.by_id(self.conn, id_)
261         return {'process': process}
262
263     def do_GET_process_descriptions(self) -> dict[str, object]:
264         """Show description historys of Process of ?id=."""
265         id_ = self.params.get_int_or_none('id')
266         process = Process.by_id(self.conn, id_)
267         return {'process': process}
268
269     def do_GET_process_efforts(self) -> dict[str, object]:
270         """Show default effort history of Process of ?id=."""
271         id_ = self.params.get_int_or_none('id')
272         process = Process.by_id(self.conn, id_)
273         return {'process': process}
274
275     def do_GET_processes(self) -> dict[str, object]:
276         """Show all Processes."""
277         pattern = self.params.get_str('pattern')
278         processes = Process.matching(self.conn, pattern)
279         sort_by = self.params.get_str('sort_by')
280         if sort_by == 'steps':
281             processes.sort(key=lambda p: len(p.explicit_steps))
282         elif sort_by == '-steps':
283             processes.sort(key=lambda p: len(p.explicit_steps), reverse=True)
284         elif sort_by == 'owners':
285             processes.sort(key=lambda p: p.n_owners or 0)
286         elif sort_by == '-owners':
287             processes.sort(key=lambda p: p.n_owners or 0, reverse=True)
288         elif sort_by == 'effort':
289             processes.sort(key=lambda p: p.effort.newest)
290         elif sort_by == '-effort':
291             processes.sort(key=lambda p: p.effort.newest, reverse=True)
292         elif sort_by == '-title':
293             processes.sort(key=lambda p: p.title.newest, reverse=True)
294         else:
295             processes.sort(key=lambda p: p.title.newest)
296         return {'processes': processes, 'sort_by': sort_by, 'pattern': pattern}
297
298     def do_POST(self) -> None:
299         """Handle any POST request."""
300         # pylint: disable=attribute-defined-outside-init
301         try:
302             self._init_handling()
303             length = int(self.headers['content-length'])
304             postvars = parse_qs(self.rfile.read(length).decode(),
305                                 keep_blank_values=True, strict_parsing=True)
306             self.form_data = InputsParser(postvars)
307             if hasattr(self, f'do_POST_{self.site}'):
308                 redir_target = getattr(self, f'do_POST_{self.site}')()
309                 self.conn.commit()
310             else:
311                 msg = f'Page not known as POST target: /{self.site}'
312                 raise NotFoundException(msg)
313             self._redirect(redir_target)
314         except HandledException as error:
315             self._send_msg(error, code=error.http_code)
316         finally:
317             self.conn.close()
318
319     def do_POST_day(self) -> str:
320         """Update or insert Day of date and Todos mapped to it."""
321         date = self.params.get_str('date')
322         day = Day.by_id(self.conn, date, create=True)
323         day.comment = self.form_data.get_str('day_comment')
324         day.save(self.conn)
325         for process_id in sorted(self.form_data.get_all_int('new_todo')):
326             Todo.create_with_children(self.conn, process_id, date)
327         done_ids = self.form_data.get_all_int('done')
328         comments = self.form_data.get_all_str('comment')
329         efforts = self.form_data.get_all_str('effort')
330         for i, todo_id in enumerate(self.form_data.get_all_int('todo_id')):
331             todo = Todo.by_id(self.conn, todo_id)
332             todo.is_done = todo_id in done_ids
333             if len(comments) > 0:
334                 todo.comment = comments[i]
335             if len(efforts) > 0:
336                 todo.effort = float(efforts[i]) if efforts[i] else None
337             todo.save(self.conn)
338             for condition in todo.enables:
339                 condition.save(self.conn)
340             for condition in todo.disables:
341                 condition.save(self.conn)
342         return f'/day?date={date}'
343
344     def do_POST_todo(self) -> str:
345         """Update Todo and its children."""
346         id_ = self.params.get_int('id')
347         for _ in self.form_data.get_all_str('delete'):
348             todo = Todo .by_id(self.conn, id_)
349             todo.remove(self.conn)
350             return '/'
351         todo = Todo.by_id(self.conn, id_)
352         adopted_child_ids = self.form_data.get_all_int('adopt')
353         for child in todo.children:
354             if child.id_ not in adopted_child_ids:
355                 assert isinstance(child.id_, int)
356                 child = Todo.by_id(self.conn, child.id_)
357                 todo.remove_child(child)
358         for child_id in adopted_child_ids:
359             if child_id in [c.id_ for c in todo.children]:
360                 continue
361             child = Todo.by_id(self.conn, child_id)
362             todo.add_child(child)
363         for process_id in self.form_data.get_all_int('make'):
364             made = Todo.create_with_children(self.conn, process_id, todo.date)
365             todo.add_child(made)
366         effort = self.form_data.get_str('effort', ignore_strict=True)
367         todo.effort = float(effort) if effort else None
368         todo.set_conditions(self.conn, self.form_data.get_all_int('condition'))
369         todo.set_blockers(self.conn, self.form_data.get_all_int('blocker'))
370         todo.set_enables(self.conn, self.form_data.get_all_int('enables'))
371         todo.set_disables(self.conn, self.form_data.get_all_int('disables'))
372         todo.is_done = len(self.form_data.get_all_str('done')) > 0
373         todo.calendarize = len(self.form_data.get_all_str('calendarize')) > 0
374         todo.comment = self.form_data.get_str('comment', ignore_strict=True)
375         todo.save(self.conn)
376         for condition in todo.enables:
377             condition.save(self.conn)
378         for condition in todo.disables:
379             condition.save(self.conn)
380         return f'/todo?id={todo.id_}'
381
382     def do_POST_process(self) -> str:
383         """Update or insert Process of ?id= and fields defined in postvars."""
384         # pylint: disable=too-many-branches
385         id_ = self.params.get_int_or_none('id')
386         for _ in self.form_data.get_all_str('delete'):
387             process = Process.by_id(self.conn, id_)
388             process.remove(self.conn)
389             return '/processes'
390         process = Process.by_id(self.conn, id_, create=True)
391         process.title.set(self.form_data.get_str('title'))
392         process.description.set(self.form_data.get_str('description'))
393         process.effort.set(self.form_data.get_float('effort'))
394         process.set_conditions(self.conn,
395                                self.form_data.get_all_int('condition'))
396         process.set_blockers(self.conn, self.form_data.get_all_int('blocker'))
397         process.set_enables(self.conn, self.form_data.get_all_int('enables'))
398         process.set_disables(self.conn, self.form_data.get_all_int('disables'))
399         process.calendarize = self.form_data.get_all_str('calendarize') != []
400         process.save(self.conn)
401         assert isinstance(process.id_, int)
402         steps: list[ProcessStep] = []
403         for step_id in self.form_data.get_all_int('keep_step'):
404             if step_id not in self.form_data.get_all_int('steps'):
405                 raise BadFormatException('trying to keep unknown step')
406         for step_id in self.form_data.get_all_int('steps'):
407             if step_id not in self.form_data.get_all_int('keep_step'):
408                 continue
409             step_process_id = self.form_data.get_int(
410                     f'step_{step_id}_process_id')
411             parent_id = self.form_data.get_int_or_none(
412                     f'step_{step_id}_parent_id')
413             steps += [ProcessStep(step_id, process.id_, step_process_id,
414                                   parent_id)]
415         for step_id in self.form_data.get_all_int('steps'):
416             for step_process_id in self.form_data.get_all_int(
417                     f'new_step_to_{step_id}'):
418                 steps += [ProcessStep(None, process.id_, step_process_id,
419                                       step_id)]
420         new_step_title = None
421         for step_identifier in self.form_data.get_all_str('new_top_step'):
422             try:
423                 step_process_id = int(step_identifier)
424                 steps += [ProcessStep(None, process.id_, step_process_id,
425                                       None)]
426             except ValueError:
427                 new_step_title = step_identifier
428         process.uncache()
429         process.set_steps(self.conn, steps)
430         process.set_step_suppressions(self.conn,
431                                       self.form_data.get_all_int('suppresses'))
432         process.save(self.conn)
433         owners_to_set = []
434         new_owner_title = None
435         for owner_identifier in self.form_data.get_all_str('step_of'):
436             try:
437                 owners_to_set += [int(owner_identifier)]
438             except ValueError:
439                 new_owner_title = owner_identifier
440         process.set_owners(self.conn, owners_to_set)
441         params = f'id={process.id_}'
442         if new_step_title:
443             title_b64_encoded = b64encode(new_step_title.encode()).decode()
444             params = f'step_to={process.id_}&title_b64={title_b64_encoded}'
445         elif new_owner_title:
446             title_b64_encoded = b64encode(new_owner_title.encode()).decode()
447             params = f'has_step={process.id_}&title_b64={title_b64_encoded}'
448         return f'/process?{params}'
449
450     def do_POST_condition(self) -> str:
451         """Update/insert Condition of ?id= and fields defined in postvars."""
452         id_ = self.params.get_int_or_none('id')
453         for _ in self.form_data.get_all_str('delete'):
454             condition = Condition.by_id(self.conn, id_)
455             condition.remove(self.conn)
456             return '/conditions'
457         condition = Condition.by_id(self.conn, id_, create=True)
458         condition.is_active = self.form_data.get_all_str('is_active') != []
459         condition.title.set(self.form_data.get_str('title'))
460         condition.description.set(self.form_data.get_str('description'))
461         condition.save(self.conn)
462         return f'/condition?id={condition.id_}'
463
464     def _init_handling(self) -> None:
465         # pylint: disable=attribute-defined-outside-init
466         self.conn = DatabaseConnection(self.server.db)
467         parsed_url = urlparse(self.path)
468         self.site = path_split(parsed_url.path)[1]
469         params = parse_qs(parsed_url.query, strict_parsing=True)
470         self.params = InputsParser(params, False)
471
472     def _redirect(self, target: str) -> None:
473         self.send_response(302)
474         self.send_header('Location', target)
475         self.end_headers()
476
477     def _send_html(self, html: str, code: int = 200) -> None:
478         """Send HTML as proper HTTP response."""
479         self.send_response(code)
480         self.end_headers()
481         self.wfile.write(bytes(html, 'utf-8'))
482
483     def _send_msg(self, msg: Exception, code: int = 400) -> None:
484         """Send message in HTML formatting as HTTP response."""
485         html = self.server.jinja.get_template('msg.html').render(msg=msg)
486         self._send_html(html, code)