home · contact · privacy
Add VersionedAttributes history pages for Conditions.
[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 self.site in {'calendar', 'day', 'process', 'process_titles',
98                              'process_descriptions', 'process_efforts',
99                              'processes', 'todo', 'condition',
100                              'condition_titles', 'condition_descriptions',
101                              'conditions'}:
102                 template = f'{self.site}.html'
103                 ctx = getattr(self, f'do_GET_{self.site}')()
104                 html = self.server.jinja.get_template(template).render(**ctx)
105                 self._send_html(html)
106             elif '' == self.site:
107                 self._redirect('/day')
108             else:
109                 raise NotFoundException(f'Unknown page: /{self.site}')
110         except HandledException as error:
111             self._send_msg(error, code=error.http_code)
112         finally:
113             self.conn.close()
114
115     def do_GET_calendar(self) -> dict[str, object]:
116         """Show Days from ?start= to ?end=."""
117         start = self.params.get_str('start')
118         end = self.params.get_str('end')
119         days = Day.all(self.conn, date_range=(start, end), fill_gaps=True)
120         return {'start': start, 'end': end, 'days': days}
121
122     def do_GET_day(self) -> dict[str, object]:
123         """Show single Day of ?date=."""
124         date = self.params.get_str('date', todays_date())
125         todays_todos = Todo.by_date(self.conn, date)
126         conditions_present = []
127         enablers_for = {}
128         for todo in todays_todos:
129             for condition in todo.conditions:
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         seen_todos: set[int] = set()
136         top_nodes = [t.get_step_tree(seen_todos)
137                      for t in todays_todos if not t.parents]
138         return {'day': Day.by_id(self.conn, date, create=True),
139                 'top_nodes': top_nodes,
140                 'enablers_for': enablers_for,
141                 'conditions_present': conditions_present,
142                 'processes': Process.all(self.conn)}
143
144     def do_GET_todo(self) -> dict[str, object]:
145         """Show single Todo of ?id=."""
146         id_ = self.params.get_int('id')
147         todo = Todo.by_id(self.conn, id_)
148         return {'todo': todo,
149                 'todo_candidates': Todo.by_date(self.conn, todo.date),
150                 'condition_candidates': Condition.all(self.conn)}
151
152     def do_GET_conditions(self) -> dict[str, object]:
153         """Show all Conditions."""
154         return {'conditions': Condition.all(self.conn)}
155
156     def do_GET_condition(self) -> dict[str, object]:
157         """Show Condition of ?id=."""
158         id_ = self.params.get_int_or_none('id')
159         return {'condition': Condition.by_id(self.conn, id_, create=True)}
160
161     def do_GET_condition_titles(self) -> dict[str, object]:
162         """Show title history of Condition of ?id=."""
163         id_ = self.params.get_int_or_none('id')
164         condition = Condition.by_id(self.conn, id_)
165         return {'condition': condition}
166
167     def do_GET_condition_descriptions(self) -> dict[str, object]:
168         """Show description historys of Condition of ?id=."""
169         id_ = self.params.get_int_or_none('id')
170         condition = Condition.by_id(self.conn, id_)
171         return {'condition': condition}
172
173     def do_GET_process(self) -> dict[str, object]:
174         """Show Process of ?id=."""
175         id_ = self.params.get_int_or_none('id')
176         process = Process.by_id(self.conn, id_, create=True)
177         return {'process': process,
178                 'steps': process.get_steps(self.conn),
179                 'owners': process.used_as_step_by(self.conn),
180                 'step_candidates': Process.all(self.conn),
181                 'condition_candidates': Condition.all(self.conn)}
182
183     def do_GET_process_titles(self) -> dict[str, object]:
184         """Show title history of Process of ?id=."""
185         id_ = self.params.get_int_or_none('id')
186         process = Process.by_id(self.conn, id_)
187         return {'process': process}
188
189     def do_GET_process_descriptions(self) -> dict[str, object]:
190         """Show description historys of Process of ?id=."""
191         id_ = self.params.get_int_or_none('id')
192         process = Process.by_id(self.conn, id_)
193         return {'process': process}
194
195     def do_GET_process_efforts(self) -> dict[str, object]:
196         """Show default effort history of Process of ?id=."""
197         id_ = self.params.get_int_or_none('id')
198         process = Process.by_id(self.conn, id_)
199         return {'process': process}
200
201     def do_GET_processes(self) -> dict[str, object]:
202         """Show all Processes."""
203         return {'processes': Process.all(self.conn)}
204
205     def do_POST(self) -> None:
206         """Handle any POST request."""
207         # pylint: disable=attribute-defined-outside-init
208         try:
209             self._init_handling()
210             length = int(self.headers['content-length'])
211             postvars = parse_qs(self.rfile.read(length).decode(),
212                                 keep_blank_values=True, strict_parsing=True)
213             self.form_data = InputsParser(postvars)
214             if self.site in ('day', 'process', 'todo', 'condition'):
215                 redir_target = getattr(self, f'do_POST_{self.site}')()
216                 self.conn.commit()
217             else:
218                 msg = f'Page not known as POST target: /{self.site}'
219                 raise NotFoundException(msg)
220             self._redirect(redir_target)
221         except HandledException as error:
222             self._send_msg(error, code=error.http_code)
223         finally:
224             self.conn.close()
225
226     def do_POST_day(self) -> str:
227         """Update or insert Day of date and Todos mapped to it."""
228         date = self.params.get_str('date')
229         day = Day.by_id(self.conn, date, create=True)
230         day.comment = self.form_data.get_str('day_comment')
231         day.save(self.conn)
232         new_todos = []
233         for process_id in self.form_data.get_all_int('new_todo'):
234             process = Process.by_id(self.conn, process_id)
235             todo = Todo(None, process, False, day.date)
236             todo.save(self.conn)
237             new_todos += [todo]
238         adopted = True
239         while adopted:
240             adopted = False
241             existing_todos = Todo.by_date(self.conn, date)
242             for todo in new_todos:
243                 if todo.adopt_from(existing_todos):
244                     adopted = True
245                 todo.make_missing_children(self.conn)
246                 todo.save(self.conn)
247         done_ids = self.form_data.get_all_int('done')
248         comments = self.form_data.get_all_str('comment')
249         for i, todo_id in enumerate(self.form_data.get_all_int('todo_id')):
250             todo = Todo.by_id(self.conn, todo_id)
251             todo.is_done = todo_id in done_ids
252             if len(comments) > 0:
253                 todo.comment = comments[i]
254             todo.save(self.conn)
255             for condition in todo.enables:
256                 condition.save(self.conn)
257             for condition in todo.disables:
258                 condition.save(self.conn)
259         return f'/day?date={date}'
260
261     def do_POST_todo(self) -> str:
262         """Update Todo and its children."""
263         id_ = self.params.get_int('id')
264         for _ in self.form_data.get_all_str('delete'):
265             todo = Todo .by_id(self.conn, id_)
266             todo.remove(self.conn)
267             return '/'
268         todo = Todo.by_id(self.conn, id_)
269         adopted_child_ids = self.form_data.get_all_int('adopt')
270         for child in todo.children:
271             if child.id_ not in adopted_child_ids:
272                 assert isinstance(child.id_, int)
273                 child = Todo.by_id(self.conn, child.id_)
274                 todo.remove_child(child)
275         for child_id in adopted_child_ids:
276             if child_id in [c.id_ for c in todo.children]:
277                 continue
278             child = Todo.by_id(self.conn, child_id)
279             todo.add_child(child)
280         todo.set_conditions(self.conn, self.form_data.get_all_int('condition'))
281         todo.set_enables(self.conn, self.form_data.get_all_int('enables'))
282         todo.set_disables(self.conn, self.form_data.get_all_int('disables'))
283         todo.is_done = len(self.form_data.get_all_str('done')) > 0
284         todo.comment = self.form_data.get_str('comment', ignore_strict=True)
285         todo.save(self.conn)
286         for condition in todo.enables:
287             condition.save(self.conn)
288         for condition in todo.disables:
289             condition.save(self.conn)
290         return f'/todo?id={todo.id_}'
291
292     def do_POST_process(self) -> str:
293         """Update or insert Process of ?id= and fields defined in postvars."""
294         id_ = self.params.get_int_or_none('id')
295         for _ in self.form_data.get_all_str('delete'):
296             process = Process.by_id(self.conn, id_)
297             process.remove(self.conn)
298             return '/processes'
299         process = Process.by_id(self.conn, id_, create=True)
300         process.title.set(self.form_data.get_str('title'))
301         process.description.set(self.form_data.get_str('description'))
302         process.effort.set(self.form_data.get_float('effort'))
303         process.set_conditions(self.conn,
304                                self.form_data.get_all_int('condition'))
305         process.set_enables(self.conn, self.form_data.get_all_int('enables'))
306         process.set_disables(self.conn, self.form_data.get_all_int('disables'))
307         process.save(self.conn)
308         process.explicit_steps = []
309         steps: list[tuple[int | None, int, int | None]] = []
310         for step_id in self.form_data.get_all_int('steps'):
311             for step_process_id in self.form_data.get_all_int(
312                     f'new_step_to_{step_id}'):
313                 steps += [(None, step_process_id, step_id)]
314             if step_id not in self.form_data.get_all_int('keep_step'):
315                 continue
316             step_process_id = self.form_data.get_int(
317                     f'step_{step_id}_process_id')
318             parent_id = self.form_data.get_int_or_none(
319                     f'step_{step_id}_parent_id')
320             steps += [(step_id, step_process_id, parent_id)]
321         for step_process_id in self.form_data.get_all_int('new_top_step'):
322             steps += [(None, step_process_id, None)]
323         process.set_steps(self.conn, steps)
324         process.save(self.conn)
325         return f'/process?id={process.id_}'
326
327     def do_POST_condition(self) -> str:
328         """Update/insert Condition of ?id= and fields defined in postvars."""
329         id_ = self.params.get_int_or_none('id')
330         for _ in self.form_data.get_all_str('delete'):
331             condition = Condition.by_id(self.conn, id_)
332             condition.remove(self.conn)
333             return '/conditions'
334         condition = Condition.by_id(self.conn, id_, create=True)
335         condition.is_active = self.form_data.get_all_str('is_active') != []
336         condition.title.set(self.form_data.get_str('title'))
337         condition.description.set(self.form_data.get_str('description'))
338         condition.save(self.conn)
339         return f'/condition?id={condition.id_}'
340
341     def _init_handling(self) -> None:
342         # pylint: disable=attribute-defined-outside-init
343         self.conn = DatabaseConnection(self.server.db)
344         parsed_url = urlparse(self.path)
345         self.site = path_split(parsed_url.path)[1]
346         params = parse_qs(parsed_url.query, strict_parsing=True)
347         self.params = InputsParser(params, False)
348
349     def _redirect(self, target: str) -> None:
350         self.send_response(302)
351         self.send_header('Location', target)
352         self.end_headers()
353
354     def _send_html(self, html: str, code: int = 200) -> None:
355         """Send HTML as proper HTTP response."""
356         self.send_response(code)
357         self.end_headers()
358         self.wfile.write(bytes(html, 'utf-8'))
359
360     def _send_msg(self, msg: Exception, code: int = 400) -> None:
361         """Send message in HTML formatting as HTTP response."""
362         html = self.server.jinja.get_template('msg.html').render(msg=msg)
363         self._send_html(html, code)