Spaces:
Paused
Paused
Update backend/main.py
Browse files- backend/main.py +215 -150
backend/main.py
CHANGED
|
@@ -1,6 +1,6 @@
|
|
| 1 |
"""
|
| 2 |
TreyOS Backend β FastAPI
|
| 3 |
-
Real Linux filesystem, WebSocket terminal, system stats
|
| 4 |
"""
|
| 5 |
|
| 6 |
import asyncio
|
|
@@ -12,16 +12,15 @@ import subprocess
|
|
| 12 |
import time
|
| 13 |
from datetime import datetime
|
| 14 |
from pathlib import Path
|
| 15 |
-
from typing import Optional
|
| 16 |
|
| 17 |
import psutil
|
| 18 |
-
from fastapi import FastAPI, WebSocket, WebSocketDisconnect, HTTPException, UploadFile, File
|
| 19 |
from fastapi.middleware.cors import CORSMiddleware
|
| 20 |
from fastapi.responses import FileResponse, JSONResponse
|
| 21 |
from fastapi.staticfiles import StaticFiles
|
| 22 |
from watchfiles import awatch
|
| 23 |
|
| 24 |
-
app = FastAPI(title="TreyOS", version="1.0.0"
|
| 25 |
|
| 26 |
app.add_middleware(
|
| 27 |
CORSMiddleware,
|
|
@@ -31,19 +30,26 @@ app.add_middleware(
|
|
| 31 |
allow_headers=["*"],
|
| 32 |
)
|
| 33 |
|
| 34 |
-
# ββ
|
| 35 |
-
|
| 36 |
-
|
|
|
|
| 37 |
|
| 38 |
def safe_path(requested: str) -> Path:
|
| 39 |
-
"""Resolve path
|
| 40 |
-
|
| 41 |
-
if
|
| 42 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 43 |
return p
|
| 44 |
|
| 45 |
def entry_info(p: Path) -> dict:
|
| 46 |
-
"""Return metadata dict for a filesystem entry."""
|
| 47 |
try:
|
| 48 |
s = p.stat()
|
| 49 |
return {
|
|
@@ -55,27 +61,27 @@ def entry_info(p: Path) -> dict:
|
|
| 55 |
"permissions": oct(stat.S_IMODE(s.st_mode)),
|
| 56 |
"extension": p.suffix.lower() if p.is_file() else None,
|
| 57 |
}
|
| 58 |
-
except PermissionError:
|
| 59 |
-
return {"name": p.name, "path": str(p), "type": "unknown",
|
|
|
|
| 60 |
|
| 61 |
|
| 62 |
# ββ Filesystem API ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 63 |
|
| 64 |
@app.get("/api/files")
|
| 65 |
async def list_files(path: str = "/", show_hidden: bool = False):
|
| 66 |
-
"""List directory contents."""
|
| 67 |
p = safe_path(path)
|
| 68 |
if not p.exists():
|
| 69 |
raise HTTPException(404, f"Path not found: {path}")
|
| 70 |
if not p.is_dir():
|
| 71 |
-
raise HTTPException(400, "
|
| 72 |
try:
|
| 73 |
entries = sorted(p.iterdir(), key=lambda x: (not x.is_dir(), x.name.lower()))
|
| 74 |
if not show_hidden:
|
| 75 |
entries = [e for e in entries if not e.name.startswith(".")]
|
| 76 |
return {
|
| 77 |
"path": str(p),
|
| 78 |
-
"parent": str(p.parent) if p !=
|
| 79 |
"entries": [entry_info(e) for e in entries],
|
| 80 |
"count": len(entries),
|
| 81 |
}
|
|
@@ -85,7 +91,6 @@ async def list_files(path: str = "/", show_hidden: bool = False):
|
|
| 85 |
|
| 86 |
@app.get("/api/files/read")
|
| 87 |
async def read_file(path: str):
|
| 88 |
-
"""Read a text file."""
|
| 89 |
p = safe_path(path)
|
| 90 |
if not p.is_file():
|
| 91 |
raise HTTPException(404, "File not found")
|
|
@@ -96,17 +101,15 @@ async def read_file(path: str):
|
|
| 96 |
|
| 97 |
|
| 98 |
@app.post("/api/files/write")
|
| 99 |
-
async def write_file(path: str, content: str):
|
| 100 |
-
"""Write content to a file."""
|
| 101 |
p = safe_path(path)
|
| 102 |
p.parent.mkdir(parents=True, exist_ok=True)
|
| 103 |
p.write_text(content)
|
| 104 |
-
return {"ok": True, "path": str(p)}
|
| 105 |
|
| 106 |
|
| 107 |
@app.post("/api/files/mkdir")
|
| 108 |
async def make_dir(path: str):
|
| 109 |
-
"""Create a directory."""
|
| 110 |
p = safe_path(path)
|
| 111 |
p.mkdir(parents=True, exist_ok=True)
|
| 112 |
return {"ok": True, "path": str(p)}
|
|
@@ -114,7 +117,6 @@ async def make_dir(path: str):
|
|
| 114 |
|
| 115 |
@app.delete("/api/files/delete")
|
| 116 |
async def delete_entry(path: str):
|
| 117 |
-
"""Delete a file or directory."""
|
| 118 |
p = safe_path(path)
|
| 119 |
if not p.exists():
|
| 120 |
raise HTTPException(404, "Not found")
|
|
@@ -127,7 +129,6 @@ async def delete_entry(path: str):
|
|
| 127 |
|
| 128 |
@app.post("/api/files/rename")
|
| 129 |
async def rename_entry(path: str, new_name: str):
|
| 130 |
-
"""Rename a file or directory."""
|
| 131 |
p = safe_path(path)
|
| 132 |
dest = p.parent / new_name
|
| 133 |
p.rename(dest)
|
|
@@ -136,28 +137,20 @@ async def rename_entry(path: str, new_name: str):
|
|
| 136 |
|
| 137 |
@app.post("/api/files/copy")
|
| 138 |
async def copy_entry(src: str, dst: str):
|
| 139 |
-
|
| 140 |
-
s
|
| 141 |
-
d = safe_path(dst)
|
| 142 |
-
if s.is_dir():
|
| 143 |
-
shutil.copytree(s, d)
|
| 144 |
-
else:
|
| 145 |
-
shutil.copy2(s, d)
|
| 146 |
return {"ok": True, "destination": str(d)}
|
| 147 |
|
| 148 |
|
| 149 |
@app.post("/api/files/move")
|
| 150 |
async def move_entry(src: str, dst: str):
|
| 151 |
-
|
| 152 |
-
s = safe_path(src)
|
| 153 |
-
d = safe_path(dst)
|
| 154 |
shutil.move(str(s), str(d))
|
| 155 |
return {"ok": True, "destination": str(d)}
|
| 156 |
|
| 157 |
|
| 158 |
@app.post("/api/files/upload")
|
| 159 |
async def upload_file(path: str, file: UploadFile = File(...)):
|
| 160 |
-
"""Upload a file to the given directory."""
|
| 161 |
dest = safe_path(path) / file.filename
|
| 162 |
dest.parent.mkdir(parents=True, exist_ok=True)
|
| 163 |
with open(dest, "wb") as f:
|
|
@@ -167,16 +160,14 @@ async def upload_file(path: str, file: UploadFile = File(...)):
|
|
| 167 |
|
| 168 |
@app.get("/api/files/download")
|
| 169 |
async def download_file(path: str):
|
| 170 |
-
"""Download a file."""
|
| 171 |
p = safe_path(path)
|
| 172 |
if not p.is_file():
|
| 173 |
raise HTTPException(404, "File not found")
|
| 174 |
-
return FileResponse(p, filename=p.name)
|
| 175 |
|
| 176 |
|
| 177 |
@app.get("/api/files/search")
|
| 178 |
async def search_files(path: str = "/", query: str = "", limit: int = 50):
|
| 179 |
-
"""Search for files by name."""
|
| 180 |
p = safe_path(path)
|
| 181 |
results = []
|
| 182 |
try:
|
|
@@ -184,7 +175,7 @@ async def search_files(path: str = "/", query: str = "", limit: int = 50):
|
|
| 184 |
results.append(entry_info(entry))
|
| 185 |
if len(results) >= limit:
|
| 186 |
break
|
| 187 |
-
except PermissionError:
|
| 188 |
pass
|
| 189 |
return {"query": query, "results": results, "count": len(results)}
|
| 190 |
|
|
@@ -193,37 +184,22 @@ async def search_files(path: str = "/", query: str = "", limit: int = 50):
|
|
| 193 |
|
| 194 |
@app.get("/api/system")
|
| 195 |
async def system_stats():
|
| 196 |
-
"""Return live system statistics."""
|
| 197 |
disk = psutil.disk_usage("/")
|
| 198 |
-
net
|
| 199 |
-
boot = datetime.fromtimestamp(psutil.boot_time())
|
| 200 |
uptime_s = int(time.time() - psutil.boot_time())
|
| 201 |
h, r = divmod(uptime_s, 3600)
|
| 202 |
m = r // 60
|
| 203 |
-
|
| 204 |
return {
|
| 205 |
-
"cpu":
|
| 206 |
-
|
| 207 |
-
|
| 208 |
-
|
| 209 |
-
|
| 210 |
-
"
|
| 211 |
-
|
| 212 |
-
|
| 213 |
-
"percent": psutil.virtual_memory().percent,
|
| 214 |
-
},
|
| 215 |
-
"disk": {
|
| 216 |
-
"total_gb": round(disk.total / 1e9, 1),
|
| 217 |
-
"used_gb": round(disk.used / 1e9, 1),
|
| 218 |
-
"free_gb": round(disk.free / 1e9, 1),
|
| 219 |
-
"percent": disk.percent,
|
| 220 |
-
},
|
| 221 |
-
"network": {
|
| 222 |
-
"bytes_sent_mb": round(net.bytes_sent / 1e6, 1),
|
| 223 |
-
"bytes_recv_mb": round(net.bytes_recv / 1e6, 1),
|
| 224 |
-
},
|
| 225 |
"uptime": f"{h}h {m}m",
|
| 226 |
-
"boot_time":
|
| 227 |
"hostname": os.uname().nodename,
|
| 228 |
"os": f"{os.uname().sysname} {os.uname().release}",
|
| 229 |
}
|
|
@@ -231,13 +207,10 @@ async def system_stats():
|
|
| 231 |
|
| 232 |
@app.get("/api/processes")
|
| 233 |
async def list_processes(limit: int = 20):
|
| 234 |
-
"""Return top processes by CPU usage."""
|
| 235 |
procs = []
|
| 236 |
-
for p in psutil.process_iter(["pid",
|
| 237 |
-
try:
|
| 238 |
-
|
| 239 |
-
except (psutil.NoSuchProcess, psutil.AccessDenied):
|
| 240 |
-
pass
|
| 241 |
procs.sort(key=lambda x: x.get("cpu_percent", 0), reverse=True)
|
| 242 |
return {"processes": procs[:limit]}
|
| 243 |
|
|
@@ -246,163 +219,255 @@ async def list_processes(limit: int = 20):
|
|
| 246 |
|
| 247 |
class TerminalSession:
|
| 248 |
def __init__(self, cwd: str = "/"):
|
| 249 |
-
self.cwd = cwd
|
| 250 |
self.env = {**os.environ, "TERM": "xterm-256color"}
|
| 251 |
|
| 252 |
async def run(self, command: str, ws: WebSocket):
|
| 253 |
-
|
| 254 |
-
#
|
| 255 |
-
if
|
| 256 |
-
target =
|
| 257 |
new_cwd = str((Path(self.cwd) / target).resolve())
|
| 258 |
if os.path.isdir(new_cwd):
|
| 259 |
self.cwd = new_cwd
|
| 260 |
-
await ws.send_json({"type": "output", "data": f"\r\n", "cwd": self.cwd})
|
| 261 |
else:
|
| 262 |
-
await ws.send_json({"type":
|
| 263 |
-
await ws.send_json({"type":
|
| 264 |
return
|
| 265 |
-
|
| 266 |
try:
|
| 267 |
proc = await asyncio.create_subprocess_shell(
|
| 268 |
-
|
| 269 |
stdout=asyncio.subprocess.PIPE,
|
| 270 |
stderr=asyncio.subprocess.STDOUT,
|
| 271 |
-
cwd=self.cwd,
|
| 272 |
-
env=self.env,
|
| 273 |
)
|
| 274 |
async for chunk in proc.stdout:
|
| 275 |
-
await ws.send_json({"type":
|
| 276 |
await proc.wait()
|
| 277 |
-
await ws.send_json({"type":
|
| 278 |
except Exception as e:
|
| 279 |
-
await ws.send_json({"type":
|
| 280 |
finally:
|
| 281 |
-
await ws.send_json({"type":
|
| 282 |
|
| 283 |
|
| 284 |
@app.websocket("/ws/terminal")
|
| 285 |
async def terminal_ws(ws: WebSocket, cwd: str = "/"):
|
| 286 |
-
"""WebSocket terminal session."""
|
| 287 |
await ws.accept()
|
| 288 |
-
|
| 289 |
-
|
| 290 |
-
|
|
|
|
|
|
|
| 291 |
try:
|
| 292 |
while True:
|
| 293 |
msg = await ws.receive_json()
|
| 294 |
if msg.get("type") == "command":
|
| 295 |
await session.run(msg["data"], ws)
|
| 296 |
elif msg.get("type") == "ping":
|
| 297 |
-
await ws.send_json({"type":
|
| 298 |
except WebSocketDisconnect:
|
| 299 |
pass
|
| 300 |
|
| 301 |
|
| 302 |
-
# ββ WebSocket Filesystem Watcher ββββββββββββββββββββββββββββββββββββββββββββββ
|
| 303 |
-
|
| 304 |
@app.websocket("/ws/watch")
|
| 305 |
async def watch_ws(ws: WebSocket, path: str = "/"):
|
| 306 |
-
"""Stream filesystem change events for a directory."""
|
| 307 |
await ws.accept()
|
| 308 |
p = safe_path(path)
|
| 309 |
-
await ws.send_json({"type":
|
| 310 |
try:
|
| 311 |
async for changes in awatch(str(p)):
|
| 312 |
events = [{"change": str(c[0].name), "path": c[1]} for c in changes]
|
| 313 |
-
await ws.send_json({"type":
|
| 314 |
except WebSocketDisconnect:
|
| 315 |
pass
|
| 316 |
-
except Exception as e:
|
| 317 |
-
await ws.send_json({"type": "error", "message": str(e)})
|
| 318 |
-
|
| 319 |
|
| 320 |
-
# ββ WebSocket System Monitor ββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 321 |
|
| 322 |
@app.websocket("/ws/system")
|
| 323 |
async def system_ws(ws: WebSocket, interval: float = 2.0):
|
| 324 |
-
"""Stream live system stats every N seconds."""
|
| 325 |
await ws.accept()
|
| 326 |
try:
|
| 327 |
while True:
|
| 328 |
stats = await system_stats()
|
| 329 |
-
await ws.send_json({"type":
|
| 330 |
-
await asyncio.sleep(interval)
|
| 331 |
except WebSocketDisconnect:
|
| 332 |
pass
|
| 333 |
|
| 334 |
|
| 335 |
-
# ββ
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 336 |
|
| 337 |
def run_docker(*args) -> dict:
|
| 338 |
try:
|
| 339 |
-
r = subprocess.run(["docker",
|
| 340 |
-
return {"ok": r.returncode
|
| 341 |
except FileNotFoundError:
|
| 342 |
-
return {"ok":
|
| 343 |
except subprocess.TimeoutExpired:
|
| 344 |
-
return {"ok":
|
| 345 |
|
| 346 |
|
| 347 |
@app.get("/api/docker/containers")
|
| 348 |
async def docker_containers():
|
| 349 |
-
r = run_docker("ps",
|
| 350 |
-
if not r["ok"]:
|
| 351 |
-
return {"containers": [], "error": r.get("error") or r.get("stderr")}
|
| 352 |
containers = []
|
| 353 |
-
for line in r
|
| 354 |
-
try:
|
| 355 |
-
|
| 356 |
-
|
| 357 |
-
pass
|
| 358 |
-
return {"containers": containers}
|
| 359 |
-
|
| 360 |
|
| 361 |
-
@app.post("/api/docker/start/{container_id}")
|
| 362 |
-
async def docker_start(container_id: str):
|
| 363 |
-
return run_docker("start", container_id)
|
| 364 |
|
|
|
|
|
|
|
| 365 |
|
| 366 |
-
@app.post("/api/docker/stop/{
|
| 367 |
-
async def docker_stop(
|
| 368 |
-
return run_docker("stop", container_id)
|
| 369 |
-
|
| 370 |
|
| 371 |
@app.get("/api/docker/images")
|
| 372 |
async def docker_images():
|
| 373 |
-
r = run_docker("images",
|
| 374 |
images = []
|
| 375 |
-
for line in r.get("stdout",
|
| 376 |
-
try:
|
| 377 |
-
|
| 378 |
-
except:
|
| 379 |
-
pass
|
| 380 |
return {"images": images}
|
| 381 |
|
| 382 |
|
| 383 |
-
# ββ Health
|
| 384 |
|
| 385 |
-
@app.get("/health")
|
| 386 |
-
async def
|
| 387 |
-
return {"status":
|
| 388 |
|
| 389 |
|
| 390 |
-
# ββ Serve
|
|
|
|
|
|
|
|
|
|
| 391 |
|
| 392 |
-
|
|
|
|
|
|
|
| 393 |
|
| 394 |
-
|
| 395 |
-
|
| 396 |
-
|
| 397 |
-
|
| 398 |
-
|
| 399 |
-
|
| 400 |
-
return root_html_path.read_text(encoding="utf-8")
|
| 401 |
-
else:
|
| 402 |
-
raise HTTPException(status_code=404, detail="TreyOS-connected.html not found in root context.")
|
| 403 |
|
|
|
|
|
|
|
|
|
|
| 404 |
|
| 405 |
-
|
| 406 |
-
|
| 407 |
-
|
| 408 |
-
|
|
|
|
|
|
| 1 |
"""
|
| 2 |
TreyOS Backend β FastAPI
|
| 3 |
+
Real Linux filesystem, WebSocket terminal, system stats, Playwright browser
|
| 4 |
"""
|
| 5 |
|
| 6 |
import asyncio
|
|
|
|
| 12 |
import time
|
| 13 |
from datetime import datetime
|
| 14 |
from pathlib import Path
|
|
|
|
| 15 |
|
| 16 |
import psutil
|
| 17 |
+
from fastapi import FastAPI, WebSocket, WebSocketDisconnect, HTTPException, UploadFile, File
|
| 18 |
from fastapi.middleware.cors import CORSMiddleware
|
| 19 |
from fastapi.responses import FileResponse, JSONResponse
|
| 20 |
from fastapi.staticfiles import StaticFiles
|
| 21 |
from watchfiles import awatch
|
| 22 |
|
| 23 |
+
app = FastAPI(title="TreyOS", version="1.0.0")
|
| 24 |
|
| 25 |
app.add_middleware(
|
| 26 |
CORSMiddleware,
|
|
|
|
| 30 |
allow_headers=["*"],
|
| 31 |
)
|
| 32 |
|
| 33 |
+
# ββ Path handling βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 34 |
+
# TREY_ROOT jails access. Default "/" means full filesystem access.
|
| 35 |
+
# The jail check is intentionally lenient β on HF the whole container is fair game.
|
| 36 |
+
ROOT_JAIL = Path(os.environ.get("TREY_ROOT", "/")).resolve()
|
| 37 |
|
| 38 |
def safe_path(requested: str) -> Path:
|
| 39 |
+
"""Resolve path. If absolute, use as-is (within jail). If relative, join to ROOT_JAIL."""
|
| 40 |
+
requested = requested.strip()
|
| 41 |
+
if requested.startswith("/"):
|
| 42 |
+
p = Path(requested).resolve()
|
| 43 |
+
else:
|
| 44 |
+
p = (ROOT_JAIL / requested).resolve()
|
| 45 |
+
# Jail check
|
| 46 |
+
try:
|
| 47 |
+
p.relative_to(ROOT_JAIL)
|
| 48 |
+
except ValueError:
|
| 49 |
+
raise HTTPException(403, f"Access denied: {p} is outside jail {ROOT_JAIL}")
|
| 50 |
return p
|
| 51 |
|
| 52 |
def entry_info(p: Path) -> dict:
|
|
|
|
| 53 |
try:
|
| 54 |
s = p.stat()
|
| 55 |
return {
|
|
|
|
| 61 |
"permissions": oct(stat.S_IMODE(s.st_mode)),
|
| 62 |
"extension": p.suffix.lower() if p.is_file() else None,
|
| 63 |
}
|
| 64 |
+
except (PermissionError, OSError):
|
| 65 |
+
return {"name": p.name, "path": str(p), "type": "unknown",
|
| 66 |
+
"size": 0, "modified": None, "permissions": None, "extension": None}
|
| 67 |
|
| 68 |
|
| 69 |
# ββ Filesystem API ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 70 |
|
| 71 |
@app.get("/api/files")
|
| 72 |
async def list_files(path: str = "/", show_hidden: bool = False):
|
|
|
|
| 73 |
p = safe_path(path)
|
| 74 |
if not p.exists():
|
| 75 |
raise HTTPException(404, f"Path not found: {path}")
|
| 76 |
if not p.is_dir():
|
| 77 |
+
raise HTTPException(400, "Not a directory")
|
| 78 |
try:
|
| 79 |
entries = sorted(p.iterdir(), key=lambda x: (not x.is_dir(), x.name.lower()))
|
| 80 |
if not show_hidden:
|
| 81 |
entries = [e for e in entries if not e.name.startswith(".")]
|
| 82 |
return {
|
| 83 |
"path": str(p),
|
| 84 |
+
"parent": str(p.parent) if str(p) != "/" else None,
|
| 85 |
"entries": [entry_info(e) for e in entries],
|
| 86 |
"count": len(entries),
|
| 87 |
}
|
|
|
|
| 91 |
|
| 92 |
@app.get("/api/files/read")
|
| 93 |
async def read_file(path: str):
|
|
|
|
| 94 |
p = safe_path(path)
|
| 95 |
if not p.is_file():
|
| 96 |
raise HTTPException(404, "File not found")
|
|
|
|
| 101 |
|
| 102 |
|
| 103 |
@app.post("/api/files/write")
|
| 104 |
+
async def write_file(path: str, content: str = ""):
|
|
|
|
| 105 |
p = safe_path(path)
|
| 106 |
p.parent.mkdir(parents=True, exist_ok=True)
|
| 107 |
p.write_text(content)
|
| 108 |
+
return {"ok": True, "path": str(p), "size": p.stat().st_size}
|
| 109 |
|
| 110 |
|
| 111 |
@app.post("/api/files/mkdir")
|
| 112 |
async def make_dir(path: str):
|
|
|
|
| 113 |
p = safe_path(path)
|
| 114 |
p.mkdir(parents=True, exist_ok=True)
|
| 115 |
return {"ok": True, "path": str(p)}
|
|
|
|
| 117 |
|
| 118 |
@app.delete("/api/files/delete")
|
| 119 |
async def delete_entry(path: str):
|
|
|
|
| 120 |
p = safe_path(path)
|
| 121 |
if not p.exists():
|
| 122 |
raise HTTPException(404, "Not found")
|
|
|
|
| 129 |
|
| 130 |
@app.post("/api/files/rename")
|
| 131 |
async def rename_entry(path: str, new_name: str):
|
|
|
|
| 132 |
p = safe_path(path)
|
| 133 |
dest = p.parent / new_name
|
| 134 |
p.rename(dest)
|
|
|
|
| 137 |
|
| 138 |
@app.post("/api/files/copy")
|
| 139 |
async def copy_entry(src: str, dst: str):
|
| 140 |
+
s, d = safe_path(src), safe_path(dst)
|
| 141 |
+
shutil.copytree(s, d) if s.is_dir() else shutil.copy2(s, d)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 142 |
return {"ok": True, "destination": str(d)}
|
| 143 |
|
| 144 |
|
| 145 |
@app.post("/api/files/move")
|
| 146 |
async def move_entry(src: str, dst: str):
|
| 147 |
+
s, d = safe_path(src), safe_path(dst)
|
|
|
|
|
|
|
| 148 |
shutil.move(str(s), str(d))
|
| 149 |
return {"ok": True, "destination": str(d)}
|
| 150 |
|
| 151 |
|
| 152 |
@app.post("/api/files/upload")
|
| 153 |
async def upload_file(path: str, file: UploadFile = File(...)):
|
|
|
|
| 154 |
dest = safe_path(path) / file.filename
|
| 155 |
dest.parent.mkdir(parents=True, exist_ok=True)
|
| 156 |
with open(dest, "wb") as f:
|
|
|
|
| 160 |
|
| 161 |
@app.get("/api/files/download")
|
| 162 |
async def download_file(path: str):
|
|
|
|
| 163 |
p = safe_path(path)
|
| 164 |
if not p.is_file():
|
| 165 |
raise HTTPException(404, "File not found")
|
| 166 |
+
return FileResponse(str(p), filename=p.name)
|
| 167 |
|
| 168 |
|
| 169 |
@app.get("/api/files/search")
|
| 170 |
async def search_files(path: str = "/", query: str = "", limit: int = 50):
|
|
|
|
| 171 |
p = safe_path(path)
|
| 172 |
results = []
|
| 173 |
try:
|
|
|
|
| 175 |
results.append(entry_info(entry))
|
| 176 |
if len(results) >= limit:
|
| 177 |
break
|
| 178 |
+
except (PermissionError, OSError):
|
| 179 |
pass
|
| 180 |
return {"query": query, "results": results, "count": len(results)}
|
| 181 |
|
|
|
|
| 184 |
|
| 185 |
@app.get("/api/system")
|
| 186 |
async def system_stats():
|
|
|
|
| 187 |
disk = psutil.disk_usage("/")
|
| 188 |
+
net = psutil.net_io_counters()
|
|
|
|
| 189 |
uptime_s = int(time.time() - psutil.boot_time())
|
| 190 |
h, r = divmod(uptime_s, 3600)
|
| 191 |
m = r // 60
|
|
|
|
| 192 |
return {
|
| 193 |
+
"cpu": {"percent": psutil.cpu_percent(interval=0.1), "cores": psutil.cpu_count(),
|
| 194 |
+
"freq_mhz": psutil.cpu_freq().current if psutil.cpu_freq() else None},
|
| 195 |
+
"memory": {"total_gb": round(psutil.virtual_memory().total/1e9,1),
|
| 196 |
+
"used_gb": round(psutil.virtual_memory().used/1e9,1),
|
| 197 |
+
"percent": psutil.virtual_memory().percent},
|
| 198 |
+
"disk": {"total_gb": round(disk.total/1e9,1), "used_gb": round(disk.used/1e9,1),
|
| 199 |
+
"free_gb": round(disk.free/1e9,1), "percent": disk.percent},
|
| 200 |
+
"network":{"bytes_sent_mb": round(net.bytes_sent/1e6,1), "bytes_recv_mb": round(net.bytes_recv/1e6,1)},
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 201 |
"uptime": f"{h}h {m}m",
|
| 202 |
+
"boot_time": datetime.fromtimestamp(psutil.boot_time()).isoformat(),
|
| 203 |
"hostname": os.uname().nodename,
|
| 204 |
"os": f"{os.uname().sysname} {os.uname().release}",
|
| 205 |
}
|
|
|
|
| 207 |
|
| 208 |
@app.get("/api/processes")
|
| 209 |
async def list_processes(limit: int = 20):
|
|
|
|
| 210 |
procs = []
|
| 211 |
+
for p in psutil.process_iter(["pid","name","cpu_percent","memory_percent","status"]):
|
| 212 |
+
try: procs.append(p.info)
|
| 213 |
+
except (psutil.NoSuchProcess, psutil.AccessDenied): pass
|
|
|
|
|
|
|
| 214 |
procs.sort(key=lambda x: x.get("cpu_percent", 0), reverse=True)
|
| 215 |
return {"processes": procs[:limit]}
|
| 216 |
|
|
|
|
| 219 |
|
| 220 |
class TerminalSession:
|
| 221 |
def __init__(self, cwd: str = "/"):
|
| 222 |
+
self.cwd = cwd if Path(cwd).is_dir() else "/"
|
| 223 |
self.env = {**os.environ, "TERM": "xterm-256color"}
|
| 224 |
|
| 225 |
async def run(self, command: str, ws: WebSocket):
|
| 226 |
+
cmd = command.strip()
|
| 227 |
+
# Handle cd internally
|
| 228 |
+
if cmd.startswith("cd"):
|
| 229 |
+
target = cmd[2:].strip() or str(Path.home())
|
| 230 |
new_cwd = str((Path(self.cwd) / target).resolve())
|
| 231 |
if os.path.isdir(new_cwd):
|
| 232 |
self.cwd = new_cwd
|
|
|
|
| 233 |
else:
|
| 234 |
+
await ws.send_json({"type":"output","data":f"cd: {target}: No such directory\r\n"})
|
| 235 |
+
await ws.send_json({"type":"prompt","cwd":self.cwd})
|
| 236 |
return
|
|
|
|
| 237 |
try:
|
| 238 |
proc = await asyncio.create_subprocess_shell(
|
| 239 |
+
cmd,
|
| 240 |
stdout=asyncio.subprocess.PIPE,
|
| 241 |
stderr=asyncio.subprocess.STDOUT,
|
| 242 |
+
cwd=self.cwd, env=self.env,
|
|
|
|
| 243 |
)
|
| 244 |
async for chunk in proc.stdout:
|
| 245 |
+
await ws.send_json({"type":"output","data":chunk.decode(errors="replace")})
|
| 246 |
await proc.wait()
|
| 247 |
+
await ws.send_json({"type":"exit","code":proc.returncode,"cwd":self.cwd})
|
| 248 |
except Exception as e:
|
| 249 |
+
await ws.send_json({"type":"error","data":str(e)})
|
| 250 |
finally:
|
| 251 |
+
await ws.send_json({"type":"prompt","cwd":self.cwd})
|
| 252 |
|
| 253 |
|
| 254 |
@app.websocket("/ws/terminal")
|
| 255 |
async def terminal_ws(ws: WebSocket, cwd: str = "/"):
|
|
|
|
| 256 |
await ws.accept()
|
| 257 |
+
# Use ROOT_JAIL as default cwd if it exists, else /
|
| 258 |
+
default_cwd = str(ROOT_JAIL) if ROOT_JAIL.is_dir() else "/"
|
| 259 |
+
session = TerminalSession(cwd=cwd if Path(cwd).is_dir() else default_cwd)
|
| 260 |
+
await ws.send_json({"type":"welcome","message":"TreyOS Terminal Ready","cwd":session.cwd})
|
| 261 |
+
await ws.send_json({"type":"prompt","cwd":session.cwd})
|
| 262 |
try:
|
| 263 |
while True:
|
| 264 |
msg = await ws.receive_json()
|
| 265 |
if msg.get("type") == "command":
|
| 266 |
await session.run(msg["data"], ws)
|
| 267 |
elif msg.get("type") == "ping":
|
| 268 |
+
await ws.send_json({"type":"pong"})
|
| 269 |
except WebSocketDisconnect:
|
| 270 |
pass
|
| 271 |
|
| 272 |
|
|
|
|
|
|
|
| 273 |
@app.websocket("/ws/watch")
|
| 274 |
async def watch_ws(ws: WebSocket, path: str = "/"):
|
|
|
|
| 275 |
await ws.accept()
|
| 276 |
p = safe_path(path)
|
| 277 |
+
await ws.send_json({"type":"watching","path":str(p)})
|
| 278 |
try:
|
| 279 |
async for changes in awatch(str(p)):
|
| 280 |
events = [{"change": str(c[0].name), "path": c[1]} for c in changes]
|
| 281 |
+
await ws.send_json({"type":"changes","events":events})
|
| 282 |
except WebSocketDisconnect:
|
| 283 |
pass
|
|
|
|
|
|
|
|
|
|
| 284 |
|
|
|
|
| 285 |
|
| 286 |
@app.websocket("/ws/system")
|
| 287 |
async def system_ws(ws: WebSocket, interval: float = 2.0):
|
|
|
|
| 288 |
await ws.accept()
|
| 289 |
try:
|
| 290 |
while True:
|
| 291 |
stats = await system_stats()
|
| 292 |
+
await ws.send_json({"type":"stats","data":stats})
|
| 293 |
+
await asyncio.sleep(max(interval, 1.0))
|
| 294 |
except WebSocketDisconnect:
|
| 295 |
pass
|
| 296 |
|
| 297 |
|
| 298 |
+
# ββ Playwright Browser Proxy ββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 299 |
+
# Streams a real Chromium screenshot as JPEG for each navigation.
|
| 300 |
+
# Install: pip install playwright && playwright install chromium
|
| 301 |
+
|
| 302 |
+
_browser = None
|
| 303 |
+
_playwright = None
|
| 304 |
+
|
| 305 |
+
async def get_browser():
|
| 306 |
+
global _browser, _playwright
|
| 307 |
+
if _browser is None:
|
| 308 |
+
try:
|
| 309 |
+
from playwright.async_api import async_playwright
|
| 310 |
+
_playwright = await async_playwright().start()
|
| 311 |
+
_browser = await _playwright.chromium.launch(
|
| 312 |
+
headless=True,
|
| 313 |
+
args=["--no-sandbox","--disable-setuid-sandbox","--disable-dev-shm-usage",
|
| 314 |
+
"--disable-gpu","--single-process"]
|
| 315 |
+
)
|
| 316 |
+
except Exception as e:
|
| 317 |
+
raise HTTPException(503, f"Playwright not available: {e}")
|
| 318 |
+
return _browser
|
| 319 |
+
|
| 320 |
+
|
| 321 |
+
@app.get("/api/browser/screenshot")
|
| 322 |
+
async def browser_screenshot(url: str, width: int = 390, height: int = 700):
|
| 323 |
+
"""Take a screenshot of a URL and return it as JPEG."""
|
| 324 |
+
if not url.startswith(("http://","https://")):
|
| 325 |
+
url = "https://" + url
|
| 326 |
+
try:
|
| 327 |
+
browser = await get_browser()
|
| 328 |
+
page = await browser.new_page(viewport={"width": width, "height": height})
|
| 329 |
+
await page.goto(url, wait_until="domcontentloaded", timeout=20000)
|
| 330 |
+
screenshot = await page.screenshot(type="jpeg", quality=80, full_page=False)
|
| 331 |
+
await page.close()
|
| 332 |
+
from fastapi.responses import Response
|
| 333 |
+
return Response(content=screenshot, media_type="image/jpeg",
|
| 334 |
+
headers={"X-Final-URL": page.url if not page.is_closed() else url})
|
| 335 |
+
except HTTPException:
|
| 336 |
+
raise
|
| 337 |
+
except Exception as e:
|
| 338 |
+
raise HTTPException(502, f"Browser error: {e}")
|
| 339 |
+
|
| 340 |
+
|
| 341 |
+
@app.websocket("/ws/browser")
|
| 342 |
+
async def browser_ws(ws: WebSocket):
|
| 343 |
+
"""
|
| 344 |
+
WebSocket browser session.
|
| 345 |
+
Client sends: {"type":"navigate","url":"https://..."}
|
| 346 |
+
Server sends: {"type":"screenshot","data":"<base64 jpeg>","url":"...","title":"..."}
|
| 347 |
+
"""
|
| 348 |
+
await ws.accept()
|
| 349 |
+
await ws.send_json({"type":"status","message":"Browser session ready"})
|
| 350 |
+
page = None
|
| 351 |
+
try:
|
| 352 |
+
browser = await get_browser()
|
| 353 |
+
page = await browser.new_page(viewport={"width":390,"height":700})
|
| 354 |
+
|
| 355 |
+
async def send_screenshot(p):
|
| 356 |
+
try:
|
| 357 |
+
shot = await p.screenshot(type="jpeg", quality=75)
|
| 358 |
+
import base64
|
| 359 |
+
await ws.send_json({
|
| 360 |
+
"type": "screenshot",
|
| 361 |
+
"data": base64.b64encode(shot).decode(),
|
| 362 |
+
"url": p.url,
|
| 363 |
+
"title": await p.title(),
|
| 364 |
+
})
|
| 365 |
+
except Exception as e:
|
| 366 |
+
await ws.send_json({"type":"error","message":str(e)})
|
| 367 |
+
|
| 368 |
+
while True:
|
| 369 |
+
msg = await ws.receive_json()
|
| 370 |
+
if msg.get("type") == "navigate":
|
| 371 |
+
url = msg["url"]
|
| 372 |
+
if not url.startswith(("http://","https://")):
|
| 373 |
+
url = "https://" + url
|
| 374 |
+
await ws.send_json({"type":"loading","url":url})
|
| 375 |
+
try:
|
| 376 |
+
await page.goto(url, wait_until="domcontentloaded", timeout=20000)
|
| 377 |
+
await send_screenshot(page)
|
| 378 |
+
except Exception as e:
|
| 379 |
+
await ws.send_json({"type":"error","message":str(e)})
|
| 380 |
+
elif msg.get("type") == "click":
|
| 381 |
+
await page.mouse.click(msg.get("x",0), msg.get("y",0))
|
| 382 |
+
await asyncio.sleep(0.5)
|
| 383 |
+
await send_screenshot(page)
|
| 384 |
+
elif msg.get("type") == "scroll":
|
| 385 |
+
await page.mouse.wheel(0, msg.get("delta",200))
|
| 386 |
+
await asyncio.sleep(0.2)
|
| 387 |
+
await send_screenshot(page)
|
| 388 |
+
elif msg.get("type") == "back":
|
| 389 |
+
await page.go_back()
|
| 390 |
+
await send_screenshot(page)
|
| 391 |
+
elif msg.get("type") == "forward":
|
| 392 |
+
await page.go_forward()
|
| 393 |
+
await send_screenshot(page)
|
| 394 |
+
elif msg.get("type") == "refresh":
|
| 395 |
+
await page.reload()
|
| 396 |
+
await send_screenshot(page)
|
| 397 |
+
except WebSocketDisconnect:
|
| 398 |
+
pass
|
| 399 |
+
finally:
|
| 400 |
+
if page and not page.is_closed():
|
| 401 |
+
await page.close()
|
| 402 |
+
|
| 403 |
+
|
| 404 |
+
# ββ Docker ββββββββββββββββββββββββββββββββββββββββββοΏ½οΏ½βββββββββββββββββββββββββ
|
| 405 |
|
| 406 |
def run_docker(*args) -> dict:
|
| 407 |
try:
|
| 408 |
+
r = subprocess.run(["docker",*args], capture_output=True, text=True, timeout=10)
|
| 409 |
+
return {"ok": r.returncode==0, "stdout": r.stdout, "stderr": r.stderr}
|
| 410 |
except FileNotFoundError:
|
| 411 |
+
return {"ok":False,"error":"Docker not installed"}
|
| 412 |
except subprocess.TimeoutExpired:
|
| 413 |
+
return {"ok":False,"error":"Timed out"}
|
| 414 |
|
| 415 |
|
| 416 |
@app.get("/api/docker/containers")
|
| 417 |
async def docker_containers():
|
| 418 |
+
r = run_docker("ps","-a","--format","json")
|
|
|
|
|
|
|
| 419 |
containers = []
|
| 420 |
+
for line in r.get("stdout","").strip().splitlines():
|
| 421 |
+
try: containers.append(json.loads(line))
|
| 422 |
+
except: pass
|
| 423 |
+
return {"containers": containers, "error": r.get("error") or r.get("stderr") if not r["ok"] else None}
|
|
|
|
|
|
|
|
|
|
| 424 |
|
|
|
|
|
|
|
|
|
|
| 425 |
|
| 426 |
+
@app.post("/api/docker/start/{cid}")
|
| 427 |
+
async def docker_start(cid: str): return run_docker("start", cid)
|
| 428 |
|
| 429 |
+
@app.post("/api/docker/stop/{cid}")
|
| 430 |
+
async def docker_stop(cid: str): return run_docker("stop", cid)
|
|
|
|
|
|
|
| 431 |
|
| 432 |
@app.get("/api/docker/images")
|
| 433 |
async def docker_images():
|
| 434 |
+
r = run_docker("images","--format","json")
|
| 435 |
images = []
|
| 436 |
+
for line in r.get("stdout","").strip().splitlines():
|
| 437 |
+
try: images.append(json.loads(line))
|
| 438 |
+
except: pass
|
|
|
|
|
|
|
| 439 |
return {"images": images}
|
| 440 |
|
| 441 |
|
| 442 |
+
# ββ Health ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 443 |
|
| 444 |
+
@app.get("/api/health")
|
| 445 |
+
async def health():
|
| 446 |
+
return {"status":"ok","name":"TreyOS","version":"1.0.0","root":str(ROOT_JAIL)}
|
| 447 |
|
| 448 |
|
| 449 |
+
# ββ Serve frontend ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 450 |
+
# HuggingFace Spaces loads the root URL "/" directly in an iframe, so the
|
| 451 |
+
# TreyOS UI must be served there β not just at /app β or the Space will
|
| 452 |
+
# render blank.
|
| 453 |
|
| 454 |
+
frontend_path = Path(__file__).parent / "frontend"
|
| 455 |
+
if not frontend_path.exists():
|
| 456 |
+
frontend_path = Path(__file__).parent.parent / "frontend"
|
| 457 |
|
| 458 |
+
if frontend_path.exists():
|
| 459 |
+
index_file = frontend_path / "index.html"
|
| 460 |
+
|
| 461 |
+
@app.get("/")
|
| 462 |
+
async def serve_root():
|
| 463 |
+
return FileResponse(str(index_file), media_type="text/html")
|
|
|
|
|
|
|
|
|
|
| 464 |
|
| 465 |
+
@app.get("/app")
|
| 466 |
+
async def serve_app():
|
| 467 |
+
return FileResponse(str(index_file), media_type="text/html")
|
| 468 |
|
| 469 |
+
app.mount("/static", StaticFiles(directory=str(frontend_path)), name="static")
|
| 470 |
+
else:
|
| 471 |
+
@app.get("/")
|
| 472 |
+
async def serve_root_fallback():
|
| 473 |
+
return JSONResponse({"status":"ok","name":"TreyOS","warning":"frontend/ directory not found"})
|