2 from http.server import BaseHTTPRequestHandler
3 from http.cookies import SimpleCookie
7 class PlomException(Exception):
13 def __init__(self, db_name):
14 self.db_file = db_name
15 self.lock_file = db_name+ '.lock'
16 if os.path.exists(self.db_file):
17 with open(self.db_file, 'r') as f:
21 if os.path.exists(self.lock_file):
22 raise PlomException('Sorry, lock file!')
23 f = open(self.lock_file, 'w+')
27 os.remove(self.lock_file)
31 from datetime import datetime, timedelta
32 if not os.path.exists(self.db_file):
35 # collect modification times of numbered .bak files
37 bak_prefix = f'{self.db_file}.bak.'
40 for path in [path for path in os.listdir(os.path.dirname(bak_prefix))
41 if path.startswith(os.path.basename(bak_prefix))]:
42 path = os.path.dirname(bak_prefix) + f'/{path}'
43 mod_time = os.path.getmtime(path)
44 print(f'DEBUG pre-exists: {path} {mod_time}')
45 mtimes_to_paths[str(datetime.fromtimestamp(mod_time))] = path
46 # backup_dates += [str(datetime.fromtimestamp(mod_time))]
48 for mtime in sorted(mtimes_to_paths.keys()):
49 print(f'DEBUG mtimes_to_paths: {mtime}:{mtimes_to_paths[mtime]}')
51 # collect what numbered .bak files to save: the older, the fewer; for each
52 # timedelta, keep the newest file that's older
53 ages_to_keep = [timedelta(minutes=4**i) for i in range(0, 8)]
54 print(f'DEBUG ages_to_keep: {ages_to_keep}')
57 for age in ages_to_keep:
59 for mtime in reversed(sorted(mtimes_to_paths.keys())):
60 print(f'DEBUG checking if {mtime} < {limit} ({now} - {age})')
61 if datetime.strptime(mtime, '%Y-%m-%d %H:%M:%S.%f') < limit:
62 print('DEBUG it is, adding!')
63 to_save[mtime] = mtimes_to_paths[mtime]
66 for path in [path for path in mtimes_to_paths.values()
67 if path not in to_save.values()]:
68 print(f'DEBUG removing {path} cause not in to_save')
72 for mtime in sorted(to_save.keys()):
73 source = to_save[mtime]
74 target = f'{bak_prefix}{i}'
75 print(f'DEBUG to_save {source} -> {target}')
77 shutil.move(source, target)
80 # put copy of current state at end of bak list
81 print(f'DEBUG saving current state to {bak_prefix}{i}')
82 shutil.copy(self.db_file, f'{bak_prefix}{i}')
84 def write_text_to_db(self, text, mode='w'):
87 with open(self.db_file, mode) as f:
92 class PlomHandler(BaseHTTPRequestHandler):
94 html_head = '<!DOCTYPE html>\n<html>\n<meta charset="UTF-8">'
95 html_foot = '</body>\n</html>'
97 def fail_400(self, e):
98 self.send_HTML(f'ERROR: {e}', 400)
100 def send_HTML(self, html, code=200):
101 self.send_code_and_headers(code, [('Content-type', 'text/html')])
102 self.wfile.write(bytes(f'{self.html_head}\n{html}\n{self.html_foot}', 'utf-8'))
104 def ensure_cookies_to_set(self):
105 if not hasattr(self, 'cookies_to_set'):
106 self.cookies_to_set = []
108 def set_cookie(self, cookie_name, cookie_path, cookie_db):
109 self.ensure_cookies_to_set()
110 cookie = SimpleCookie()
111 cookie[cookie_name] = json.dumps(cookie_db)
112 cookie[cookie_name]['path'] = cookie_path
113 self.cookies_to_set += [cookie]
115 def unset_cookie(self, cookie_name, cookie_path):
116 self.ensure_cookies_to_set()
117 cookie = SimpleCookie()
118 cookie[cookie_name] = ''
119 cookie[cookie_name]['path'] = cookie_path
120 cookie[cookie_name]['expires'] = 'Thu, 01 Jan 1970 00:00:00 GMT'
121 self.cookies_to_set += [cookie]
123 def get_cookie_db(self, cookie_name):
125 if 'Cookie' in self.headers:
126 cookie = SimpleCookie(self.headers['Cookie'])
127 if cookie_name in cookie:
128 cookie_db = json.loads(cookie[cookie_name].value)
131 def send_code_and_headers(self, code, headers=[]):
132 self.ensure_cookies_to_set()
133 self.send_response(code)
134 for cookie in self.cookies_to_set:
135 for morsel in cookie.values():
136 self.send_header('Set-Cookie', morsel.OutputString())
137 for fieldname, content in headers:
138 self.send_header(fieldname, content)
141 def redirect(self, url='/'):
142 self.send_code_and_headers(302, [('Location', url)])
144 def try_do(self, do_method):
147 except PlomException as e:
152 def run_server(port, handler_class):
153 from http.server import HTTPServer
154 webServer = HTTPServer(('localhost', port), handler_class)
155 print(f"Server started http://localhost:{port}")
157 webServer.serve_forever()
158 except KeyboardInterrupt:
160 webServer.server_close()
161 print("Server stopped.")