home · contact · privacy
When opening new Process from ProcessStep add field, pre-set as owned by previous...
[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                 'todo_candidates': Todo.by_date(self.conn, todo.date),
160                 'condition_candidates': Condition.all(self.conn)}
161
162     def do_GET_todos(self) -> dict[str, object]:
163         """Show Todos from ?start= to ?end=, of ?process=, ?comment= pattern"""
164         sort_by = self.params.get_str('sort_by')
165         start = self.params.get_str('start')
166         end = self.params.get_str('end')
167         process_id = self.params.get_int_or_none('process_id')
168         comment_pattern = self.params.get_str('comment_pattern')
169         todos = []
170         ret = Todo.by_date_range_with_limits(self.conn, (start, end))
171         todos_by_date_range, start, end = ret
172         todos = [t for t in todos_by_date_range
173                  if comment_pattern in t.comment
174                  and ((not process_id) or t.process.id_ == process_id)]
175         if sort_by == 'doneness':
176             todos.sort(key=lambda t: t.is_done)
177         elif sort_by == '-doneness':
178             todos.sort(key=lambda t: t.is_done, reverse=True)
179         elif sort_by == 'title':
180             todos.sort(key=lambda t: t.title_then)
181         elif sort_by == '-title':
182             todos.sort(key=lambda t: t.title_then, reverse=True)
183         elif sort_by == 'comment':
184             todos.sort(key=lambda t: t.comment)
185         elif sort_by == '-comment':
186             todos.sort(key=lambda t: t.comment, reverse=True)
187         elif sort_by == '-date':
188             todos.sort(key=lambda t: t.date, reverse=True)
189         else:
190             todos.sort(key=lambda t: t.date)
191         return {'start': start, 'end': end, 'process_id': process_id,
192                 'comment_pattern': comment_pattern, 'todos': todos,
193                 'all_processes': Process.all(self.conn), 'sort_by': sort_by}
194
195     def do_GET_conditions(self) -> dict[str, object]:
196         """Show all Conditions."""
197         pattern = self.params.get_str('pattern')
198         conditions = Condition.matching(self.conn, pattern)
199         sort_by = self.params.get_str('sort_by')
200         if sort_by == 'is_active':
201             conditions.sort(key=lambda c: c.is_active)
202         elif sort_by == '-is_active':
203             conditions.sort(key=lambda c: c.is_active, reverse=True)
204         elif sort_by == '-title':
205             conditions.sort(key=lambda c: c.title.newest, reverse=True)
206         else:
207             conditions.sort(key=lambda c: c.title.newest)
208         return {'conditions': conditions,
209                 'sort_by': sort_by,
210                 'pattern': pattern}
211
212     def do_GET_condition(self) -> dict[str, object]:
213         """Show Condition of ?id=."""
214         id_ = self.params.get_int_or_none('id')
215         c = Condition.by_id(self.conn, id_, create=True)
216         ps = Process.all(self.conn)
217         return {'condition': c, 'is_new': c.id_ is None,
218                 'enabled_processes': [p for p in ps if c in p.conditions],
219                 'disabled_processes': [p for p in ps if c in p.blockers],
220                 'enabling_processes': [p for p in ps if c in p.enables],
221                 'disabling_processes': [p for p in ps if c in p.disables]}
222
223     def do_GET_condition_titles(self) -> dict[str, object]:
224         """Show title history 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_condition_descriptions(self) -> dict[str, object]:
230         """Show description historys of Condition of ?id=."""
231         id_ = self.params.get_int_or_none('id')
232         condition = Condition.by_id(self.conn, id_)
233         return {'condition': condition}
234
235     def do_GET_process(self) -> dict[str, object]:
236         """Show Process of ?id=."""
237         id_ = self.params.get_int_or_none('id')
238         process = Process.by_id(self.conn, id_, create=True)
239         title_64 = self.params.get_str('title_b64')
240         if title_64:
241             title = b64decode(title_64.encode()).decode()
242             process.title.set(title)
243         owners = process.used_as_step_by(self.conn)
244         for step_id in self.params.get_all_int('step_to'):
245             owners += [Process.by_id(self.conn, step_id)]
246         return {'process': process, 'is_new': process.id_ is None,
247                 'steps': process.get_steps(self.conn),
248                 'owners': owners,
249                 'n_todos': len(Todo.by_process_id(self.conn, process.id_)),
250                 'process_candidates': Process.all(self.conn),
251                 'condition_candidates': Condition.all(self.conn)}
252
253     def do_GET_process_titles(self) -> dict[str, object]:
254         """Show title history of Process of ?id=."""
255         id_ = self.params.get_int_or_none('id')
256         process = Process.by_id(self.conn, id_)
257         return {'process': process}
258
259     def do_GET_process_descriptions(self) -> dict[str, object]:
260         """Show description historys of Process of ?id=."""
261         id_ = self.params.get_int_or_none('id')
262         process = Process.by_id(self.conn, id_)
263         return {'process': process}
264
265     def do_GET_process_efforts(self) -> dict[str, object]:
266         """Show default effort history of Process of ?id=."""
267         id_ = self.params.get_int_or_none('id')
268         process = Process.by_id(self.conn, id_)
269         return {'process': process}
270
271     def do_GET_processes(self) -> dict[str, object]:
272         """Show all Processes."""
273         pattern = self.params.get_str('pattern')
274         processes = Process.matching(self.conn, pattern)
275         sort_by = self.params.get_str('sort_by')
276         if sort_by == 'steps':
277             processes.sort(key=lambda p: len(p.explicit_steps))
278         elif sort_by == '-steps':
279             processes.sort(key=lambda p: len(p.explicit_steps), reverse=True)
280         elif sort_by == 'effort':
281             processes.sort(key=lambda p: p.effort.newest)
282         elif sort_by == '-effort':
283             processes.sort(key=lambda p: p.effort.newest, reverse=True)
284         elif sort_by == '-title':
285             processes.sort(key=lambda p: p.title.newest, reverse=True)
286         else:
287             processes.sort(key=lambda p: p.title.newest)
288         return {'processes': processes, 'sort_by': sort_by, 'pattern': pattern}
289
290     def do_POST(self) -> None:
291         """Handle any POST request."""
292         # pylint: disable=attribute-defined-outside-init
293         try:
294             self._init_handling()
295             length = int(self.headers['content-length'])
296             postvars = parse_qs(self.rfile.read(length).decode(),
297                                 keep_blank_values=True, strict_parsing=True)
298             self.form_data = InputsParser(postvars)
299             if hasattr(self, f'do_POST_{self.site}'):
300                 redir_target = getattr(self, f'do_POST_{self.site}')()
301                 self.conn.commit()
302             else:
303                 msg = f'Page not known as POST target: /{self.site}'
304                 raise NotFoundException(msg)
305             self._redirect(redir_target)
306         except HandledException as error:
307             self._send_msg(error, code=error.http_code)
308         finally:
309             self.conn.close()
310
311     def do_POST_day(self) -> str:
312         """Update or insert Day of date and Todos mapped to it."""
313         date = self.params.get_str('date')
314         day = Day.by_id(self.conn, date, create=True)
315         day.comment = self.form_data.get_str('day_comment')
316         day.save(self.conn)
317         for process_id in sorted(self.form_data.get_all_int('new_todo')):
318             Todo.create_with_children(self.conn, process_id, date)
319         done_ids = self.form_data.get_all_int('done')
320         comments = self.form_data.get_all_str('comment')
321         efforts = self.form_data.get_all_str('effort')
322         for i, todo_id in enumerate(self.form_data.get_all_int('todo_id')):
323             todo = Todo.by_id(self.conn, todo_id)
324             todo.is_done = todo_id in done_ids
325             if len(comments) > 0:
326                 todo.comment = comments[i]
327             if len(efforts) > 0:
328                 todo.effort = float(efforts[i]) if efforts[i] else None
329             todo.save(self.conn)
330             for condition in todo.enables:
331                 condition.save(self.conn)
332             for condition in todo.disables:
333                 condition.save(self.conn)
334         return f'/day?date={date}'
335
336     def do_POST_todo(self) -> str:
337         """Update Todo and its children."""
338         id_ = self.params.get_int('id')
339         for _ in self.form_data.get_all_str('delete'):
340             todo = Todo .by_id(self.conn, id_)
341             todo.remove(self.conn)
342             return '/'
343         todo = Todo.by_id(self.conn, id_)
344         adopted_child_ids = self.form_data.get_all_int('adopt')
345         for child in todo.children:
346             if child.id_ not in adopted_child_ids:
347                 assert isinstance(child.id_, int)
348                 child = Todo.by_id(self.conn, child.id_)
349                 todo.remove_child(child)
350         for child_id in adopted_child_ids:
351             if child_id in [c.id_ for c in todo.children]:
352                 continue
353             child = Todo.by_id(self.conn, child_id)
354             todo.add_child(child)
355         effort = self.form_data.get_str('effort', ignore_strict=True)
356         todo.effort = float(effort) if effort else None
357         todo.set_conditions(self.conn, self.form_data.get_all_int('condition'))
358         todo.set_blockers(self.conn, self.form_data.get_all_int('blocker'))
359         todo.set_enables(self.conn, self.form_data.get_all_int('enables'))
360         todo.set_disables(self.conn, self.form_data.get_all_int('disables'))
361         todo.is_done = len(self.form_data.get_all_str('done')) > 0
362         todo.calendarize = len(self.form_data.get_all_str('calendarize')) > 0
363         todo.comment = self.form_data.get_str('comment', ignore_strict=True)
364         todo.save(self.conn)
365         for condition in todo.enables:
366             condition.save(self.conn)
367         for condition in todo.disables:
368             condition.save(self.conn)
369         return f'/todo?id={todo.id_}'
370
371     def do_POST_process(self) -> str:
372         """Update or insert Process of ?id= and fields defined in postvars."""
373         id_ = self.params.get_int_or_none('id')
374         for _ in self.form_data.get_all_str('delete'):
375             process = Process.by_id(self.conn, id_)
376             process.remove(self.conn)
377             return '/processes'
378         process = Process.by_id(self.conn, id_, create=True)
379         process.title.set(self.form_data.get_str('title'))
380         process.description.set(self.form_data.get_str('description'))
381         process.effort.set(self.form_data.get_float('effort'))
382         process.set_conditions(self.conn,
383                                self.form_data.get_all_int('condition'))
384         process.set_blockers(self.conn, self.form_data.get_all_int('blocker'))
385         process.set_enables(self.conn, self.form_data.get_all_int('enables'))
386         process.set_disables(self.conn, self.form_data.get_all_int('disables'))
387         process.calendarize = self.form_data.get_all_str('calendarize') != []
388         process.save(self.conn)
389         assert isinstance(process.id_, int)
390         steps: list[ProcessStep] = []
391         for step_id in self.form_data.get_all_int('keep_step'):
392             if step_id not in self.form_data.get_all_int('steps'):
393                 raise BadFormatException('trying to keep unknown step')
394         for step_id in self.form_data.get_all_int('steps'):
395             if step_id not in self.form_data.get_all_int('keep_step'):
396                 continue
397             step_process_id = self.form_data.get_int(
398                     f'step_{step_id}_process_id')
399             parent_id = self.form_data.get_int_or_none(
400                     f'step_{step_id}_parent_id')
401             steps += [ProcessStep(step_id, process.id_, step_process_id,
402                                   parent_id)]
403         for step_id in self.form_data.get_all_int('steps'):
404             for step_process_id in self.form_data.get_all_int(
405                     f'new_step_to_{step_id}'):
406                 steps += [ProcessStep(None, process.id_, step_process_id,
407                                       step_id)]
408         new_process_title = None
409         for step_identifier in self.form_data.get_all_str('new_top_step'):
410             try:
411                 step_process_id = int(step_identifier)
412                 steps += [ProcessStep(None, process.id_, step_process_id,
413                                       None)]
414             except ValueError:
415                 new_process_title = step_identifier
416         process.uncache()
417         process.set_steps(self.conn, steps)
418         process.set_step_suppressions(self.conn,
419                                       self.form_data.get_all_int('suppresses'))
420         process.save(self.conn)
421         process.set_owners(self.conn, self.form_data.get_all_int('step_of'))
422         if new_process_title:
423             title_b64_encoded = b64encode(new_process_title.encode()).decode()
424             params = f'step_to={process.id_}&title_b64={title_b64_encoded}'
425             return f'/process?{params}'
426         return f'/process?id={process.id_}'
427
428     def do_POST_condition(self) -> str:
429         """Update/insert Condition of ?id= and fields defined in postvars."""
430         id_ = self.params.get_int_or_none('id')
431         for _ in self.form_data.get_all_str('delete'):
432             condition = Condition.by_id(self.conn, id_)
433             condition.remove(self.conn)
434             return '/conditions'
435         condition = Condition.by_id(self.conn, id_, create=True)
436         condition.is_active = self.form_data.get_all_str('is_active') != []
437         condition.title.set(self.form_data.get_str('title'))
438         condition.description.set(self.form_data.get_str('description'))
439         condition.save(self.conn)
440         return f'/condition?id={condition.id_}'
441
442     def _init_handling(self) -> None:
443         # pylint: disable=attribute-defined-outside-init
444         self.conn = DatabaseConnection(self.server.db)
445         parsed_url = urlparse(self.path)
446         self.site = path_split(parsed_url.path)[1]
447         params = parse_qs(parsed_url.query, strict_parsing=True)
448         self.params = InputsParser(params, False)
449
450     def _redirect(self, target: str) -> None:
451         self.send_response(302)
452         self.send_header('Location', target)
453         self.end_headers()
454
455     def _send_html(self, html: str, code: int = 200) -> None:
456         """Send HTML as proper HTTP response."""
457         self.send_response(code)
458         self.end_headers()
459         self.wfile.write(bytes(html, 'utf-8'))
460
461     def _send_msg(self, msg: Exception, code: int = 400) -> None:
462         """Send message in HTML formatting as HTTP response."""
463         html = self.server.jinja.get_template('msg.html').render(msg=msg)
464         self._send_html(html, code)