1 """Web server stuff."""
2 from __future__ import annotations
3 from dataclasses import dataclass
4 from typing import Any, Callable
5 from base64 import b64encode, b64decode
6 from http.server import BaseHTTPRequestHandler
7 from http.server import HTTPServer
8 from urllib.parse import urlparse, parse_qs
9 from os.path import split as path_split
10 from jinja2 import Environment as JinjaEnv, FileSystemLoader as JinjaFSLoader
11 from plomtask.dating import date_in_n_days
12 from plomtask.days import Day
13 from plomtask.exceptions import HandledException, BadFormatException, \
15 from plomtask.db import DatabaseConnection, DatabaseFile
16 from plomtask.processes import Process, ProcessStep, ProcessStepsNode
17 from plomtask.conditions import Condition
18 from plomtask.todos import Todo
20 TEMPLATES_DIR = 'templates'
25 """Collect what's useful for Todo steps tree display."""
28 process: Process | None
29 children: list[TodoStepsNode]
30 fillable: bool = False
33 class TaskServer(HTTPServer):
34 """Variant of HTTPServer that knows .jinja as Jinja Environment."""
36 def __init__(self, db_file: DatabaseFile,
37 *args: Any, **kwargs: Any) -> None:
38 super().__init__(*args, **kwargs)
40 self.jinja = JinjaEnv(loader=JinjaFSLoader(TEMPLATES_DIR))
44 """Wrapper for validating and retrieving dict-like HTTP inputs."""
46 def __init__(self, dict_: dict[str, list[str]],
47 strictness: bool = True) -> None:
49 self.strict = strictness
51 def get_str(self, key: str, default: str = '',
52 ignore_strict: bool = False) -> str:
53 """Retrieve single/first string value of key, or default."""
54 if key not in self.inputs.keys() or 0 == len(self.inputs[key]):
55 if self.strict and not ignore_strict:
56 raise BadFormatException(f'no value found for key {key}')
58 return self.inputs[key][0]
60 def get_first_strings_starting(self, prefix: str) -> dict[str, str]:
61 """Retrieve dict of (first) strings at key starting with prefix."""
63 for key in [k for k in self.inputs.keys() if k.startswith(prefix)]:
64 ret[key] = self.inputs[key][0]
67 def get_int(self, key: str) -> int:
68 """Retrieve single/first value of key as int, error if empty."""
69 val = self.get_int_or_none(key)
71 raise BadFormatException(f'unexpected empty value for: {key}')
74 def get_int_or_none(self, key: str) -> int | None:
75 """Retrieve single/first value of key as int, return None if empty."""
76 val = self.get_str(key, ignore_strict=True)
81 except ValueError as e:
82 msg = f'cannot int form field value for key {key}: {val}'
83 raise BadFormatException(msg) from e
85 def get_float(self, key: str) -> float:
86 """Retrieve float value of key from self.postvars."""
87 val = self.get_str(key)
90 except ValueError as e:
91 msg = f'cannot float form field value for key {key}: {val}'
92 raise BadFormatException(msg) from e
94 def get_all_str(self, key: str) -> list[str]:
95 """Retrieve list of string values at key."""
96 if key not in self.inputs.keys():
98 return self.inputs[key]
100 def get_all_int(self, key: str) -> list[int]:
101 """Retrieve list of int values at key."""
102 all_str = self.get_all_str(key)
104 return [int(s) for s in all_str if len(s) > 0]
105 except ValueError as e:
106 msg = f'cannot int a form field value for key {key} in: {all_str}'
107 raise BadFormatException(msg) from e
110 class TaskHandler(BaseHTTPRequestHandler):
111 """Handles single HTTP request."""
112 # pylint: disable=too-many-public-methods
114 conn: DatabaseConnection
116 form_data: InputsParser
119 def send_html(self, html: str, code: int = 200) -> None:
120 """Send HTML as proper HTTP response."""
121 self.send_response(code)
123 self.wfile.write(bytes(html, 'utf-8'))
126 def _wrap(method: str, not_found_msg: str
127 ) -> Callable[..., Callable[..., None]]:
128 def decorator(http_method_handler: Callable[..., str]
129 ) -> Callable[..., None]:
130 def wrapper(self: TaskHandler) -> None:
132 self.conn = DatabaseConnection(self.server.db)
133 parsed_url = urlparse(self.path)
134 self.site = path_split(parsed_url.path)[1]
135 params = parse_qs(parsed_url.query, strict_parsing=True)
136 self.params = InputsParser(params, False)
137 handler_name = f'do_{method}_{self.site}'
138 if hasattr(self, handler_name):
139 handler = getattr(self, handler_name)
140 redir_target = http_method_handler(self, handler)
142 self.send_response(302)
143 self.send_header('Location', redir_target)
146 msg = f'{not_found_msg}: {self.site}'
147 raise NotFoundException(msg)
148 except HandledException as error:
149 html = self.server.jinja.\
150 get_template('msg.html').render(msg=error)
151 self.send_html(html, error.http_code)
157 @_wrap('GET', 'Unknown page')
158 def do_GET(self, handler: Callable[..., str | dict[str, object]]
160 """Render page with result of handler, or redirect if result is str."""
161 template = f'{self.site}.html'
162 ctx_or_redir = handler()
163 if str == type(ctx_or_redir):
165 assert isinstance(ctx_or_redir, dict)
166 html = self.server.jinja.get_template(template).render(**ctx_or_redir)
170 @_wrap('POST', 'Unknown POST target')
171 def do_POST(self, handler: Callable[..., str]) -> str:
172 """Handle POST with handler, prepare redirection to result."""
173 length = int(self.headers['content-length'])
174 postvars = parse_qs(self.rfile.read(length).decode(),
175 keep_blank_values=True, strict_parsing=True)
176 self.form_data = InputsParser(postvars)
177 redir_target = handler()
181 def _do_GET_calendar(self) -> dict[str, object]:
182 """Show Days from ?start= to ?end=."""
183 start = self.params.get_str('start')
184 end = self.params.get_str('end')
186 end = date_in_n_days(366)
187 ret = Day.by_date_range_with_limits(self.conn, (start, end), 'id')
188 days, start, end = ret
189 days = Day.with_filled_gaps(days, start, end)
191 day.collect_calendarized_todos(self.conn)
192 today = date_in_n_days(0)
193 return {'start': start, 'end': end, 'days': days, 'today': today}
195 def do_GET_(self) -> str:
196 """Return redirect target on GET /."""
199 def do_GET_calendar(self) -> dict[str, object]:
200 """Show Days from ?start= to ?end= – normal view."""
201 return self._do_GET_calendar()
203 def do_GET_calendar_txt(self) -> dict[str, object]:
204 """Show Days from ?start= to ?end= – minimalist view."""
205 return self._do_GET_calendar()
207 def do_GET_day(self) -> dict[str, object]:
208 """Show single Day of ?date=."""
209 date = self.params.get_str('date', date_in_n_days(0))
210 make_type = self.params.get_str('make_type')
211 todays_todos = Todo.by_date(self.conn, date)
213 for todo in todays_todos:
214 total_effort += todo.performed_effort
215 conditions_present = []
218 for todo in todays_todos:
219 for condition in todo.conditions + todo.blockers:
220 if condition not in conditions_present:
221 conditions_present += [condition]
222 enablers_for[condition.id_] = [p for p in
223 Process.all(self.conn)
224 if condition in p.enables]
225 disablers_for[condition.id_] = [p for p in
226 Process.all(self.conn)
227 if condition in p.disables]
228 seen_todos: set[int] = set()
229 top_nodes = [t.get_step_tree(seen_todos)
230 for t in todays_todos if not t.parents]
231 return {'day': Day.by_id(self.conn, date, create=True),
232 'total_effort': total_effort,
233 'top_nodes': top_nodes,
234 'make_type': make_type,
235 'enablers_for': enablers_for,
236 'disablers_for': disablers_for,
237 'conditions_present': conditions_present,
238 'processes': Process.all(self.conn)}
240 def do_GET_todo(self) -> dict[str, object]:
241 """Show single Todo of ?id=."""
243 def walk_process_steps(id_: int,
244 process_step_nodes: list[ProcessStepsNode],
245 steps_nodes: list[TodoStepsNode]) -> None:
246 for process_step_node in process_step_nodes:
248 node = TodoStepsNode(id_, None, process_step_node.process, [])
249 steps_nodes += [node]
250 walk_process_steps(id_, list(process_step_node.steps.values()),
253 def walk_todo_steps(id_: int, todos: list[Todo],
254 steps_nodes: list[TodoStepsNode]) -> None:
257 for match in [item for item in steps_nodes
259 and item.process == todo.process]:
262 for child in match.children:
263 child.fillable = True
264 walk_todo_steps(id_, todo.children, match.children)
267 node = TodoStepsNode(id_, todo, None, [])
268 steps_nodes += [node]
269 walk_todo_steps(id_, todo.children, node.children)
271 def collect_adoptables_keys(steps_nodes: list[TodoStepsNode]
274 for node in steps_nodes:
276 assert isinstance(node.process, Process)
277 assert isinstance(node.process.id_, int)
278 ids.add(node.process.id_)
279 ids = ids | collect_adoptables_keys(node.children)
282 id_ = self.params.get_int('id')
283 todo = Todo.by_id(self.conn, id_)
284 todo_steps = [step.todo for step in todo.get_step_tree(set()).children]
285 process_tree = todo.process.get_steps(self.conn, None)
286 steps_todo_to_process: list[TodoStepsNode] = []
287 walk_process_steps(0, list(process_tree.values()),
288 steps_todo_to_process)
289 for steps_node in steps_todo_to_process:
290 steps_node.fillable = True
291 walk_todo_steps(len(steps_todo_to_process), todo_steps,
292 steps_todo_to_process)
293 adoptables: dict[int, list[Todo]] = {}
294 any_adoptables = [Todo.by_id(self.conn, t.id_)
295 for t in Todo.by_date(self.conn, todo.date)
297 for id_ in collect_adoptables_keys(steps_todo_to_process):
298 adoptables[id_] = [t for t in any_adoptables
299 if t.process.id_ == id_]
300 return {'todo': todo, 'steps_todo_to_process': steps_todo_to_process,
301 'adoption_candidates_for': adoptables,
302 'process_candidates': Process.all(self.conn),
303 'todo_candidates': any_adoptables,
304 'condition_candidates': Condition.all(self.conn)}
306 def do_GET_todos(self) -> dict[str, object]:
307 """Show Todos from ?start= to ?end=, of ?process=, ?comment= pattern"""
308 sort_by = self.params.get_str('sort_by')
309 start = self.params.get_str('start')
310 end = self.params.get_str('end')
311 process_id = self.params.get_int_or_none('process_id')
312 comment_pattern = self.params.get_str('comment_pattern')
314 ret = Todo.by_date_range_with_limits(self.conn, (start, end))
315 todos_by_date_range, start, end = ret
316 todos = [t for t in todos_by_date_range
317 if comment_pattern in t.comment
318 and ((not process_id) or t.process.id_ == process_id)]
319 if sort_by == 'doneness':
320 todos.sort(key=lambda t: t.is_done)
321 elif sort_by == '-doneness':
322 todos.sort(key=lambda t: t.is_done, reverse=True)
323 elif sort_by == 'title':
324 todos.sort(key=lambda t: t.title_then)
325 elif sort_by == '-title':
326 todos.sort(key=lambda t: t.title_then, reverse=True)
327 elif sort_by == 'comment':
328 todos.sort(key=lambda t: t.comment)
329 elif sort_by == '-comment':
330 todos.sort(key=lambda t: t.comment, reverse=True)
331 elif sort_by == '-date':
332 todos.sort(key=lambda t: t.date, reverse=True)
334 todos.sort(key=lambda t: t.date)
335 return {'start': start, 'end': end, 'process_id': process_id,
336 'comment_pattern': comment_pattern, 'todos': todos,
337 'all_processes': Process.all(self.conn), 'sort_by': sort_by}
339 def do_GET_conditions(self) -> dict[str, object]:
340 """Show all Conditions."""
341 pattern = self.params.get_str('pattern')
342 conditions = Condition.matching(self.conn, pattern)
343 sort_by = self.params.get_str('sort_by')
344 if sort_by == 'is_active':
345 conditions.sort(key=lambda c: c.is_active)
346 elif sort_by == '-is_active':
347 conditions.sort(key=lambda c: c.is_active, reverse=True)
348 elif sort_by == '-title':
349 conditions.sort(key=lambda c: c.title.newest, reverse=True)
351 conditions.sort(key=lambda c: c.title.newest)
352 return {'conditions': conditions,
356 def do_GET_condition(self) -> dict[str, object]:
357 """Show Condition of ?id=."""
358 id_ = self.params.get_int_or_none('id')
359 c = Condition.by_id(self.conn, id_, create=True)
360 ps = Process.all(self.conn)
361 return {'condition': c, 'is_new': c.id_ is None,
362 'enabled_processes': [p for p in ps if c in p.conditions],
363 'disabled_processes': [p for p in ps if c in p.blockers],
364 'enabling_processes': [p for p in ps if c in p.enables],
365 'disabling_processes': [p for p in ps if c in p.disables]}
367 def do_GET_condition_titles(self) -> dict[str, object]:
368 """Show title history of Condition of ?id=."""
369 id_ = self.params.get_int_or_none('id')
370 condition = Condition.by_id(self.conn, id_)
371 return {'condition': condition}
373 def do_GET_condition_descriptions(self) -> dict[str, object]:
374 """Show description historys of Condition of ?id=."""
375 id_ = self.params.get_int_or_none('id')
376 condition = Condition.by_id(self.conn, id_)
377 return {'condition': condition}
379 def do_GET_process(self) -> dict[str, object]:
380 """Show Process of ?id=."""
381 id_ = self.params.get_int_or_none('id')
382 process = Process.by_id(self.conn, id_, create=True)
383 title_64 = self.params.get_str('title_b64')
385 title = b64decode(title_64.encode()).decode()
386 process.title.set(title)
387 owners = process.used_as_step_by(self.conn)
388 for step_id in self.params.get_all_int('step_to'):
389 owners += [Process.by_id(self.conn, step_id)]
390 preset_top_step = None
391 for process_id in self.params.get_all_int('has_step'):
392 preset_top_step = process_id
393 return {'process': process, 'is_new': process.id_ is None,
394 'preset_top_step': preset_top_step,
395 'steps': process.get_steps(self.conn), 'owners': owners,
396 'n_todos': len(Todo.by_process_id(self.conn, process.id_)),
397 'process_candidates': Process.all(self.conn),
398 'condition_candidates': Condition.all(self.conn)}
400 def do_GET_process_titles(self) -> dict[str, object]:
401 """Show title history of Process of ?id=."""
402 id_ = self.params.get_int_or_none('id')
403 process = Process.by_id(self.conn, id_)
404 return {'process': process}
406 def do_GET_process_descriptions(self) -> dict[str, object]:
407 """Show description historys of Process of ?id=."""
408 id_ = self.params.get_int_or_none('id')
409 process = Process.by_id(self.conn, id_)
410 return {'process': process}
412 def do_GET_process_efforts(self) -> dict[str, object]:
413 """Show default effort history of Process of ?id=."""
414 id_ = self.params.get_int_or_none('id')
415 process = Process.by_id(self.conn, id_)
416 return {'process': process}
418 def do_GET_processes(self) -> dict[str, object]:
419 """Show all Processes."""
420 pattern = self.params.get_str('pattern')
421 processes = Process.matching(self.conn, pattern)
422 sort_by = self.params.get_str('sort_by')
423 if sort_by == 'steps':
424 processes.sort(key=lambda p: len(p.explicit_steps))
425 elif sort_by == '-steps':
426 processes.sort(key=lambda p: len(p.explicit_steps), reverse=True)
427 elif sort_by == 'owners':
428 processes.sort(key=lambda p: p.n_owners or 0)
429 elif sort_by == '-owners':
430 processes.sort(key=lambda p: p.n_owners or 0, reverse=True)
431 elif sort_by == 'effort':
432 processes.sort(key=lambda p: p.effort.newest)
433 elif sort_by == '-effort':
434 processes.sort(key=lambda p: p.effort.newest, reverse=True)
435 elif sort_by == '-title':
436 processes.sort(key=lambda p: p.title.newest, reverse=True)
438 processes.sort(key=lambda p: p.title.newest)
439 return {'processes': processes, 'sort_by': sort_by, 'pattern': pattern}
441 def do_POST_day(self) -> str:
442 """Update or insert Day of date and Todos mapped to it."""
443 date = self.params.get_str('date')
444 day = Day.by_id(self.conn, date, create=True)
445 day.comment = self.form_data.get_str('day_comment')
447 make_type = self.form_data.get_str('make_type')
448 for process_id in sorted(self.form_data.get_all_int('new_todo')):
449 if 'empty' == make_type:
450 process = Process.by_id(self.conn, process_id)
451 todo = Todo(None, process, False, date)
454 Todo.create_with_children(self.conn, process_id, date)
455 done_ids = self.form_data.get_all_int('done')
456 comments = self.form_data.get_all_str('comment')
457 efforts = self.form_data.get_all_str('effort')
458 for i, todo_id in enumerate(self.form_data.get_all_int('todo_id')):
459 todo = Todo.by_id(self.conn, todo_id)
460 todo.is_done = todo_id in done_ids
461 if len(comments) > 0:
462 todo.comment = comments[i]
464 todo.effort = float(efforts[i]) if efforts[i] else None
466 for condition in todo.enables:
467 condition.save(self.conn)
468 for condition in todo.disables:
469 condition.save(self.conn)
470 return f'/day?date={date}&make_type={make_type}'
472 def do_POST_todo(self) -> str:
473 """Update Todo and its children."""
474 # pylint: disable=too-many-locals
475 # pylint: disable=too-many-branches
476 id_ = self.params.get_int('id')
477 for _ in self.form_data.get_all_str('delete'):
478 todo = Todo .by_id(self.conn, id_)
479 todo.remove(self.conn)
481 todo = Todo.by_id(self.conn, id_)
482 adopted_child_ids = self.form_data.get_all_int('adopt')
483 processes_to_make_full = self.form_data.get_all_int('make_full')
484 processes_to_make_empty = self.form_data.get_all_int('make_empty')
485 fill_fors = self.form_data.get_first_strings_starting('fill_for_')
486 for v in fill_fors.values():
487 if v.startswith('make_empty_'):
488 processes_to_make_empty += [int(v[11:])]
489 elif v.startswith('make_full_'):
490 processes_to_make_full += [int(v[10:])]
492 adopted_child_ids += [int(v)]
494 for child in todo.children:
495 assert isinstance(child.id_, int)
496 if child.id_ not in adopted_child_ids:
497 to_remove += [child.id_]
498 for id_ in to_remove:
499 child = Todo.by_id(self.conn, id_)
500 todo.remove_child(child)
501 for child_id in adopted_child_ids:
502 if child_id in [c.id_ for c in todo.children]:
504 child = Todo.by_id(self.conn, child_id)
505 todo.add_child(child)
506 for process_id in processes_to_make_empty:
507 process = Process.by_id(self.conn, process_id)
508 made = Todo(None, process, False, todo.date)
511 for process_id in processes_to_make_full:
512 made = Todo.create_with_children(self.conn, process_id, todo.date)
514 effort = self.form_data.get_str('effort', ignore_strict=True)
515 todo.effort = float(effort) if effort else None
516 todo.set_conditions(self.conn,
517 self.form_data.get_all_int('condition'))
518 todo.set_blockers(self.conn, self.form_data.get_all_int('blocker'))
519 todo.set_enables(self.conn, self.form_data.get_all_int('enables'))
520 todo.set_disables(self.conn, self.form_data.get_all_int('disables'))
521 todo.is_done = len(self.form_data.get_all_str('done')) > 0
522 todo.calendarize = len(self.form_data.get_all_str('calendarize')) > 0
523 todo.comment = self.form_data.get_str('comment', ignore_strict=True)
525 for condition in todo.enables:
526 condition.save(self.conn)
527 for condition in todo.disables:
528 condition.save(self.conn)
529 return f'/todo?id={todo.id_}'
531 def _do_POST_versioned_timestamps(self, cls: Any, attr_name: str) -> str:
532 """Update history timestamps for VersionedAttribute."""
533 id_ = self.params.get_int_or_none('id')
534 item = cls.by_id(self.conn, id_)
535 attr = getattr(item, attr_name)
536 for k, v in self.form_data.get_first_strings_starting('at:').items():
539 attr.reset_timestamp(old, f'{v}.0')
541 cls_name = cls.__name__.lower()
542 return f'/{cls_name}_{attr_name}s?id={item.id_}'
544 def do_POST_process_descriptions(self) -> str:
545 """Update history timestamps for Process.description."""
546 return self._do_POST_versioned_timestamps(Process, 'description')
548 def do_POST_process_efforts(self) -> str:
549 """Update history timestamps for Process.effort."""
550 return self._do_POST_versioned_timestamps(Process, 'effort')
552 def do_POST_process_titles(self) -> str:
553 """Update history timestamps for Process.title."""
554 return self._do_POST_versioned_timestamps(Process, 'title')
556 def do_POST_process(self) -> str:
557 """Update or insert Process of ?id= and fields defined in postvars."""
558 # pylint: disable=too-many-branches
559 id_ = self.params.get_int_or_none('id')
560 for _ in self.form_data.get_all_str('delete'):
561 process = Process.by_id(self.conn, id_)
562 process.remove(self.conn)
564 process = Process.by_id(self.conn, id_, create=True)
565 process.title.set(self.form_data.get_str('title'))
566 process.description.set(self.form_data.get_str('description'))
567 process.effort.set(self.form_data.get_float('effort'))
568 process.set_conditions(self.conn,
569 self.form_data.get_all_int('condition'))
570 process.set_blockers(self.conn, self.form_data.get_all_int('blocker'))
571 process.set_enables(self.conn, self.form_data.get_all_int('enables'))
572 process.set_disables(self.conn,
573 self.form_data.get_all_int('disables'))
574 process.calendarize = self.form_data.get_all_str('calendarize') != []
575 process.save(self.conn)
576 assert isinstance(process.id_, int)
577 steps: list[ProcessStep] = []
578 for step_id in self.form_data.get_all_int('keep_step'):
579 if step_id not in self.form_data.get_all_int('steps'):
580 raise BadFormatException('trying to keep unknown step')
581 for step_id in self.form_data.get_all_int('steps'):
582 if step_id not in self.form_data.get_all_int('keep_step'):
584 step_process_id = self.form_data.get_int(
585 f'step_{step_id}_process_id')
586 parent_id = self.form_data.get_int_or_none(
587 f'step_{step_id}_parent_id')
588 steps += [ProcessStep(step_id, process.id_, step_process_id,
590 for step_id in self.form_data.get_all_int('steps'):
591 for step_process_id in self.form_data.get_all_int(
592 f'new_step_to_{step_id}'):
593 steps += [ProcessStep(None, process.id_, step_process_id,
595 new_step_title = None
596 for step_identifier in self.form_data.get_all_str('new_top_step'):
598 step_process_id = int(step_identifier)
599 steps += [ProcessStep(None, process.id_, step_process_id,
602 new_step_title = step_identifier
604 process.set_steps(self.conn, steps)
605 process.set_step_suppressions(self.conn,
607 get_all_int('suppresses'))
608 process.save(self.conn)
610 new_owner_title = None
611 for owner_identifier in self.form_data.get_all_str('step_of'):
613 owners_to_set += [int(owner_identifier)]
615 new_owner_title = owner_identifier
616 process.set_owners(self.conn, owners_to_set)
617 params = f'id={process.id_}'
619 title_b64_encoded = b64encode(new_step_title.encode()).decode()
620 params = f'step_to={process.id_}&title_b64={title_b64_encoded}'
621 elif new_owner_title:
622 title_b64_encoded = b64encode(new_owner_title.encode()).decode()
623 params = f'has_step={process.id_}&title_b64={title_b64_encoded}'
624 return f'/process?{params}'
626 def do_POST_condition_descriptions(self) -> str:
627 """Update history timestamps for Condition.description."""
628 return self._do_POST_versioned_timestamps(Condition, 'description')
630 def do_POST_condition_titles(self) -> str:
631 """Update history timestamps for Condition.title."""
632 return self._do_POST_versioned_timestamps(Condition, 'title')
634 def do_POST_condition(self) -> str:
635 """Update/insert Condition of ?id= and fields defined in postvars."""
636 id_ = self.params.get_int_or_none('id')
637 for _ in self.form_data.get_all_str('delete'):
638 condition = Condition.by_id(self.conn, id_)
639 condition.remove(self.conn)
641 condition = Condition.by_id(self.conn, id_, create=True)
642 condition.is_active = self.form_data.get_all_str('is_active') != []
643 condition.title.set(self.form_data.get_str('title'))
644 condition.description.set(self.form_data.get_str('description'))
645 condition.save(self.conn)
646 return f'/condition?id={condition.id_}'