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 todays_todos = Todo.by_date(self.conn, date)
160 for todo in todays_todos:
161 total_effort += todo.performed_effort
162 conditions_present = []
165 for todo in todays_todos:
166 for condition in todo.conditions + todo.blockers:
167 if condition not in conditions_present:
168 conditions_present += [condition]
169 enablers_for[condition.id_] = [p for p in
170 Process.all(self.conn)
171 if condition in p.enables]
172 disablers_for[condition.id_] = [p for p in
173 Process.all(self.conn)
174 if condition in p.disables]
175 seen_todos: set[int] = set()
176 top_nodes = [t.get_step_tree(seen_todos)
177 for t in todays_todos if not t.parents]
178 return {'day': Day.by_id(self.conn, date, create=True),
179 'total_effort': total_effort,
180 'top_nodes': top_nodes,
181 'enablers_for': enablers_for,
182 'disablers_for': disablers_for,
183 'conditions_present': conditions_present,
184 'processes': Process.all(self.conn)}
186 def do_GET_todo(self) -> dict[str, object]:
187 """Show single Todo of ?id=."""
189 def walk_process_steps(id_: int,
190 process_step_nodes: list[ProcessStepsNode],
191 steps_nodes: list[TodoStepsNode]) -> None:
192 for process_step_node in process_step_nodes:
194 node = TodoStepsNode(id_, None, process_step_node.process, [])
195 steps_nodes += [node]
196 walk_process_steps(id_, list(process_step_node.steps.values()),
199 def walk_todo_steps(id_: int, todos: list[Todo],
200 steps_nodes: list[TodoStepsNode]) -> None:
203 for match in [item for item in steps_nodes
205 and item.process == todo.process]:
208 for child in match.children:
209 child.fillable = True
210 walk_todo_steps(id_, todo.children, match.children)
213 node = TodoStepsNode(id_, todo, None, [])
214 steps_nodes += [node]
215 walk_todo_steps(id_, todo.children, node.children)
217 def collect_adoptables_keys(steps_nodes: list[TodoStepsNode]
220 for node in steps_nodes:
222 assert isinstance(node.process, Process)
223 assert isinstance(node.process.id_, int)
224 ids.add(node.process.id_)
225 ids = ids | collect_adoptables_keys(node.children)
228 id_ = self.params.get_int('id')
229 todo = Todo.by_id(self.conn, id_)
230 todo_steps = [step.todo for step in todo.get_step_tree(set()).children]
231 process_tree = todo.process.get_steps(self.conn, None)
232 steps_todo_to_process: list[TodoStepsNode] = []
233 walk_process_steps(0, list(process_tree.values()),
234 steps_todo_to_process)
235 for steps_node in steps_todo_to_process:
236 steps_node.fillable = True
237 walk_todo_steps(len(steps_todo_to_process), todo_steps,
238 steps_todo_to_process)
239 adoptables: dict[int, list[Todo]] = {}
240 any_adoptables = [Todo.by_id(self.conn, t.id_)
241 for t in Todo.by_date(self.conn, todo.date)
243 for id_ in collect_adoptables_keys(steps_todo_to_process):
244 adoptables[id_] = [t for t in any_adoptables
245 if t.process.id_ == id_]
246 return {'todo': todo, 'steps_todo_to_process': steps_todo_to_process,
247 'adoption_candidates_for': adoptables,
248 'process_candidates': Process.all(self.conn),
249 'todo_candidates': any_adoptables,
250 'condition_candidates': Condition.all(self.conn)}
252 def do_GET_todos(self) -> dict[str, object]:
253 """Show Todos from ?start= to ?end=, of ?process=, ?comment= pattern"""
254 sort_by = self.params.get_str('sort_by')
255 start = self.params.get_str('start')
256 end = self.params.get_str('end')
257 process_id = self.params.get_int_or_none('process_id')
258 comment_pattern = self.params.get_str('comment_pattern')
260 ret = Todo.by_date_range_with_limits(self.conn, (start, end))
261 todos_by_date_range, start, end = ret
262 todos = [t for t in todos_by_date_range
263 if comment_pattern in t.comment
264 and ((not process_id) or t.process.id_ == process_id)]
265 if sort_by == 'doneness':
266 todos.sort(key=lambda t: t.is_done)
267 elif sort_by == '-doneness':
268 todos.sort(key=lambda t: t.is_done, reverse=True)
269 elif sort_by == 'title':
270 todos.sort(key=lambda t: t.title_then)
271 elif sort_by == '-title':
272 todos.sort(key=lambda t: t.title_then, reverse=True)
273 elif sort_by == 'comment':
274 todos.sort(key=lambda t: t.comment)
275 elif sort_by == '-comment':
276 todos.sort(key=lambda t: t.comment, reverse=True)
277 elif sort_by == '-date':
278 todos.sort(key=lambda t: t.date, reverse=True)
280 todos.sort(key=lambda t: t.date)
281 return {'start': start, 'end': end, 'process_id': process_id,
282 'comment_pattern': comment_pattern, 'todos': todos,
283 'all_processes': Process.all(self.conn), 'sort_by': sort_by}
285 def do_GET_conditions(self) -> dict[str, object]:
286 """Show all Conditions."""
287 pattern = self.params.get_str('pattern')
288 conditions = Condition.matching(self.conn, pattern)
289 sort_by = self.params.get_str('sort_by')
290 if sort_by == 'is_active':
291 conditions.sort(key=lambda c: c.is_active)
292 elif sort_by == '-is_active':
293 conditions.sort(key=lambda c: c.is_active, reverse=True)
294 elif sort_by == '-title':
295 conditions.sort(key=lambda c: c.title.newest, reverse=True)
297 conditions.sort(key=lambda c: c.title.newest)
298 return {'conditions': conditions,
302 def do_GET_condition(self) -> dict[str, object]:
303 """Show Condition of ?id=."""
304 id_ = self.params.get_int_or_none('id')
305 c = Condition.by_id(self.conn, id_, create=True)
306 ps = Process.all(self.conn)
307 return {'condition': c, 'is_new': c.id_ is None,
308 'enabled_processes': [p for p in ps if c in p.conditions],
309 'disabled_processes': [p for p in ps if c in p.blockers],
310 'enabling_processes': [p for p in ps if c in p.enables],
311 'disabling_processes': [p for p in ps if c in p.disables]}
313 def do_GET_condition_titles(self) -> dict[str, object]:
314 """Show title history of Condition of ?id=."""
315 id_ = self.params.get_int_or_none('id')
316 condition = Condition.by_id(self.conn, id_)
317 return {'condition': condition}
319 def do_GET_condition_descriptions(self) -> dict[str, object]:
320 """Show description historys of Condition of ?id=."""
321 id_ = self.params.get_int_or_none('id')
322 condition = Condition.by_id(self.conn, id_)
323 return {'condition': condition}
325 def do_GET_process(self) -> dict[str, object]:
326 """Show Process of ?id=."""
327 id_ = self.params.get_int_or_none('id')
328 process = Process.by_id(self.conn, id_, create=True)
329 title_64 = self.params.get_str('title_b64')
331 title = b64decode(title_64.encode()).decode()
332 process.title.set(title)
333 owners = process.used_as_step_by(self.conn)
334 for step_id in self.params.get_all_int('step_to'):
335 owners += [Process.by_id(self.conn, step_id)]
336 preset_top_step = None
337 for process_id in self.params.get_all_int('has_step'):
338 preset_top_step = process_id
339 return {'process': process, 'is_new': process.id_ is None,
340 'preset_top_step': preset_top_step,
341 'steps': process.get_steps(self.conn), 'owners': owners,
342 'n_todos': len(Todo.by_process_id(self.conn, process.id_)),
343 'process_candidates': Process.all(self.conn),
344 'condition_candidates': Condition.all(self.conn)}
346 def do_GET_process_titles(self) -> dict[str, object]:
347 """Show title history of Process of ?id=."""
348 id_ = self.params.get_int_or_none('id')
349 process = Process.by_id(self.conn, id_)
350 return {'process': process}
352 def do_GET_process_descriptions(self) -> dict[str, object]:
353 """Show description historys of Process of ?id=."""
354 id_ = self.params.get_int_or_none('id')
355 process = Process.by_id(self.conn, id_)
356 return {'process': process}
358 def do_GET_process_efforts(self) -> dict[str, object]:
359 """Show default effort history of Process of ?id=."""
360 id_ = self.params.get_int_or_none('id')
361 process = Process.by_id(self.conn, id_)
362 return {'process': process}
364 def do_GET_processes(self) -> dict[str, object]:
365 """Show all Processes."""
366 pattern = self.params.get_str('pattern')
367 processes = Process.matching(self.conn, pattern)
368 sort_by = self.params.get_str('sort_by')
369 if sort_by == 'steps':
370 processes.sort(key=lambda p: len(p.explicit_steps))
371 elif sort_by == '-steps':
372 processes.sort(key=lambda p: len(p.explicit_steps), reverse=True)
373 elif sort_by == 'owners':
374 processes.sort(key=lambda p: p.n_owners or 0)
375 elif sort_by == '-owners':
376 processes.sort(key=lambda p: p.n_owners or 0, reverse=True)
377 elif sort_by == 'effort':
378 processes.sort(key=lambda p: p.effort.newest)
379 elif sort_by == '-effort':
380 processes.sort(key=lambda p: p.effort.newest, reverse=True)
381 elif sort_by == '-title':
382 processes.sort(key=lambda p: p.title.newest, reverse=True)
384 processes.sort(key=lambda p: p.title.newest)
385 return {'processes': processes, 'sort_by': sort_by, 'pattern': pattern}
387 def do_POST(self) -> None:
388 """Handle any POST request."""
389 # pylint: disable=attribute-defined-outside-init
391 self._init_handling()
392 length = int(self.headers['content-length'])
393 postvars = parse_qs(self.rfile.read(length).decode(),
394 keep_blank_values=True, strict_parsing=True)
395 self.form_data = InputsParser(postvars)
396 if hasattr(self, f'do_POST_{self.site}'):
397 redir_target = getattr(self, f'do_POST_{self.site}')()
400 msg = f'Page not known as POST target: /{self.site}'
401 raise NotFoundException(msg)
402 self._redirect(redir_target)
403 except HandledException as error:
404 self._send_msg(error, code=error.http_code)
408 def do_POST_day(self) -> str:
409 """Update or insert Day of date and Todos mapped to it."""
410 date = self.params.get_str('date')
411 day = Day.by_id(self.conn, date, create=True)
412 day.comment = self.form_data.get_str('day_comment')
414 for process_id in sorted(self.form_data.get_all_int('new_todo')):
415 Todo.create_with_children(self.conn, process_id, date)
416 done_ids = self.form_data.get_all_int('done')
417 comments = self.form_data.get_all_str('comment')
418 efforts = self.form_data.get_all_str('effort')
419 for i, todo_id in enumerate(self.form_data.get_all_int('todo_id')):
420 todo = Todo.by_id(self.conn, todo_id)
421 todo.is_done = todo_id in done_ids
422 if len(comments) > 0:
423 todo.comment = comments[i]
425 todo.effort = float(efforts[i]) if efforts[i] else None
427 for condition in todo.enables:
428 condition.save(self.conn)
429 for condition in todo.disables:
430 condition.save(self.conn)
431 return f'/day?date={date}'
433 def do_POST_todo(self) -> str:
434 """Update Todo and its children."""
435 id_ = self.params.get_int('id')
436 for _ in self.form_data.get_all_str('delete'):
437 todo = Todo .by_id(self.conn, id_)
438 todo.remove(self.conn)
440 todo = Todo.by_id(self.conn, id_)
441 adopted_child_ids = self.form_data.get_all_int('adopt')
442 processes_to_make = self.form_data.get_all_int('make')
443 fill_fors = self.form_data.get_first_strings_starting('fill_for_')
444 for v in fill_fors.values():
445 if v.startswith('make_'):
446 processes_to_make += [int(v[5:])]
448 adopted_child_ids += [int(v)]
450 for child in todo.children:
451 assert isinstance(child.id_, int)
452 if child.id_ not in adopted_child_ids:
453 to_remove += [child.id_]
454 for id_ in to_remove:
455 child = Todo.by_id(self.conn, id_)
456 todo.remove_child(child)
457 for child_id in adopted_child_ids:
458 if child_id in [c.id_ for c in todo.children]:
460 child = Todo.by_id(self.conn, child_id)
461 todo.add_child(child)
462 for process_id in processes_to_make:
463 made = Todo.create_with_children(self.conn, process_id, todo.date)
465 effort = self.form_data.get_str('effort', ignore_strict=True)
466 todo.effort = float(effort) if effort else None
467 todo.set_conditions(self.conn, self.form_data.get_all_int('condition'))
468 todo.set_blockers(self.conn, self.form_data.get_all_int('blocker'))
469 todo.set_enables(self.conn, self.form_data.get_all_int('enables'))
470 todo.set_disables(self.conn, self.form_data.get_all_int('disables'))
471 todo.is_done = len(self.form_data.get_all_str('done')) > 0
472 todo.calendarize = len(self.form_data.get_all_str('calendarize')) > 0
473 todo.comment = self.form_data.get_str('comment', ignore_strict=True)
475 for condition in todo.enables:
476 condition.save(self.conn)
477 for condition in todo.disables:
478 condition.save(self.conn)
479 return f'/todo?id={todo.id_}'
481 def _do_POST_versioned_timestamps(self, cls: Any, attr_name: str) -> str:
482 """Update history timestamps for VersionedAttribute."""
483 id_ = self.params.get_int_or_none('id')
484 item = cls.by_id(self.conn, id_)
485 attr = getattr(item, attr_name)
486 for k, v in self.form_data.get_first_strings_starting('at:').items():
489 attr.reset_timestamp(old, f'{v}.0')
491 cls_name = cls.__name__.lower()
492 return f'/{cls_name}_{attr_name}s?id={item.id_}'
494 def do_POST_process_descriptions(self) -> str:
495 """Update history timestamps for Process.description."""
496 return self._do_POST_versioned_timestamps(Process, 'description')
498 def do_POST_process_efforts(self) -> str:
499 """Update history timestamps for Process.effort."""
500 return self._do_POST_versioned_timestamps(Process, 'effort')
502 def do_POST_process_titles(self) -> str:
503 """Update history timestamps for Process.title."""
504 return self._do_POST_versioned_timestamps(Process, 'title')
506 def do_POST_process(self) -> str:
507 """Update or insert Process of ?id= and fields defined in postvars."""
508 # pylint: disable=too-many-branches
509 id_ = self.params.get_int_or_none('id')
510 for _ in self.form_data.get_all_str('delete'):
511 process = Process.by_id(self.conn, id_)
512 process.remove(self.conn)
514 process = Process.by_id(self.conn, id_, create=True)
515 process.title.set(self.form_data.get_str('title'))
516 process.description.set(self.form_data.get_str('description'))
517 process.effort.set(self.form_data.get_float('effort'))
518 process.set_conditions(self.conn,
519 self.form_data.get_all_int('condition'))
520 process.set_blockers(self.conn, self.form_data.get_all_int('blocker'))
521 process.set_enables(self.conn, self.form_data.get_all_int('enables'))
522 process.set_disables(self.conn, self.form_data.get_all_int('disables'))
523 process.calendarize = self.form_data.get_all_str('calendarize') != []
524 process.save(self.conn)
525 assert isinstance(process.id_, int)
526 steps: list[ProcessStep] = []
527 for step_id in self.form_data.get_all_int('keep_step'):
528 if step_id not in self.form_data.get_all_int('steps'):
529 raise BadFormatException('trying to keep unknown step')
530 for step_id in self.form_data.get_all_int('steps'):
531 if step_id not in self.form_data.get_all_int('keep_step'):
533 step_process_id = self.form_data.get_int(
534 f'step_{step_id}_process_id')
535 parent_id = self.form_data.get_int_or_none(
536 f'step_{step_id}_parent_id')
537 steps += [ProcessStep(step_id, process.id_, step_process_id,
539 for step_id in self.form_data.get_all_int('steps'):
540 for step_process_id in self.form_data.get_all_int(
541 f'new_step_to_{step_id}'):
542 steps += [ProcessStep(None, process.id_, step_process_id,
544 new_step_title = None
545 for step_identifier in self.form_data.get_all_str('new_top_step'):
547 step_process_id = int(step_identifier)
548 steps += [ProcessStep(None, process.id_, step_process_id,
551 new_step_title = step_identifier
553 process.set_steps(self.conn, steps)
554 process.set_step_suppressions(self.conn,
555 self.form_data.get_all_int('suppresses'))
556 process.save(self.conn)
558 new_owner_title = None
559 for owner_identifier in self.form_data.get_all_str('step_of'):
561 owners_to_set += [int(owner_identifier)]
563 new_owner_title = owner_identifier
564 process.set_owners(self.conn, owners_to_set)
565 params = f'id={process.id_}'
567 title_b64_encoded = b64encode(new_step_title.encode()).decode()
568 params = f'step_to={process.id_}&title_b64={title_b64_encoded}'
569 elif new_owner_title:
570 title_b64_encoded = b64encode(new_owner_title.encode()).decode()
571 params = f'has_step={process.id_}&title_b64={title_b64_encoded}'
572 return f'/process?{params}'
574 def do_POST_condition_descriptions(self) -> str:
575 """Update history timestamps for Condition.description."""
576 return self._do_POST_versioned_timestamps(Condition, 'description')
578 def do_POST_condition_titles(self) -> str:
579 """Update history timestamps for Condition.title."""
580 return self._do_POST_versioned_timestamps(Condition, 'title')
582 def do_POST_condition(self) -> str:
583 """Update/insert Condition of ?id= and fields defined in postvars."""
584 id_ = self.params.get_int_or_none('id')
585 for _ in self.form_data.get_all_str('delete'):
586 condition = Condition.by_id(self.conn, id_)
587 condition.remove(self.conn)
589 condition = Condition.by_id(self.conn, id_, create=True)
590 condition.is_active = self.form_data.get_all_str('is_active') != []
591 condition.title.set(self.form_data.get_str('title'))
592 condition.description.set(self.form_data.get_str('description'))
593 condition.save(self.conn)
594 return f'/condition?id={condition.id_}'
596 def _init_handling(self) -> None:
597 # pylint: disable=attribute-defined-outside-init
598 self.conn = DatabaseConnection(self.server.db)
599 parsed_url = urlparse(self.path)
600 self.site = path_split(parsed_url.path)[1]
601 params = parse_qs(parsed_url.query, strict_parsing=True)
602 self.params = InputsParser(params, False)
604 def _redirect(self, target: str) -> None:
605 self.send_response(302)
606 self.send_header('Location', target)
609 def _send_html(self, html: str, code: int = 200) -> None:
610 """Send HTML as proper HTTP response."""
611 self.send_response(code)
613 self.wfile.write(bytes(html, 'utf-8'))
615 def _send_msg(self, msg: Exception, code: int = 400) -> None:
616 """Send message in HTML formatting as HTTP response."""
617 html = self.server.jinja.get_template('msg.html').render(msg=msg)
618 self._send_html(html, code)