-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathserver.py
More file actions
executable file
·9710 lines (8488 loc) · 396 KB
/
server.py
File metadata and controls
executable file
·9710 lines (8488 loc) · 396 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
#!/usr/bin/env python3
"""
DeQ - Alles schläft, einer wacht.
USE BEHIND VPN ONLY! DO NOT EXPOSE TO PUBLIC INTERNET!
"""
import subprocess
import json
import os
import socket
import time
import threading
import argparse
import re
import glob
import shutil
import random
import shlex
import hashlib
import secrets
import hmac
from datetime import datetime, timedelta
from http.server import HTTPServer, BaseHTTPRequestHandler
from urllib.parse import urlparse, parse_qs
from http.cookies import SimpleCookie
# === CONFIGURATION ===
DEFAULT_PORT = 5050
DATA_DIR = "/opt/deq"
CONFIG_FILE = f"{DATA_DIR}/config.json"
SCRIPTS_DIR = f"{DATA_DIR}/scripts"
PASSWORD_FILE = f"{DATA_DIR}/.password"
SESSION_SECRET_FILE = f"{DATA_DIR}/.session_secret"
SESSION_COOKIE_NAME = "deq_session"
VERSION = "0.9.15"
# SSH ControlMaster for connection reuse (reduces overhead when File Manager makes many SSH calls)
SSH_CONTROL_OPTS = ["-o", "ControlMaster=auto", "-o", "ControlPath=/tmp/deq-ssh-%r@%h:%p", "-o", "ControlPersist=60", "-o", "ServerAliveInterval=10", "-o", "ServerAliveCountMax=2"]
SSH_CONTROL_STR = "-o ControlMaster=auto -o ControlPath=/tmp/deq-ssh-%r@%h:%p -o ControlPersist=60 -o ServerAliveInterval=10 -o ServerAliveCountMax=2"
# Transfer job tracking (in-memory, lost on restart)
transfer_jobs = {}
transfer_jobs_lock = threading.Lock()
# === AUTHENTICATION ===
def is_auth_enabled():
"""Check if authentication is enabled (password file exists)."""
return os.path.exists(PASSWORD_FILE)
def verify_password(password):
"""Verify password against stored hash."""
if not is_auth_enabled():
return True
try:
with open(PASSWORD_FILE, 'r') as f:
stored = f.read().strip()
salt_hex, key_hex = stored.split(':')
salt = bytes.fromhex(salt_hex)
key = hashlib.scrypt(password.encode('utf-8'), salt=salt, n=16384, r=8, p=1, dklen=32)
return secrets.compare_digest(key.hex(), key_hex)
except:
return False
def get_session_secret():
"""Get or create session signing secret."""
if os.path.exists(SESSION_SECRET_FILE):
with open(SESSION_SECRET_FILE, 'r') as f:
return f.read().strip()
secret = secrets.token_hex(32)
with open(SESSION_SECRET_FILE, 'w') as f:
f.write(secret)
os.chmod(SESSION_SECRET_FILE, 0o600)
return secret
def create_session_token():
"""Create signed session token."""
timestamp = str(int(time.time()))
signature = hmac.new(get_session_secret().encode(), timestamp.encode(), 'sha256').hexdigest()
return f"{timestamp}:{signature}"
def verify_session_token(token):
"""Verify session token signature."""
if not token:
return False
try:
timestamp, signature = token.split(':')
expected = hmac.new(get_session_secret().encode(), timestamp.encode(), 'sha256').hexdigest()
return secrets.compare_digest(signature, expected)
except:
return False
def format_size(bytes_val):
"""Format bytes as human-readable string."""
if bytes_val < 1024:
return f"{bytes_val} B"
elif bytes_val < 1024 * 1024:
return f"{bytes_val / 1024:.1f} KB"
elif bytes_val < 1024 * 1024 * 1024:
return f"{bytes_val / (1024 * 1024):.1f} MB"
elif bytes_val < 1024 * 1024 * 1024 * 1024:
return f"{bytes_val / (1024 * 1024 * 1024):.1f} GB"
else:
return f"{bytes_val / (1024 * 1024 * 1024 * 1024):.1f} TB"
def get_path_size(device, path):
"""Get size of path in bytes via du -sb. Returns int or None on error."""
try:
safe_path = shlex.quote(path)
if device.get('is_host', False):
result = subprocess.run(f"du -sb {safe_path} 2>/dev/null | cut -f1",
shell=True, capture_output=True, text=True, timeout=60)
else:
ssh_config = device.get('ssh', {})
user = ssh_config.get('user')
port = ssh_config.get('port', 22)
ip = device.get('ip')
if not user:
return None
result = subprocess.run(
["ssh"] + SSH_CONTROL_OPTS + ["-o", "StrictHostKeyChecking=no", "-o", "ConnectTimeout=5",
"-p", str(port), f"{user}@{ip}", f"du -sb {safe_path} 2>/dev/null | cut -f1"],
capture_output=True, text=True, timeout=60
)
if result.returncode == 0 and result.stdout.strip():
return int(result.stdout.strip())
return None
except:
return None
def get_free_space(device, path):
"""Get free space at path in bytes. Returns int or None on error."""
try:
safe_path = shlex.quote(path)
if device.get('is_host', False):
return shutil.disk_usage(path).free
else:
ssh_config = device.get('ssh', {})
user = ssh_config.get('user')
port = ssh_config.get('port', 22)
ip = device.get('ip')
if not user:
return None
result = subprocess.run(
["ssh"] + SSH_CONTROL_OPTS + ["-o", "StrictHostKeyChecking=no", "-o", "ConnectTimeout=5",
"-p", str(port), f"{user}@{ip}", f"df -B1 {safe_path} 2>/dev/null | tail -1 | awk '{{print $4}}'"],
capture_output=True, text=True, timeout=30
)
if result.returncode == 0 and result.stdout.strip():
return int(result.stdout.strip())
return None
except:
return None
def run_rsync_with_progress(cmd, progress_callback, idle_timeout=60):
"""Run rsync and call progress_callback(percent, speed, eta) on updates.
Returns (success: bool, error: str or None). Timeout only on idle (no progress)."""
try:
import fcntl
process = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
# Set non-blocking
fd = process.stdout.fileno()
flags = fcntl.fcntl(fd, fcntl.F_GETFL)
fcntl.fcntl(fd, fcntl.F_SETFL, flags | os.O_NONBLOCK)
last_progress_time = time.time()
buffer = ""
last_error = ""
while True:
try:
chunk = process.stdout.read(4096)
if chunk:
buffer += chunk.decode('utf-8', errors='replace')
last_progress_time = time.time()
except (BlockingIOError, IOError):
pass
# Process complete lines
while '\r' in buffer or '\n' in buffer:
r_pos = buffer.find('\r')
n_pos = buffer.find('\n')
if r_pos == -1: r_pos = len(buffer)
if n_pos == -1: n_pos = len(buffer)
pos = min(r_pos, n_pos)
line = buffer[:pos]
buffer = buffer[pos+1:]
if not line.strip():
continue
match = re.search(r'(\d+)%\s+([\d.,]+\s*\w+/s)\s+(\d+:\d+(?::\d+)?)', line)
if match:
percent = int(match.group(1))
speed = match.group(2)
eta = match.group(3)
progress_callback(percent, speed, eta)
elif 'error' in line.lower() or 'failed' in line.lower():
last_error = line.strip()
if process.poll() is not None:
break
if time.time() - last_progress_time > idle_timeout:
process.kill()
return False, "Transfer stalled (no output for 60 seconds)"
time.sleep(0.1)
process.wait()
return process.returncode == 0, last_error if process.returncode != 0 else None
except Exception as e:
return False, str(e)
def start_transfer_job(device, paths, dest_device, dest_path, operation, cleanup_path=None):
"""Start a transfer job in background thread. Returns job_id."""
job_id = f"transfer_{int(time.time())}_{random.randint(1000, 9999)}"
is_host = device.get('is_host', False)
dest_is_host = dest_device.get('is_host', False)
phases = 2 if (not is_host and not dest_is_host) else 1
with transfer_jobs_lock:
transfer_jobs[job_id] = {
"status": "running",
"progress": 0,
"phase": 1,
"phases": phases,
"speed": None,
"eta": None,
"error": None,
"started_at": time.time()
}
thread = threading.Thread(
target=run_transfer_job,
args=(job_id, device, paths, dest_device, dest_path, operation, cleanup_path)
)
thread.daemon = True
thread.start()
return job_id
def update_job_progress(job_id, progress, speed=None, eta=None, phase=None):
"""Update job progress."""
with transfer_jobs_lock:
if job_id in transfer_jobs:
transfer_jobs[job_id]["progress"] = progress
if speed:
transfer_jobs[job_id]["speed"] = speed
if eta:
transfer_jobs[job_id]["eta"] = eta
if phase:
transfer_jobs[job_id]["phase"] = phase
def complete_job(job_id, error=None):
"""Mark job as complete or failed."""
with transfer_jobs_lock:
if job_id in transfer_jobs:
transfer_jobs[job_id]["status"] = "error" if error else "complete"
transfer_jobs[job_id]["error"] = error
transfer_jobs[job_id]["completed_at"] = time.time()
def get_job_status(job_id):
"""Get current job status."""
cleanup_old_jobs()
with transfer_jobs_lock:
job = transfer_jobs.get(job_id)
if not job:
return {"status": "not_found"}
return job.copy()
def cleanup_old_jobs(max_age=300):
"""Remove completed jobs older than max_age seconds."""
now = time.time()
with transfer_jobs_lock:
to_remove = [
jid for jid, job in transfer_jobs.items()
if job["status"] in ("complete", "error")
and job.get("completed_at", 0) + max_age < now
]
for jid in to_remove:
del transfer_jobs[jid]
def run_transfer_job(job_id, device, paths, dest_device, dest_path, operation, cleanup_path=None):
"""Execute transfer in background thread."""
try:
ssh_config = device.get('ssh', {})
user = ssh_config.get('user')
port = ssh_config.get('port', 22)
ip = device.get('ip')
is_host = device.get('is_host', False)
dest_ssh = dest_device.get('ssh', {})
dest_user = dest_ssh.get('user')
dest_port = dest_ssh.get('port', 22)
dest_ip = dest_device.get('ip')
dest_is_host = dest_device.get('is_host', False)
for src_path in paths:
safe_src = shlex.quote(src_path)
safe_dest = shlex.quote(dest_path)
def progress_callback(percent, speed, eta):
update_job_progress(job_id, percent, speed, eta)
if is_host and dest_is_host:
cmd = f"rsync -a --progress {safe_src} {safe_dest}/"
success, err = run_rsync_with_progress(cmd, progress_callback)
elif is_host and not dest_is_host:
cmd = f"rsync -a --progress -e 'ssh {SSH_CONTROL_STR} -o StrictHostKeyChecking=no -p {dest_port}' {safe_src} {dest_user}@{dest_ip}:{safe_dest}/"
success, err = run_rsync_with_progress(cmd, progress_callback)
elif not is_host and dest_is_host:
cmd = f"rsync -a --progress -e 'ssh {SSH_CONTROL_STR} -o StrictHostKeyChecking=no -p {port}' {user}@{ip}:{safe_src} {safe_dest}/"
success, err = run_rsync_with_progress(cmd, progress_callback)
elif device.get('id') == dest_device.get('id'):
# Same remote device - run rsync directly on remote
ssh_cmd = ["ssh"] + SSH_CONTROL_OPTS + ["-o", "StrictHostKeyChecking=no", "-p", str(port), f"{user}@{ip}",
f"rsync -a {safe_src} {safe_dest}/"]
result = subprocess.run(ssh_cmd, capture_output=True, text=True)
success = result.returncode == 0
err = result.stderr.strip() if not success else None
else:
# Remote to remote (two phases, via host)
temp_path = f"/tmp/deq_transfer_{job_id}"
safe_temp = shlex.quote(temp_path)
# Phase 1: Remote to Host
update_job_progress(job_id, 0, phase=1)
cmd1 = f"rsync -a --progress -e 'ssh {SSH_CONTROL_STR} -o StrictHostKeyChecking=no -p {port}' {user}@{ip}:{safe_src} {safe_temp}/"
success, err = run_rsync_with_progress(cmd1, progress_callback)
if not success:
subprocess.run(f"rm -rf {safe_temp}", shell=True)
complete_job(job_id, f"Download failed: {err}")
return
# Phase 2: Host to Remote
update_job_progress(job_id, 0, phase=2)
src_name = src_path.rstrip('/').split('/')[-1]
safe_temp_src = shlex.quote(f"{temp_path}/{src_name}")
cmd2 = f"rsync -a --progress -e 'ssh {SSH_CONTROL_STR} -o StrictHostKeyChecking=no -p {dest_port}' {safe_temp_src} {dest_user}@{dest_ip}:{safe_dest}/"
success, err = run_rsync_with_progress(cmd2, progress_callback)
subprocess.run(f"rm -rf {safe_temp}", shell=True)
if not success:
complete_job(job_id, f"Failed to {operation} {src_path}: {err}")
return
# For move: delete source after successful copy
if operation == 'move':
if is_host:
subprocess.run(f"rm -rf {safe_src}", shell=True)
else:
subprocess.run(
["ssh"] + SSH_CONTROL_OPTS + ["-o", "StrictHostKeyChecking=no",
"-p", str(port), f"{user}@{ip}", f"rm -rf {safe_src}"],
capture_output=True
)
# Cleanup temp directory if specified (used by extract cross-device)
if cleanup_path:
is_host = device.get('is_host', False)
if is_host:
subprocess.run(f"rm -rf {shlex.quote(cleanup_path)}", shell=True)
else:
ssh_config = device.get('ssh', {})
subprocess.run(
["ssh"] + SSH_CONTROL_OPTS + ["-o", "StrictHostKeyChecking=no",
"-p", str(ssh_config.get('port', 22)), f"{ssh_config.get('user')}@{device.get('ip')}",
f"rm -rf {shlex.quote(cleanup_path)}"],
capture_output=True
)
complete_job(job_id)
except Exception as e:
complete_job(job_id, str(e))
# === DEFAULT CONFIG ===
DEFAULT_ALERTS = {"online": True, "cpu": 90, "ram": 90, "cpu_temp": 80, "disk_usage": 90, "disk_temp": 60, "smart": True}
DEFAULT_HOST_DEVICE = {
"id": "host",
"name": "DeQ Host",
"ip": "localhost",
"icon": "cpu",
"is_host": True
}
DEFAULT_CONFIG = {
"settings": {
"theme": "dark",
"text_color": "#e0e0e0",
"accent_color": "#2ed573",
"section_order": ["devices", "links", "quick_actions", "tasks"]
},
"links": [],
"quick_actions": [],
"devices": [],
"tasks": []
}
# === DATA MANAGEMENT ===
TASK_LOGS_DIR = f"{DATA_DIR}/task-logs"
def ensure_dirs():
os.makedirs(DATA_DIR, exist_ok=True)
os.makedirs(SCRIPTS_DIR, exist_ok=True)
os.makedirs(TASK_LOGS_DIR, exist_ok=True)
def load_config():
if os.path.exists(CONFIG_FILE):
with open(CONFIG_FILE, 'r') as f:
cfg = json.load(f)
# Merge with defaults for missing keys
for key in DEFAULT_CONFIG:
if key not in cfg:
cfg[key] = DEFAULT_CONFIG[key]
# Merge settings with defaults
for key in DEFAULT_CONFIG.get('settings', {}):
if key not in cfg.get('settings', {}):
cfg['settings'][key] = DEFAULT_CONFIG['settings'][key]
else:
cfg = DEFAULT_CONFIG.copy()
cfg["devices"] = []
# Ensure host device exists
host_exists = any(d.get("is_host") for d in cfg.get("devices", []))
if not host_exists:
cfg["devices"].insert(0, DEFAULT_HOST_DEVICE.copy())
return cfg
def save_config(config):
with open(CONFIG_FILE, 'w') as f:
json.dump(config, f, indent=2)
def get_config_with_defaults():
cfg = CONFIG.copy()
cfg['devices'] = []
for dev in CONFIG.get('devices', []):
d = dev.copy()
d['alerts'] = {**DEFAULT_ALERTS, **dev.get('alerts', {})}
cfg['devices'].append(d)
return cfg
ensure_dirs()
CONFIG = load_config()
# === DEVICE STATUS CACHE ===
device_status_cache = {}
cache_lock = threading.Lock()
refresh_in_progress = set()
def get_cached_status(device_id):
with cache_lock:
return device_status_cache.get(device_id)
def set_cached_status(device_id, status):
with cache_lock:
device_status_cache[device_id] = status
def refresh_device_status_async(device):
dev_id = device.get('id')
if dev_id in refresh_in_progress:
return
refresh_in_progress.add(dev_id)
def do_refresh():
try:
container_statuses = get_all_container_statuses(device)
if device.get('is_host'):
stats = get_local_stats()
status = {"online": True, "stats": stats, "containers": container_statuses}
else:
online = ping_host(device.get('ip', ''))
stats = None
if online and device.get('ssh', {}).get('user'):
stats = get_remote_stats(device['ip'], device['ssh']['user'], device['ssh'].get('port', 22))
status = {"online": online, "stats": stats, "containers": container_statuses}
set_cached_status(dev_id, status)
finally:
refresh_in_progress.discard(dev_id)
threading.Thread(target=do_refresh, daemon=True).start()
# === SYSTEM STATS (LOCAL) ===
def get_disk_smart_info():
"""Get SMART info and temps for all disks. Returns dict keyed by device name."""
disks = {}
try:
result = subprocess.run(["lsblk", "-d", "-n", "-o", "NAME,TYPE"],
capture_output=True, text=True, timeout=5)
for line in result.stdout.strip().split('\n'):
parts = line.split()
if len(parts) >= 2 and parts[1] == 'disk':
dev_name = parts[0]
disks[dev_name] = {"temp": None, "smart": None}
except:
pass
for dev_name in disks:
try:
result = subprocess.run(["sudo", "smartctl", "-A", "-H", f"/dev/{dev_name}"],
capture_output=True, text=True, timeout=10)
output = result.stdout
if "PASSED" in output:
disks[dev_name]["smart"] = "ok"
elif "FAILED" in output:
disks[dev_name]["smart"] = "failed"
for line in output.split('\n'):
if 'Temperature' in line and '-' in line:
after_dash = line.split('-')[-1].strip()
first_num = after_dash.split()[0] if after_dash else ''
if first_num.isdigit() and 0 < int(first_num) < 100:
disks[dev_name]["temp"] = int(first_num)
break
except:
pass
return disks
def get_container_stats():
"""Get CPU and RAM stats for all running containers."""
containers = {}
try:
result = subprocess.run(
["docker", "stats", "--no-stream", "--format", "{{.Name}}:{{.CPUPerc}}:{{.MemPerc}}"],
capture_output=True, text=True, timeout=10
)
if result.returncode == 0:
for line in result.stdout.strip().split('\n'):
if ':' in line:
parts = line.split(':')
if len(parts) >= 3:
name = parts[0]
cpu = parts[1].replace('%', '').strip()
mem = parts[2].replace('%', '').strip()
try:
containers[name] = {
"cpu": float(cpu),
"mem": float(mem)
}
except:
pass
except:
pass
return containers
def get_local_stats():
"""Get stats for the device running DeQ."""
stats = {"cpu": 0, "ram_used": 0, "ram_total": 0, "temp": None, "disks": [], "uptime": "", "disk_smart": {}, "container_stats": {}}
try:
with open('/proc/loadavg', 'r') as f:
load = float(f.read().split()[0])
cpu_count = os.cpu_count() or 1
stats["cpu"] = min(100, int(load / cpu_count * 100))
with open('/proc/meminfo', 'r') as f:
meminfo = {}
for line in f:
parts = line.split()
if len(parts) >= 2:
meminfo[parts[0].rstrip(':')] = int(parts[1]) * 1024
stats["ram_total"] = meminfo.get("MemTotal", 0)
stats["ram_used"] = stats["ram_total"] - meminfo.get("MemAvailable", 0)
thermal_zones = ["/sys/class/thermal/thermal_zone0/temp"]
for zone in thermal_zones:
if os.path.exists(zone):
with open(zone, 'r') as f:
stats["temp"] = int(f.read().strip()) // 1000
break
result = subprocess.run(["df", "-B1", "--output=source,target,size,used"],
capture_output=True, text=True, timeout=5)
for line in result.stdout.strip().split('\n')[1:]:
parts = line.split()
if len(parts) >= 4:
source = parts[0]
mount = parts[1]
if mount in ['/', '/home'] or mount.startswith(('/mnt', '/media', '/srv')):
if int(parts[2]) > 1e9:
dev_name = source.split('/')[-1].rstrip('0123456789')
stats["disks"].append({
"mount": mount,
"total": int(parts[2]),
"used": int(parts[3]),
"device": dev_name
})
with open('/proc/uptime', 'r') as f:
uptime_seconds = float(f.read().split()[0])
days = int(uptime_seconds // 86400)
hours = int((uptime_seconds % 86400) // 3600)
stats["uptime"] = f"{days}d {hours}h" if days > 0 else f"{hours}h"
stats["disk_smart"] = get_disk_smart_info()
stats["container_stats"] = get_container_stats()
except Exception as e:
print(f"Error getting local stats: {e}")
return stats
# === QUICK ACTIONS (Script Execution) ===
def discover_scripts():
"""Find all executable scripts in SCRIPTS_DIR recursively."""
scripts = []
if not os.path.exists(SCRIPTS_DIR):
return scripts
for root, dirs, files in os.walk(SCRIPTS_DIR):
for f in files:
full_path = os.path.join(root, f)
if os.access(full_path, os.X_OK):
rel_path = os.path.relpath(full_path, SCRIPTS_DIR)
scripts.append({"path": rel_path, "name": f})
return sorted(scripts, key=lambda x: x["path"])
def execute_quick_action(script_path):
"""Start a script in the background."""
full_path = os.path.join(SCRIPTS_DIR, script_path)
if not os.path.realpath(full_path).startswith(os.path.realpath(SCRIPTS_DIR)):
return {"success": False, "error": "Invalid script path"}
if not os.path.exists(full_path):
return {"success": False, "error": "Script not found"}
if not os.access(full_path, os.X_OK):
return {"success": False, "error": "Script not executable"}
try:
subprocess.Popen([full_path], cwd=SCRIPTS_DIR, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, start_new_session=True)
return {"success": True}
except Exception as e:
return {"success": False, "error": str(e)}
# === REMOTE STATS (SSH) ===
def get_remote_stats(ip, user, port=22):
"""Get stats from remote device via SSH."""
stats = {"cpu": 0, "ram_used": 0, "ram_total": 0, "temp": None, "disks": [], "uptime": "", "disk_smart": {}, "container_stats": {}}
ssh_base = ["ssh"] + SSH_CONTROL_OPTS + ["-o", "StrictHostKeyChecking=no", "-o", "ConnectTimeout=3", "-o", "BatchMode=yes", "-p", str(port), f"{user}@{ip}"]
# Basic stats (required)
try:
cmd = "nproc; echo '---'; cat /proc/loadavg; echo '---'; cat /proc/meminfo | head -10; echo '---'; cat /sys/class/thermal/thermal_zone*/temp 2>/dev/null | head -1; echo '---'; cat /proc/uptime"
result = subprocess.run(ssh_base + [cmd], capture_output=True, text=True, timeout=10)
if result.returncode != 0:
return None
parts = result.stdout.split('---')
cpu_count = int(parts[0].strip()) if parts[0].strip().isdigit() else 4
load = float(parts[1].strip().split()[0])
stats["cpu"] = min(100, int(load / cpu_count * 100))
meminfo = {}
for line in parts[2].strip().split('\n'):
if ':' in line:
key, val = line.split(':')
meminfo[key.strip()] = int(val.split()[0]) * 1024
stats["ram_total"] = meminfo.get("MemTotal", 0)
if "MemAvailable" in meminfo:
stats["ram_used"] = stats["ram_total"] - meminfo["MemAvailable"]
else:
free = meminfo.get("MemFree", 0) + meminfo.get("Buffers", 0) + meminfo.get("Cached", 0)
stats["ram_used"] = stats["ram_total"] - free
temp_str = parts[3].strip()
if temp_str.isdigit():
stats["temp"] = int(temp_str) // 1000
uptime_seconds = float(parts[4].strip().split()[0])
days = int(uptime_seconds // 86400)
hours = int((uptime_seconds % 86400) // 3600)
stats["uptime"] = f"{days}d {hours}h" if days > 0 else f"{hours}h"
except:
return None
# Disks (optional)
try:
result = subprocess.run(ssh_base + ["df -B1 --output=source,target,size,used 2>/dev/null || df -B1"], capture_output=True, text=True, timeout=5)
if result.returncode == 0:
for line in result.stdout.strip().split('\n')[1:]:
cols = line.split()
if len(cols) >= 4:
source, mount = cols[0], cols[1]
if mount in ['/', '/home'] or mount.startswith(('/mnt', '/media', '/srv')):
try:
if int(cols[2]) > 1e9:
stats["disks"].append({"mount": mount, "total": int(cols[2]), "used": int(cols[3])})
except:
pass
except:
pass
# SMART (optional)
try:
result = subprocess.run(ssh_base + ["lsblk -d -n -o NAME,TYPE 2>/dev/null"], capture_output=True, text=True, timeout=5)
if result.returncode == 0:
disk_names = []
for line in result.stdout.strip().split('\n'):
cols = line.split()
if len(cols) >= 2 and cols[1] == 'disk':
disk_names.append(cols[0])
stats["disk_smart"][cols[0]] = {"temp": None, "smart": None}
for dev in disk_names:
try:
result = subprocess.run(ssh_base + [f"sudo smartctl -A -H /dev/{dev} 2>/dev/null"], capture_output=True, text=True, timeout=5)
output = result.stdout
if "PASSED" in output:
stats["disk_smart"][dev]["smart"] = "ok"
elif "FAILED" in output:
stats["disk_smart"][dev]["smart"] = "failed"
for line in output.split('\n'):
if 'Temperature' in line and '-' in line:
after_dash = line.split('-')[-1].strip()
first_num = after_dash.split()[0] if after_dash else ''
if first_num.isdigit() and 0 < int(first_num) < 100:
stats["disk_smart"][dev]["temp"] = int(first_num)
break
except:
pass
except:
pass
# Docker stats (optional)
try:
result = subprocess.run(ssh_base + ["docker stats --no-stream --format '{{.Name}}:{{.CPUPerc}}:{{.MemPerc}}' 2>/dev/null"], capture_output=True, text=True, timeout=5)
if result.returncode == 0:
for line in result.stdout.strip().split('\n'):
if ':' in line:
cols = line.split(':')
if len(cols) >= 3:
try:
stats["container_stats"][cols[0]] = {"cpu": float(cols[1].replace('%', '')), "mem": float(cols[2].replace('%', ''))}
except:
pass
except:
pass
return stats
# === FOLDER BROWSING ===
def browse_folder(device, path="/"):
"""List folders in a directory on a device (local or remote via SSH)."""
try:
# Normalize path
path = path.rstrip('/') or '/'
if device.get('is_host'):
# Local browsing
if not os.path.isdir(path):
return {"success": False, "error": f"Not a directory: {path}"}
folders = []
try:
for entry in os.listdir(path):
full_path = os.path.join(path, entry)
if os.path.isdir(full_path) and not entry.startswith('.'):
folders.append(entry)
except PermissionError:
return {"success": False, "error": "Permission denied"}
folders.sort(key=str.lower)
return {"success": True, "path": path, "folders": folders}
else:
# Remote browsing via SSH
ssh_config = device.get('ssh', {})
user = ssh_config.get('user')
port = ssh_config.get('port', 22)
ip = device.get('ip')
if not user:
return {"success": False, "error": "SSH not configured for this device"}
# Use find to list only directories, exclude hidden
cmd = f"find '{path}' -maxdepth 1 -mindepth 1 -type d ! -name '.*' -printf '%f\\n' 2>/dev/null | sort -f"
result = subprocess.run(
["ssh"] + SSH_CONTROL_OPTS + ["-o", "StrictHostKeyChecking=no", "-o", "ConnectTimeout=5",
"-p", str(port), f"{user}@{ip}", cmd],
capture_output=True, text=True, timeout=15
)
if result.returncode != 0 and not result.stdout:
# Check if path exists
check_cmd = f"test -d '{path}' && echo 'exists' || echo 'notfound'"
check_result = subprocess.run(
["ssh"] + SSH_CONTROL_OPTS + ["-o", "StrictHostKeyChecking=no", "-o", "ConnectTimeout=5",
"-p", str(port), f"{user}@{ip}", check_cmd],
capture_output=True, text=True, timeout=10
)
if "notfound" in check_result.stdout:
return {"success": False, "error": f"Path not found: {path}"}
return {"success": False, "error": "Permission denied or SSH error"}
folders = [f for f in result.stdout.strip().split('\n') if f]
return {"success": True, "path": path, "folders": folders}
except subprocess.TimeoutExpired:
return {"success": False, "error": "SSH timeout"}
except Exception as e:
return {"success": False, "error": str(e)}
# === FILE MANAGER ===
def list_files(device, path="/"):
"""List files and folders with size and date."""
try:
path = path.rstrip('/') or '/'
files = []
if device.get('is_host'):
# Local listing
if not os.path.isdir(path):
return {"success": False, "error": f"Not a directory: {path}"}
try:
for entry in os.listdir(path):
if entry.startswith('.'):
continue
full_path = os.path.join(path, entry)
try:
stat = os.stat(full_path)
is_dir = os.path.isdir(full_path)
files.append({
"name": entry,
"is_dir": is_dir,
"size": stat.st_size if not is_dir else 0,
"mtime": int(stat.st_mtime)
})
except (PermissionError, OSError):
continue
except PermissionError:
return {"success": False, "error": "Permission denied"}
else:
# Remote listing via SSH
ssh_config = device.get('ssh', {})
user = ssh_config.get('user')
port = ssh_config.get('port', 22)
ip = device.get('ip')
if not user:
return {"success": False, "error": "SSH not configured"}
# Use ls -la (works on BusyBox/Synology too)
# Format: drwxr-xr-x 2 user group 4096 Dec 3 10:30 filename
cmd = f"ls -la '{path}' 2>/dev/null"
result = subprocess.run(
["ssh"] + SSH_CONTROL_OPTS + ["-o", "StrictHostKeyChecking=no", "-o", "ConnectTimeout=5",
"-p", str(port), f"{user}@{ip}", cmd],
capture_output=True, text=True, timeout=30
)
if result.returncode != 0:
return {"success": False, "error": "Failed to list directory"}
for line in result.stdout.strip().split('\n'):
if not line or line.startswith('total'):
continue
parts = line.split()
if len(parts) < 9:
continue
perms = parts[0]
size = int(parts[4]) if parts[4].isdigit() else 0
# Parse date: "Dec 3 10:30" or "Dec 3 2023"
month = parts[5]
day = parts[6]
time_or_year = parts[7]
name = ' '.join(parts[8:])
if name in ('.', '..') or name.startswith('.'):
continue
# Convert to timestamp (approximate)
try:
months = {'Jan':1,'Feb':2,'Mar':3,'Apr':4,'May':5,'Jun':6,
'Jul':7,'Aug':8,'Sep':9,'Oct':10,'Nov':11,'Dec':12}
mon = months.get(month, 1)
d = int(day)
now = datetime.now()
if ':' in time_or_year:
# This year
yr = now.year
else:
yr = int(time_or_year)
mtime = int(datetime(yr, mon, d).timestamp())
except Exception:
mtime = 0
is_dir = perms.startswith('d')
files.append({
"name": name,
"is_dir": is_dir,
"size": size if not is_dir else 0,
"mtime": mtime
})
# Sort: folders first, then by name
files.sort(key=lambda f: (not f['is_dir'], f['name'].lower()))
# Get disk space for current path
storage = None
try:
if device.get('is_host'):
stat = os.statvfs(path)
total = stat.f_blocks * stat.f_frsize
free = stat.f_bavail * stat.f_frsize
used = total - free
storage = {
"total": total,
"used": used,
"free": free,
"percent": round((used / total) * 100) if total > 0 else 0
}
else:
# Remote via SSH - use df for the path
ssh_config = device.get('ssh', {})
user = ssh_config.get('user')
port = ssh_config.get('port', 22)
ip = device.get('ip')
if user:
cmd = f"df -B1 '{path}' 2>/dev/null | tail -1"
result = subprocess.run(
["ssh"] + SSH_CONTROL_OPTS + ["-o", "StrictHostKeyChecking=no", "-o", "ConnectTimeout=5",
"-p", str(port), f"{user}@{ip}", cmd],
capture_output=True, text=True, timeout=10
)
if result.returncode == 0 and result.stdout.strip():
parts = result.stdout.strip().split()
if len(parts) >= 4:
total = int(parts[1]) if parts[1].isdigit() else 0
used = int(parts[2]) if parts[2].isdigit() else 0
free = int(parts[3]) if parts[3].isdigit() else 0
storage = {
"total": total,
"used": used,
"free": free,
"percent": round((used / total) * 100) if total > 0 else 0
}
except Exception:
pass # Storage info is optional
return {"success": True, "path": path, "files": files, "storage": storage}
except subprocess.TimeoutExpired:
return {"success": False, "error": "SSH timeout"}
except Exception as e:
return {"success": False, "error": str(e)}
def file_operation(device, operation, paths, dest_device=None, dest_path=None, new_name=None):
"""Execute file operations: copy, move, rename, delete, zip."""
try:
ssh_config = device.get('ssh', {})
user = ssh_config.get('user')
port = ssh_config.get('port', 22)
ip = device.get('ip')
is_host = device.get('is_host', False)
if not is_host and not user:
return {"success": False, "error": "SSH not configured"}
def run_local(cmd):
result = subprocess.run(cmd, shell=True, capture_output=True, text=True, timeout=300)
return result.returncode == 0, result.stderr
def run_remote(cmd):
result = subprocess.run(
["ssh"] + SSH_CONTROL_OPTS + ["-o", "StrictHostKeyChecking=no", "-o", "ConnectTimeout=5",
"-p", str(port), f"{user}@{ip}", cmd],
capture_output=True, text=True, timeout=300
)
return result.returncode == 0, result.stderr
run_cmd = run_local if is_host else run_remote
if operation == 'delete':
for p in paths:
safe_path = shlex.quote(p)
success, err = run_cmd(f"rm -rf {safe_path}")
if not success:
return {"success": False, "error": f"Failed to delete {p}: {err}"}
return {"success": True}
elif operation == 'rename':
if len(paths) != 1 or not new_name:
return {"success": False, "error": "Rename requires exactly one file and new name"}
old_path = shlex.quote(paths[0])
parent = '/'.join(paths[0].rstrip('/').split('/')[:-1]) or '/'