1 """Web server stuff."""
3 from collections import namedtuple
4 from http.server import BaseHTTPRequestHandler
5 from http.server import HTTPServer
6 from urllib.parse import urlparse, parse_qs
7 from os.path import split as path_split
8 from jinja2 import Environment as JinjaEnv, FileSystemLoader as JinjaFSLoader
9 from plomtask.days import Day, todays_date
10 from plomtask.exceptions import HandledException, BadFormatException, \
12 from plomtask.db import DatabaseConnection, DatabaseFile
13 from plomtask.processes import Process
14 from plomtask.conditions import Condition
15 from plomtask.todos import Todo
17 TEMPLATES_DIR = 'templates'
20 class TaskServer(HTTPServer):
21 """Variant of HTTPServer that knows .jinja as Jinja Environment."""
23 def __init__(self, db_file: DatabaseFile,
24 *args: Any, **kwargs: Any) -> None:
25 super().__init__(*args, **kwargs)
27 self.jinja = JinjaEnv(loader=JinjaFSLoader(TEMPLATES_DIR))
31 """Wrapper for validating and retrieving dict-like HTTP inputs."""
33 def __init__(self, dict_: dict[str, list[str]],
34 strictness: bool = True) -> None:
36 self.strict = strictness
38 def get_str(self, key: str, default: str = '',
39 ignore_strict: bool = False) -> str:
40 """Retrieve single/first string value of key, or default."""
41 if key not in self.inputs.keys() or 0 == len(self.inputs[key]):
42 if self.strict and not ignore_strict:
43 raise BadFormatException(f'no value found for key {key}')
45 return self.inputs[key][0]
47 def get_int(self, key: str) -> int:
48 """Retrieve single/first value of key as int, error if empty."""
49 val = self.get_int_or_none(key)
51 raise BadFormatException(f'unexpected empty value for: {key}')
54 def get_int_or_none(self, key: str) -> int | None:
55 """Retrieve single/first value of key as int, return None if empty."""
56 val = self.get_str(key, ignore_strict=True)
61 except ValueError as e:
62 msg = f'cannot int form field value for key {key}: {val}'
63 raise BadFormatException(msg) from e
65 def get_float(self, key: str) -> float:
66 """Retrieve float value of key from self.postvars."""
67 val = self.get_str(key)
70 except ValueError as e:
71 msg = f'cannot float form field value for key {key}: {val}'
72 raise BadFormatException(msg) from e
74 def get_all_str(self, key: str) -> list[str]:
75 """Retrieve list of string values at key."""
76 if key not in self.inputs.keys():
78 return self.inputs[key]
80 def get_all_int(self, key: str) -> list[int]:
81 """Retrieve list of int values at key."""
82 all_str = self.get_all_str(key)
84 return [int(s) for s in all_str if len(s) > 0]
85 except ValueError as e:
86 msg = f'cannot int a form field value for key {key} in: {all_str}'
87 raise BadFormatException(msg) from e
90 class TaskHandler(BaseHTTPRequestHandler):
91 """Handles single HTTP request."""
94 def do_GET(self) -> None:
95 """Handle any GET request."""
98 if self.site in {'calendar', 'day', 'process', 'processes', 'todo',
99 'condition', 'conditions'}:
100 template = f'{self.site}.html'
101 ctx = getattr(self, f'do_GET_{self.site}')()
102 html = self.server.jinja.get_template(template).render(**ctx)
103 self._send_html(html)
104 elif '' == self.site:
105 self._redirect('/day')
107 raise NotFoundException(f'Unknown page: /{self.site}')
108 except HandledException as error:
109 self._send_msg(error, code=error.http_code)
113 def do_GET_calendar(self) -> dict[str, object]:
114 """Show Days from ?start= to ?end=."""
115 start = self.params.get_str('start')
116 end = self.params.get_str('end')
117 days = Day.all(self.conn, date_range=(start, end), fill_gaps=True)
118 return {'start': start, 'end': end, 'days': days}
120 def do_GET_day(self) -> dict[str, object]:
121 """Show single Day of ?date=."""
122 date = self.params.get_str('date', todays_date())
123 top_todos = [t for t in Todo.by_date(self.conn, date) if not t.parents]
124 seen_todos: set[int] = set()
125 seen_conditions: set[int] = set()
126 todo_trees = [t.get_step_tree(seen_todos, seen_conditions)
128 ConditionsNode = namedtuple('ConditionsNode',
129 ('condition', 'enablers', 'disablers'))
130 conditions_nodes: list[ConditionsNode] = []
131 for condi in Condition.all(self.conn):
132 enablers = Todo.enablers_for_at(self.conn, condi, date)
133 disablers = Todo.disablers_for_at(self.conn, condi, date)
134 conditions_nodes += [ConditionsNode(condi, enablers, disablers)]
135 return {'day': Day.by_id(self.conn, date, create=True),
136 'todo_trees': todo_trees,
137 'processes': Process.all(self.conn),
138 'conditions_nodes': conditions_nodes}
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 return {'conditions': Condition.all(self.conn)}
152 def do_GET_condition(self) -> dict[str, object]:
153 """Show Condition of ?id=."""
154 id_ = self.params.get_int_or_none('id')
155 return {'condition': Condition.by_id(self.conn, id_, create=True)}
157 def do_GET_process(self) -> dict[str, object]:
158 """Show process of ?id=."""
159 id_ = self.params.get_int_or_none('id')
160 process = Process.by_id(self.conn, id_, create=True)
161 return {'process': process,
162 'steps': process.get_steps(self.conn),
163 'owners': process.used_as_step_by(self.conn),
164 'step_candidates': Process.all(self.conn),
165 'condition_candidates': Condition.all(self.conn)}
167 def do_GET_processes(self) -> dict[str, object]:
168 """Show all Processes."""
169 return {'processes': Process.all(self.conn)}
171 def do_POST(self) -> None:
172 """Handle any POST request."""
173 # pylint: disable=attribute-defined-outside-init
175 self._init_handling()
176 length = int(self.headers['content-length'])
177 postvars = parse_qs(self.rfile.read(length).decode(),
178 keep_blank_values=True, strict_parsing=True)
179 self.form_data = InputsParser(postvars)
180 if self.site in ('day', 'process', 'todo', 'condition'):
181 getattr(self, f'do_POST_{self.site}')()
184 msg = f'Page not known as POST target: /{self.site}'
185 raise NotFoundException(msg)
187 except HandledException as error:
188 self._send_msg(error, code=error.http_code)
192 def do_POST_day(self) -> None:
193 """Update or insert Day of date and Todos mapped to it."""
194 date = self.params.get_str('date')
195 day = Day.by_id(self.conn, date, create=True)
196 day.comment = self.form_data.get_str('comment')
198 existing_todos = Todo.by_date(self.conn, date)
199 for process_id in self.form_data.get_all_int('new_todo'):
200 process = Process.by_id(self.conn, process_id)
201 todo = Todo(None, process, False, day.date)
203 todo.adopt_from(existing_todos)
204 todo.make_missing_children(self.conn)
207 def do_POST_todo(self) -> None:
208 """Update Todo and its children."""
209 id_ = self.params.get_int('id')
210 todo = Todo.by_id(self.conn, id_)
211 adopted_child_ids = self.form_data.get_all_int('adopt')
212 for child in todo.children:
213 if child.id_ not in adopted_child_ids:
214 assert isinstance(child.id_, int)
215 child = Todo.by_id(self.conn, child.id_)
216 todo.remove_child(child)
217 for child_id in adopted_child_ids:
218 if child_id in [c.id_ for c in todo.children]:
220 child = Todo.by_id(self.conn, child_id)
221 todo.add_child(child)
222 todo.set_conditions(self.conn, self.form_data.get_all_int('condition'))
223 todo.set_enables(self.conn, self.form_data.get_all_int('enables'))
224 todo.set_disables(self.conn, self.form_data.get_all_int('disables'))
225 todo.is_done = len(self.form_data.get_all_str('done')) > 0
227 for condition in todo.enables:
228 condition.save(self.conn)
229 for condition in todo.disables:
230 condition.save(self.conn)
232 def do_POST_process(self) -> None:
233 """Update or insert Process of ?id= and fields defined in postvars."""
234 id_ = self.params.get_int_or_none('id')
235 process = Process.by_id(self.conn, id_, create=True)
236 process.title.set(self.form_data.get_str('title'))
237 process.description.set(self.form_data.get_str('description'))
238 process.effort.set(self.form_data.get_float('effort'))
239 process.set_conditions(self.conn,
240 self.form_data.get_all_int('condition'))
241 process.set_enables(self.conn, self.form_data.get_all_int('enables'))
242 process.set_disables(self.conn, self.form_data.get_all_int('disables'))
243 process.save_core(self.conn)
244 assert process.id_ is not None # for mypy
245 process.explicit_steps = []
246 steps: list[tuple[int | None, int, int | None]] = []
247 for step_id in self.form_data.get_all_int('steps'):
248 for step_process_id in self.form_data.get_all_int(
249 f'new_step_to_{step_id}'):
250 steps += [(None, step_process_id, step_id)]
251 if step_id not in self.form_data.get_all_int('keep_step'):
253 step_process_id = self.form_data.get_int(
254 f'step_{step_id}_process_id')
255 parent_id = self.form_data.get_int_or_none(
256 f'step_{step_id}_parent_id')
257 steps += [(step_id, step_process_id, parent_id)]
258 for step_process_id in self.form_data.get_all_int('new_top_step'):
259 steps += [(None, step_process_id, None)]
260 process.set_steps(self.conn, steps)
261 process.save(self.conn)
263 def do_POST_condition(self) -> None:
264 """Update/insert Condition of ?id= and fields defined in postvars."""
265 id_ = self.params.get_int_or_none('id')
266 condition = Condition.by_id(self.conn, id_, create=True)
267 condition.title.set(self.form_data.get_str('title'))
268 condition.description.set(self.form_data.get_str('description'))
269 condition.save(self.conn)
271 def _init_handling(self) -> None:
272 # pylint: disable=attribute-defined-outside-init
273 self.conn = DatabaseConnection(self.server.db)
274 parsed_url = urlparse(self.path)
275 self.site = path_split(parsed_url.path)[1]
276 params = parse_qs(parsed_url.query, strict_parsing=True)
277 self.params = InputsParser(params, False)
279 def _redirect(self, target: str) -> None:
280 self.send_response(302)
281 self.send_header('Location', target)
284 def _send_html(self, html: str, code: int = 200) -> None:
285 """Send HTML as proper HTTP response."""
286 self.send_response(code)
288 self.wfile.write(bytes(html, 'utf-8'))
290 def _send_msg(self, msg: Exception, code: int = 400) -> None:
291 """Send message in HTML formatting as HTTP response."""
292 html = self.server.jinja.get_template('msg.html').render(msg=msg)
293 self._send_html(html, code)