1 """Web server stuff."""
3 from http.server import BaseHTTPRequestHandler
4 from http.server import HTTPServer
5 from urllib.parse import urlparse, parse_qs
6 from os.path import split as path_split
7 from jinja2 import Environment as JinjaEnv, FileSystemLoader as JinjaFSLoader
8 from plomtask.days import Day, todays_date
9 from plomtask.exceptions import HandledException, BadFormatException, \
11 from plomtask.db import DatabaseConnection, DatabaseFile
12 from plomtask.processes import Process
13 from plomtask.conditions import Condition
14 from plomtask.todos import Todo
16 TEMPLATES_DIR = 'templates'
19 class TaskServer(HTTPServer):
20 """Variant of HTTPServer that knows .jinja as Jinja Environment."""
22 def __init__(self, db_file: DatabaseFile,
23 *args: Any, **kwargs: Any) -> None:
24 super().__init__(*args, **kwargs)
26 self.jinja = JinjaEnv(loader=JinjaFSLoader(TEMPLATES_DIR))
30 """Wrapper for validating and retrieving dict-like HTTP inputs."""
32 def __init__(self, dict_: dict[str, list[str]],
33 strictness: bool = True) -> None:
35 self.strict = strictness
37 def get_str(self, key: str, default: str = '',
38 ignore_strict: bool = False) -> str:
39 """Retrieve single/first string value of key, or default."""
40 if key not in self.inputs.keys() or 0 == len(self.inputs[key]):
41 if self.strict and not ignore_strict:
42 raise BadFormatException(f'no value found for key {key}')
44 return self.inputs[key][0]
46 def get_int(self, key: str) -> int:
47 """Retrieve single/first value of key as int, error if empty."""
48 val = self.get_int_or_none(key)
50 raise BadFormatException(f'unexpected empty value for: {key}')
53 def get_int_or_none(self, key: str) -> int | None:
54 """Retrieve single/first value of key as int, return None if empty."""
55 val = self.get_str(key, ignore_strict=True)
60 except ValueError as e:
61 msg = f'cannot int form field value for key {key}: {val}'
62 raise BadFormatException(msg) from e
64 def get_float(self, key: str) -> float:
65 """Retrieve float value of key from self.postvars."""
66 val = self.get_str(key)
69 except ValueError as e:
70 msg = f'cannot float form field value for key {key}: {val}'
71 raise BadFormatException(msg) from e
73 def get_all_str(self, key: str) -> list[str]:
74 """Retrieve list of string values at key."""
75 if key not in self.inputs.keys():
77 return self.inputs[key]
79 def get_all_int(self, key: str) -> list[int]:
80 """Retrieve list of int values at key."""
81 all_str = self.get_all_str(key)
83 return [int(s) for s in all_str if len(s) > 0]
84 except ValueError as e:
85 msg = f'cannot int a form field value for key {key} in: {all_str}'
86 raise BadFormatException(msg) from e
89 class TaskHandler(BaseHTTPRequestHandler):
90 """Handles single HTTP request."""
93 def do_GET(self) -> None:
94 """Handle any GET request."""
97 if hasattr(self, f'do_GET_{self.site}'):
98 template = f'{self.site}.html'
99 ctx = getattr(self, f'do_GET_{self.site}')()
100 html = self.server.jinja.get_template(template).render(**ctx)
101 self._send_html(html)
102 elif '' == self.site:
103 self._redirect('/day')
105 raise NotFoundException(f'Unknown page: /{self.site}')
106 except HandledException as error:
107 self._send_msg(error, code=error.http_code)
111 def do_GET_calendar(self) -> dict[str, object]:
112 """Show Days from ?start= to ?end=."""
113 start = self.params.get_str('start')
114 end = self.params.get_str('end')
115 days = Day.all(self.conn, date_range=(start, end), fill_gaps=True)
116 return {'start': start, 'end': end, 'days': days}
118 def do_GET_day(self) -> dict[str, object]:
119 """Show single Day of ?date=."""
120 date = self.params.get_str('date', todays_date())
121 todays_todos = Todo.by_date(self.conn, date)
122 conditions_present = []
124 for todo in todays_todos:
125 for condition in todo.conditions:
126 if condition not in conditions_present:
127 conditions_present += [condition]
128 enablers_for[condition.id_] = [p for p in
129 Process.all(self.conn)
130 if condition in p.enables]
131 seen_todos: set[int] = set()
132 top_nodes = [t.get_step_tree(seen_todos)
133 for t in todays_todos if not t.parents]
134 return {'day': Day.by_id(self.conn, date, create=True),
135 'top_nodes': top_nodes,
136 'enablers_for': enablers_for,
137 'conditions_present': conditions_present,
138 'processes': Process.all(self.conn)}
140 def do_GET_todo(self) -> dict[str, object]:
141 """Show single Todo of ?id=."""
142 id_ = self.params.get_int('id')
143 todo = Todo.by_id(self.conn, id_)
144 return {'todo': todo,
145 'todo_candidates': Todo.by_date(self.conn, todo.date),
146 'condition_candidates': Condition.all(self.conn)}
148 def do_GET_conditions(self) -> dict[str, object]:
149 """Show all Conditions."""
150 conditions = Condition.all(self.conn)
151 sort_by = self.params.get_str('sort_by')
152 if sort_by == 'is_active':
153 conditions.sort(key=lambda c: c.is_active)
154 elif sort_by == '-is_active':
155 conditions.sort(key=lambda c: c.is_active, reverse=True)
156 elif sort_by == '-title':
157 conditions.sort(key=lambda c: c.title.newest, reverse=True)
159 conditions.sort(key=lambda c: c.title.newest)
160 return {'conditions': conditions, 'sort_by': sort_by}
162 def do_GET_condition(self) -> dict[str, object]:
163 """Show Condition of ?id=."""
164 id_ = self.params.get_int_or_none('id')
165 return {'condition': Condition.by_id(self.conn, id_, create=True)}
167 def do_GET_condition_titles(self) -> dict[str, object]:
168 """Show title history of Condition of ?id=."""
169 id_ = self.params.get_int_or_none('id')
170 condition = Condition.by_id(self.conn, id_)
171 return {'condition': condition}
173 def do_GET_condition_descriptions(self) -> dict[str, object]:
174 """Show description historys of Condition of ?id=."""
175 id_ = self.params.get_int_or_none('id')
176 condition = Condition.by_id(self.conn, id_)
177 return {'condition': condition}
179 def do_GET_process(self) -> dict[str, object]:
180 """Show Process of ?id=."""
181 id_ = self.params.get_int_or_none('id')
182 process = Process.by_id(self.conn, id_, create=True)
183 return {'process': process,
184 'steps': process.get_steps(self.conn),
185 'owners': process.used_as_step_by(self.conn),
186 'step_candidates': Process.all(self.conn),
187 'condition_candidates': Condition.all(self.conn)}
189 def do_GET_process_titles(self) -> dict[str, object]:
190 """Show title history of Process of ?id=."""
191 id_ = self.params.get_int_or_none('id')
192 process = Process.by_id(self.conn, id_)
193 return {'process': process}
195 def do_GET_process_descriptions(self) -> dict[str, object]:
196 """Show description historys of Process of ?id=."""
197 id_ = self.params.get_int_or_none('id')
198 process = Process.by_id(self.conn, id_)
199 return {'process': process}
201 def do_GET_process_efforts(self) -> dict[str, object]:
202 """Show default effort history of Process of ?id=."""
203 id_ = self.params.get_int_or_none('id')
204 process = Process.by_id(self.conn, id_)
205 return {'process': process}
207 def do_GET_processes(self) -> dict[str, object]:
208 """Show all Processes."""
209 processes = Process.all(self.conn)
210 sort_by = self.params.get_str('sort_by')
211 if sort_by == 'steps':
212 processes.sort(key=lambda c: len(c.explicit_steps))
213 elif sort_by == '-steps':
214 processes.sort(key=lambda c: len(c.explicit_steps), reverse=True)
215 elif sort_by == '-title':
216 processes.sort(key=lambda c: c.title.newest, reverse=True)
218 processes.sort(key=lambda c: c.title.newest)
219 return {'processes': processes, 'sort_by': sort_by}
221 def do_POST(self) -> None:
222 """Handle any POST request."""
223 # pylint: disable=attribute-defined-outside-init
225 self._init_handling()
226 length = int(self.headers['content-length'])
227 postvars = parse_qs(self.rfile.read(length).decode(),
228 keep_blank_values=True, strict_parsing=True)
229 self.form_data = InputsParser(postvars)
230 if hasattr(self, f'do_POST_{self.site}'):
231 redir_target = getattr(self, f'do_POST_{self.site}')()
234 msg = f'Page not known as POST target: /{self.site}'
235 raise NotFoundException(msg)
236 self._redirect(redir_target)
237 except HandledException as error:
238 self._send_msg(error, code=error.http_code)
242 def do_POST_day(self) -> str:
243 """Update or insert Day of date and Todos mapped to it."""
244 date = self.params.get_str('date')
245 day = Day.by_id(self.conn, date, create=True)
246 day.comment = self.form_data.get_str('day_comment')
249 for process_id in self.form_data.get_all_int('new_todo'):
250 process = Process.by_id(self.conn, process_id)
251 todo = Todo(None, process, False, day.date)
257 existing_todos = Todo.by_date(self.conn, date)
258 for todo in new_todos:
259 if todo.adopt_from(existing_todos):
261 todo.make_missing_children(self.conn)
263 done_ids = self.form_data.get_all_int('done')
264 comments = self.form_data.get_all_str('comment')
265 efforts = self.form_data.get_all_str('effort')
266 for i, todo_id in enumerate(self.form_data.get_all_int('todo_id')):
267 todo = Todo.by_id(self.conn, todo_id)
268 todo.is_done = todo_id in done_ids
269 if len(comments) > 0:
270 todo.comment = comments[i]
272 todo.effort = float(efforts[i]) if efforts[i] else None
274 for condition in todo.enables:
275 condition.save(self.conn)
276 for condition in todo.disables:
277 condition.save(self.conn)
278 return f'/day?date={date}'
280 def do_POST_todo(self) -> str:
281 """Update Todo and its children."""
282 id_ = self.params.get_int('id')
283 for _ in self.form_data.get_all_str('delete'):
284 todo = Todo .by_id(self.conn, id_)
285 todo.remove(self.conn)
287 todo = Todo.by_id(self.conn, id_)
288 adopted_child_ids = self.form_data.get_all_int('adopt')
289 for child in todo.children:
290 if child.id_ not in adopted_child_ids:
291 assert isinstance(child.id_, int)
292 child = Todo.by_id(self.conn, child.id_)
293 todo.remove_child(child)
294 for child_id in adopted_child_ids:
295 if child_id in [c.id_ for c in todo.children]:
297 child = Todo.by_id(self.conn, child_id)
298 todo.add_child(child)
299 effort = self.form_data.get_str('effort', ignore_strict=True)
300 todo.effort = float(effort) if effort else None
301 todo.set_conditions(self.conn, self.form_data.get_all_int('condition'))
302 todo.set_enables(self.conn, self.form_data.get_all_int('enables'))
303 todo.set_disables(self.conn, self.form_data.get_all_int('disables'))
304 todo.is_done = len(self.form_data.get_all_str('done')) > 0
305 todo.comment = self.form_data.get_str('comment', ignore_strict=True)
307 for condition in todo.enables:
308 condition.save(self.conn)
309 for condition in todo.disables:
310 condition.save(self.conn)
311 return f'/todo?id={todo.id_}'
313 def do_POST_process(self) -> str:
314 """Update or insert Process of ?id= and fields defined in postvars."""
315 id_ = self.params.get_int_or_none('id')
316 for _ in self.form_data.get_all_str('delete'):
317 process = Process.by_id(self.conn, id_)
318 process.remove(self.conn)
320 process = Process.by_id(self.conn, id_, create=True)
321 process.title.set(self.form_data.get_str('title'))
322 process.description.set(self.form_data.get_str('description'))
323 process.effort.set(self.form_data.get_float('effort'))
324 process.set_conditions(self.conn,
325 self.form_data.get_all_int('condition'))
326 process.set_enables(self.conn, self.form_data.get_all_int('enables'))
327 process.set_disables(self.conn, self.form_data.get_all_int('disables'))
328 process.save(self.conn)
329 process.explicit_steps = []
330 steps: list[tuple[int | None, int, int | None]] = []
331 for step_id in self.form_data.get_all_int('steps'):
332 for step_process_id in self.form_data.get_all_int(
333 f'new_step_to_{step_id}'):
334 steps += [(None, step_process_id, step_id)]
335 if step_id not in self.form_data.get_all_int('keep_step'):
337 step_process_id = self.form_data.get_int(
338 f'step_{step_id}_process_id')
339 parent_id = self.form_data.get_int_or_none(
340 f'step_{step_id}_parent_id')
341 steps += [(step_id, step_process_id, parent_id)]
342 for step_process_id in self.form_data.get_all_int('new_top_step'):
343 steps += [(None, step_process_id, None)]
344 process.set_steps(self.conn, steps)
345 process.save(self.conn)
346 return f'/process?id={process.id_}'
348 def do_POST_condition(self) -> str:
349 """Update/insert Condition of ?id= and fields defined in postvars."""
350 id_ = self.params.get_int_or_none('id')
351 for _ in self.form_data.get_all_str('delete'):
352 condition = Condition.by_id(self.conn, id_)
353 condition.remove(self.conn)
355 condition = Condition.by_id(self.conn, id_, create=True)
356 condition.is_active = self.form_data.get_all_str('is_active') != []
357 condition.title.set(self.form_data.get_str('title'))
358 condition.description.set(self.form_data.get_str('description'))
359 condition.save(self.conn)
360 return f'/condition?id={condition.id_}'
362 def _init_handling(self) -> None:
363 # pylint: disable=attribute-defined-outside-init
364 self.conn = DatabaseConnection(self.server.db)
365 parsed_url = urlparse(self.path)
366 self.site = path_split(parsed_url.path)[1]
367 params = parse_qs(parsed_url.query, strict_parsing=True)
368 self.params = InputsParser(params, False)
370 def _redirect(self, target: str) -> None:
371 self.send_response(302)
372 self.send_header('Location', target)
375 def _send_html(self, html: str, code: int = 200) -> None:
376 """Send HTML as proper HTTP response."""
377 self.send_response(code)
379 self.wfile.write(bytes(html, 'utf-8'))
381 def _send_msg(self, msg: Exception, code: int = 400) -> None:
382 """Send message in HTML formatting as HTTP response."""
383 html = self.server.jinja.get_template('msg.html').render(msg=msg)
384 self._send_html(html, code)