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
14 TEMPLATES_DIR = 'templates'
17 class TaskServer(HTTPServer):
18 """Variant of HTTPServer that knows .jinja as Jinja Environment."""
20 def __init__(self, db_file: DatabaseFile,
21 *args: Any, **kwargs: Any) -> None:
22 super().__init__(*args, **kwargs)
24 self.jinja = JinjaEnv(loader=JinjaFSLoader(TEMPLATES_DIR))
28 """Wrapper for validating and retrieving GET params."""
30 def __init__(self, params: dict[str, list[str]]) -> None:
33 def get_str(self, key: str, default: str = '') -> str:
34 """Retrieve string value of key from self.params."""
35 if key not in self.params or 0 == len(self.params[key]):
37 return self.params[key][0]
39 def get_int_or_none(self, key: str) -> int | None:
40 """Retrieve int value of key from self.params, on empty return None."""
41 if key not in self.params or \
42 0 == len(''.join(list(self.params[key]))):
44 val_str = self.params[key][0]
47 except ValueError as e:
48 raise BadFormatException(f'Bad ?{key}= value: {val_str}') from e
52 """Postvars wrapper for validating and retrieving form data."""
54 def __init__(self, postvars: dict[str, list[str]]) -> None:
55 self.postvars = postvars
57 def get_str(self, key: str) -> str:
58 """Retrieve string value of key from self.postvars."""
59 all_str = self.get_all_str(key)
61 raise BadFormatException(f'missing value for key: {key}')
64 def get_int(self, key: str) -> int:
65 """Retrieve int value of key from self.postvars."""
66 val = self.get_str(key)
69 except ValueError as e:
70 msg = f'cannot int form field value: {val}'
71 raise BadFormatException(msg) from e
73 def get_int_or_none(self, key: str) -> int | None:
74 """Retrieve int value of key from self.postvars, or None."""
75 if key not in self.postvars or \
76 0 == len(''.join(list(self.postvars[key]))):
78 return self.get_int(key)
80 def get_float(self, key: str) -> float:
81 """Retrieve float value of key from self.postvars."""
82 val = self.get_str(key)
85 except ValueError as e:
86 msg = f'cannot float form field value: {val}'
87 raise BadFormatException(msg) from e
89 def get_all_str(self, key: str) -> list[str]:
90 """Retrieve list of string values at key from self.postvars."""
91 if key not in self.postvars:
93 return self.postvars[key]
95 def get_all_int(self, key: str) -> list[int]:
96 """Retrieve list of int values at key from self.postvars."""
97 all_str = self.get_all_str(key)
99 return [int(s) for s in all_str if len(s) > 0]
100 except ValueError as e:
101 msg = f'cannot int a form field value: {all_str}'
102 raise BadFormatException(msg) from e
105 class TaskHandler(BaseHTTPRequestHandler):
106 """Handles single HTTP request."""
109 def do_GET(self) -> None:
110 """Handle any GET request."""
112 conn, site, params = self._init_handling()
113 if site in {'calendar', 'day', 'process', 'processes'}:
114 html = getattr(self, f'do_GET_{site}')(conn, params)
116 self._redirect('/day')
119 raise NotFoundException(f'Unknown page: /{site}')
120 self._send_html(html)
121 except HandledException as error:
122 self._send_msg(error, code=error.http_code)
126 def do_GET_calendar(self, conn: DatabaseConnection,
127 params: ParamsParser) -> str:
128 """Show Days from ?start= to ?end=."""
129 start = params.get_str('start')
130 end = params.get_str('end')
131 days = Day.all(conn, date_range=(start, end), fill_gaps=True)
132 return self.server.jinja.get_template('calendar.html').render(
133 days=days, start=start, end=end)
135 def do_GET_day(self, conn: DatabaseConnection,
136 params: ParamsParser) -> str:
137 """Show single Day of ?date=."""
138 date = params.get_str('date', todays_date())
139 day = Day.by_date(conn, date, create=True)
140 return self.server.jinja.get_template('day.html').render(day=day)
142 def do_GET_process(self, conn: DatabaseConnection,
143 params: ParamsParser) -> str:
144 """Show process of ?id=."""
145 id_ = params.get_int_or_none('id')
146 process = Process.by_id(conn, id_, create=True)
147 owners = process.used_as_step_by(conn)
148 return self.server.jinja.get_template('process.html').render(
149 process=process, steps=process.get_steps(conn),
150 owners=owners, candidates=Process.all(conn))
152 def do_GET_processes(self, conn: DatabaseConnection,
153 _: ParamsParser) -> str:
154 """Show all Processes."""
155 return self.server.jinja.get_template('processes.html').render(
156 processes=Process.all(conn))
158 def do_POST(self) -> None:
159 """Handle any POST request."""
161 conn, site, params = self._init_handling()
162 length = int(self.headers['content-length'])
163 postvars = parse_qs(self.rfile.read(length).decode(),
164 keep_blank_values=True, strict_parsing=True)
165 form_data = PostvarsParser(postvars)
166 if site in ('day', 'process'):
167 getattr(self, f'do_POST_{site}')(conn, params, form_data)
170 msg = f'Page not known as POST target: /{site}'
171 raise NotFoundException(msg)
173 except HandledException as error:
174 self._send_msg(error, code=error.http_code)
178 def do_POST_day(self, conn: DatabaseConnection, params: ParamsParser,
179 form_data: PostvarsParser) -> None:
180 """Update or insert Day of date and fields defined in postvars."""
181 date = params.get_str('date')
182 day = Day.by_date(conn, date, create=True)
183 day.comment = form_data.get_str('comment')
186 def do_POST_process(self, conn: DatabaseConnection, params: ParamsParser,
187 form_data: PostvarsParser) -> None:
188 """Update or insert Process of ?id= and fields defined in postvars."""
189 id_ = params.get_int_or_none('id')
190 process = Process.by_id(conn, id_, create=True)
191 process.title.set(form_data.get_str('title'))
192 process.description.set(form_data.get_str('description'))
193 process.effort.set(form_data.get_float('effort'))
194 process.save_without_steps(conn)
195 assert process.id_ is not None # for mypy
196 process.explicit_steps = []
197 for step_id in form_data.get_all_int('steps'):
198 for step_process_id in\
199 form_data.get_all_int(f'new_step_to_{step_id}'):
200 process.add_step(conn, None, step_process_id, step_id)
201 if step_id not in form_data.get_all_int('keep_step'):
203 step_process_id = form_data.get_int(f'step_{step_id}_process_id')
204 parent_id = form_data.get_int_or_none(f'step_{step_id}_parent_id')
205 process.add_step(conn, step_id, step_process_id, parent_id)
206 for step_process_id in form_data.get_all_int('new_top_step'):
207 process.add_step(conn, None, step_process_id, None)
208 process.fix_steps(conn)
210 def _init_handling(self) -> tuple[DatabaseConnection, str, ParamsParser]:
211 conn = DatabaseConnection(self.server.db)
212 parsed_url = urlparse(self.path)
213 site = path_split(parsed_url.path)[1]
214 params = ParamsParser(parse_qs(parsed_url.query, strict_parsing=True))
215 return conn, site, params
217 def _redirect(self, target: str) -> None:
218 self.send_response(302)
219 self.send_header('Location', target)
222 def _send_html(self, html: str, code: int = 200) -> None:
223 """Send HTML as proper HTTP response."""
224 self.send_response(code)
226 self.wfile.write(bytes(html, 'utf-8'))
228 def _send_msg(self, msg: Exception, code: int = 400) -> None:
229 """Send message in HTML formatting as HTTP response."""
230 html = self.server.jinja.get_template('msg.html').render(msg=msg)
231 self._send_html(html, code)