-
Notifications
You must be signed in to change notification settings - Fork 25
Expand file tree
/
Copy pathapp.py
More file actions
1684 lines (1546 loc) · 53.2 KB
/
Copy pathapp.py
File metadata and controls
1684 lines (1546 loc) · 53.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
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
from __future__ import annotations
import base64
import html
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
import json
import os
import re
import shutil
import subprocess
import sys
import threading
import time
import uuid
from collections import deque
from pathlib import Path
from urllib.parse import parse_qs, unquote, urlsplit
from dotenv import load_dotenv
import requests
from task_store import (
DATA_DIR,
DOWNLOAD_DIR,
FAILED_FILE,
QUEUE_DIR,
QUEUE_FILE,
SESSION_DIR,
append_task,
apply_runtime_settings,
clear_worker_pid,
ensure_storage_dirs,
human_size,
is_cancelled,
load_processing,
load_runtime_settings,
normalize_upload_filename,
processing_task_is_active,
queue_size,
read_completed_entries,
read_failed_entries,
read_queue_tasks,
remove_queued_task,
runtime_path,
safe_filename,
mark_cancelled,
cleanup_local_file,
)
load_dotenv()
ensure_storage_dirs()
BASE_DIR = Path(__file__).resolve().parent
LOG_LINES: deque[str] = deque(maxlen=250)
STATE_LOCK = threading.Lock()
STOP_EVENT = threading.Event()
WEB_DOWNLOADS: dict[str, dict] = {}
WEB_DOWNLOAD_LOCK = threading.Lock()
def env_int(name: str, default: int) -> int:
raw = os.getenv(name, "").strip()
if not raw:
return default
try:
return int(raw)
except ValueError:
print(f"ignoring invalid integer value for {name}: {raw!r}", flush=True)
return default
DIRECT_URL_TIMEOUT = env_int("WALRUS_DIRECT_URL_TIMEOUT", 30)
DIRECT_URL_CHUNK_SIZE = 1024 * 512
MAX_FILE_BYTES = env_int("WALRUS_MAX_FILE_BYTES", 8 * 1024 * 1024 * 1024)
MIN_FREE_BYTES = env_int("WALRUS_MIN_FREE_BYTES", 512 * 1024 * 1024)
telegram_proc: subprocess.Popen | None = None
rubika_proc: subprocess.Popen | None = None
supervisor_started = False
def append_log(source: str, text: str) -> None:
line = text.rstrip()
if not line:
return
timestamp = time.strftime("%H:%M:%S")
formatted = f"[{timestamp}] {source}: {line}"
print(formatted, flush=True)
with STATE_LOCK:
LOG_LINES.append(formatted)
def decode_secret_file(env_name: str, output_path: Path) -> None:
encoded = os.getenv(env_name, "").strip()
if not encoded or output_path.exists():
return
try:
output_path.parent.mkdir(parents=True, exist_ok=True)
output_path.write_bytes(base64.b64decode(encoded))
append_log("setup", f"decoded {env_name} to {output_path.name}")
except Exception as error:
append_log("setup", f"failed to decode {env_name}: {error}")
def decode_session_secrets() -> None:
settings = load_runtime_settings()
rubika_session = runtime_path(settings["rubika_session"], SESSION_DIR)
if rubika_session.suffix == "":
rubika_session = rubika_session.with_suffix(".rp")
telegram_session = runtime_path(
os.getenv("TELEGRAM_SESSION", "walrus").strip() or "walrus",
SESSION_DIR,
)
if telegram_session.suffix == "":
telegram_session = telegram_session.with_suffix(".session")
decode_secret_file("RUBIKA_SESSION_B64", rubika_session)
decode_secret_file("TELEGRAM_SESSION_B64", telegram_session)
def stream_process_output(name: str, proc: subprocess.Popen) -> None:
if proc.stdout is None:
return
for line in proc.stdout:
append_log(name, line)
def start_process(script_name: str, name: str) -> subprocess.Popen:
env = {**os.environ, "PYTHONUNBUFFERED": "1"}
proc = subprocess.Popen(
[sys.executable, "-u", str(BASE_DIR / script_name)],
cwd=str(BASE_DIR),
env=env,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
text=True,
bufsize=1,
)
threading.Thread(target=stream_process_output, args=(name, proc), daemon=True).start()
append_log("supervisor", f"started {name} with pid {proc.pid}")
return proc
def required_env_status() -> list[str]:
checks = {
"API_ID": os.getenv("API_ID", "").strip(),
"API_HASH": os.getenv("API_HASH", "").strip(),
"BOT_TOKEN": os.getenv("BOT_TOKEN", "").strip(),
}
missing = []
for name, value in checks.items():
if not value or value == "0" or value == name or value.startswith("your_"):
missing.append(name)
return missing
def supervisor_loop() -> None:
global telegram_proc, rubika_proc
decode_session_secrets()
logged_missing: tuple[str, ...] | None = None
while not STOP_EVENT.is_set():
missing = tuple(required_env_status())
if missing:
if missing != logged_missing:
append_log("setup", f"missing required secrets: {', '.join(missing)}")
logged_missing = missing
time.sleep(5)
continue
logged_missing = None
if telegram_proc is None:
telegram_proc = start_process("telegram_bot.py", "telegram")
elif telegram_proc.poll() is not None:
append_log("telegram", f"exited with code {telegram_proc.returncode}")
telegram_proc = None
if rubika_proc is None:
rubika_proc = start_process("rubika_worker.py", "rubika")
elif rubika_proc.poll() is not None:
append_log("rubika", f"exited with code {rubika_proc.returncode}; restarting")
clear_worker_pid()
rubika_proc = None
time.sleep(2)
def ensure_supervisor() -> None:
global supervisor_started
if supervisor_started:
return
supervisor_started = True
threading.Thread(target=supervisor_loop, daemon=True).start()
def proc_label(proc: subprocess.Popen | None) -> str:
if proc is None:
return "not started"
code = proc.poll()
if code is None:
return f"running (pid {proc.pid})"
return f"stopped (exit {code})"
def interrupt_rubika_worker_for_cancel(task_id: str) -> None:
global rubika_proc
proc = rubika_proc
if proc is None or proc.poll() is not None:
return
append_log("supervisor", f"stopping rubika worker to cancel active upload id={task_id}")
proc.terminate()
try:
proc.wait(timeout=3)
except subprocess.TimeoutExpired:
append_log("supervisor", f"killing rubika worker after cancel timeout id={task_id}")
proc.kill()
try:
proc.wait(timeout=3)
except subprocess.TimeoutExpired:
append_log("supervisor", f"rubika worker did not stop after kill id={task_id}")
def storage_size(path: Path) -> int:
if not path.exists():
return 0
if path.is_file():
return path.stat().st_size
return sum(item.stat().st_size for item in path.rglob("*") if item.is_file())
def clean_old_web_downloads() -> None:
cutoff = time.time() - 10 * 60
with WEB_DOWNLOAD_LOCK:
old_task_ids = [
task_id
for task_id, item in WEB_DOWNLOADS.items()
if item.get("finished_at")
and float(item["finished_at"]) < cutoff
and item.get("status") in {"completed", "failed", "cancelled"}
]
for task_id in old_task_ids:
WEB_DOWNLOADS.pop(task_id, None)
def failed_task_by_id() -> dict[str, dict]:
failed = {}
for entry in read_failed_entries():
task = entry.get("task") or {}
task_id = task.get("task_id")
if task_id:
failed[task_id] = entry
return failed
def completed_task_by_id() -> dict[str, dict]:
completed = {}
for entry in read_completed_entries():
task = entry.get("task") or {}
task_id = task.get("task_id")
if task_id:
completed[task_id] = entry
return completed
def enrich_web_download(item: dict) -> dict:
task_id = item.get("task_id", "")
if not task_id:
return item
if item.get("cancel_requested") or is_cancelled(task_id):
item.update(
{
"status": "cancelled",
"note": item.get("note") or "Cancel requested.",
"finished_at": item.get("finished_at") or time.time(),
}
)
return item
queued = {task.get("task_id"): task for task in read_queue_tasks()}
processing = load_processing()
completed = completed_task_by_id()
failed = failed_task_by_id()
now = time.time()
if item.get("status") == "downloading":
return item
if task_id in completed:
entry = completed[task_id]
task = entry.get("task") or {}
item.update(
{
"status": "completed",
"download_percent": 100,
"upload_percent": 100,
"note": "Uploaded to Rubika.",
"file_name": task.get("file_name") or item.get("file_name"),
"size": human_size(int(task.get("file_size", 0) or 0)),
"finished_at": item.get("finished_at") or entry.get("completed_at") or now,
}
)
return item
processing_active = (
processing
and processing.get("task_id") == task_id
and processing_task_is_active(processing)
)
if processing_active:
item.update(
{
"status": "uploading",
"upload_percent": int(processing.get("upload_percent", 0) or 0),
"note": processing.get("attempt_text") or "Uploading to Rubika.",
"file_name": processing.get("file_name") or item.get("file_name"),
"size": human_size(int(processing.get("file_size", 0) or 0)),
"finished_at": None,
}
)
return item
if task_id in queued:
task = queued[task_id]
item.update(
{
"status": "queued",
"upload_percent": 0,
"note": "Waiting for Rubika worker.",
"file_name": task.get("file_name") or item.get("file_name"),
"size": human_size(int(task.get("file_size", 0) or 0)),
"finished_at": None,
}
)
return item
if task_id in failed:
entry = failed[task_id]
task = entry.get("task") or {}
item.update(
{
"status": "failed",
"upload_percent": int(task.get("upload_percent", 0) or 0),
"note": entry.get("error") or "Upload failed.",
"file_name": task.get("file_name") or item.get("file_name"),
"size": human_size(int(task.get("file_size", 0) or 0)),
"finished_at": item.get("finished_at") or now,
}
)
return item
if item.get("status") in {"queued", "uploading"}:
item.update(
{
"status": "completed",
"upload_percent": 100,
"note": "Uploaded to Rubika.",
"finished_at": item.get("finished_at") or now,
}
)
return item
def web_download_snapshot() -> list[dict]:
clean_old_web_downloads()
with WEB_DOWNLOAD_LOCK:
items = [dict(item) for item in WEB_DOWNLOADS.values()]
enriched = [enrich_web_download(item) for item in items]
with WEB_DOWNLOAD_LOCK:
for item in enriched:
task_id = item.get("task_id")
if task_id in WEB_DOWNLOADS:
WEB_DOWNLOADS[task_id].update(item)
status_order = {
"downloading": 0,
"queued": 1,
"uploading": 2,
"failed": 3,
"cancelled": 4,
"completed": 5,
}
return sorted(
enriched,
key=lambda item: (
status_order.get(str(item.get("status")), 9),
-float(item.get("started_at") or 0),
),
)
def web_task_cancel_requested(task_id: str) -> bool:
with WEB_DOWNLOAD_LOCK:
item = WEB_DOWNLOADS.get(task_id) or {}
return bool(item.get("cancel_requested"))
def update_web_download(task_id: str, **updates) -> None:
with WEB_DOWNLOAD_LOCK:
current = WEB_DOWNLOADS.setdefault(
task_id,
{
"task_id": task_id,
"status": "starting",
"file_name": "file",
"download_percent": 0,
"upload_percent": 0,
"size": "unknown",
"url": "",
"note": "",
"cancel_requested": False,
},
)
current.update(updates)
def parse_content_disposition_filename(value: str | None) -> str | None:
if not value:
return None
match = re.search(r"filename\*=UTF-8''([^;]+)", value, flags=re.IGNORECASE)
if match:
return unquote(match.group(1).strip().strip('"'))
match = re.search(r'filename="([^"]+)"', value, flags=re.IGNORECASE)
if match:
return match.group(1).strip()
match = re.search(r"filename=([^;]+)", value, flags=re.IGNORECASE)
if match:
return match.group(1).strip().strip('"')
return None
def direct_url_filename(url: str, response: requests.Response) -> str:
header_name = parse_content_disposition_filename(response.headers.get("content-disposition"))
if header_name:
return safe_filename(header_name, "download.bin")
path_name = Path(unquote(urlsplit(url).path)).name
return safe_filename(path_name or "download.bin", "download.bin")
def unique_download_path(filename: str) -> Path:
DOWNLOAD_DIR.mkdir(parents=True, exist_ok=True)
path = DOWNLOAD_DIR / filename
if not path.exists():
return path
stem = path.stem
suffix = path.suffix
for index in range(1, 1000):
candidate = DOWNLOAD_DIR / f"{stem} {index}{suffix}"
if not candidate.exists():
return candidate
return DOWNLOAD_DIR / f"{stem} {uuid.uuid4().hex[:8]}{suffix}"
def ensure_download_allowed(total_size: int | None) -> None:
if total_size and MAX_FILE_BYTES > 0 and total_size > MAX_FILE_BYTES:
raise RuntimeError(
f"File is too large ({human_size(total_size)}). Limit is {human_size(MAX_FILE_BYTES)}."
)
free_bytes = shutil.disk_usage(DATA_DIR).free
required_free = (total_size or 0) + MIN_FREE_BYTES
if total_size and free_bytes < required_free:
raise RuntimeError(
f"Not enough free storage. Need {human_size(required_free)}, have {human_size(free_bytes)}."
)
def download_url_for_upload(task_id: str, url: str) -> None:
parsed = urlsplit(url)
if parsed.scheme not in {"http", "https"}:
update_web_download(
task_id,
status="failed",
note="Only http:// and https:// URLs are supported.",
finished_at=time.time(),
)
return
started_at = time.time()
update_web_download(task_id, status="downloading", url=url, started_at=started_at)
append_log("web-url", f"started download id={task_id} url={url}")
download_path: Path | None = None
try:
if web_task_cancel_requested(task_id):
raise RuntimeError("Cancelled.")
with requests.get(url, stream=True, timeout=DIRECT_URL_TIMEOUT) as response:
response.raise_for_status()
total_size = int(response.headers.get("content-length") or 0)
ensure_download_allowed(total_size or None)
filename = normalize_upload_filename(direct_url_filename(url, response), "download.bin")
download_path = unique_download_path(filename)
downloaded = 0
update_web_download(
task_id,
file_name=filename,
size=human_size(total_size) if total_size else "unknown",
path=str(download_path),
download_percent=0,
upload_percent=0,
)
with download_path.open("wb") as file:
for chunk in response.iter_content(chunk_size=DIRECT_URL_CHUNK_SIZE):
if web_task_cancel_requested(task_id):
raise RuntimeError("Cancelled.")
if not chunk:
continue
file.write(chunk)
downloaded += len(chunk)
if MAX_FILE_BYTES > 0 and downloaded > MAX_FILE_BYTES:
raise RuntimeError(
f"File exceeded limit of {human_size(MAX_FILE_BYTES)}."
)
percent = int((downloaded * 100) / total_size) if total_size else 0
update_web_download(
task_id,
download_percent=max(0, min(100, percent)),
size=human_size(total_size or downloaded),
)
file_size = download_path.stat().st_size
task = {
"task_id": task_id,
"type": "local_file",
"path": str(download_path),
"caption": "",
"file_name": normalize_upload_filename(download_path.name, "download.bin"),
"file_size": file_size,
"media_type": "document",
"started_at": started_at,
"source": "space_ui",
"source_url": url,
}
apply_runtime_settings(task)
append_task(task)
update_web_download(
task_id,
status="queued",
download_percent=100,
upload_percent=0,
size=human_size(file_size),
note="Queued for Rubika upload.",
finished_at=None,
)
append_log("web-url", f"queued upload id={task_id} file={download_path.name}")
except Exception as error:
if download_path and download_path.exists():
try:
download_path.unlink()
except OSError:
pass
update_web_download(
task_id,
status="cancelled" if "cancelled" in str(error).lower() else "failed",
note=str(error),
finished_at=time.time(),
)
append_log("web-url", f"failed id={task_id} error={error}")
def start_web_url_download(url: str) -> str:
task_id = uuid.uuid4().hex[:10]
update_web_download(task_id, status="starting", url=url, started_at=time.time())
thread = threading.Thread(
target=download_url_for_upload,
args=(task_id, url),
daemon=True,
)
thread.start()
return task_id
def cancel_web_task(task_id: str) -> bool:
did_cancel = False
item_status = ""
with WEB_DOWNLOAD_LOCK:
item = WEB_DOWNLOADS.get(task_id)
if item:
item_status = str(item.get("status") or "")
item["cancel_requested"] = True
item["note"] = "Cancel requested."
did_cancel = True
if item_status in {"starting", "downloading"}:
item["status"] = "cancelled"
item["finished_at"] = time.time()
queued_task = remove_queued_task(task_id)
if queued_task:
cleanup_local_file(queued_task.get("path", ""))
update_web_download(
task_id,
status="cancelled",
note="Removed from upload queue.",
finished_at=time.time(),
)
did_cancel = True
processing = load_processing()
if processing and processing.get("task_id") == task_id:
mark_cancelled(task_id)
interrupt_rubika_worker_for_cancel(task_id)
update_web_download(
task_id,
status="cancelled",
note="Active upload stopped.",
finished_at=time.time(),
)
did_cancel = True
elif not queued_task and item_status in {"queued", "uploading"}:
mark_cancelled(task_id)
update_web_download(
task_id,
status="cancelled",
note="Cancel requested before upload started.",
finished_at=time.time(),
)
did_cancel = True
if did_cancel:
append_log("web-url", f"cancel requested id={task_id}")
return did_cancel
def clear_web_tasks() -> int:
web_download_snapshot()
with WEB_DOWNLOAD_LOCK:
removable = [
task_id
for task_id, item in WEB_DOWNLOADS.items()
if item.get("status") in {"completed", "failed", "cancelled"}
]
for task_id in removable:
WEB_DOWNLOADS.pop(task_id, None)
append_log("web-url", f"cleared {len(removable)} web transfer item(s)")
return len(removable)
def dashboard_snapshot() -> dict:
ensure_supervisor()
settings = load_runtime_settings()
processing = load_processing()
completed = completed_task_by_id()
failed_count = len(read_failed_entries()) if FAILED_FILE.exists() else 0
queue_count = queue_size() if QUEUE_FILE.exists() else 0
web_downloads = web_download_snapshot()
upload_percent = 0
active = "none"
stale_processing = bool(
processing
and (
not processing_task_is_active(processing)
or is_cancelled(processing.get("task_id", ""))
or processing.get("task_id", "") in completed
)
)
if processing and not stale_processing:
upload_percent = int(processing.get("upload_percent", 0) or 0)
active = (
f"{processing.get('file_name') or Path(processing.get('path', '')).name} "
f"({upload_percent}%)"
)
missing = required_env_status()
config_text = "ok" if not missing else f"missing {', '.join(missing)}"
telegram_label = proc_label(telegram_proc)
rubika_label = proc_label(rubika_proc)
runtime_storage = (
storage_size(DOWNLOAD_DIR)
+ storage_size(QUEUE_DIR)
+ storage_size(SESSION_DIR)
)
status = "\n".join(
[
f"Telegram bot: {telegram_label}",
f"Rubika worker: {rubika_label}",
f"Config: {config_text}",
f"Rubika session: {settings['rubika_session']}",
f"Destination: {settings['rubika_target_title']} ({settings['rubika_target']})",
f"Data dir: {DATA_DIR}",
f"Queue: {queue_count}",
f"Active upload: {active}",
f"Stale upload state: {'yes, run /cleanup confirm' if stale_processing else 'no'}",
f"Failed transfers: {failed_count}",
f"Runtime storage: {human_size(runtime_storage)}",
]
)
with STATE_LOCK:
logs = "\n".join(LOG_LINES) or "No logs yet."
return {
"status": status,
"logs": logs,
"updated_at": time.strftime("%H:%M:%S"),
"metrics": {
"telegram": telegram_label,
"rubika": rubika_label,
"config": config_text,
"rubika_session": settings["rubika_session"],
"destination": f"{settings['rubika_target_title']} ({settings['rubika_target']})",
"data_dir": str(DATA_DIR),
"queue": queue_count,
"active_upload": active,
"failed": failed_count,
"runtime_storage": human_size(runtime_storage),
"upload_percent": upload_percent,
"stale_processing": stale_processing,
"web_downloads": web_downloads,
},
}
def dashboard_text() -> tuple[str, str]:
snapshot = dashboard_snapshot()
return snapshot["status"], snapshot["logs"]
def dashboard_payload() -> dict:
return dashboard_snapshot()
def render_dashboard() -> bytes:
payload = dashboard_payload()
page = f"""<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>WalrusHF</title>
<style>
:root {{
color-scheme: dark;
--bg: #080808;
--bg-2: #11110f;
--panel: rgba(18, 18, 16, 0.88);
--panel-strong: rgba(22, 22, 19, 0.96);
--line: rgba(255, 255, 255, 0.13);
--line-strong: rgba(255, 255, 255, 0.26);
--text: #f5f2e8;
--muted: #9b9a91;
--accent: #ff7a18;
--accent-2: #f5f2e8;
--danger: #ff7a7a;
--warn: #ffb84d;
--glow: rgba(255, 122, 24, 0.28);
--shadow: 0 26px 90px rgba(0, 0, 0, 0.48);
}}
* {{
box-sizing: border-box;
}}
body {{
margin: 0;
min-height: 100vh;
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
font-feature-settings: "cv02", "cv03", "cv04", "cv11";
background:
radial-gradient(circle at 12% 7%, rgba(255, 122, 24, 0.14), transparent 27rem),
radial-gradient(circle at 86% 0%, rgba(245, 242, 232, 0.08), transparent 29rem),
linear-gradient(135deg, var(--bg), var(--bg-2) 48%, #0b0b09);
color: var(--text);
}}
body::before {{
content: "";
position: fixed;
inset: 0;
pointer-events: none;
background-image:
linear-gradient(rgba(255, 255, 255, 0.045) 1px, transparent 1px),
linear-gradient(90deg, rgba(255, 255, 255, 0.035) 1px, transparent 1px),
radial-gradient(circle, rgba(255,255,255,0.08) 1px, transparent 1.4px);
background-size: 34px 34px;
background-position: 0 0, 0 0, 0 0;
mask-image: linear-gradient(to bottom, rgba(0,0,0,0.85), transparent 78%);
}}
body::after {{
content: "";
position: fixed;
inset: 0;
pointer-events: none;
background:
repeating-linear-gradient(0deg, rgba(255,255,255,0.035) 0 1px, transparent 1px 4px),
linear-gradient(180deg, transparent, rgba(255, 122, 24, 0.035), transparent);
background-size: 100% 220px;
animation: scan 7s linear infinite;
opacity: 0.4;
}}
@keyframes scan {{
from {{ background-position: 0 -220px; }}
to {{ background-position: 0 100vh; }}
}}
main {{
position: relative;
max-width: 1180px;
margin: 0 auto;
padding: 28px 20px 46px;
}}
.hero {{
position: relative;
display: grid;
grid-template-columns: auto 1fr auto;
align-items: center;
gap: 22px;
min-height: 168px;
padding: 18px 28px 30px;
border: 1px solid var(--line-strong);
border-radius: 8px;
background:
linear-gradient(135deg, rgba(17, 17, 15, 0.98), rgba(9, 9, 8, 0.86)),
repeating-linear-gradient(120deg, rgba(255,255,255,0.035) 0 1px, transparent 1px 18px);
box-shadow: var(--shadow);
overflow: hidden;
}}
.hero::before {{
content: "";
position: absolute;
inset: 0;
border-radius: inherit;
background:
linear-gradient(90deg, transparent, rgba(255, 122, 24, 0.11), transparent),
linear-gradient(180deg, rgba(255,255,255,0.04), transparent 35%);
transform: translateX(-68%);
animation: sweep 8s ease-in-out infinite;
pointer-events: none;
}}
.hero::after {{
content: "";
position: absolute;
width: 360px;
height: 360px;
right: max(-120px, -9vw);
top: -145px;
border: 1px solid rgba(255, 122, 24, 0.16);
border-radius: 8px;
box-shadow:
inset 0 0 0 36px rgba(255, 122, 24, 0.018),
0 0 80px rgba(255, 122, 24, 0.08);
pointer-events: none;
transform: rotate(18deg);
}}
@keyframes sweep {{
0%, 54% {{ transform: translateX(-75%); opacity: 0; }}
64% {{ opacity: 1; }}
100% {{ transform: translateX(82%); opacity: 0; }}
}}
.chrome {{
position: relative;
z-index: 1;
grid-column: 1 / -1;
display: flex;
align-items: center;
gap: 8px;
min-height: 24px;
margin: -4px -10px 10px;
padding: 0 0 13px;
border-bottom: 1px solid rgba(255,255,255,0.12);
}}
.chrome span {{
width: 9px;
height: 9px;
border-radius: 50%;
background: var(--accent);
box-shadow: 17px 0 #f5f2e8, 34px 0 #74736b;
}}
.chrome b {{
margin-left: auto;
color: #6f6e67;
font-family: "SF Mono", "Cascadia Code", ui-monospace, Menlo, Consolas, monospace;
font-size: 10px;
font-weight: 700;
letter-spacing: 0.12em;
text-transform: uppercase;
}}
.mark {{
position: relative;
z-index: 1;
display: grid;
place-items: center;
width: 78px;
height: 78px;
border: 1px solid rgba(255, 122, 24, 0.48);
border-radius: 8px;
background:
radial-gradient(circle at 50% 42%, rgba(255, 122, 24, 0.16), transparent 58%),
linear-gradient(145deg, rgba(255, 122, 24, 0.13), rgba(255, 255, 255, 0.04));
font-size: 38px;
box-shadow:
0 0 28px rgba(255, 122, 24, 0.18),
inset 0 0 22px rgba(255, 122, 24, 0.08);
}}
.kicker {{
margin: 0 0 7px;
color: var(--accent);
font-size: 11px;
font-weight: 760;
letter-spacing: 0.18em;
text-transform: uppercase;
}}
h1 {{
margin: 0 0 8px;
font-size: clamp(42px, 6.8vw, 74px);
line-height: 0.95;
font-weight: 860;
letter-spacing: -0.035em;
text-shadow: 0 0 28px rgba(255, 122, 24, 0.08);
}}
p {{
color: var(--muted);
margin: 0;
max-width: 660px;
line-height: 1.6;
}}
.live {{
position: relative;
z-index: 1;
display: flex;
align-items: center;
gap: 9px;
flex: 0 0 auto;
align-self: start;
color: var(--text);
border: 1px solid rgba(255, 122, 24, 0.38);
border-radius: 8px;
padding: 10px 12px;
background: rgba(255, 122, 24, 0.08);
font-size: 12px;
font-weight: 800;
text-transform: uppercase;
}}
.live::before {{
content: "";
width: 8px;
height: 8px;
border-radius: 50%;
background: var(--accent);
box-shadow: 0 0 18px var(--accent);
}}
.live[data-state="stale"] {{
color: var(--warn);
border-color: rgba(246, 198, 106, 0.35);
background: rgba(246, 198, 106, 0.08);
}}
.live[data-state="stale"]::before {{
background: var(--warn);
box-shadow: 0 0 18px var(--warn);
}}
.status-grid {{
display: grid;
grid-template-columns: repeat(4, minmax(0, 1fr));
gap: 12px;
margin: 16px 0;
}}
.url-panel {{
position: relative;
margin: 16px 0;
padding: 16px;
border: 1px solid var(--line);
border-radius: 8px;
background:
linear-gradient(135deg, rgba(255, 122, 24, 0.08), transparent 44%),
var(--panel);
box-shadow: 0 12px 42px rgba(0, 0, 0, 0.24);
backdrop-filter: blur(12px);
overflow: hidden;
}}
.url-panel::before {{
content: "";
position: absolute;
inset: 0;
pointer-events: none;
background:
linear-gradient(90deg, rgba(255,255,255,0.05), transparent 38%),
repeating-linear-gradient(90deg, rgba(255,255,255,0.025) 0 1px, transparent 1px 18px);
}}
.url-panel h2 {{
position: relative;
padding: 0;
border-bottom: 0;
background: transparent;
}}
.url-form {{
position: relative;
display: grid;
grid-template-columns: minmax(0, 1fr) auto;
gap: 10px;