forked from deqrocks/deq
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.py
More file actions
executable file
·5909 lines (5074 loc) · 222 KB
/
server.py
File metadata and controls
executable file
·5909 lines (5074 loc) · 222 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 - Homelab Dashboard
Control devices, view stats, manage links - all in one place.
"""
import subprocess
import json
import os
import socket
import time
import threading
import argparse
from datetime import datetime, timedelta
from http.server import HTTPServer, BaseHTTPRequestHandler
from urllib.parse import urlparse, parse_qs
# === CONFIGURATION ===
DEFAULT_PORT = 5050
DATA_DIR = "/opt/deq"
CONFIG_FILE = f"{DATA_DIR}/config.json"
HISTORY_DIR = f"{DATA_DIR}/history"
VERSION = "0.9.1"
# === DEFAULT CONFIG ===
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"
},
"links": [],
"devices": [],
"tasks": []
}
# === DATA MANAGEMENT ===
TASK_LOGS_DIR = f"{DATA_DIR}/task-logs"
def ensure_dirs():
os.makedirs(DATA_DIR, exist_ok=True)
os.makedirs(HISTORY_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]
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)
ensure_dirs()
CONFIG = load_config()
# === HISTORY MANAGEMENT ===
def get_history_file(device_id):
return f"{HISTORY_DIR}/{device_id}.json"
def load_history(device_id):
path = get_history_file(device_id)
if os.path.exists(path):
with open(path, 'r') as f:
return json.load(f)
return {}
def save_history(device_id, history):
# Keep only last 400 days
cutoff = (datetime.now() - timedelta(days=400)).strftime("%Y-%m-%d")
history = {k: v for k, v in history.items() if k >= cutoff}
with open(get_history_file(device_id), 'w') as f:
json.dump(history, f)
def record_stats(device_id, cpu, temp):
history = load_history(device_id)
today = datetime.now().strftime("%Y-%m-%d")
hour = datetime.now().hour
if today not in history:
history[today] = {"hourly": {}, "totals": {"samples": 0, "cpu_sum": 0, "temp_max": 0}}
# Record hourly (keep latest per hour)
history[today]["hourly"][str(hour)] = {"cpu": cpu, "temp": temp}
# Update totals
history[today]["totals"]["samples"] += 1
history[today]["totals"]["cpu_sum"] += cpu
history[today]["totals"]["temp_max"] = max(history[today]["totals"].get("temp_max", 0), temp or 0)
save_history(device_id, history)
# === SYSTEM STATS (LOCAL) ===
def get_local_stats():
"""Get stats for the device running DeQ."""
stats = {"cpu": 0, "ram_used": 0, "ram_total": 0, "temp": None, "disks": [], "uptime": ""}
try:
# CPU load (1 min average)
with open('/proc/loadavg', 'r') as f:
load = float(f.read().split()[0])
# Get CPU count for percentage
cpu_count = os.cpu_count() or 1
stats["cpu"] = min(100, int(load / cpu_count * 100))
# RAM
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 # KB to bytes
stats["ram_total"] = meminfo.get("MemTotal", 0)
stats["ram_used"] = stats["ram_total"] - meminfo.get("MemAvailable", 0)
# Temperature
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
# Disks
result = subprocess.run(["df", "-B1", "--output=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) >= 3 and parts[0] in ['/', '/home', '/mnt', '/media']:
if int(parts[1]) > 1e9: # Only show disks > 1GB
stats["disks"].append({
"mount": parts[0],
"total": int(parts[1]),
"used": int(parts[2])
})
# Uptime
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)
if days > 0:
stats["uptime"] = f"{days}d {hours}h"
else:
stats["uptime"] = f"{hours}h"
except Exception as e:
print(f"Error getting local stats: {e}")
return stats
# === REMOTE STATS (SSH) ===
def get_remote_stats(ip, user, port=22):
"""Get stats from remote device via SSH."""
try:
# Get more meminfo lines for Synology compatibility (no MemAvailable)
cmd = "cat /proc/loadavg; echo '---'; cat /proc/meminfo | head -10; echo '---'; cat /sys/class/thermal/thermal_zone*/temp 2>/dev/null | head -1; echo '---'; df -B1 / | tail -1; echo '---'; cat /proc/uptime"
result = subprocess.run(
["ssh", "-o", "StrictHostKeyChecking=no", "-o", "ConnectTimeout=3",
"-p", str(port), f"{user}@{ip}", cmd],
capture_output=True, text=True, timeout=10
)
if result.returncode != 0:
return None
parts = result.stdout.split('---')
stats = {"cpu": 0, "ram_used": 0, "ram_total": 0, "temp": None, "disks": [], "uptime": ""}
# CPU (load / cpu_count * 100)
load = float(parts[0].strip().split()[0])
cpu_count = os.cpu_count() or 4
stats["cpu"] = min(100, int(load / cpu_count * 100))
# RAM - handle both modern (MemAvailable) and older kernels (MemFree+Buffers+Cached)
meminfo = {}
for line in parts[1].strip().split('\n'):
if ':' in line:
key, val = line.split(':')
meminfo[key.strip()] = int(val.split()[0]) * 1024 # kB to bytes
stats["ram_total"] = meminfo.get("MemTotal", 0)
if "MemAvailable" in meminfo:
stats["ram_used"] = stats["ram_total"] - meminfo["MemAvailable"]
else:
# Fallback for older kernels (Synology): Free + Buffers + Cached
free = meminfo.get("MemFree", 0) + meminfo.get("Buffers", 0) + meminfo.get("Cached", 0)
stats["ram_used"] = stats["ram_total"] - free
# Temp
temp_str = parts[2].strip()
if temp_str.isdigit():
stats["temp"] = int(temp_str) // 1000
# Disk
disk_parts = parts[3].strip().split()
if len(disk_parts) >= 3:
stats["disks"].append({
"mount": "/",
"total": int(disk_parts[1]),
"used": int(disk_parts[2])
})
# Uptime
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"
return stats
except Exception as e:
print(f"Error getting remote stats: {e}")
return None
# === 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", "-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", "-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", "-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:
import calendar
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()))
return {"success": True, "path": path, "files": files}
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", "-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 = p.replace("'", "'\\''")
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 = paths[0].replace("'", "'\\''")
parent = '/'.join(paths[0].rstrip('/').split('/')[:-1]) or '/'
new_path = f"{parent}/{new_name}".replace("'", "'\\''")
success, err = run_cmd(f"mv '{old_path}' '{new_path}'")
if not success:
return {"success": False, "error": f"Failed to rename: {err}"}
return {"success": True}
elif operation == 'zip':
if not paths:
return {"success": False, "error": "No files selected"}
# Determine output path (in same directory as first file)
first_path = paths[0].rstrip('/')
parent = '/'.join(first_path.split('/')[:-1]) or '/'
base_name = first_path.split('/')[-1]
# Check if zip is available, else use tar
check_zip = "which zip > /dev/null 2>&1 && echo 'zip' || echo 'tar'"
if is_host:
result = subprocess.run(check_zip, shell=True, capture_output=True, text=True)
use_zip = 'zip' in result.stdout
else:
result = subprocess.run(
["ssh", "-o", "StrictHostKeyChecking=no", "-p", str(port), f"{user}@{ip}", check_zip],
capture_output=True, text=True, timeout=10
)
use_zip = 'zip' in result.stdout
if len(paths) == 1:
archive_name = f"{base_name}.zip" if use_zip else f"{base_name}.tar.gz"
else:
archive_name = f"archive_{int(time.time())}.zip" if use_zip else f"archive_{int(time.time())}.tar.gz"
archive_path = f"{parent}/{archive_name}"
# Build file list for command
file_args = ' '.join([f"'{p.replace(chr(39), chr(39)+chr(92)+chr(39)+chr(39))}'" for p in paths])
if use_zip:
# For zip, we need to be in parent dir and use relative paths
rel_names = ' '.join([f"'{p.split('/')[-1]}'" for p in paths])
cmd = f"cd '{parent}' && zip -r '{archive_name}' {rel_names}"
else:
rel_names = ' '.join([f"'{p.split('/')[-1]}'" for p in paths])
cmd = f"cd '{parent}' && tar -czf '{archive_name}' {rel_names}"
success, err = run_cmd(cmd)
if not success:
return {"success": False, "error": f"Failed to create archive: {err}"}
return {"success": True, "archive": archive_path}
elif operation in ('copy', 'move'):
if not dest_device or not dest_path:
return {"success": False, "error": "Destination required"}
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)
if not dest_is_host and not dest_user:
return {"success": False, "error": "Destination SSH not configured"}
for src_path in paths:
safe_src = src_path.replace("'", "'\\''")
safe_dest = dest_path.replace("'", "'\\''")
# Determine rsync source and destination
if is_host and dest_is_host:
# Local to local
rsync_cmd = f"rsync -a '{safe_src}' '{safe_dest}/'"
success, err = run_local(rsync_cmd)
elif is_host and not dest_is_host:
# Local to remote
rsync_cmd = f"rsync -a -e 'ssh -o StrictHostKeyChecking=no -p {dest_port}' '{safe_src}' {dest_user}@{dest_ip}:'{safe_dest}/'"
success, err = run_local(rsync_cmd)
elif not is_host and dest_is_host:
# Remote to local
rsync_cmd = f"rsync -a -e 'ssh -o StrictHostKeyChecking=no -p {port}' {user}@{ip}:'{safe_src}' '{safe_dest}/'"
success, err = run_local(rsync_cmd)
else:
# Remote to remote - copy through host
# First copy to temp, then to dest
temp_path = f"/tmp/deq_transfer_{int(time.time())}"
rsync_cmd1 = f"rsync -a -e 'ssh -o StrictHostKeyChecking=no -p {port}' {user}@{ip}:'{safe_src}' '{temp_path}/'"
success, err = run_local(rsync_cmd1)
if success:
src_name = src_path.rstrip('/').split('/')[-1]
rsync_cmd2 = f"rsync -a -e 'ssh -o StrictHostKeyChecking=no -p {dest_port}' '{temp_path}/{src_name}' {dest_user}@{dest_ip}:'{safe_dest}/'"
success, err = run_local(rsync_cmd2)
run_local(f"rm -rf '{temp_path}'")
if not success:
return {"success": False, "error": f"Failed to {operation} {src_path}: {err}"}
# For move, delete source after successful copy
if operation == 'move':
del_success, del_err = run_cmd(f"rm -rf '{safe_src}'")
if not del_success:
return {"success": False, "error": f"Copied but failed to delete source: {del_err}"}
return {"success": True}
else:
return {"success": False, "error": f"Unknown operation: {operation}"}
except subprocess.TimeoutExpired:
return {"success": False, "error": "Operation timeout"}
except Exception as e:
return {"success": False, "error": str(e)}
def get_file_for_download(device, file_path):
"""Get file content for download. Returns (content_bytes, filename, error)."""
try:
if device.get('is_host'):
if not os.path.isfile(file_path):
return None, None, "Not a file"
with open(file_path, 'rb') as f:
content = f.read()
filename = os.path.basename(file_path)
return content, filename, None
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, None, "SSH not configured"
# Use cat to get file content
result = subprocess.run(
["ssh", "-o", "StrictHostKeyChecking=no", "-p", str(port),
f"{user}@{ip}", f"cat '{file_path}'"],
capture_output=True, timeout=60
)
if result.returncode != 0:
return None, None, "Failed to read file"
filename = file_path.rstrip('/').split('/')[-1]
return result.stdout, filename, None
except subprocess.TimeoutExpired:
return None, None, "Timeout"
except Exception as e:
return None, None, str(e)
def upload_file(device, dest_path, filename, content):
"""Upload file content to device. Returns {"success": bool, "error": str}."""
try:
full_path = os.path.join(dest_path, filename)
if device.get('is_host'):
# Direct write for host
with open(full_path, 'wb') as f:
f.write(content)
return {"success": True}
else:
# Remote: write temp file, then SCP
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"}
# Write to temp file
import tempfile
with tempfile.NamedTemporaryFile(delete=False) as tmp:
tmp.write(content)
tmp_path = tmp.name
try:
# SCP to remote
result = subprocess.run(
["scp", "-o", "StrictHostKeyChecking=no", "-P", str(port),
tmp_path, f"{user}@{ip}:{full_path}"],
capture_output=True, timeout=600
)
if result.returncode != 0:
return {"success": False, "error": result.stderr.decode().strip() or "SCP failed"}
return {"success": True}
finally:
os.unlink(tmp_path)
except Exception as e:
return {"success": False, "error": str(e)}
# === DEVICE OPERATIONS ===
def ping_host(ip, timeout=1):
try:
result = subprocess.run(
["ping", "-c", "1", "-W", str(timeout), ip],
capture_output=True, timeout=timeout + 2
)
return result.returncode == 0
except:
return False
def send_wol(mac, broadcast="255.255.255.255"):
try:
mac = mac.replace(":", "").replace("-", "").upper()
if len(mac) != 12:
return {"success": False, "error": "Invalid MAC address"}
magic = b'\xff' * 6 + bytes.fromhex(mac) * 16
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
sock.sendto(magic, (broadcast, 9))
sock.close()
return {"success": True}
except Exception as e:
return {"success": False, "error": str(e)}
def docker_action(container, action):
try:
if action == "status":
result = subprocess.run(
["docker", "inspect", "-f", "{{.State.Status}}", container],
capture_output=True, text=True, timeout=10
)
if result.returncode == 0:
status = result.stdout.strip()
return {"success": True, "status": status, "running": status == "running"}
return {"success": False, "error": "Container not found"}
elif action in ["start", "stop"]:
result = subprocess.run(
["docker", action, container],
capture_output=True, text=True, timeout=60
)
if result.returncode == 0:
return {"success": True}
return {"success": False, "error": result.stderr.strip()[:100] if result.stderr else f"docker {action} failed"}
except Exception as e:
return {"success": False, "error": str(e)}
def ssh_shutdown(ip, user, port=22):
try:
result = subprocess.run(
["ssh", "-o", "StrictHostKeyChecking=no", "-o", "ConnectTimeout=5",
"-p", str(port), f"{user}@{ip}", "sudo", "shutdown", "-h", "now"],
capture_output=True, text=True, timeout=30
)
return {"success": True}
except subprocess.TimeoutExpired:
return {"success": True} # Expected - shutdown kills connection
except Exception as e:
return {"success": False, "error": str(e)}
# === HTML TEMPLATE ===
HTML_PAGE = '''<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
<meta name="mobile-web-app-capable" content="yes">
<meta name="theme-color" content="#0a0a0f">
<meta name="application-name" content="DeQ">
<meta name="apple-mobile-web-app-title" content="DeQ">
<title>DeQ</title>
<link rel="manifest" href="/manifest.json">
<link rel="icon" type="image/svg+xml" href="/icon.svg">
<link rel="apple-touch-icon" href="/icon.svg">
<style>
@font-face {
font-family: 'JetBrains Mono';
src: url('/fonts/JetBrainsMono-Regular.woff2') format('woff2');
font-weight: 400;
font-style: normal;
}
@font-face {
font-family: 'JetBrains Mono';
src: url('/fonts/JetBrainsMono-Medium.woff2') format('woff2');
font-weight: 500;
font-style: normal;
}
:root {
--bg-primary: #0a0a0f;
--bg-secondary: #12121a;
--bg-tertiary: #1a1a24;
--border: #2a2a3a;
--text-primary: #e0e0e0;
--text-secondary: #808090;
--accent: #2ed573;
--accent-muted: rgba(46, 213, 115, 0.6);
--danger: #ff4757;
--danger-muted: rgba(255, 71, 87, 0.6);
--warning: #ffa502;
}
* { box-sizing: border-box; margin: 0; padding: 0; }
body {
font-family: 'JetBrains Mono', 'SF Mono', Consolas, monospace;
background: var(--bg-primary);
color: var(--text-primary);
min-height: 100vh;
padding: 24px;
font-size: 13px;
line-height: 1.5;
}
.container {
max-width: 800px;
margin: 0 auto;
}
/* Header */
.header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 32px;
}
.logo {
display: flex;
align-items: center;
padding: 8px;
}
.logo svg {
width: 38px;
height: 38px;
}
.header-actions {
display: flex;
gap: 12px;
align-items: center;
}
.icon-btn {
background: none;
border: none;
color: var(--text-secondary);
cursor: pointer;
padding: 8px;
border-radius: 6px;
transition: all 0.15s;
display: flex;
align-items: center;
justify-content: center;
}
.icon-btn:hover {
background: var(--bg-tertiary);
color: var(--text-primary);
}
.icon-btn.active {
color: var(--accent);
}
.icon-btn svg {
width: 18px;
height: 18px;
}
#files-btn svg,
#edit-toggle svg {
width: 32px;
height: 32px;
}
/* Header icon backgrounds with glass effect */
.logo,
#files-btn,
#edit-toggle {
background: var(--bg-secondary);
border-radius: 12px;
backdrop-filter: blur(var(--glass-blur, 0px));
-webkit-backdrop-filter: blur(var(--glass-blur, 0px));
border: 1px solid transparent;
transition: border-color 0.15s, box-shadow 0.15s;
}
#files-btn,
#edit-toggle {
color: var(--text-primary);
}
#files-btn:hover,
#edit-toggle:hover {
background: var(--bg-secondary);
color: var(--text-primary);
border-color: var(--accent);
box-shadow: 0 0 4px var(--accent);
}
.logo svg .icon-bg,
#files-btn svg .icon-bg,
#edit-toggle svg .icon-bg {
fill: transparent;
}
.logo svg .icon-accent,
#files-btn svg .icon-accent,
#edit-toggle svg .icon-accent {
stroke: var(--accent);
}
/* Sections */
.section {
margin-bottom: 24px;
}
/* Hidden sections: invisible normally, collapsed in edit mode */
.section-hidden {
display: none;
}
.edit-mode .section-hidden {
display: block;
opacity: 0.4;
}
.edit-mode .section-hidden > *:not(.section-header) {
display: none;
}
.section-header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 12px;
padding: 4px 8px;
border-radius: 8px;
border: 1px solid transparent;
transition: border-color 0.15s;
background: var(--bg-secondary);
}
.edit-mode .section-header {
border-color: var(--border);
background: var(--bg-secondary);
}
.section-header-left {
display: flex;
align-items: center;
gap: 8px;
}
.section-title {
font-size: 11px;
font-weight: 500;
color: var(--text-secondary);
text-transform: uppercase;
letter-spacing: 0.5px;
}
.section-add {
opacity: 0;
pointer-events: none;
transition: all 0.15s;
background: var(--bg-secondary) !important;
}
.section-add:hover {
background: var(--bg-tertiary) !important;
}
.edit-mode .section-add,
.task-add {
opacity: 1;
pointer-events: auto;
}
.edit-mode .section-add,
.edit-mode .section-add svg,
.edit-mode .layout-btn {
color: #fff;
}
.layout-btn {
font-size: 13px;
font-weight: 500;
min-width: 36px;
}
/* Links */
.links-grid {
display: flex;
flex-wrap: wrap;
gap: 8px;
}
.links-grid.layout-1-4 {
flex-direction: column;
align-items: stretch;
}
.links-grid.layout-1-4 .link-item {
justify-content: center;
}
.links-grid.layout-2-4 {
display: grid;
grid-template-columns: repeat(2, 1fr);
}
.links-grid.layout-2-4 .link-item,
.links-grid.layout-4-4 .link-item {
min-width: 0;
width: 100%;
}
.links-grid.layout-4-4 {
display: grid;
grid-template-columns: repeat(4, 1fr);
}
.edit-mode .links-grid.layout-2-4,
.edit-mode .links-grid.layout-4-4 {
overflow: visible;
padding-top: 12px;
padding-right: 12px;
}
.links-grid.layout-2-4 .link-name,
.links-grid.layout-4-4 .link-name {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
flex: 1;
min-width: 0;
}
@media (max-width: 768px) {
.links-grid.layout-4-4 {
grid-template-columns: repeat(2, 1fr);
}
}
.link-item {
background: var(--bg-secondary);
border: 1px solid var(--border);
border-radius: 8px;
padding: 12px 16px;
display: flex;
align-items: center;
gap: 10px;
cursor: pointer;
transition: all 0.15s;
text-decoration: none;
color: var(--text-primary);
position: relative;
}