1 """Web server stuff."""
2 from typing import Any, NamedTuple
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 self.site in {'calendar', 'day', 'process', 'processes', 'todo',
98 'condition', 'conditions'}:
99 template = f'{self.site}.html'
100 ctx = getattr(self, f'do_GET_{self.site}')()
101 html = self.server.jinja.get_template(template).render(**ctx)
102 self._send_html(html)
103 elif '' == self.site:
104 self._redirect('/day')
106 raise NotFoundException(f'Unknown page: /{self.site}')
107 except HandledException as error:
108 self._send_msg(error, code=error.http_code)
112 def do_GET_calendar(self) -> dict[str, object]:
113 """Show Days from ?start= to ?end=."""
114 start = self.params.get_str('start')
115 end = self.params.get_str('end')
116 days = Day.all(self.conn, date_range=(start, end), fill_gaps=True)
117 return {'start': start, 'end': end, 'days': days}
119 def do_GET_day(self) -> dict[str, object]:
120 """Show single Day of ?date=."""
122 class ConditionListing(NamedTuple):
123 """Listing of Condition augmented with its enablers, disablers."""
126 disablers: list[Todo]
128 date = self.params.get_str('date', todays_date())
129 top_todos = [t for t in Todo.by_date(self.conn, date) if not t.parents]
130 seen_todos: set[int] = set()
131 seen_conditions: set[int] = set()
132 todo_trees = [t.get_step_tree(seen_todos, seen_conditions)
134 condition_listings: list[ConditionListing] = []
135 for cond in Condition.all(self.conn):
136 enablers = Todo.enablers_for_at(self.conn, cond, date)
137 disablers = Todo.disablers_for_at(self.conn, cond, date)
138 condition_listings += [ConditionListing(cond, enablers, disablers)]
139 return {'day': Day.by_id(self.conn, date, create=True),
140 'todo_trees': todo_trees,
141 'processes': Process.all(self.conn),
142 'condition_listings': condition_listings}
144 def do_GET_todo(self) -> dict[str, object]:
145 """Show single Todo of ?id=."""
146 id_ = self.params.get_int('id')
147 todo = Todo.by_id(self.conn, id_)
148 return {'todo': todo,
149 'todo_candidates': Todo.by_date(self.conn, todo.date),
150 'condition_candidates': Condition.all(self.conn)}
152 def do_GET_conditions(self) -> dict[str, object]:
153 """Show all Conditions."""
154 return {'conditions': Condition.all(self.conn)}
156 def do_GET_condition(self) -> dict[str, object]:
157 """Show Condition of ?id=."""
158 id_ = self.params.get_int_or_none('id')
159 return {'condition': Condition.by_id(self.conn, id_, create=True)}
161 def do_GET_process(self) -> dict[str, object]:
162 """Show process of ?id=."""
163 id_ = self.params.get_int_or_none('id')
164 process = Process.by_id(self.conn, id_, create=True)
165 return {'process': process,
166 'steps': process.get_steps(self.conn),
167 'owners': process.used_as_step_by(self.conn),
168 'step_candidates': Process.all(self.conn),
169 'condition_candidates': Condition.all(self.conn)}
171 def do_GET_processes(self) -> dict[str, object]:
172 """Show all Processes."""
173 return {'processes': Process.all(self.conn)}
175 def do_POST(self) -> None:
176 """Handle any POST request."""
177 # pylint: disable=attribute-defined-outside-init
179 self._init_handling()
180 length = int(self.headers['content-length'])
181 postvars = parse_qs(self.rfile.read(length).decode(),
182 keep_blank_values=True, strict_parsing=True)
183 self.form_data = InputsParser(postvars)
184 if self.site in ('day', 'process', 'todo', 'condition'):
185 getattr(self, f'do_POST_{self.site}')()
188 msg = f'Page not known as POST target: /{self.site}'
189 raise NotFoundException(msg)
191 except HandledException as error:
192 self._send_msg(error, code=error.http_code)
196 def do_POST_day(self) -> None:
197 """Update or insert Day of date and Todos mapped to it."""
198 date = self.params.get_str('date')
199 day = Day.by_id(self.conn, date, create=True)
200 day.comment = self.form_data.get_str('comment')
202 existing_todos = Todo.by_date(self.conn, date)
203 for process_id in self.form_data.get_all_int('new_todo'):
204 process = Process.by_id(self.conn, process_id)
205 todo = Todo(None, process, False, day.date)
207 todo.adopt_from(existing_todos)
208 todo.make_missing_children(self.conn)
211 def do_POST_todo(self) -> None:
212 """Update Todo and its children."""
213 id_ = self.params.get_int('id')
214 todo = Todo.by_id(self.conn, id_)
215 adopted_child_ids = self.form_data.get_all_int('adopt')
216 for child in todo.children:
217 if child.id_ not in adopted_child_ids:
218 assert isinstance(child.id_, int)
219 child = Todo.by_id(self.conn, child.id_)
220 todo.remove_child(child)
221 for child_id in adopted_child_ids:
222 if child_id in [c.id_ for c in todo.children]:
224 child = Todo.by_id(self.conn, child_id)
225 todo.add_child(child)
226 todo.set_conditions(self.conn, self.form_data.get_all_int('condition'))
227 todo.set_enables(self.conn, self.form_data.get_all_int('enables'))
228 todo.set_disables(self.conn, self.form_data.get_all_int('disables'))
229 todo.is_done = len(self.form_data.get_all_str('done')) > 0
231 for condition in todo.enables:
232 condition.save(self.conn)
233 for condition in todo.disables:
234 condition.save(self.conn)
236 def do_POST_process(self) -> None:
237 """Update or insert Process of ?id= and fields defined in postvars."""
238 id_ = self.params.get_int_or_none('id')
239 for _ in self.form_data.get_all_str('delete'):
240 process = Process.by_id(self.conn, id_)
241 process.remove(self.conn)
243 process = Process.by_id(self.conn, id_, create=True)
244 process.title.set(self.form_data.get_str('title'))
245 process.description.set(self.form_data.get_str('description'))
246 process.effort.set(self.form_data.get_float('effort'))
247 process.set_conditions(self.conn,
248 self.form_data.get_all_int('condition'))
249 process.set_enables(self.conn, self.form_data.get_all_int('enables'))
250 process.set_disables(self.conn, self.form_data.get_all_int('disables'))
251 process.save_core(self.conn)
252 process.explicit_steps = []
253 steps: list[tuple[int | None, int, int | None]] = []
254 for step_id in self.form_data.get_all_int('steps'):
255 for step_process_id in self.form_data.get_all_int(
256 f'new_step_to_{step_id}'):
257 steps += [(None, step_process_id, step_id)]
258 if step_id not in self.form_data.get_all_int('keep_step'):
260 step_process_id = self.form_data.get_int(
261 f'step_{step_id}_process_id')
262 parent_id = self.form_data.get_int_or_none(
263 f'step_{step_id}_parent_id')
264 steps += [(step_id, step_process_id, parent_id)]
265 for step_process_id in self.form_data.get_all_int('new_top_step'):
266 steps += [(None, step_process_id, None)]
267 process.set_steps(self.conn, steps)
268 process.save(self.conn)
270 def do_POST_condition(self) -> None:
271 """Update/insert Condition of ?id= and fields defined in postvars."""
272 id_ = self.params.get_int_or_none('id')
273 condition = Condition.by_id(self.conn, id_, create=True)
274 condition.title.set(self.form_data.get_str('title'))
275 condition.description.set(self.form_data.get_str('description'))
276 condition.save(self.conn)
278 def _init_handling(self) -> None:
279 # pylint: disable=attribute-defined-outside-init
280 self.conn = DatabaseConnection(self.server.db)
281 parsed_url = urlparse(self.path)
282 self.site = path_split(parsed_url.path)[1]
283 params = parse_qs(parsed_url.query, strict_parsing=True)
284 self.params = InputsParser(params, False)
286 def _redirect(self, target: str) -> None:
287 self.send_response(302)
288 self.send_header('Location', target)
291 def _send_html(self, html: str, code: int = 200) -> None:
292 """Send HTML as proper HTTP response."""
293 self.send_response(code)
295 self.wfile.write(bytes(html, 'utf-8'))
297 def _send_msg(self, msg: Exception, code: int = 400) -> None:
298 """Send message in HTML formatting as HTTP response."""
299 html = self.server.jinja.get_template('msg.html').render(msg=msg)
300 self._send_html(html, code)