1 """Web server stuff."""
2 from __future__ import annotations
3 from dataclasses import dataclass
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
115 def do_GET(self) -> None:
116 """Handle any GET request."""
118 self._init_handling()
119 if hasattr(self, f'do_GET_{self.site}'):
120 template = f'{self.site}.html'
121 ctx = getattr(self, f'do_GET_{self.site}')()
122 html = self.server.jinja.get_template(template).render(**ctx)
123 self._send_html(html)
124 elif '' == self.site:
125 self._redirect('/day')
127 raise NotFoundException(f'Unknown page: /{self.site}')
128 except HandledException as error:
129 self._send_msg(error, code=error.http_code)
133 def _do_GET_calendar(self) -> dict[str, object]:
134 """Show Days from ?start= to ?end=."""
135 start = self.params.get_str('start')
136 end = self.params.get_str('end')
138 end = date_in_n_days(366)
139 ret = Day.by_date_range_with_limits(self.conn, (start, end), 'id')
140 days, start, end = ret
141 days = Day.with_filled_gaps(days, start, end)
143 day.collect_calendarized_todos(self.conn)
144 today = date_in_n_days(0)
145 return {'start': start, 'end': end, 'days': days, 'today': today}
147 def do_GET_calendar(self) -> dict[str, object]:
148 """Show Days from ?start= to ?end= – normal view."""
149 return self._do_GET_calendar()
151 def do_GET_calendar_txt(self) -> dict[str, object]:
152 """Show Days from ?start= to ?end= – minimalist view."""
153 return self._do_GET_calendar()
155 def do_GET_day(self) -> dict[str, object]:
156 """Show single Day of ?date=."""
157 date = self.params.get_str('date', date_in_n_days(0))
158 make_type = self.params.get_str('make_type')
159 todays_todos = Todo.by_date(self.conn, date)
161 for todo in todays_todos:
162 total_effort += todo.performed_effort
163 conditions_present = []
166 for todo in todays_todos:
167 for condition in todo.conditions + todo.blockers:
168 if condition not in conditions_present:
169 conditions_present += [condition]
170 enablers_for[condition.id_] = [p for p in
171 Process.all(self.conn)
172 if condition in p.enables]
173 disablers_for[condition.id_] = [p for p in
174 Process.all(self.conn)
175 if condition in p.disables]
176 seen_todos: set[int] = set()
177 top_nodes = [t.get_step_tree(seen_todos)
178 for t in todays_todos if not t.parents]
179 return {'day': Day.by_id(self.conn, date, create=True),
180 'total_effort': total_effort,
181 'top_nodes': top_nodes,
182 'make_type': make_type,
183 'enablers_for': enablers_for,
184 'disablers_for': disablers_for,
185 'conditions_present': conditions_present,
186 'processes': Process.all(self.conn)}
188 def do_GET_todo(self) -> dict[str, object]:
189 """Show single Todo of ?id=."""
191 def walk_process_steps(id_: int,
192 process_step_nodes: list[ProcessStepsNode],
193 steps_nodes: list[TodoStepsNode]) -> None:
194 for process_step_node in process_step_nodes:
196 node = TodoStepsNode(id_, None, process_step_node.process, [])
197 steps_nodes += [node]
198 walk_process_steps(id_, list(process_step_node.steps.values()),
201 def walk_todo_steps(id_: int, todos: list[Todo],
202 steps_nodes: list[TodoStepsNode]) -> None:
205 for match in [item for item in steps_nodes
207 and item.process == todo.process]:
210 for child in match.children:
211 child.fillable = True
212 walk_todo_steps(id_, todo.children, match.children)
215 node = TodoStepsNode(id_, todo, None, [])
216 steps_nodes += [node]
217 walk_todo_steps(id_, todo.children, node.children)
219 def collect_adoptables_keys(steps_nodes: list[TodoStepsNode]
222 for node in steps_nodes:
224 assert isinstance(node.process, Process)
225 assert isinstance(node.process.id_, int)
226 ids.add(node.process.id_)
227 ids = ids | collect_adoptables_keys(node.children)
230 id_ = self.params.get_int('id')
231 todo = Todo.by_id(self.conn, id_)
232 todo_steps = [step.todo for step in todo.get_step_tree(set()).children]
233 process_tree = todo.process.get_steps(self.conn, None)
234 steps_todo_to_process: list[TodoStepsNode] = []
235 walk_process_steps(0, list(process_tree.values()),
236 steps_todo_to_process)
237 for steps_node in steps_todo_to_process:
238 steps_node.fillable = True
239 walk_todo_steps(len(steps_todo_to_process), todo_steps,
240 steps_todo_to_process)
241 adoptables: dict[int, list[Todo]] = {}
242 any_adoptables = [Todo.by_id(self.conn, t.id_)
243 for t in Todo.by_date(self.conn, todo.date)
245 for id_ in collect_adoptables_keys(steps_todo_to_process):
246 adoptables[id_] = [t for t in any_adoptables
247 if t.process.id_ == id_]
248 return {'todo': todo, 'steps_todo_to_process': steps_todo_to_process,
249 'adoption_candidates_for': adoptables,
250 'process_candidates': Process.all(self.conn),
251 'todo_candidates': any_adoptables,
252 'condition_candidates': Condition.all(self.conn)}
254 def do_GET_todos(self) -> dict[str, object]:
255 """Show Todos from ?start= to ?end=, of ?process=, ?comment= pattern"""
256 sort_by = self.params.get_str('sort_by')
257 start = self.params.get_str('start')
258 end = self.params.get_str('end')
259 process_id = self.params.get_int_or_none('process_id')
260 comment_pattern = self.params.get_str('comment_pattern')
262 ret = Todo.by_date_range_with_limits(self.conn, (start, end))
263 todos_by_date_range, start, end = ret
264 todos = [t for t in todos_by_date_range
265 if comment_pattern in t.comment
266 and ((not process_id) or t.process.id_ == process_id)]
267 if sort_by == 'doneness':
268 todos.sort(key=lambda t: t.is_done)
269 elif sort_by == '-doneness':
270 todos.sort(key=lambda t: t.is_done, reverse=True)
271 elif sort_by == 'title':
272 todos.sort(key=lambda t: t.title_then)
273 elif sort_by == '-title':
274 todos.sort(key=lambda t: t.title_then, reverse=True)
275 elif sort_by == 'comment':
276 todos.sort(key=lambda t: t.comment)
277 elif sort_by == '-comment':
278 todos.sort(key=lambda t: t.comment, reverse=True)
279 elif sort_by == '-date':
280 todos.sort(key=lambda t: t.date, reverse=True)
282 todos.sort(key=lambda t: t.date)
283 return {'start': start, 'end': end, 'process_id': process_id,
284 'comment_pattern': comment_pattern, 'todos': todos,
285 'all_processes': Process.all(self.conn), 'sort_by': sort_by}
287 def do_GET_conditions(self) -> dict[str, object]:
288 """Show all Conditions."""
289 pattern = self.params.get_str('pattern')
290 conditions = Condition.matching(self.conn, pattern)
291 sort_by = self.params.get_str('sort_by')
292 if sort_by == 'is_active':
293 conditions.sort(key=lambda c: c.is_active)
294 elif sort_by == '-is_active':
295 conditions.sort(key=lambda c: c.is_active, reverse=True)
296 elif sort_by == '-title':
297 conditions.sort(key=lambda c: c.title.newest, reverse=True)
299 conditions.sort(key=lambda c: c.title.newest)
300 return {'conditions': conditions,
304 def do_GET_condition(self) -> dict[str, object]:
305 """Show Condition of ?id=."""
306 id_ = self.params.get_int_or_none('id')
307 c = Condition.by_id(self.conn, id_, create=True)
308 ps = Process.all(self.conn)
309 return {'condition': c, 'is_new': c.id_ is None,
310 'enabled_processes': [p for p in ps if c in p.conditions],
311 'disabled_processes': [p for p in ps if c in p.blockers],
312 'enabling_processes': [p for p in ps if c in p.enables],
313 'disabling_processes': [p for p in ps if c in p.disables]}
315 def do_GET_condition_titles(self) -> dict[str, object]:
316 """Show title history of Condition of ?id=."""
317 id_ = self.params.get_int_or_none('id')
318 condition = Condition.by_id(self.conn, id_)
319 return {'condition': condition}
321 def do_GET_condition_descriptions(self) -> dict[str, object]:
322 """Show description historys of Condition of ?id=."""
323 id_ = self.params.get_int_or_none('id')
324 condition = Condition.by_id(self.conn, id_)
325 return {'condition': condition}
327 def do_GET_process(self) -> dict[str, object]:
328 """Show Process of ?id=."""
329 id_ = self.params.get_int_or_none('id')
330 process = Process.by_id(self.conn, id_, create=True)
331 title_64 = self.params.get_str('title_b64')
333 title = b64decode(title_64.encode()).decode()
334 process.title.set(title)
335 owners = process.used_as_step_by(self.conn)
336 for step_id in self.params.get_all_int('step_to'):
337 owners += [Process.by_id(self.conn, step_id)]
338 preset_top_step = None
339 for process_id in self.params.get_all_int('has_step'):
340 preset_top_step = process_id
341 return {'process': process, 'is_new': process.id_ is None,
342 'preset_top_step': preset_top_step,
343 'steps': process.get_steps(self.conn), 'owners': owners,
344 'n_todos': len(Todo.by_process_id(self.conn, process.id_)),
345 'process_candidates': Process.all(self.conn),
346 'condition_candidates': Condition.all(self.conn)}
348 def do_GET_process_titles(self) -> dict[str, object]:
349 """Show title history of Process of ?id=."""
350 id_ = self.params.get_int_or_none('id')
351 process = Process.by_id(self.conn, id_)
352 return {'process': process}
354 def do_GET_process_descriptions(self) -> dict[str, object]:
355 """Show description historys of Process of ?id=."""
356 id_ = self.params.get_int_or_none('id')
357 process = Process.by_id(self.conn, id_)
358 return {'process': process}
360 def do_GET_process_efforts(self) -> dict[str, object]:
361 """Show default effort history of Process of ?id=."""
362 id_ = self.params.get_int_or_none('id')
363 process = Process.by_id(self.conn, id_)
364 return {'process': process}
366 def do_GET_processes(self) -> dict[str, object]:
367 """Show all Processes."""
368 pattern = self.params.get_str('pattern')
369 processes = Process.matching(self.conn, pattern)
370 sort_by = self.params.get_str('sort_by')
371 if sort_by == 'steps':
372 processes.sort(key=lambda p: len(p.explicit_steps))
373 elif sort_by == '-steps':
374 processes.sort(key=lambda p: len(p.explicit_steps), reverse=True)
375 elif sort_by == 'owners':
376 processes.sort(key=lambda p: p.n_owners or 0)
377 elif sort_by == '-owners':
378 processes.sort(key=lambda p: p.n_owners or 0, reverse=True)
379 elif sort_by == 'effort':
380 processes.sort(key=lambda p: p.effort.newest)
381 elif sort_by == '-effort':
382 processes.sort(key=lambda p: p.effort.newest, reverse=True)
383 elif sort_by == '-title':
384 processes.sort(key=lambda p: p.title.newest, reverse=True)
386 processes.sort(key=lambda p: p.title.newest)
387 return {'processes': processes, 'sort_by': sort_by, 'pattern': pattern}
389 def do_POST(self) -> None:
390 """Handle any POST request."""
391 # pylint: disable=attribute-defined-outside-init
393 self._init_handling()
394 length = int(self.headers['content-length'])
395 postvars = parse_qs(self.rfile.read(length).decode(),
396 keep_blank_values=True, strict_parsing=True)
397 self.form_data = InputsParser(postvars)
398 if hasattr(self, f'do_POST_{self.site}'):
399 redir_target = getattr(self, f'do_POST_{self.site}')()
402 msg = f'Page not known as POST target: /{self.site}'
403 raise NotFoundException(msg)
404 self._redirect(redir_target)
405 except HandledException as error:
406 self._send_msg(error, code=error.http_code)
410 def do_POST_day(self) -> str:
411 """Update or insert Day of date and Todos mapped to it."""
412 date = self.params.get_str('date')
413 day = Day.by_id(self.conn, date, create=True)
414 day.comment = self.form_data.get_str('day_comment')
416 make_type = self.form_data.get_str('make_type')
417 for process_id in sorted(self.form_data.get_all_int('new_todo')):
418 if 'empty' == make_type:
419 process = Process.by_id(self.conn, process_id)
420 todo = Todo(None, process, False, date)
423 Todo.create_with_children(self.conn, process_id, date)
424 done_ids = self.form_data.get_all_int('done')
425 comments = self.form_data.get_all_str('comment')
426 efforts = self.form_data.get_all_str('effort')
427 for i, todo_id in enumerate(self.form_data.get_all_int('todo_id')):
428 todo = Todo.by_id(self.conn, todo_id)
429 todo.is_done = todo_id in done_ids
430 if len(comments) > 0:
431 todo.comment = comments[i]
433 todo.effort = float(efforts[i]) if efforts[i] else None
435 for condition in todo.enables:
436 condition.save(self.conn)
437 for condition in todo.disables:
438 condition.save(self.conn)
439 return f'/day?date={date}&make_type={make_type}'
441 def do_POST_todo(self) -> str:
442 """Update Todo and its children."""
443 # pylint: disable=too-many-locals
444 # pylint: disable=too-many-branches
445 id_ = self.params.get_int('id')
446 for _ in self.form_data.get_all_str('delete'):
447 todo = Todo .by_id(self.conn, id_)
448 todo.remove(self.conn)
450 todo = Todo.by_id(self.conn, id_)
451 adopted_child_ids = self.form_data.get_all_int('adopt')
452 processes_to_make_full = self.form_data.get_all_int('make_full')
453 processes_to_make_empty = self.form_data.get_all_int('make_empty')
454 fill_fors = self.form_data.get_first_strings_starting('fill_for_')
455 for v in fill_fors.values():
456 if v.startswith('make_empty_'):
457 processes_to_make_empty += [int(v[11:])]
458 elif v.startswith('make_full_'):
459 processes_to_make_full += [int(v[10:])]
461 adopted_child_ids += [int(v)]
463 for child in todo.children:
464 assert isinstance(child.id_, int)
465 if child.id_ not in adopted_child_ids:
466 to_remove += [child.id_]
467 for id_ in to_remove:
468 child = Todo.by_id(self.conn, id_)
469 todo.remove_child(child)
470 for child_id in adopted_child_ids:
471 if child_id in [c.id_ for c in todo.children]:
473 child = Todo.by_id(self.conn, child_id)
474 todo.add_child(child)
475 for process_id in processes_to_make_empty:
476 process = Process.by_id(self.conn, process_id)
477 made = Todo(None, process, False, todo.date)
480 for process_id in processes_to_make_full:
481 made = Todo.create_with_children(self.conn, process_id, todo.date)
483 effort = self.form_data.get_str('effort', ignore_strict=True)
484 todo.effort = float(effort) if effort else None
485 todo.set_conditions(self.conn, self.form_data.get_all_int('condition'))
486 todo.set_blockers(self.conn, self.form_data.get_all_int('blocker'))
487 todo.set_enables(self.conn, self.form_data.get_all_int('enables'))
488 todo.set_disables(self.conn, self.form_data.get_all_int('disables'))
489 todo.is_done = len(self.form_data.get_all_str('done')) > 0
490 todo.calendarize = len(self.form_data.get_all_str('calendarize')) > 0
491 todo.comment = self.form_data.get_str('comment', ignore_strict=True)
493 for condition in todo.enables:
494 condition.save(self.conn)
495 for condition in todo.disables:
496 condition.save(self.conn)
497 return f'/todo?id={todo.id_}'
499 def _do_POST_versioned_timestamps(self, cls: Any, attr_name: str) -> str:
500 """Update history timestamps for VersionedAttribute."""
501 id_ = self.params.get_int_or_none('id')
502 item = cls.by_id(self.conn, id_)
503 attr = getattr(item, attr_name)
504 for k, v in self.form_data.get_first_strings_starting('at:').items():
507 attr.reset_timestamp(old, f'{v}.0')
509 cls_name = cls.__name__.lower()
510 return f'/{cls_name}_{attr_name}s?id={item.id_}'
512 def do_POST_process_descriptions(self) -> str:
513 """Update history timestamps for Process.description."""
514 return self._do_POST_versioned_timestamps(Process, 'description')
516 def do_POST_process_efforts(self) -> str:
517 """Update history timestamps for Process.effort."""
518 return self._do_POST_versioned_timestamps(Process, 'effort')
520 def do_POST_process_titles(self) -> str:
521 """Update history timestamps for Process.title."""
522 return self._do_POST_versioned_timestamps(Process, 'title')
524 def do_POST_process(self) -> str:
525 """Update or insert Process of ?id= and fields defined in postvars."""
526 # pylint: disable=too-many-branches
527 id_ = self.params.get_int_or_none('id')
528 for _ in self.form_data.get_all_str('delete'):
529 process = Process.by_id(self.conn, id_)
530 process.remove(self.conn)
532 process = Process.by_id(self.conn, id_, create=True)
533 process.title.set(self.form_data.get_str('title'))
534 process.description.set(self.form_data.get_str('description'))
535 process.effort.set(self.form_data.get_float('effort'))
536 process.set_conditions(self.conn,
537 self.form_data.get_all_int('condition'))
538 process.set_blockers(self.conn, self.form_data.get_all_int('blocker'))
539 process.set_enables(self.conn, self.form_data.get_all_int('enables'))
540 process.set_disables(self.conn, self.form_data.get_all_int('disables'))
541 process.calendarize = self.form_data.get_all_str('calendarize') != []
542 process.save(self.conn)
543 assert isinstance(process.id_, int)
544 steps: list[ProcessStep] = []
545 for step_id in self.form_data.get_all_int('keep_step'):
546 if step_id not in self.form_data.get_all_int('steps'):
547 raise BadFormatException('trying to keep unknown step')
548 for step_id in self.form_data.get_all_int('steps'):
549 if step_id not in self.form_data.get_all_int('keep_step'):
551 step_process_id = self.form_data.get_int(
552 f'step_{step_id}_process_id')
553 parent_id = self.form_data.get_int_or_none(
554 f'step_{step_id}_parent_id')
555 steps += [ProcessStep(step_id, process.id_, step_process_id,
557 for step_id in self.form_data.get_all_int('steps'):
558 for step_process_id in self.form_data.get_all_int(
559 f'new_step_to_{step_id}'):
560 steps += [ProcessStep(None, process.id_, step_process_id,
562 new_step_title = None
563 for step_identifier in self.form_data.get_all_str('new_top_step'):
565 step_process_id = int(step_identifier)
566 steps += [ProcessStep(None, process.id_, step_process_id,
569 new_step_title = step_identifier
571 process.set_steps(self.conn, steps)
572 process.set_step_suppressions(self.conn,
573 self.form_data.get_all_int('suppresses'))
574 process.save(self.conn)
576 new_owner_title = None
577 for owner_identifier in self.form_data.get_all_str('step_of'):
579 owners_to_set += [int(owner_identifier)]
581 new_owner_title = owner_identifier
582 process.set_owners(self.conn, owners_to_set)
583 params = f'id={process.id_}'
585 title_b64_encoded = b64encode(new_step_title.encode()).decode()
586 params = f'step_to={process.id_}&title_b64={title_b64_encoded}'
587 elif new_owner_title:
588 title_b64_encoded = b64encode(new_owner_title.encode()).decode()
589 params = f'has_step={process.id_}&title_b64={title_b64_encoded}'
590 return f'/process?{params}'
592 def do_POST_condition_descriptions(self) -> str:
593 """Update history timestamps for Condition.description."""
594 return self._do_POST_versioned_timestamps(Condition, 'description')
596 def do_POST_condition_titles(self) -> str:
597 """Update history timestamps for Condition.title."""
598 return self._do_POST_versioned_timestamps(Condition, 'title')
600 def do_POST_condition(self) -> str:
601 """Update/insert Condition of ?id= and fields defined in postvars."""
602 id_ = self.params.get_int_or_none('id')
603 for _ in self.form_data.get_all_str('delete'):
604 condition = Condition.by_id(self.conn, id_)
605 condition.remove(self.conn)
607 condition = Condition.by_id(self.conn, id_, create=True)
608 condition.is_active = self.form_data.get_all_str('is_active') != []
609 condition.title.set(self.form_data.get_str('title'))
610 condition.description.set(self.form_data.get_str('description'))
611 condition.save(self.conn)
612 return f'/condition?id={condition.id_}'
614 def _init_handling(self) -> None:
615 # pylint: disable=attribute-defined-outside-init
616 self.conn = DatabaseConnection(self.server.db)
617 parsed_url = urlparse(self.path)
618 self.site = path_split(parsed_url.path)[1]
619 params = parse_qs(parsed_url.query, strict_parsing=True)
620 self.params = InputsParser(params, False)
622 def _redirect(self, target: str) -> None:
623 self.send_response(302)
624 self.send_header('Location', target)
627 def _send_html(self, html: str, code: int = 200) -> None:
628 """Send HTML as proper HTTP response."""
629 self.send_response(code)
631 self.wfile.write(bytes(html, 'utf-8'))
633 def _send_msg(self, msg: Exception, code: int = 400) -> None:
634 """Send message in HTML formatting as HTTP response."""
635 html = self.server.jinja.get_template('msg.html').render(msg=msg)
636 self._send_html(html, code)