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