-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbasic_prog.py
More file actions
276 lines (204 loc) · 7.28 KB
/
basic_prog.py
File metadata and controls
276 lines (204 loc) · 7.28 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
from onefad_web import *
ent['version'] = 1
ent['internal_name'] = 'default'
def register_page(k, kind):
global ent
n = k
if not k.endswith('_base'):
n = '_'.join(k.split('_')[1:])
try:
ent[kind][n] = globals()[k]()
except Exception as e:
if 'required positional argument' not in str(e):
logging.error(f"class {k}", exc_info=True)
def register_pages():
for k in list(globals()):
if k.startswith('builtin_'):
register_page(k, 'builtin')
elif k.startswith('post_'):
register_page(k, 'builtin_post')
def create_menus():
if 'all_pages' not in menus['pages']:
menus['pages']['all_pages'] = {
"title": "All Pages",
"mode": "wide-icons-flat",
"buttons": "all_pages_buttons",
"icon": [9, 9]
}
for m, c in list(ent['builtin'].items()):
if type(c) == builtin_menu:
del ent['builtin'][m]
for m in menus['pages']:
ent['builtin'][m] = builtin_menu(which=m)
menus['all_pages_buttons'] = []
rbcat = {}
for m, v in ent['builtin'].items():
c = ''
pagetype = v.pagetype
if cfg.get('purge') and hasattr(v, 'purge'):
v.purge(1)
icn = {'label': m, 'href': m, 'label2': ''}
sorter = '_' + m
c = pagetype.replace('_', ' ')
if pagetype == 'pages':
icn['label'] = v.title
elif pagetype.startswith('builtin'):
if v.pages:
icn['label2'] = ' pages'
else:
icn['href'] = '/'+icn['href']
if icn['label'] == icn['label2']:
del icn['label2']
elif icn['label2'] != '':
icn['label'] = f"<b>{icn['label']}</b><br><i>{icn['label2']}</i>"
sorter = icn['label2'] + m
del icn['label2']
if c not in rbcat:
rbcat[c] = []
rbcat[c].append((sorter, icn))
for c, d in rbcat.items():
if not d:continue
menus['all_pages_buttons'].append({'type': 'section', 'label': c.title()})
menus['all_pages_buttons'] += [icn for m, icn in sorted(d)]
def big_action_list_time(reload=0):
logging.info('Performing all actions')
start = time.perf_counter()
ent['built_at'] = datetime.now()
ent['building_entries'] = True
read_config()
register_pages()
create_menus()
save_config()
# do work here
logging.info(f'Done in {time.perf_counter() - start}')
ent['building_entries'] = False
class fa_req_handler(BaseHTTPRequestHandler):
def do_GET(self):
path_long = self.path[1:].lower()
path_nice = urllib.parse.unquote(self.path)[1:]
path_split = path_nice.lower().split('/')
if path_split[-1] in ent['resources']:
serve_resource(self, path_split[-1])
return
b = builtin_base()
target = ent['builtin'].get(path_split[0], b)
if path_split[0] in ent['builtin'] and target.pages is False:
target.serve(self, path_split)
return
elif path_split == ['']:
home = ent['builtin'].get(cfg['homepage_menu'])
if home is None:
home = ent['builtin'].get('all_pages', b)
home.serve(self, path_split)
return
elif path_split[0] == 'unstuck':
ent['building_entries'] = False
self.send_response(307)
self.send_header('Location', '/')
self.end_headers()
return
elif path_split[0] == 'stop':
b.do_head = True
b.do_foot = True
b.title = f'Server terminated'
b.error(self, b.title, 'Goodbye')
stop()
return
if path_split[-1].isdigit():
path_split[-1] = int(path_split[-1])
else:
self.send_response(307)
p = self.path
if not p.endswith('/'):p += '/'
self.send_header('Location', p + '1')
self.end_headers()
return
if ent['building_entries']:
b.do_head = True
b.do_foot = True
b.building_entries(self)
return
elif path_split[0] in ent['builtin']:
target.serve(self, path_split)
return
b.do_head = True
b.do_foot = True
b.title = f'/{path_nice} not found'
b.error(self, b.title, 'I don\'t know what do')
return
def do_POST(self):
path_long = self.path[1:].lower()
path_split = urllib.parse.unquote(self.path)[1:].lower().split('/')
content_length = int(self.headers['Content-Length'])
post_data = self.rfile.read(content_length)
try:
ripdata = json.loads(post_data.decode('utf-8'))
except:
ripdata = {}
logging.debug(json.dumps(ripdata))
if path_split[0] in ent['builtin_post']:
ent['builtin_post'][path_split[0]].serve_post(self, path_split, ripdata)
return
self.send_response(200)
self.send_header('Content-type', 'application/json')
self.end_headers()
ret = {}
if path_split[0] == 'rebuild':
level = 0
if len(path_split) > 1:level = path_split[1]
big_action_list_time(reload=level)
ret['status'] = 'success'
self.wfile.write(bytes(json.dumps(ret), 'utf-8'))
return
def stop():
logging.info('Stopping server')
time.sleep(2)
httpd.shutdown()
if __name__ == '__main__':
code_path = os.path.dirname(__file__)
os.chdir(code_path)
name = ent.get('internal_name', '')
if len(name) < 4:name += 'srv'
init_logger(name, disp=':' in code_path)
load_global('cfg', {
'developer': False,
'server_name': name,
'server_addr': '127.0.0.1',
'server_port': 6770,
'apd_dir': 'data/',
'res_dir': 'res/',# prepend resource files
'homepage_menu': 'all_pages',
'dropdown_menu': 'all_pages',
'static_cfg': False
})
load_global('menus', {
'pages': {}
})
load_global('ent', {
'resources': [
'style.css',
'parrot.svg',
'icons.svg',
'mark.js',
'client.js',
'chart.js',
'logger.js',
],
'builtin': {},
'builtin_post': {},
'config_file': f'{name}_options.json',
'menu_file': f'{name}_menus.json',
'strings_file': f'{name}_strings.txt',
'building_entries': False,
'reentry_buttons': [
(' rebuild', 'rebuild', 'Rebuild')
]
})
if not os.path.isdir(cfg['apd_dir']):
os.mkdir(cfg['apd_dir'])
register_pages()
big_action_list_time(reload=3)
httpd = ThreadedHTTPServer(
(cfg['server_addr'], cfg['server_port']),
fa_req_handler)
httpd.serve_forever()