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_float(self, key: str) -> float:
74 """Retrieve float value of key from self.postvars."""
75 val = self.get_str(key)
78 except ValueError as e:
79 msg = f'cannot float form field value: {val}'
80 raise BadFormatException(msg) from e
82 def get_all_str(self, key: str) -> list[str]:
83 """Retrieve list of string values at key from self.postvars."""
84 if key not in self.postvars:
86 return self.postvars[key]
88 def get_all_int(self, key: str) -> list[int]:
89 """Retrieve list of int values at key from self.postvars."""
90 all_str = self.get_all_str(key)
92 return [int(s) for s in all_str if len(s) > 0]
93 except ValueError as e:
94 msg = f'cannot int a form field value: {all_str}'
95 raise BadFormatException(msg) from e
98 class TaskHandler(BaseHTTPRequestHandler):
99 """Handles single HTTP request."""
102 def do_GET(self) -> None:
103 """Handle any GET request."""
105 conn, site, params = self._init_handling()
106 if site in {'calendar', 'day', 'process', 'processes'}:
107 html = getattr(self, f'do_GET_{site}')(conn, params)
109 self._redirect('/day')
112 raise NotFoundException(f'Unknown page: /{site}')
113 self._send_html(html)
114 except HandledException as error:
115 self._send_msg(error, code=error.http_code)
119 def do_GET_calendar(self, conn: DatabaseConnection,
120 params: ParamsParser) -> str:
121 """Show Days from ?start= to ?end=."""
122 start = params.get_str('start')
123 end = params.get_str('end')
124 days = Day.all(conn, date_range=(start, end), fill_gaps=True)
125 return self.server.jinja.get_template('calendar.html').render(
126 days=days, start=start, end=end)
128 def do_GET_day(self, conn: DatabaseConnection,
129 params: ParamsParser) -> str:
130 """Show single Day of ?date=."""
131 date = params.get_str('date', todays_date())
132 day = Day.by_date(conn, date, create=True)
133 return self.server.jinja.get_template('day.html').render(day=day)
135 def do_GET_process(self, conn: DatabaseConnection,
136 params: ParamsParser) -> str:
137 """Show process of ?id=."""
138 id_ = params.get_int_or_none('id')
139 process = Process.by_id(conn, id_, create=True)
140 return self.server.jinja.get_template('process.html').render(
141 process=process, children=process.get_descendants(conn),
142 candidates=Process.all(conn))
144 def do_GET_processes(self, conn: DatabaseConnection,
145 _: ParamsParser) -> str:
146 """Show all Processes."""
147 return self.server.jinja.get_template('processes.html').render(
148 processes=Process.all(conn))
150 def do_POST(self) -> None:
151 """Handle any POST request."""
153 conn, site, params = self._init_handling()
154 length = int(self.headers['content-length'])
155 postvars = parse_qs(self.rfile.read(length).decode(),
156 keep_blank_values=True, strict_parsing=True)
157 form_data = PostvarsParser(postvars)
158 if site in ('day', 'process'):
159 getattr(self, f'do_POST_{site}')(conn, params, form_data)
162 msg = f'Page not known as POST target: /{site}'
163 raise NotFoundException(msg)
165 except HandledException as error:
166 self._send_msg(error, code=error.http_code)
170 def do_POST_day(self, conn: DatabaseConnection, params: ParamsParser,
171 form_data: PostvarsParser) -> None:
172 """Update or insert Day of date and fields defined in postvars."""
173 date = params.get_str('date')
174 day = Day.by_date(conn, date, create=True)
175 day.comment = form_data.get_str('comment')
178 def do_POST_process(self, conn: DatabaseConnection, params: ParamsParser,
179 form_data: PostvarsParser) -> None:
180 """Update or insert Process of ?id= and fields defined in postvars."""
181 id_ = params.get_int_or_none('id')
182 process = Process.by_id(conn, id_, create=True)
183 process.title.set(form_data.get_str('title'))
184 process.description.set(form_data.get_str('description'))
185 process.effort.set(form_data.get_float('effort'))
186 process.child_ids = form_data.get_all_int('children')
189 def _init_handling(self) -> tuple[DatabaseConnection, str, ParamsParser]:
190 conn = DatabaseConnection(self.server.db)
191 parsed_url = urlparse(self.path)
192 site = path_split(parsed_url.path)[1]
193 params = ParamsParser(parse_qs(parsed_url.query, strict_parsing=True))
194 return conn, site, params
196 def _redirect(self, target: str) -> None:
197 self.send_response(302)
198 self.send_header('Location', target)
201 def _send_html(self, html: str, code: int = 200) -> None:
202 """Send HTML as proper HTTP response."""
203 self.send_response(code)
205 self.wfile.write(bytes(html, 'utf-8'))
207 def _send_msg(self, msg: Exception, code: int = 400) -> None:
208 """Send message in HTML formatting as HTTP response."""
209 html = self.server.jinja.get_template('msg.html').render(msg=msg)
210 self._send_html(html, code)