home · contact · privacy
Re-factor date ranging and default to range 'yesterday' to 'tomorrow'.
[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         ret = Day.by_date_range_with_limits(self.conn, (start, end), 'id')
117         days, start, end = ret
118         days = Day.with_filled_gaps(days, start, end)
119         for day in days:
120             day.collect_calendarized_todos(self.conn)
121         return {'start': start, 'end': end, 'days': days}
122
123     def do_GET_day(self) -> dict[str, object]:
124         """Show single Day of ?date=."""
125         date = self.params.get_str('date', todays_date())
126         todays_todos = Todo.by_date(self.conn, date)
127         conditions_present = []
128         enablers_for = {}
129         disablers_for = {}
130         for todo in todays_todos:
131             for condition in todo.conditions + todo.blockers:
132                 if condition not in conditions_present:
133                     conditions_present += [condition]
134                     enablers_for[condition.id_] = [p for p in
135                                                    Process.all(self.conn)
136                                                    if condition in p.enables]
137                     disablers_for[condition.id_] = [p for p in
138                                                     Process.all(self.conn)
139                                                     if condition in p.disables]
140         seen_todos: set[int] = set()
141         top_nodes = [t.get_step_tree(seen_todos)
142                      for t in todays_todos if not t.parents]
143         return {'day': Day.by_id(self.conn, date, create=True),
144                 'top_nodes': top_nodes,
145                 'enablers_for': enablers_for,
146                 'disablers_for': disablers_for,
147                 'conditions_present': conditions_present,
148                 'processes': Process.all(self.conn)}
149
150     def do_GET_todo(self) -> dict[str, object]:
151         """Show single Todo of ?id=."""
152         id_ = self.params.get_int('id')
153         todo = Todo.by_id(self.conn, id_)
154         return {'todo': todo,
155                 'todo_candidates': Todo.by_date(self.conn, todo.date),
156                 'condition_candidates': Condition.all(self.conn)}
157
158     def do_GET_todos(self) -> dict[str, object]:
159         """Show Todos from ?start= to ?end=, of ?process=, ?comment= pattern"""
160         sort_by = self.params.get_str('sort_by')
161         start = self.params.get_str('start')
162         end = self.params.get_str('end')
163         process_id = self.params.get_int_or_none('process_id')
164         comment_pattern = self.params.get_str('comment_pattern')
165         todos = []
166         ret = Todo.by_date_range_with_limits(self.conn, (start, end))
167         todos_by_date_range, start, end = ret
168         todos = [t for t in todos_by_date_range
169                  if comment_pattern in t.comment
170                  and ((not process_id) or t.process.id_ == process_id)]
171         if sort_by == 'doneness':
172             todos.sort(key=lambda t: t.is_done)
173         elif sort_by == '-doneness':
174             todos.sort(key=lambda t: t.is_done, reverse=True)
175         elif sort_by == 'process':
176             todos.sort(key=lambda t: t.title_then)
177         elif sort_by == '-process':
178             todos.sort(key=lambda t: t.title_then, reverse=True)
179         elif sort_by == 'comment':
180             todos.sort(key=lambda t: t.comment)
181         elif sort_by == '-comment':
182             todos.sort(key=lambda t: t.comment, reverse=True)
183         elif sort_by == '-date':
184             todos.sort(key=lambda t: t.date, reverse=True)
185         else:
186             todos.sort(key=lambda t: t.date)
187         return {'start': start, 'end': end, 'process_id': process_id,
188                 'comment_pattern': comment_pattern, 'todos': todos,
189                 'all_processes': Process.all(self.conn), 'sort_by': sort_by}
190
191     def do_GET_conditions(self) -> dict[str, object]:
192         """Show all Conditions."""
193         pattern = self.params.get_str('pattern')
194         conditions = Condition.matching(self.conn, pattern)
195         sort_by = self.params.get_str('sort_by')
196         if sort_by == 'is_active':
197             conditions.sort(key=lambda c: c.is_active)
198         elif sort_by == '-is_active':
199             conditions.sort(key=lambda c: c.is_active, reverse=True)
200         elif sort_by == '-title':
201             conditions.sort(key=lambda c: c.title.newest, reverse=True)
202         else:
203             conditions.sort(key=lambda c: c.title.newest)
204         return {'conditions': conditions,
205                 'sort_by': sort_by,
206                 'pattern': pattern}
207
208     def do_GET_condition(self) -> dict[str, object]:
209         """Show Condition of ?id=."""
210         id_ = self.params.get_int_or_none('id')
211         c = Condition.by_id(self.conn, id_, create=True)
212         ps = Process.all(self.conn)
213         return {'condition': c,
214                 'enabled_processes': [p for p in ps if c in p.conditions],
215                 'disabled_processes': [p for p in ps if c in p.blockers],
216                 'enabling_processes': [p for p in ps if c in p.enables],
217                 'disabling_processes': [p for p in ps if c in p.disables]}
218
219     def do_GET_condition_titles(self) -> dict[str, object]:
220         """Show title history of Condition of ?id=."""
221         id_ = self.params.get_int_or_none('id')
222         condition = Condition.by_id(self.conn, id_)
223         return {'condition': condition}
224
225     def do_GET_condition_descriptions(self) -> dict[str, object]:
226         """Show description historys of Condition of ?id=."""
227         id_ = self.params.get_int_or_none('id')
228         condition = Condition.by_id(self.conn, id_)
229         return {'condition': condition}
230
231     def do_GET_process(self) -> dict[str, object]:
232         """Show Process of ?id=."""
233         id_ = self.params.get_int_or_none('id')
234         process = Process.by_id(self.conn, id_, create=True)
235         return {'process': process,
236                 'steps': process.get_steps(self.conn),
237                 'owners': process.used_as_step_by(self.conn),
238                 'n_todos': len(Todo.by_process_id(self.conn, process.id_)),
239                 'step_candidates': Process.all(self.conn),
240                 'condition_candidates': Condition.all(self.conn)}
241
242     def do_GET_process_titles(self) -> dict[str, object]:
243         """Show title history of Process of ?id=."""
244         id_ = self.params.get_int_or_none('id')
245         process = Process.by_id(self.conn, id_)
246         return {'process': process}
247
248     def do_GET_process_descriptions(self) -> dict[str, object]:
249         """Show description historys of Process of ?id=."""
250         id_ = self.params.get_int_or_none('id')
251         process = Process.by_id(self.conn, id_)
252         return {'process': process}
253
254     def do_GET_process_efforts(self) -> dict[str, object]:
255         """Show default effort history of Process of ?id=."""
256         id_ = self.params.get_int_or_none('id')
257         process = Process.by_id(self.conn, id_)
258         return {'process': process}
259
260     def do_GET_processes(self) -> dict[str, object]:
261         """Show all Processes."""
262         pattern = self.params.get_str('pattern')
263         processes = Process.matching(self.conn, pattern)
264         sort_by = self.params.get_str('sort_by')
265         if sort_by == 'steps':
266             processes.sort(key=lambda p: len(p.explicit_steps))
267         elif sort_by == '-steps':
268             processes.sort(key=lambda p: len(p.explicit_steps), reverse=True)
269         elif sort_by == '-title':
270             processes.sort(key=lambda p: p.title.newest, reverse=True)
271         else:
272             processes.sort(key=lambda p: p.title.newest)
273         return {'processes': processes, 'sort_by': sort_by, 'pattern': pattern}
274
275     def do_POST(self) -> None:
276         """Handle any POST request."""
277         # pylint: disable=attribute-defined-outside-init
278         try:
279             self._init_handling()
280             length = int(self.headers['content-length'])
281             postvars = parse_qs(self.rfile.read(length).decode(),
282                                 keep_blank_values=True, strict_parsing=True)
283             self.form_data = InputsParser(postvars)
284             if hasattr(self, f'do_POST_{self.site}'):
285                 redir_target = getattr(self, f'do_POST_{self.site}')()
286                 self.conn.commit()
287             else:
288                 msg = f'Page not known as POST target: /{self.site}'
289                 raise NotFoundException(msg)
290             self._redirect(redir_target)
291         except HandledException as error:
292             self._send_msg(error, code=error.http_code)
293         finally:
294             self.conn.close()
295
296     def do_POST_day(self) -> str:
297         """Update or insert Day of date and Todos mapped to it."""
298         date = self.params.get_str('date')
299         day = Day.by_id(self.conn, date, create=True)
300         day.comment = self.form_data.get_str('day_comment')
301         day.save(self.conn)
302         Todo.create_with_children(self.conn, date,
303                                   self.form_data.get_all_int('new_todo'))
304         done_ids = self.form_data.get_all_int('done')
305         comments = self.form_data.get_all_str('comment')
306         efforts = self.form_data.get_all_str('effort')
307         for i, todo_id in enumerate(self.form_data.get_all_int('todo_id')):
308             todo = Todo.by_id(self.conn, todo_id)
309             todo.is_done = todo_id in done_ids
310             if len(comments) > 0:
311                 todo.comment = comments[i]
312             if len(efforts) > 0:
313                 todo.effort = float(efforts[i]) if efforts[i] else None
314             todo.save(self.conn)
315             for condition in todo.enables:
316                 condition.save(self.conn)
317             for condition in todo.disables:
318                 condition.save(self.conn)
319         return f'/day?date={date}'
320
321     def do_POST_todo(self) -> str:
322         """Update Todo and its children."""
323         id_ = self.params.get_int('id')
324         for _ in self.form_data.get_all_str('delete'):
325             todo = Todo .by_id(self.conn, id_)
326             todo.remove(self.conn)
327             return '/'
328         todo = Todo.by_id(self.conn, id_)
329         adopted_child_ids = self.form_data.get_all_int('adopt')
330         for child in todo.children:
331             if child.id_ not in adopted_child_ids:
332                 assert isinstance(child.id_, int)
333                 child = Todo.by_id(self.conn, child.id_)
334                 todo.remove_child(child)
335         for child_id in adopted_child_ids:
336             if child_id in [c.id_ for c in todo.children]:
337                 continue
338             child = Todo.by_id(self.conn, child_id)
339             todo.add_child(child)
340         effort = self.form_data.get_str('effort', ignore_strict=True)
341         todo.effort = float(effort) if effort else None
342         todo.set_conditions(self.conn, self.form_data.get_all_int('condition'))
343         todo.set_blockers(self.conn, self.form_data.get_all_int('blocker'))
344         todo.set_enables(self.conn, self.form_data.get_all_int('enables'))
345         todo.set_disables(self.conn, self.form_data.get_all_int('disables'))
346         todo.is_done = len(self.form_data.get_all_str('done')) > 0
347         todo.calendarize = len(self.form_data.get_all_str('calendarize')) > 0
348         todo.comment = self.form_data.get_str('comment', ignore_strict=True)
349         todo.save(self.conn)
350         for condition in todo.enables:
351             condition.save(self.conn)
352         for condition in todo.disables:
353             condition.save(self.conn)
354         return f'/todo?id={todo.id_}'
355
356     def do_POST_process(self) -> str:
357         """Update or insert Process of ?id= and fields defined in postvars."""
358         id_ = self.params.get_int_or_none('id')
359         for _ in self.form_data.get_all_str('delete'):
360             process = Process.by_id(self.conn, id_)
361             process.remove(self.conn)
362             return '/processes'
363         process = Process.by_id(self.conn, id_, create=True)
364         process.title.set(self.form_data.get_str('title'))
365         process.description.set(self.form_data.get_str('description'))
366         process.effort.set(self.form_data.get_float('effort'))
367         process.set_conditions(self.conn,
368                                self.form_data.get_all_int('condition'))
369         process.set_blockers(self.conn, self.form_data.get_all_int('blocker'))
370         process.set_enables(self.conn, self.form_data.get_all_int('enables'))
371         process.set_disables(self.conn, self.form_data.get_all_int('disables'))
372         process.calendarize = self.form_data.get_all_str('calendarize') != []
373         process.save(self.conn)
374         steps: list[tuple[int | None, int, int | None]] = []
375         for step_id in self.form_data.get_all_int('keep_step'):
376             if step_id not in self.form_data.get_all_int('steps'):
377                 raise BadFormatException('trying to keep unknown step')
378         for step_id in self.form_data.get_all_int('steps'):
379             for step_process_id in self.form_data.get_all_int(
380                     f'new_step_to_{step_id}'):
381                 steps += [(None, step_process_id, step_id)]
382             if step_id not in self.form_data.get_all_int('keep_step'):
383                 continue
384             step_process_id = self.form_data.get_int(
385                     f'step_{step_id}_process_id')
386             parent_id = self.form_data.get_int_or_none(
387                     f'step_{step_id}_parent_id')
388             steps += [(step_id, step_process_id, parent_id)]
389         for step_process_id in self.form_data.get_all_int('new_top_step'):
390             steps += [(None, step_process_id, None)]
391         process.set_steps(self.conn, steps)
392         process.save(self.conn)
393         return f'/process?id={process.id_}'
394
395     def do_POST_condition(self) -> str:
396         """Update/insert Condition of ?id= and fields defined in postvars."""
397         id_ = self.params.get_int_or_none('id')
398         for _ in self.form_data.get_all_str('delete'):
399             condition = Condition.by_id(self.conn, id_)
400             condition.remove(self.conn)
401             return '/conditions'
402         condition = Condition.by_id(self.conn, id_, create=True)
403         condition.is_active = self.form_data.get_all_str('is_active') != []
404         condition.title.set(self.form_data.get_str('title'))
405         condition.description.set(self.form_data.get_str('description'))
406         condition.save(self.conn)
407         return f'/condition?id={condition.id_}'
408
409     def _init_handling(self) -> None:
410         # pylint: disable=attribute-defined-outside-init
411         self.conn = DatabaseConnection(self.server.db)
412         parsed_url = urlparse(self.path)
413         self.site = path_split(parsed_url.path)[1]
414         params = parse_qs(parsed_url.query, strict_parsing=True)
415         self.params = InputsParser(params, False)
416
417     def _redirect(self, target: str) -> None:
418         self.send_response(302)
419         self.send_header('Location', target)
420         self.end_headers()
421
422     def _send_html(self, html: str, code: int = 200) -> None:
423         """Send HTML as proper HTTP response."""
424         self.send_response(code)
425         self.end_headers()
426         self.wfile.write(bytes(html, 'utf-8'))
427
428     def _send_msg(self, msg: Exception, code: int = 400) -> None:
429         """Send message in HTML formatting as HTTP response."""
430         html = self.server.jinja.get_template('msg.html').render(msg=msg)
431         self._send_html(html, code)