Uh oh!
There was an error while loading. Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
Latest commit
358 lines (278 loc) · 11.2 KB
/
Copy pathmain.py
File metadata and controls
358 lines (278 loc) · 11.2 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
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
from __future__ importannotations
importargparse
importjson
importos
importsys
importthreading
frompathlibimportPath
# Prepare project imports
BASE_DIR=os.path.dirname(os.path.abspath(__file__))
ifBASE_DIRnotinsys.path:
sys.path.insert(0, BASE_DIR)
# Lazy Flask application
classLazyFlaskApplication:
"""Bind the port before Flask loads so ASLM can reserve example-port immediately."""
# Initialize loader state (app not created yet).
def__init__(self) ->None:
"""Initialize loader state (app not created yet)."""
self._application=None
self._error: BaseException|None=None
self._ready=threading.Event()
self._lock=threading.Lock()
# Start a daemon thread that imports and builds the Flask app.
defload_in_background(self) ->None:
"""Start a daemon thread that imports and builds the Flask app."""
thread=threading.Thread(
target=self._load,
name="aslm-example-flask-loader",
daemon=True,
)
thread.start()
# Import App.app.create_app once; store result or error for WSGI.
def_load(self) ->None:
"""Import App.app.create_app once; store result or error for WSGI."""
withself._lock:
ifself._applicationisnotNoneorself._errorisnotNone:
return
try:
fromApp.appimportcreate_app
self._application=create_app()
exceptBaseExceptionasexc:
self._error=exc
finally:
self._ready.set()
# Serve requests: Flask app, startup error page, or loading placeholder.
def__call__(self, environ, start_response):
"""Serve requests: Flask app, startup error page, or loading placeholder."""
# Flask finished loading — delegate to the real application.
ifself._applicationisnotNone:
returnself._application(environ, start_response)
# Import or create_app failed — return plain-text 500.
ifself._errorisnotNone:
body=f"ASLM-Example failed to start: {self._error}".encode("utf-8", errors="replace")
start_response(
"500 Internal Server Error",
[("Content-Type", "text/plain; charset=utf-8"), ("Content-Length", str(len(body)))],
)
return [body]
# Still loading — auto-refresh HTML so the WebView retries.
body= (
"<!doctype html><html><head><meta charset=\"utf-8\">"
"<meta http-equiv=\"refresh\" content=\"1\">"
"<title>Example Python Module starting</title></head>"
"<body style=\"font-family:Segoe UI,sans-serif;background:#111;color:#eee;\">"
"Example Python Module is starting\u2026"
"</body></html>"
).encode("utf-8")
start_response(
"503 Service Unavailable",
[
("Content-Type", "text/html; charset=utf-8"),
("Content-Length", str(len(body))),
("Retry-After", "1"),
],
)
return [body]
# Run runserver
defcmd_runserver(port: int, log: bool) ->None:
"""Start the Flask UI server on the requested port."""
iflog:
print(f"[ASLM-Example] Starting server on port {port}...")
fromsocketserverimportThreadingMixIn
fromwsgiref.simple_serverimportWSGIRequestHandler, WSGIServer, make_server
classThreadedWSGIServer(ThreadingMixIn, WSGIServer):
"""Serve requests concurrently."""
daemon_threads=True
classQuietWSGIRequestHandler(WSGIRequestHandler):
"""Suppress routine HTTP access logs in the ASLM console."""
# Suppress per-request access log lines.
deflog_message(self, format: str, *args) ->None:
return
# Bind socket immediately; load Flask on a background thread.
app=LazyFlaskApplication()
withmake_server(
"127.0.0.1",
port,
app,
server_class=ThreadedWSGIServer,
handler_class=QuietWSGIRequestHandler,
) ashttpd:
app.load_in_background()
iflog:
print(f"[ASLM-Example] UI server listening at http://127.0.0.1:{port}/", flush=True)
httpd.serve_forever()
# Run first_run
defcmd_first_run(log: bool, ui_port: int) ->None:
"""Run Settings/first_run.py (settings.json only; venv is host-managed)."""
fromSettings.first_runimportrunasfirst_run
first_run(log=log, ui_port=ui_port)
# Run get_setting
defcmd_get_setting(key: str) ->None:
"""Print one setting value to stdout for ASLM getExec."""
fromSettings.settingsimportget
value=get(key)
print(valueifvalueisnotNoneelse"")
# Run set_setting
defcmd_set_setting(key: str, value: str) ->None:
"""Parse {value} and persist one setting for ASLM setExec."""
fromSettings.settingsimportnormalize_setting_value, setassettings_set
parsed=normalize_setting_value(value)
settings_set(key, parsed)
print(f"[ASLM-Example] Setting '{key}' updated to {parsed!r}")
# Run apply_aslm_host_theme
defcmd_apply_aslm_host_theme(theme_file: str) ->None:
"""Load host theme JSON from --file and write Settings/host_theme.json."""
fromSettings.host_themeimportsave_host_theme_payload
# Read temp file written by ASLM before setExec.
path=Path(theme_file)
ifnotpath.is_file():
print(f"Error: theme file not found: {theme_file}")
sys.exit(1)
try:
raw=path.read_text(encoding="utf-8")
exceptOSErrorasexc:
print(f"Error: could not read theme file: {exc}")
sys.exit(1)
# .NET may write UTF-8 with BOM; strip it before JSON parsing.
raw=raw.lstrip("\ufeff").strip()
try:
data=json.loads(raw)
exceptjson.JSONDecodeErrorasexc:
print(f"Error: invalid JSON in theme file: {exc}")
sys.exit(1)
ifnotisinstance(data, dict):
print("Error: host theme JSON must be an object.")
sys.exit(1)
save_host_theme_payload(data)
print("[ASLM-Example] Host theme snapshot updated.")
# Run apply_aslm_locale
defcmd_apply_aslm_locale(locale_file: str) ->None:
"""Load host locale JSON from --file and write Settings/host_locale.json."""
fromSettings.host_localeimportsave_host_locale_payload
path=Path(locale_file)
ifnotpath.is_file():
print(f"Error: locale file not found: {locale_file}")
sys.exit(1)
try:
raw=path.read_text(encoding="utf-8")
exceptOSErrorasexc:
print(f"Error: could not read locale file: {exc}")
sys.exit(1)
raw=raw.lstrip("\ufeff").strip()
try:
data=json.loads(raw)
exceptjson.JSONDecodeErrorasexc:
print(f"Error: invalid JSON in locale file: {exc}")
sys.exit(1)
ifnotisinstance(data, dict):
print("Error: host locale JSON must be an object.")
sys.exit(1)
save_host_locale_payload(data)
print("[ASLM-Example] Host locale snapshot updated.")
# Run downloads_bridge
defcmd_downloads_bridge() ->None:
"""Dispatch one bridge request from stdin and print the JSON response."""
fromServices.downloads_bridgeimportrun_cli
raiseSystemExit(run_cli())
# CLI parser
def_build_parser() ->argparse.ArgumentParser:
"""Return the argparse definition for main.py."""
parser=argparse.ArgumentParser(
prog="main.py",
description="Example Python Module — ASLM command entry point",
)
parser.add_argument("command", type=str, help="Command to execute")
parser.add_argument("--port", type=int, default=20100, help="Port for runserver (default: 20100)")
parser.add_argument("--key", type=str, default=None, help="Setting key for get_setting/set_setting")
parser.add_argument("--value", type=str, default=None, help="Setting value for set_setting")
parser.add_argument(
"--file",
type=str,
default=None,
help="Path to JSON payload for apply_aslm_host_theme or apply_aslm_locale",
)
parser.add_argument("--log", action="store_true", help="Enable verbose output")
returnparser
# Startup banner
def_maybe_print_banner(command: str) ->None:
"""Print the module name for commands that are not machine-readable hooks."""
# Hooks that must emit only machine-readable stdout.
silent= {
"get_setting",
"set_setting",
"downloads_bridge",
"apply_aslm_host_theme",
"apply_aslm_locale",
}
ifcommandnotinsilent:
try:
manifest_path=Path(BASE_DIR) /"ASLM_Module.json"
ifmanifest_path.exists():
manifest=json.loads(manifest_path.read_text(encoding="utf-8"))
name=manifest.get("name", "Example Python Module")
version=manifest.get("version", "")
print(f"[ASLM-Example] {name} v{version}")
exceptException:
pass
# Port resolution
def_resolve_runserver_port(requested_port: int) ->int:
"""Prefer CLI port, then ASLM_UI_PORT, then settings.json example-port."""
# Explicit CLI override (not the default 20100 placeholder).
ifrequested_port!=20100:
returnrequested_port
# Host-injected port when ASLM starts runserver.
env_port=os.environ.get("ASLM_UI_PORT")
ifenv_port:
try:
returnint(env_port)
exceptValueError:
pass
# Fall back to persisted settings.
try:
fromSettings.settingsimportload_settings
runtime_settings=load_settings()
returnint(runtime_settings.get("example-port", 20100))
exceptException:
return20100
# Main entry
defmain() ->None:
"""Parse argv and dispatch the requested command."""
parser=_build_parser()
args=parser.parse_args()
_maybe_print_banner(args.command)
matchargs.command:
case"runserver":
port=_resolve_runserver_port(args.port)
cmd_runserver(port, log=args.log)
case"first_run":
cmd_first_run(log=True, ui_port=args.port)
case"get_setting":
ifnotargs.key:
print("Error: --key argument is required.")
sys.exit(1)
cmd_get_setting(args.key)
case"set_setting":
ifnotargs.keyorargs.valueisNone:
print("Error: --key and --value arguments are required.")
sys.exit(1)
cmd_set_setting(args.key, args.value)
case"apply_aslm_host_theme":
ifnotargs.file:
print("Error: --file argument is required.")
sys.exit(1)
cmd_apply_aslm_host_theme(args.file)
case"apply_aslm_locale":
ifnotargs.file:
print("Error: --file argument is required.")
sys.exit(1)
cmd_apply_aslm_locale(args.file)
case"downloads_bridge":
cmd_downloads_bridge()
case"help":
parser.print_help()
case _:
print(f"[ASLM-Example] Unknown command: '{args.command}'")
print("Run 'python main.py help' for usage.")
sys.exit(1)
if__name__=="__main__":
main()