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