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