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