home · contact · privacy
Improve todo accounting.
[misc] / plomlib.py
1 import os
2 from http.server import BaseHTTPRequestHandler
3 from http.cookies import SimpleCookie
4 import json
5
6
7 class PlomException(Exception):
8     pass
9
10
11 class PlomDB:
12
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:
18                 self.read_db_file(f)
19
20     def lock(self):
21         if os.path.exists(self.lock_file):
22             raise PlomException('Sorry, lock file!')
23         f = open(self.lock_file, 'w+')
24         f.close()
25
26     def unlock(self):
27         os.remove(self.lock_file)
28
29     def backup(self):
30         import shutil
31         from datetime import datetime, timedelta
32         if not os.path.exists(self.db_file):
33             return
34
35         # collect modification times of numbered .bak files
36         print('DEBUG BACKUP')
37         bak_prefix = f'{self.db_file}.bak.'
38         # backup_dates = []
39         mtimes_to_paths = {}
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))]
47
48         for mtime in sorted(mtimes_to_paths.keys()):
49             print(f'DEBUG mtimes_to_paths: {mtime}:{mtimes_to_paths[mtime]}')
50
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}')
55         now = datetime.now()
56         to_save = {}
57         for age in ages_to_keep:
58             limit = now - age
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]
64                     break
65
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')
69             os.remove(path)
70
71         i = 0
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}')
76             if source != target:
77                 shutil.move(source, target)
78             i += 1
79
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}')
83
84     def write_text_to_db(self, text, mode='w'):
85         self.lock()
86         self.backup()
87         with open(self.db_file, mode) as f:
88             f.write(text);
89         self.unlock()
90
91
92 class PlomHandler(BaseHTTPRequestHandler):
93     homepage = '/'
94     html_head = '<!DOCTYPE html>\n<html>\n<meta charset="UTF-8">'
95     html_foot = '</body>\n</html>'
96
97     def fail_400(self, e):
98         self.send_HTML(f'ERROR: {e}', 400)
99
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'))
103
104     def ensure_cookies_to_set(self):
105         if not hasattr(self, 'cookies_to_set'):
106             self.cookies_to_set = []
107
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]
114
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]
122
123     def get_cookie_db(self, cookie_name):
124         cookie_db = {}
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)
129         return cookie_db
130
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)
139         self.end_headers()
140
141     def redirect(self, url='/'):
142         self.send_code_and_headers(302, [('Location', url)])
143
144     def try_do(self, do_method):
145         try:
146             do_method()
147         except PlomException as e:
148             self.fail_400(e)
149
150
151
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}")
156     try:
157         webServer.serve_forever()
158     except KeyboardInterrupt:
159         pass
160     webServer.server_close()
161     print("Server stopped.")