-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathweb_server.py
More file actions
2204 lines (2102 loc) · 105 KB
/
web_server.py
File metadata and controls
2204 lines (2102 loc) · 105 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
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import os
import sys
import json
import time
import threading
import urllib.parse
import base64
from http import HTTPStatus
from http.server import ThreadingHTTPServer, BaseHTTPRequestHandler
from io import BytesIO
# Optional dependencies used if available
try:
import mss
import mss.tools
except Exception:
mss = None
try:
import pyautogui
except Exception:
pyautogui = None
# Optional system process metrics
try:
import psutil
except Exception:
psutil = None
# Optional Pillow for JPEG/WebP encoding
try:
from PIL import Image, features as PIL_features
except Exception:
Image = None
PIL_features = None
# Resolve project root for both source and frozen builds
try:
if getattr(sys, 'frozen', False):
# In PyInstaller builds, use the executable directory
PROJECT_ROOT = os.path.dirname(sys.executable)
else:
PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__))
except Exception:
PROJECT_ROOT = os.path.abspath('.')
SERVER_CONFIG_PATH = os.path.join(PROJECT_ROOT, 'server_config.json')
def load_server_config():
cfg = {
"bind": "127.0.0.1",
"port": 8765,
"token": "CHANGE_ME_TOKEN",
"mjpeg_fps": 6,
}
try:
if os.path.exists(SERVER_CONFIG_PATH):
with open(SERVER_CONFIG_PATH, 'r') as f:
user_cfg = json.load(f)
if isinstance(user_cfg, dict):
cfg.update(user_cfg)
except Exception:
pass
# Allow env override
cfg['bind'] = os.environ.get('WEB_BIND', cfg['bind'])
cfg['port'] = int(os.environ.get('WEB_PORT', cfg['port']))
cfg['token'] = os.environ.get('WEB_TOKEN', cfg['token'])
return cfg
def read_config_json():
path = os.path.join(PROJECT_ROOT, 'config.json')
try:
if os.path.exists(path):
with open(path, 'r') as f:
return json.load(f)
except Exception:
return {}
return {}
def bring_app_to_foreground(window_title: str = "Image Detection Bot") -> bool:
"""Bring the bot GUI to foreground so F5/F8 are received by the app.
Returns True if a window was focused, False otherwise.
"""
try:
import ctypes
user32 = ctypes.windll.user32
# Try FindWindow by title
FindWindowW = user32.FindWindowW
SetForegroundWindow = user32.SetForegroundWindow
ShowWindow = user32.ShowWindow
SW_RESTORE = 9
hwnd = FindWindowW(None, window_title)
if hwnd:
# Restore if minimized and bring to front
ShowWindow(hwnd, SW_RESTORE)
SetForegroundWindow(hwnd)
return True
return False
except Exception:
return False
def write_config_json(new_cfg: dict) -> None:
cfg_path = os.path.join(PROJECT_ROOT, 'config.json')
# Backup current config
try:
if os.path.exists(cfg_path):
import shutil, time as _time
# Save backups under a dedicated folder: "backup configs"
backup_dir = os.path.join(PROJECT_ROOT, 'backup configs')
try:
os.makedirs(backup_dir, exist_ok=True)
except Exception:
pass
backup = os.path.join(backup_dir, f'config.backup.{int(_time.time())}.json')
shutil.copyfile(cfg_path, backup)
# Prune old backups to avoid folder flooding (configurable)
try:
# Read retention from server config (default 20)
MAX_BACKUPS = int(load_server_config().get('backup_retention', 20))
files = [f for f in os.listdir(backup_dir) if f.startswith('config.backup.') and f.endswith('.json')]
def _ts(name):
try:
# config.backup.<ts>.json
return int(name.split('.')[2])
except Exception:
# Fallback to mtime
return int(os.path.getmtime(os.path.join(backup_dir, name)))
files.sort(key=_ts, reverse=True)
for old in files[MAX_BACKUPS:]:
try:
os.remove(os.path.join(backup_dir, old))
except Exception:
pass
except Exception:
pass
except Exception:
pass
with open(cfg_path, 'w', encoding='utf-8') as f:
json.dump(new_cfg, f, indent=2)
def trigger_reload_config_ipc():
cmd_path = os.path.join(PROJECT_ROOT, 'ipc_command.json')
try:
with open(cmd_path, 'w', encoding='utf-8') as f:
json.dump({"command": "reload_config"}, f)
except Exception:
pass
class WebHandler(BaseHTTPRequestHandler):
server_version = "BotWeb/0.1"
def _cfg(self):
return self.server._cfg
def _write_json(self, obj, status=HTTPStatus.OK):
data = json.dumps(obj).encode('utf-8')
try:
self.send_response(status)
self.send_header('Content-Type', 'application/json')
self.send_header('Content-Length', str(len(data)))
self.end_headers()
self.wfile.write(data)
except (BrokenPipeError, ConnectionAbortedError, ConnectionResetError, OSError):
# Client disconnected; avoid noisy traceback
try:
self.close_connection = True
except Exception:
pass
return
def _check_auth(self):
# Accept token via Authorization: Bearer <token> or query param ?token=<token>
expected = self._cfg().get('token') or ''
# Header
auth = self.headers.get('Authorization')
if auth and auth.startswith('Bearer '):
if auth.split(' ', 1)[1].strip() == expected:
return True
# Query param
try:
parsed = urllib.parse.urlparse(self.path)
qs = urllib.parse.parse_qs(parsed.query)
if 'token' in qs and qs['token'][0] == expected:
return True
except Exception:
pass
return False
def _serve_static_file(self, rel_path):
# Sanitize
safe_path = rel_path.replace('..', '').replace('\\', '/').strip('/')
primary = os.path.join(PROJECT_ROOT, 'web', 'static', safe_path)
alt = os.path.join(PROJECT_ROOT, '_internal', 'web', 'static', safe_path)
full_path = primary if os.path.isfile(primary) else alt
if not os.path.isfile(full_path):
self.send_error(HTTPStatus.NOT_FOUND)
return
ctype = 'text/plain'
if full_path.endswith('.html'):
ctype = 'text/html; charset=utf-8'
elif full_path.endswith('.js'):
ctype = 'application/javascript'
elif full_path.endswith('.css'):
ctype = 'text/css'
elif full_path.endswith('.png'):
ctype = 'image/png'
elif full_path.endswith('.jpg') or full_path.endswith('.jpeg'):
ctype = 'image/jpeg'
self.send_response(HTTPStatus.OK)
self.send_header('Content-Type', ctype)
fs = os.stat(full_path)
self.send_header('Content-Length', str(fs.st_size))
self.end_headers()
with open(full_path, 'rb') as f:
self.wfile.write(f.read())
def do_GET(self):
parsed = urllib.parse.urlparse(self.path)
path = parsed.path
if path == '/' or path == '/index.html':
return self._serve_static_file('index.html')
if path.startswith('/static/'):
return self._serve_static_file(path[len('/static/'):])
# Token validation (no auth required): quickly check whether provided token matches server config
if path == '/api/status/check':
try:
expected = self._cfg().get('token') or ''
# Prefer header token; fallback to query param
auth = self.headers.get('Authorization') or ''
tok = ''
if auth.startswith('Bearer '):
tok = auth.split(' ', 1)[1].strip()
else:
qs = urllib.parse.parse_qs(parsed.query)
tok = (qs.get('token') or [''])[0]
return self._write_json({
"valid": bool(tok) and (tok == expected),
"time": int(time.time())
})
except Exception as e:
return self._write_json({"valid": False, "error": str(e)}, HTTPStatus.OK)
# Auth-required endpoints
if path == '/api/config':
if not self._check_auth():
return self._write_json({"error": "unauthorized"}, HTTPStatus.UNAUTHORIZED)
cfg = read_config_json()
return self._write_json(cfg)
if path == '/api/sequences':
if not self._check_auth():
return self._write_json({"error": "unauthorized"}, HTTPStatus.UNAUTHORIZED)
cfg = read_config_json()
names = [s.get('name', 'Unnamed Sequence') for s in cfg.get('sequences', [])]
return self._write_json({"sequences": names})
# Break settings
if path == '/api/break-settings':
if not self._check_auth():
return self._write_json({"error": "unauthorized"}, HTTPStatus.UNAUTHORIZED)
cfg = read_config_json()
br = cfg.get('break_settings', {})
return self._write_json({
'enabled': bool(br.get('enabled', False)),
'max_runtime_seconds': int(br.get('max_runtime_seconds', 0)),
'run_final_after_break': bool(br.get('run_final_after_break', False)),
'final_sequence_name': br.get('final_sequence_name', '(none)')
})
# Failsafe settings
if path == '/api/failsafe':
if not self._check_auth():
return self._write_json({"error": "unauthorized"}, HTTPStatus.UNAUTHORIZED)
cfg = read_config_json()
fs = cfg.get('failsafe', {}) or {}
return self._write_json({
'enabled': bool(fs.get('enabled', False)),
'template_name': fs.get('template_name') or fs.get('template'),
'confidence': fs.get('confidence', 0.8),
'region': fs.get('region')
})
# Failsafe sequence (list steps)
if path == '/api/failsafe/sequence':
if not self._check_auth():
return self._write_json({"error": "unauthorized"}, HTTPStatus.UNAUTHORIZED)
cfg = read_config_json()
fs = cfg.get('failsafe', {}) or {}
steps = fs.get('sequence', []) or []
return self._write_json({ 'steps': steps })
# Get a specific sequence by name
if path.startswith('/api/sequences/'):
if not self._check_auth():
return self._write_json({"error": "unauthorized"}, HTTPStatus.UNAUTHORIZED)
name = urllib.parse.unquote(path[len('/api/sequences/'):])
cfg = read_config_json()
seq = next((s for s in cfg.get('sequences', []) if s.get('name') == name), None)
if not seq:
return self._write_json({"error": "not found"}, HTTPStatus.NOT_FOUND)
return self._write_json(seq)
if path == '/api/status':
if not self._check_auth():
return self._write_json({"error": "unauthorized"}, HTTPStatus.UNAUTHORIZED)
# Enriched status including uptime and last-run snapshot
uptime = 0
try:
uptime = int(time.time() - (getattr(self.server, '_start_ts', time.time())))
except Exception:
uptime = 0
return self._write_json({
"status": "ok",
"time": int(time.time()),
"uptime": uptime,
"last_run": getattr(self.server, '_last_run', {
"status": "idle",
"sequence": None,
"group": None,
"last_event_ts": None
})
})
# Lightweight ping for latency measurement
if path == '/api/ping':
if not self._check_auth():
return self._write_json({"error": "unauthorized"}, HTTPStatus.UNAUTHORIZED)
qs = urllib.parse.parse_qs(parsed.query)
echo = (qs.get('echo') or [''])[0]
return self._write_json({"time": int(time.time()), "echo": echo})
# Metrics endpoint: basic server/process metrics and connection counts
if path == '/api/metrics':
if not self._check_auth():
return self._write_json({"error": "unauthorized"}, HTTPStatus.UNAUTHORIZED)
try:
now = int(time.time())
uptime = int(now - (getattr(self.server, '_start_ts', now)))
# Aggregate app-only stats: current process + descendants
app_stats = None
try:
if psutil is not None:
proc = getattr(self.server, '_proc', None)
if proc is None:
proc = psutil.Process(os.getpid())
# Non-blocking snapshot; values stabilize over time
cpu_main = float(proc.cpu_percent(interval=None) or 0.0)
mem_main = int(proc.memory_info().rss or 0)
children = proc.children(recursive=True)
cpu_children = 0.0
mem_children = 0
for ch in children:
try:
cpu_children += float(ch.cpu_percent(interval=None) or 0.0)
mem_children += int(ch.memory_info().rss or 0)
except Exception:
continue
app_stats = {
"cpu_percent": round(cpu_main + cpu_children, 1),
"mem_rss_bytes": int(mem_main + mem_children),
"process_count": int(1 + len(children)),
# Optional breakdown
"cpu_main_percent": round(cpu_main, 1),
"cpu_children_percent": round(cpu_children, 1),
"mem_main_rss_bytes": int(mem_main),
"mem_children_rss_bytes": int(mem_children),
}
except Exception:
app_stats = None
data = {
"time": now,
"uptime": uptime,
"connections": {
"status_sse": int(getattr(self.server, '_sse_clients', 0)),
"preview_mjpeg": int(getattr(self.server, '_mjpeg_clients', 0)),
"log_sse": int(getattr(self.server, '_log_clients', 0)),
},
"totals": {
"status_sse_messages": int(getattr(self.server, '_sse_messages_total', 0)),
"preview_mjpeg_frames": int(getattr(self.server, '_mjpeg_frames_total', 0)),
"log_sse_messages": int(getattr(self.server, '_log_messages_total', 0)),
},
"app": app_stats,
"capabilities": {
"mss_available": bool(mss is not None),
"pyautogui_available": bool(pyautogui is not None),
"pillow_available": bool('Image' in globals() and Image is not None),
"jpeg_supported": bool('PIL_features' in globals() and PIL_features is not None and (
bool(PIL_features.check('jpg')) or bool(PIL_features.check('jpeg'))
)),
"psutil_available": bool(psutil is not None),
},
"last_run": getattr(self.server, '_last_run', {
"status": "idle",
"sequence": None,
"group": None,
"last_event_ts": None
})
}
return self._write_json(data)
except Exception as e:
return self._write_json({"error": str(e)}, HTTPStatus.INTERNAL_SERVER_ERROR)
# Server-Sent Events: live status stream (heartbeat + last-run info)
if path == '/api/status/stream':
if not self._check_auth():
self.send_error(HTTPStatus.UNAUTHORIZED)
return
# Interval control via query param (milliseconds)
qs = urllib.parse.parse_qs(parsed.query)
try:
interval_ms = int((qs.get('interval_ms') or ['1000'])[0])
except Exception:
interval_ms = 1000
interval_ms = max(250, min(interval_ms, 10000))
counted = False
try:
try:
self.server._sse_clients = int(getattr(self.server, '_sse_clients', 0)) + 1
counted = True
except Exception:
pass
self.send_response(HTTPStatus.OK)
self.send_header('Content-Type', 'text/event-stream')
self.send_header('Cache-Control', 'no-cache')
self.send_header('Connection', 'keep-alive')
self.end_headers()
# Stream loop
while True:
try:
uptime = int(time.time() - (getattr(self.server, '_start_ts', time.time())))
except Exception:
uptime = 0
payload = {
"heartbeat": int(time.time()),
"uptime": uptime,
"last_run": getattr(self.server, '_last_run', {
"status": "idle",
"sequence": None,
"group": None,
"last_event_ts": None
})
}
data = json.dumps(payload)
try:
self.wfile.write(b'data: ' + data.encode('utf-8') + b'\n\n')
# Attempt to flush to client
try:
self.wfile.flush()
except Exception:
pass
try:
self.server._sse_messages_total = int(getattr(self.server, '_sse_messages_total', 0)) + 1
except Exception:
pass
except (BrokenPipeError, ConnectionAbortedError, ConnectionResetError, OSError):
# Client disconnected
try:
self.close_connection = True
except Exception:
pass
return
time.sleep(interval_ms / 1000.0)
except Exception:
# Any other error: stop streaming silently
return
finally:
if counted:
try:
self.server._sse_clients = int(getattr(self.server, '_sse_clients', 1)) - 1
except Exception:
pass
# Debug log tail
if path == '/api/debug-log':
if not self._check_auth():
return self._write_json({"error": "unauthorized"}, HTTPStatus.UNAUTHORIZED)
try:
qs = urllib.parse.parse_qs(parsed.query)
try:
max_lines = int((qs.get('lines') or ['500'])[0])
except Exception:
max_lines = 500
max_lines = max(1, min(max_lines, 5000))
log_path = os.path.join(PROJECT_ROOT, 'bot_debug.log')
if not os.path.exists(log_path):
return self._write_json({"exists": False, "lines": []})
# Read tail lines (simple approach, acceptable for moderate sizes)
with open(log_path, 'r', encoding='utf-8', errors='ignore') as f:
content = f.read()
lines = content.splitlines()
tail = lines[-max_lines:]
return self._write_json({
"exists": True,
"lines": tail,
"count": len(tail),
"total": len(lines)
})
except Exception as e:
return self._write_json({"error": str(e)}, HTTPStatus.INTERNAL_SERVER_ERROR)
# Debug log SSE stream: periodically send tail lines
if path == '/api/debug-log/stream':
if not self._check_auth():
self.send_error(HTTPStatus.UNAUTHORIZED)
return
qs = urllib.parse.parse_qs(parsed.query)
try:
interval_ms = int((qs.get('interval_ms') or ['1000'])[0])
except Exception:
interval_ms = 1000
interval_ms = max(250, min(interval_ms, 10000))
try:
max_lines = int((qs.get('lines') or ['500'])[0])
except Exception:
max_lines = 500
max_lines = max(1, min(max_lines, 5000))
log_path = os.path.join(PROJECT_ROOT, 'bot_debug.log')
counted = False
try:
try:
self.server._log_clients = int(getattr(self.server, '_log_clients', 0)) + 1
counted = True
except Exception:
pass
self.send_response(HTTPStatus.OK)
self.send_header('Content-Type', 'text/event-stream')
self.send_header('Cache-Control', 'no-cache')
self.send_header('Connection', 'keep-alive')
self.end_headers()
while True:
exists = os.path.exists(log_path)
lines = []
total = 0
if exists:
try:
with open(log_path, 'r', encoding='utf-8', errors='ignore') as f:
content = f.read()
lines = content.splitlines()
total = len(lines)
lines = lines[-max_lines:]
except Exception:
exists = False
lines = []
total = 0
payload = {
"time": int(time.time()),
"exists": bool(exists),
"count": len(lines),
"total": int(total),
"lines": lines,
}
data = json.dumps(payload)
try:
self.wfile.write(b'data: ' + data.encode('utf-8') + b'\n\n')
try:
self.wfile.flush()
except Exception:
pass
try:
self.server._log_messages_total = int(getattr(self.server, '_log_messages_total', 0)) + 1
except Exception:
pass
except (BrokenPipeError, ConnectionAbortedError, ConnectionResetError, OSError):
try:
self.close_connection = True
except Exception:
pass
return
time.sleep(interval_ms / 1000.0)
except Exception:
return
finally:
if counted:
try:
self.server._log_clients = int(getattr(self.server, '_log_clients', 1)) - 1
except Exception:
pass
# Scheduled sequences
if path == '/api/schedules':
if not self._check_auth():
return self._write_json({"error": "unauthorized"}, HTTPStatus.UNAUTHORIZED)
cfg = read_config_json()
return self._write_json({"schedules": cfg.get('scheduled_sequences', [])})
# Groups listing
if path == '/api/groups':
if not self._check_auth():
return self._write_json({"error": "unauthorized"}, HTTPStatus.UNAUTHORIZED)
try:
cfg = read_config_json()
groups = cfg.get('groups', {}) or {}
names = sorted(list(groups.keys()))
return self._write_json({"groups": names})
except Exception as e:
return self._write_json({"error": str(e)}, HTTPStatus.INTERNAL_SERVER_ERROR)
# Group details
if path.startswith('/api/groups/'):
if not self._check_auth():
return self._write_json({"error": "unauthorized"}, HTTPStatus.UNAUTHORIZED)
try:
name = urllib.parse.unquote(path[len('/api/groups/'):])
cfg = read_config_json()
groups = cfg.get('groups', {}) or {}
if name not in groups:
return self._write_json({"error": "not found"}, HTTPStatus.NOT_FOUND)
g = groups[name]
# Support both dict-based groups and list-based groups (steps-only)
if isinstance(g, list):
out = {
'name': name,
'steps': g,
'loop': False,
'loop_count': 1
}
else:
out = {
'name': name,
'steps': (g.get('steps') or []),
'loop': bool(g.get('loop', False)),
'loop_count': int(g.get('loop_count', 1))
}
return self._write_json(out)
except Exception as e:
return self._write_json({"error": str(e)}, HTTPStatus.INTERNAL_SERVER_ERROR)
# Monitors listing (0 = All, then 1..N)
if path == '/api/monitors':
if not self._check_auth():
return self._write_json({"error": "unauthorized"}, HTTPStatus.UNAUTHORIZED)
try:
mons = []
if mss is None:
return self._write_json({"monitors": mons})
with mss.mss() as sct:
for idx, mon in enumerate(sct.monitors):
mons.append({
"index": idx,
"left": mon.get('left', 0),
"top": mon.get('top', 0),
"width": mon.get('width', 0),
"height": mon.get('height', 0)
})
return self._write_json({"monitors": mons})
except Exception as e:
return self._write_json({"error": str(e)}, HTTPStatus.INTERNAL_SERVER_ERROR)
# Templates listing
if path == '/api/templates':
if not self._check_auth():
return self._write_json({"error": "unauthorized"}, HTTPStatus.UNAUTHORIZED)
cfg = read_config_json()
tpl_map = cfg.get('templates', {})
out = []
for name, p in tpl_map.items():
full = os.path.join(PROJECT_ROOT, p) if not os.path.isabs(p) else p
out.append({
'name': name,
'path': p,
'exists': bool(full and os.path.exists(full))
})
return self._write_json({'templates': out})
# Template detail
if path.startswith('/api/templates/'):
if not self._check_auth():
return self._write_json({"error": "unauthorized"}, HTTPStatus.UNAUTHORIZED)
name = urllib.parse.unquote(path[len('/api/templates/'):])
cfg = read_config_json()
tpl_map = cfg.get('templates', {})
p = tpl_map.get(name)
if p is None:
return self._write_json({"error": "not found"}, HTTPStatus.NOT_FOUND)
full = os.path.join(PROJECT_ROOT, p) if not os.path.isabs(p) else p
return self._write_json({'name': name, 'path': p, 'exists': bool(full and os.path.exists(full))})
# Serve template image preview
if path == '/api/template-image':
if not self._check_auth():
self.send_error(HTTPStatus.UNAUTHORIZED)
return
qs = urllib.parse.parse_qs(parsed.query)
name = (qs.get('name') or [None])[0]
if not name:
self.send_error(HTTPStatus.BAD_REQUEST, 'name required')
return
cfg = read_config_json()
p = (cfg.get('templates', {}) or {}).get(name)
if not p:
self.send_error(HTTPStatus.NOT_FOUND, 'template not found')
return
full = os.path.join(PROJECT_ROOT, p) if not os.path.isabs(p) else p
if not (full and os.path.exists(full)):
self.send_error(HTTPStatus.NOT_FOUND, 'image file not found')
return
ctype = 'image/png'
if full.lower().endswith('.jpg') or full.lower().endswith('.jpeg'):
ctype = 'image/jpeg'
self.send_response(HTTPStatus.OK)
self.send_header('Content-Type', ctype)
fs = os.stat(full)
self.send_header('Content-Length', str(fs.st_size))
self.end_headers()
with open(full, 'rb') as f:
self.wfile.write(f.read())
if path == '/stream.mjpeg':
if not self._check_auth():
self.send_error(HTTPStatus.UNAUTHORIZED)
return
# MJPEG multipart stream
if mss is None:
self.send_error(HTTPStatus.SERVICE_UNAVAILABLE, "mss not available")
return
# FPS target (allow override via query ?fps=<int>, else use config)
qs_for_fps = urllib.parse.parse_qs(parsed.query)
try:
fps_override = int((qs_for_fps.get('fps') or [str(self._cfg().get('mjpeg_fps', 6))])[0])
except Exception:
fps_override = int(self._cfg().get('mjpeg_fps', 6))
fps = max(1, min(fps_override, 60))
delay = 1.0 / float(fps)
boundary = 'frameboundary'
self.send_response(HTTPStatus.OK)
self.send_header('Content-Type', f'multipart/x-mixed-replace; boundary={boundary}')
self.end_headers()
counted = False
try:
try:
self.server._mjpeg_clients = int(getattr(self.server, '_mjpeg_clients', 0)) + 1
counted = True
except Exception:
pass
with mss.mss() as sct:
# monitor index via query param ?monitor=<int>, default 0 (All)
qs = urllib.parse.parse_qs(parsed.query)
mon_idx = 0
try:
mon_idx = int((qs.get('monitor') or ['0'])[0])
except Exception:
mon_idx = 0
if mon_idx < 0 or mon_idx >= len(sct.monitors):
mon_idx = 0
monitor = sct.monitors[mon_idx]
# Quality and scale options
try:
quality = int((qs.get('quality') or ['70'])[0])
except Exception:
quality = 70
# Allow lower qualities for speed; clamp to [10, 95]
quality = max(10, min(quality, 95))
try:
scale = float((qs.get('scale') or ['1.0'])[0])
except Exception:
scale = 1.0
scale = max(0.25, min(scale, 1.0))
while True:
frame_start = time.time()
img = sct.grab(monitor)
# Select output format via query (?format=jpeg|png); default PNG for compatibility
fmt = (qs.get('format') or ['png'])[0].lower()
frame_bytes = None
ctype = 'image/png'
if fmt == 'jpeg' and Image is not None:
try:
pil = Image.frombytes('RGB', img.size, img.rgb)
if scale != 1.0:
new_w = max(1, int(pil.width * scale))
new_h = max(1, int(pil.height * scale))
pil = pil.resize((new_w, new_h), Image.BILINEAR)
buf = BytesIO()
# Use faster save settings for higher throughput
pil.save(buf, format='JPEG', quality=quality, optimize=False, subsampling='2')
frame_bytes = buf.getvalue()
ctype = 'image/jpeg'
except Exception:
frame_bytes = None
if frame_bytes is None:
# PNG fallback (optionally scaled via Pillow)
if scale != 1.0 and Image is not None:
try:
pil = Image.frombytes('RGB', img.size, img.rgb)
new_w = max(1, int(pil.width * scale))
new_h = max(1, int(pil.height * scale))
pil = pil.resize((new_w, new_h), Image.BILINEAR)
buf = BytesIO()
# Avoid optimize for speed; default compression is sufficient
pil.save(buf, format='PNG', optimize=False)
frame_bytes = buf.getvalue()
except Exception:
frame_bytes = None
if frame_bytes is None:
frame_bytes = mss.tools.to_png(img.rgb, img.size)
self.wfile.write(bytes(f'--{boundary}\r\n', 'utf-8'))
self.wfile.write(bytes(f'Content-Type: {ctype}\r\n', 'utf-8'))
self.wfile.write(bytes(f'Content-Length: {len(frame_bytes)}\r\n\r\n', 'utf-8'))
self.wfile.write(frame_bytes)
self.wfile.write(b'\r\n')
try:
self.server._mjpeg_frames_total = int(getattr(self.server, '_mjpeg_frames_total', 0)) + 1
except Exception:
pass
# Sleep only the remaining time to hit target FPS; don't slow below encode time
elapsed = time.time() - frame_start
remaining = max(0.0, delay - elapsed)
time.sleep(remaining)
except Exception:
# client closed or error
return
finally:
if counted:
try:
self.server._mjpeg_clients = int(getattr(self.server, '_mjpeg_clients', 1)) - 1
except Exception:
pass
# Single-frame snapshot fallback
if path == '/api/snapshot.png':
if not self._check_auth():
self.send_error(HTTPStatus.UNAUTHORIZED)
return
if mss is None:
self.send_error(HTTPStatus.SERVICE_UNAVAILABLE, "mss not available")
return
try:
qs = urllib.parse.parse_qs(parsed.query)
mon_idx = 0
try:
mon_idx = int((qs.get('monitor') or ['0'])[0])
except Exception:
mon_idx = 0
with mss.mss() as sct:
if mon_idx < 0 or mon_idx >= len(sct.monitors):
mon_idx = 0
monitor = sct.monitors[mon_idx]
img = sct.grab(monitor)
png = mss.tools.to_png(img.rgb, img.size)
self.send_response(HTTPStatus.OK)
self.send_header('Content-Type', 'image/png')
self.send_header('Cache-Control', 'no-cache')
self.send_header('Content-Length', str(len(png)))
self.end_headers()
self.wfile.write(png)
return
except Exception:
self.send_error(HTTPStatus.INTERNAL_SERVER_ERROR)
return
self.send_error(HTTPStatus.NOT_FOUND)
def do_POST(self):
parsed = urllib.parse.urlparse(self.path)
path = parsed.path
length = int(self.headers.get('Content-Length', '0') or '0')
body = b''
if length:
body = self.rfile.read(length)
if not self._check_auth():
return self._write_json({"error": "unauthorized"}, HTTPStatus.UNAUTHORIZED)
if path == '/api/config':
# Replace config.json with provided JSON, then notify GUI to reload
try:
if not body:
return self._write_json({"error": "empty body"}, HTTPStatus.BAD_REQUEST)
new_cfg = json.loads(body.decode('utf-8'))
if not isinstance(new_cfg, dict):
return self._write_json({"error": "config must be an object"}, HTTPStatus.BAD_REQUEST)
write_config_json(new_cfg)
trigger_reload_config_ipc()
return self._write_json({"ok": True})
except (BrokenPipeError, ConnectionAbortedError, ConnectionResetError, OSError):
return
except Exception as e:
return self._write_json({"error": str(e)}, HTTPStatus.INTERNAL_SERVER_ERROR)
# Create a new sequence
if path == '/api/sequences':
try:
payload = {}
if body:
payload = json.loads(body.decode('utf-8'))
name = payload.get('name')
if not name:
return self._write_json({"error": "name required"}, HTTPStatus.BAD_REQUEST)
cfg = read_config_json()
if any(s.get('name') == name for s in cfg.get('sequences', [])):
return self._write_json({"error": "sequence exists"}, HTTPStatus.CONFLICT)
seq = {
'name': name,
'steps': payload.get('steps', []),
'loop': payload.get('loop', False),
'loop_count': payload.get('loop_count', 1),
}
cfg.setdefault('sequences', []).append(seq)
write_config_json(cfg)
trigger_reload_config_ipc()
return self._write_json({"ok": True})
except (BrokenPipeError, ConnectionAbortedError, ConnectionResetError, OSError):
return
except Exception as e:
return self._write_json({"error": str(e)}, HTTPStatus.INTERNAL_SERVER_ERROR)
# Append a step to failsafe sequence
if path == '/api/failsafe/sequence':
try:
payload = {}
if body:
payload = json.loads(body.decode('utf-8'))
new_step = payload.get('step')
if not isinstance(new_step, dict):
return self._write_json({"error": "step must be object"}, HTTPStatus.BAD_REQUEST)
cfg = read_config_json()
fs = cfg.get('failsafe', {}) or {}
fs.setdefault('sequence', [])
fs['sequence'].append(new_step)
cfg['failsafe'] = fs
write_config_json(cfg)
trigger_reload_config_ipc()
return self._write_json({"ok": True, "index": len(fs['sequence']) - 1})
except (BrokenPipeError, ConnectionAbortedError, ConnectionResetError, OSError):
return
except Exception as e:
return self._write_json({"error": str(e)}, HTTPStatus.INTERNAL_SERVER_ERROR)
# Create a new group
if path == '/api/groups':
try:
payload = json.loads(body.decode('utf-8')) if body else {}
name = (payload.get('name') or '').strip()
if not name:
return self._write_json({"error": "name required"}, HTTPStatus.BAD_REQUEST)
cfg = read_config_json()
groups = cfg.get('groups', {}) or {}
if name in groups:
return self._write_json({"error": "exists"}, HTTPStatus.BAD_REQUEST)
groups[name] = {"name": name, "steps": [], "loop": False, "loop_count": 1}
cfg['groups'] = groups
write_config_json(cfg)
trigger_reload_config_ipc()
return self._write_json({"ok": True})
except (BrokenPipeError, ConnectionAbortedError, ConnectionResetError, OSError):
return
except Exception as e:
return self._write_json({"error": str(e)}, HTTPStatus.INTERNAL_SERVER_ERROR)
# Append a step to a group
if path.startswith('/api/groups/') and path.endswith('/steps'):
try:
name = urllib.parse.unquote(path[len('/api/groups/'):-len('/steps')])
payload = json.loads(body.decode('utf-8')) if body else {}
new_step = payload.get('step')
if not isinstance(new_step, dict):
return self._write_json({"error": "step must be object"}, HTTPStatus.BAD_REQUEST)
cfg = read_config_json()
groups = cfg.get('groups', {}) or {}
if name not in groups:
return self._write_json({"error": "not found"}, HTTPStatus.NOT_FOUND)
grp = groups[name]
if isinstance(grp, list):
grp.append(new_step)
groups[name] = grp
else:
steps = grp.setdefault('steps', [])
steps.append(new_step)
groups[name] = grp
cfg['groups'] = groups
write_config_json(cfg)
trigger_reload_config_ipc()
# compute index
idx = len(groups[name]) - 1 if isinstance(groups[name], list) else (len(groups[name].get('steps', [])) - 1)
return self._write_json({"ok": True, "index": idx})
except (BrokenPipeError, ConnectionAbortedError, ConnectionResetError, OSError):
return
except Exception as e:
return self._write_json({"error": str(e)}, HTTPStatus.INTERNAL_SERVER_ERROR)
# Append an action to a group step
if '/steps/' in path and path.endswith('/actions') and path.startswith('/api/groups/'):
try:
# path: /api/groups/<name>/steps/<idx>/actions
base, _, _ = path.partition('/actions')
head, _, tail = base.partition('/steps/')
name = urllib.parse.unquote(head[len('/api/groups/'):])
idx = int(tail)
payload = json.loads(body.decode('utf-8')) if body else {}
new_action = payload.get('action')
if not isinstance(new_action, dict):
return self._write_json({"error": "action must be object"}, HTTPStatus.BAD_REQUEST)
cfg = read_config_json()
groups = cfg.get('groups', {}) or {}
if name not in groups:
return self._write_json({"error": "not found"}, HTTPStatus.NOT_FOUND)
grp = groups[name]
steps = grp if isinstance(grp, list) else grp.setdefault('steps', [])