Spaces:
Paused
Paused
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,13 +1,12 @@
|
|
| 1 |
"""
|
| 2 |
-
THE Z AI — Computer Mode Server (
|
| 3 |
-
==========================================
|
| 4 |
-
|
| 5 |
-
- ا
|
| 6 |
-
-
|
| 7 |
-
-
|
| 8 |
-
-
|
| 9 |
-
-
|
| 10 |
-
- navigate action لفتح URLs في Firefox
|
| 11 |
"""
|
| 12 |
|
| 13 |
import asyncio
|
|
@@ -18,7 +17,6 @@ import os
|
|
| 18 |
import re
|
| 19 |
import subprocess
|
| 20 |
import time
|
| 21 |
-
import traceback
|
| 22 |
|
| 23 |
from fastapi import FastAPI, WebSocket, WebSocketDisconnect
|
| 24 |
from fastapi.middleware.cors import CORSMiddleware
|
|
@@ -28,9 +26,8 @@ import uvicorn
|
|
| 28 |
# ─── ENV ────────────────────────────────────────────
|
| 29 |
DISPLAY = os.environ.get("DISPLAY", ":1")
|
| 30 |
os.environ["DISPLAY"] = DISPLAY
|
| 31 |
-
DEFAULT_BROWSER = os.environ.get("DEFAULT_BROWSER", "firefox")
|
| 32 |
|
| 33 |
-
app = FastAPI(title="Z-Computer-Mode API
|
| 34 |
app.add_middleware(
|
| 35 |
CORSMiddleware,
|
| 36 |
allow_origins=["*"],
|
|
@@ -46,120 +43,116 @@ stream_quality = 60
|
|
| 46 |
stream_scale = 0.5
|
| 47 |
|
| 48 |
|
| 49 |
-
# ─── Screen Capture ────────────────────────────────
|
| 50 |
|
| 51 |
-
def capture_screen(scale=0.
|
| 52 |
-
"""Capture real screen using scrot → base64 JPEG"""
|
| 53 |
try:
|
| 54 |
-
tmp = f"/tmp/
|
| 55 |
-
|
| 56 |
["scrot", "-q", "90", tmp],
|
| 57 |
env={**os.environ, "DISPLAY": DISPLAY},
|
| 58 |
timeout=8, capture_output=True
|
| 59 |
)
|
| 60 |
-
if
|
| 61 |
-
return
|
| 62 |
-
|
| 63 |
from PIL import Image
|
| 64 |
img = Image.open(tmp)
|
| 65 |
os.unlink(tmp)
|
| 66 |
-
|
| 67 |
if scale < 1.0:
|
| 68 |
-
|
| 69 |
-
h = int(img.height * scale)
|
| 70 |
-
img = img.resize((w, h), Image.LANCZOS)
|
| 71 |
-
|
| 72 |
buf = io.BytesIO()
|
| 73 |
img.convert("RGB").save(buf, format="JPEG", quality=quality, optimize=True)
|
| 74 |
return base64.b64encode(buf.getvalue()).decode()
|
| 75 |
except Exception as e:
|
| 76 |
-
print(f"[
|
| 77 |
return ""
|
| 78 |
|
| 79 |
|
| 80 |
-
def
|
| 81 |
-
"""Fallback: use xwd + PIL"""
|
| 82 |
try:
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
subprocess.run(
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
timeout=8, capture_output=True
|
| 89 |
-
)
|
| 90 |
-
subprocess.run(
|
| 91 |
-
["convert", tmp_xwd, tmp_png],
|
| 92 |
-
timeout=8, capture_output=True
|
| 93 |
-
)
|
| 94 |
from PIL import Image
|
| 95 |
-
if not os.path.exists(
|
| 96 |
return ""
|
| 97 |
-
img = Image.open(
|
| 98 |
-
for f in [
|
| 99 |
try: os.unlink(f)
|
| 100 |
except: pass
|
| 101 |
-
|
| 102 |
if scale < 1.0:
|
| 103 |
-
|
| 104 |
-
h = int(img.height * scale)
|
| 105 |
-
img = img.resize((w, h), Image.LANCZOS)
|
| 106 |
buf = io.BytesIO()
|
| 107 |
img.convert("RGB").save(buf, format="JPEG", quality=quality, optimize=True)
|
| 108 |
return base64.b64encode(buf.getvalue()).decode()
|
| 109 |
except Exception as e:
|
| 110 |
-
print(f"[
|
| 111 |
return ""
|
| 112 |
|
| 113 |
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
timeout=timeout, capture_output=True, text=True
|
| 132 |
-
)
|
| 133 |
-
return {"rc": result.returncode, "out": result.stdout, "err": result.stderr}
|
| 134 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 135 |
|
| 136 |
-
def run_command(cmd: str, timeout: int = 30) -> dict:
|
| 137 |
try:
|
| 138 |
result = subprocess.run(
|
| 139 |
-
cmd,
|
| 140 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 141 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 142 |
return {
|
| 143 |
-
"stdout":
|
| 144 |
-
"stderr":
|
| 145 |
"returncode": result.returncode,
|
| 146 |
}
|
| 147 |
except subprocess.TimeoutExpired:
|
| 148 |
-
return {"stdout": "", "stderr": f"Timeout after {timeout}s", "returncode": -1}
|
| 149 |
except Exception as e:
|
| 150 |
return {"stdout": "", "stderr": str(e), "returncode": -1}
|
| 151 |
|
| 152 |
|
| 153 |
-
def
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
|
|
|
| 159 |
|
| 160 |
|
| 161 |
async def broadcast(msg: dict):
|
| 162 |
-
txt = json.dumps(msg)
|
| 163 |
dead = []
|
| 164 |
for ws in active_connections:
|
| 165 |
try:
|
|
@@ -187,38 +180,6 @@ async def screen_stream_loop():
|
|
| 187 |
stream_active = False
|
| 188 |
|
| 189 |
|
| 190 |
-
# ─── Wait for screen change ──────────────────────────
|
| 191 |
-
|
| 192 |
-
async def wait_for_screen_change(ws, before_frame: str, label: str,
|
| 193 |
-
max_wait: float = 8.0, check_interval: float = 0.8):
|
| 194 |
-
"""Wait until screen changes from before_frame, send updates"""
|
| 195 |
-
elapsed = 0.0
|
| 196 |
-
while elapsed < max_wait:
|
| 197 |
-
await asyncio.sleep(check_interval)
|
| 198 |
-
elapsed += check_interval
|
| 199 |
-
current = capture_screen(scale=0.75, quality=72)
|
| 200 |
-
if current and screen_changed(before_frame, current):
|
| 201 |
-
await ws.send_text(json.dumps({
|
| 202 |
-
"type": "screenshot",
|
| 203 |
-
"data": current,
|
| 204 |
-
"ts": int(time.time() * 1000),
|
| 205 |
-
"auto": True,
|
| 206 |
-
"label": label
|
| 207 |
-
}))
|
| 208 |
-
return current
|
| 209 |
-
# Even if no change detected, send final screenshot
|
| 210 |
-
final = capture_screen(scale=0.75, quality=72)
|
| 211 |
-
if final:
|
| 212 |
-
await ws.send_text(json.dumps({
|
| 213 |
-
"type": "screenshot",
|
| 214 |
-
"data": final,
|
| 215 |
-
"ts": int(time.time() * 1000),
|
| 216 |
-
"auto": True,
|
| 217 |
-
"label": f"{label} (no change)"
|
| 218 |
-
}))
|
| 219 |
-
return final
|
| 220 |
-
|
| 221 |
-
|
| 222 |
# ─── Action Handler ──────────────────────────────────
|
| 223 |
|
| 224 |
async def handle_action(ws: WebSocket, msg: dict):
|
|
@@ -226,10 +187,11 @@ async def handle_action(ws: WebSocket, msg: dict):
|
|
| 226 |
data = msg.get("data", {})
|
| 227 |
|
| 228 |
async def send(obj):
|
| 229 |
-
await ws.send_text(json.dumps(obj))
|
| 230 |
|
| 231 |
-
async def
|
| 232 |
-
|
|
|
|
| 233 |
if frame:
|
| 234 |
await send({
|
| 235 |
"type": "screenshot",
|
|
@@ -245,81 +207,28 @@ async def handle_action(ws: WebSocket, msg: dict):
|
|
| 245 |
frame = capture_screen(scale=0.8, quality=75)
|
| 246 |
await send({"type": "screenshot", "data": frame, "ts": int(time.time() * 1000)})
|
| 247 |
|
| 248 |
-
# ── TERMINAL ──
|
| 249 |
elif action == "terminal":
|
| 250 |
cmd = data.get("cmd", "")
|
| 251 |
-
|
| 252 |
-
|
| 253 |
-
|
| 254 |
-
|
| 255 |
-
|
| 256 |
-
|
| 257 |
-
|
| 258 |
-
|
| 259 |
-
|
| 260 |
-
|
| 261 |
-
|
| 262 |
-
|
| 263 |
-
|
| 264 |
-
|
| 265 |
-
|
| 266 |
-
|
| 267 |
-
|
| 268 |
-
|
| 269 |
-
|
| 270 |
-
"data": after,
|
| 271 |
-
"ts": int(time.time() * 1000),
|
| 272 |
-
"auto": True,
|
| 273 |
-
"label": f"بعد: {cmd[:50]}"
|
| 274 |
-
})
|
| 275 |
-
|
| 276 |
-
# ── OPEN BROWSER / NAVIGATE ──
|
| 277 |
-
elif action in ("open_browser", "navigate"):
|
| 278 |
-
url = data.get("url", "https://www.google.com")
|
| 279 |
-
browser = get_browser_cmd()
|
| 280 |
-
|
| 281 |
-
before = capture_screen(scale=0.75, quality=72)
|
| 282 |
-
await send({"type": "ack", "action": action, "url": url, "browser": browser})
|
| 283 |
-
|
| 284 |
-
if browser:
|
| 285 |
-
# Kill existing browser instances cleanly
|
| 286 |
-
run_command(f"pkill -f {browser} 2>/dev/null || true", timeout=3)
|
| 287 |
-
await asyncio.sleep(0.5)
|
| 288 |
-
|
| 289 |
-
# Open browser with URL
|
| 290 |
-
subprocess.Popen(
|
| 291 |
-
f"{browser} --no-sandbox --new-window '{url}'",
|
| 292 |
-
shell=True,
|
| 293 |
-
env={**os.environ, "DISPLAY": DISPLAY},
|
| 294 |
-
stdout=subprocess.DEVNULL,
|
| 295 |
-
stderr=subprocess.DEVNULL
|
| 296 |
-
)
|
| 297 |
-
|
| 298 |
-
await send({"type": "log", "msg": f"✅ فتح {browser} على {url}..."})
|
| 299 |
-
|
| 300 |
-
# Wait for browser to appear (up to 12 seconds)
|
| 301 |
-
await wait_for_screen_change(ws, before, f"فتح المتصفح: {url}", max_wait=12.0)
|
| 302 |
-
else:
|
| 303 |
-
await send({"type": "error", "msg": "❌ لا يوجد متصفح مثبت"})
|
| 304 |
-
|
| 305 |
-
# ── OPEN APP ──
|
| 306 |
-
elif action == "open_app":
|
| 307 |
-
app_cmd = data.get("cmd", "")
|
| 308 |
-
if app_cmd:
|
| 309 |
-
before = capture_screen(scale=0.75, quality=72)
|
| 310 |
-
|
| 311 |
-
subprocess.Popen(
|
| 312 |
-
app_cmd, shell=True,
|
| 313 |
-
env={**os.environ, "DISPLAY": DISPLAY},
|
| 314 |
-
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL
|
| 315 |
-
)
|
| 316 |
-
await send({"type": "ack", "action": "open_app", "cmd": app_cmd})
|
| 317 |
-
await send({"type": "log", "msg": f"✅ تشغيل: {app_cmd}"})
|
| 318 |
-
|
| 319 |
-
# Wait for app to appear
|
| 320 |
-
await wait_for_screen_change(ws, before, f"بعد فتح: {app_cmd}", max_wait=8.0)
|
| 321 |
-
else:
|
| 322 |
-
await send({"type": "ack", "action": "open_app"})
|
| 323 |
|
| 324 |
# ── MOUSE MOVE ──
|
| 325 |
elif action == "mouse_move":
|
|
@@ -340,9 +249,7 @@ async def handle_action(ws: WebSocket, msg: dict):
|
|
| 340 |
else:
|
| 341 |
xdo(["click", btn_num])
|
| 342 |
await send({"type": "ack", "action": "mouse_click"})
|
| 343 |
-
|
| 344 |
-
await asyncio.sleep(0.5)
|
| 345 |
-
await take_screenshot("بعد النقر")
|
| 346 |
|
| 347 |
# ── MOUSE DRAG ──
|
| 348 |
elif action == "mouse_drag":
|
|
@@ -362,18 +269,15 @@ async def handle_action(ws: WebSocket, msg: dict):
|
|
| 362 |
if text:
|
| 363 |
xdo(["type", "--clearmodifiers", "--delay", "30", text])
|
| 364 |
await send({"type": "ack", "action": "keyboard_type"})
|
| 365 |
-
await
|
| 366 |
-
await take_screenshot("بعد الكتابة")
|
| 367 |
|
| 368 |
# ── KEYBOARD HOTKEY ──
|
| 369 |
elif action == "keyboard_hotkey":
|
| 370 |
keys = data.get("keys", [])
|
| 371 |
if keys:
|
| 372 |
-
|
| 373 |
-
xdo(["key", "--clearmodifiers", combo])
|
| 374 |
await send({"type": "ack", "action": "keyboard_hotkey"})
|
| 375 |
-
await
|
| 376 |
-
await take_screenshot("بعد الاختصار")
|
| 377 |
|
| 378 |
# ── KEYBOARD PRESS ──
|
| 379 |
elif action == "keyboard_press":
|
|
@@ -407,15 +311,20 @@ async def handle_action(ws: WebSocket, msg: dict):
|
|
| 407 |
for _ in range(abs(clicks)):
|
| 408 |
xdo(["click", btn])
|
| 409 |
await send({"type": "ack", "action": "scroll"})
|
| 410 |
-
await asyncio.sleep(0.3)
|
| 411 |
-
await take_screenshot("بعد التمرير")
|
| 412 |
|
| 413 |
-
# ──
|
| 414 |
-
elif action == "
|
| 415 |
-
|
| 416 |
-
|
| 417 |
-
|
| 418 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 419 |
|
| 420 |
# ── STREAM ──
|
| 421 |
elif action == "start_stream":
|
|
@@ -449,11 +358,6 @@ async def handle_action(ws: WebSocket, msg: dict):
|
|
| 449 |
await send({"type": "screen_info", "width": w, "height": h,
|
| 450 |
"mouse_x": mx, "mouse_y": my})
|
| 451 |
|
| 452 |
-
# ── BROWSER INFO ──
|
| 453 |
-
elif action == "browser_info":
|
| 454 |
-
browser = get_browser_cmd()
|
| 455 |
-
await send({"type": "browser_info", "browser": browser, "available": bool(browser)})
|
| 456 |
-
|
| 457 |
else:
|
| 458 |
await send({"type": "error", "msg": f"Unknown action: {action}"})
|
| 459 |
|
|
@@ -473,18 +377,14 @@ async def websocket_endpoint(ws: WebSocket):
|
|
| 473 |
except:
|
| 474 |
w, h = 1920, 1080
|
| 475 |
|
| 476 |
-
# Detect browser
|
| 477 |
-
browser = get_browser_cmd()
|
| 478 |
-
|
| 479 |
await ws.send_text(json.dumps({
|
| 480 |
"type": "connected",
|
| 481 |
"screen_width": w,
|
| 482 |
"screen_height": h,
|
| 483 |
-
"
|
| 484 |
-
|
| 485 |
-
}))
|
| 486 |
|
| 487 |
-
#
|
| 488 |
frame = capture_screen(scale=0.75, quality=72)
|
| 489 |
if frame:
|
| 490 |
await ws.send_text(json.dumps({
|
|
@@ -517,7 +417,7 @@ async def rest_screenshot():
|
|
| 517 |
@app.post("/terminal")
|
| 518 |
async def rest_terminal(body: dict):
|
| 519 |
cmd = body.get("cmd", "")
|
| 520 |
-
res = run_command(cmd, timeout=body.get("timeout",
|
| 521 |
return JSONResponse(res)
|
| 522 |
|
| 523 |
|
|
@@ -525,21 +425,23 @@ async def rest_terminal(body: dict):
|
|
| 525 |
async def health():
|
| 526 |
res = run_command("xdotool getdisplaygeometry", timeout=4)
|
| 527 |
display_ok = res["returncode"] == 0
|
| 528 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 529 |
return {
|
| 530 |
"status": "ok",
|
| 531 |
"display": DISPLAY,
|
| 532 |
"display_working": display_ok,
|
| 533 |
-
"
|
|
|
|
| 534 |
}
|
| 535 |
|
| 536 |
|
| 537 |
-
@app.get("/browser")
|
| 538 |
-
async def browser_info():
|
| 539 |
-
browser = get_browser_cmd()
|
| 540 |
-
return {"browser": browser, "available": bool(browser)}
|
| 541 |
-
|
| 542 |
-
|
| 543 |
if __name__ == "__main__":
|
| 544 |
port = int(os.environ.get("PORT", 7860))
|
| 545 |
uvicorn.run("app:app", host="0.0.0.0", port=port, log_level="info")
|
|
|
|
| 1 |
"""
|
| 2 |
+
THE Z AI — Computer Mode Server (v4 — Terminal-Optimized)
|
| 3 |
+
==========================================================
|
| 4 |
+
مصمم خصيصاً ليتوافق مع طريقة تفكير الذكاء الاصطناعي:
|
| 5 |
+
- الذكاء يستخدم terminal + curl حصراً
|
| 6 |
+
- السيرفر ينتظر كل أمر حتى ينتهي فعلاً
|
| 7 |
+
- النتائج كاملة وغير مقطوعة
|
| 8 |
+
- screenshot تلقائي بعد كل terminal
|
| 9 |
+
- دعم المواقع المحجوبة عبر user-agent صحيح
|
|
|
|
| 10 |
"""
|
| 11 |
|
| 12 |
import asyncio
|
|
|
|
| 17 |
import re
|
| 18 |
import subprocess
|
| 19 |
import time
|
|
|
|
| 20 |
|
| 21 |
from fastapi import FastAPI, WebSocket, WebSocketDisconnect
|
| 22 |
from fastapi.middleware.cors import CORSMiddleware
|
|
|
|
| 26 |
# ─── ENV ────────────────────────────────────────────
|
| 27 |
DISPLAY = os.environ.get("DISPLAY", ":1")
|
| 28 |
os.environ["DISPLAY"] = DISPLAY
|
|
|
|
| 29 |
|
| 30 |
+
app = FastAPI(title="Z-Computer-Mode API v4")
|
| 31 |
app.add_middleware(
|
| 32 |
CORSMiddleware,
|
| 33 |
allow_origins=["*"],
|
|
|
|
| 43 |
stream_scale = 0.5
|
| 44 |
|
| 45 |
|
| 46 |
+
# ─── Screen Capture ─────────────────────────────────
|
| 47 |
|
| 48 |
+
def capture_screen(scale=0.6, quality=65) -> str:
|
|
|
|
| 49 |
try:
|
| 50 |
+
tmp = f"/tmp/zs_{int(time.time()*1000)}.png"
|
| 51 |
+
r = subprocess.run(
|
| 52 |
["scrot", "-q", "90", tmp],
|
| 53 |
env={**os.environ, "DISPLAY": DISPLAY},
|
| 54 |
timeout=8, capture_output=True
|
| 55 |
)
|
| 56 |
+
if r.returncode != 0 or not os.path.exists(tmp):
|
| 57 |
+
return _capture_xwd(scale, quality)
|
|
|
|
| 58 |
from PIL import Image
|
| 59 |
img = Image.open(tmp)
|
| 60 |
os.unlink(tmp)
|
|
|
|
| 61 |
if scale < 1.0:
|
| 62 |
+
img = img.resize((int(img.width*scale), int(img.height*scale)), Image.LANCZOS)
|
|
|
|
|
|
|
|
|
|
| 63 |
buf = io.BytesIO()
|
| 64 |
img.convert("RGB").save(buf, format="JPEG", quality=quality, optimize=True)
|
| 65 |
return base64.b64encode(buf.getvalue()).decode()
|
| 66 |
except Exception as e:
|
| 67 |
+
print(f"[capture] {e}")
|
| 68 |
return ""
|
| 69 |
|
| 70 |
|
| 71 |
+
def _capture_xwd(scale=0.6, quality=65) -> str:
|
|
|
|
| 72 |
try:
|
| 73 |
+
xwd = f"/tmp/zs_{int(time.time()*1000)}.xwd"
|
| 74 |
+
png = xwd.replace(".xwd", ".png")
|
| 75 |
+
subprocess.run(["xwd", "-root", "-silent", "-out", xwd],
|
| 76 |
+
env={**os.environ, "DISPLAY": DISPLAY}, timeout=8, capture_output=True)
|
| 77 |
+
subprocess.run(["convert", xwd, png], timeout=8, capture_output=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 78 |
from PIL import Image
|
| 79 |
+
if not os.path.exists(png):
|
| 80 |
return ""
|
| 81 |
+
img = Image.open(png)
|
| 82 |
+
for f in [xwd, png]:
|
| 83 |
try: os.unlink(f)
|
| 84 |
except: pass
|
|
|
|
| 85 |
if scale < 1.0:
|
| 86 |
+
img = img.resize((int(img.width*scale), int(img.height*scale)), Image.LANCZOS)
|
|
|
|
|
|
|
| 87 |
buf = io.BytesIO()
|
| 88 |
img.convert("RGB").save(buf, format="JPEG", quality=quality, optimize=True)
|
| 89 |
return base64.b64encode(buf.getvalue()).decode()
|
| 90 |
except Exception as e:
|
| 91 |
+
print(f"[capture_xwd] {e}")
|
| 92 |
return ""
|
| 93 |
|
| 94 |
|
| 95 |
+
# ─── Command Runner — ينتظر حتى ينتهي الأمر فعلاً ──
|
| 96 |
+
|
| 97 |
+
def run_command(cmd: str, timeout: int = 45) -> dict:
|
| 98 |
+
"""
|
| 99 |
+
ينفذ أمر bash وينتظر حتى ينتهي.
|
| 100 |
+
يدعم:
|
| 101 |
+
- curl مع user-agent صحيح
|
| 102 |
+
- python3 مع المكتبات المثبتة
|
| 103 |
+
- أوامر طويلة حتى 45 ثانية
|
| 104 |
+
"""
|
| 105 |
+
# حقن user-agent تلقائياً لأوامر curl بدونه
|
| 106 |
+
if "curl" in cmd and "user-agent" not in cmd.lower() and "-A" not in cmd:
|
| 107 |
+
cmd = cmd.replace(
|
| 108 |
+
"curl ",
|
| 109 |
+
'curl -A "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 Chrome/120.0.0.0 Safari/537.36" ',
|
| 110 |
+
1
|
| 111 |
+
)
|
|
|
|
|
|
|
|
|
|
| 112 |
|
| 113 |
+
env = {
|
| 114 |
+
**os.environ,
|
| 115 |
+
"DISPLAY": DISPLAY,
|
| 116 |
+
"PYTHONIOENCODING": "utf-8",
|
| 117 |
+
"LANG": "en_US.UTF-8",
|
| 118 |
+
}
|
| 119 |
|
|
|
|
| 120 |
try:
|
| 121 |
result = subprocess.run(
|
| 122 |
+
cmd,
|
| 123 |
+
shell=True,
|
| 124 |
+
capture_output=True,
|
| 125 |
+
text=True,
|
| 126 |
+
timeout=timeout,
|
| 127 |
+
env=env,
|
| 128 |
+
executable="/bin/bash"
|
| 129 |
)
|
| 130 |
+
stdout = result.stdout
|
| 131 |
+
stderr = result.stderr
|
| 132 |
+
|
| 133 |
+
# لا نقطع النتائج — كاملة دائماً (حتى 15000 حرف)
|
| 134 |
return {
|
| 135 |
+
"stdout": stdout[-15000:] if len(stdout) > 15000 else stdout,
|
| 136 |
+
"stderr": stderr[-4000:] if len(stderr) > 4000 else stderr,
|
| 137 |
"returncode": result.returncode,
|
| 138 |
}
|
| 139 |
except subprocess.TimeoutExpired:
|
| 140 |
+
return {"stdout": "", "stderr": f"⏱️ Timeout after {timeout}s", "returncode": -1}
|
| 141 |
except Exception as e:
|
| 142 |
return {"stdout": "", "stderr": str(e), "returncode": -1}
|
| 143 |
|
| 144 |
|
| 145 |
+
def xdo(args: list, timeout=10) -> dict:
|
| 146 |
+
r = subprocess.run(
|
| 147 |
+
["xdotool"] + args,
|
| 148 |
+
env={**os.environ, "DISPLAY": DISPLAY},
|
| 149 |
+
timeout=timeout, capture_output=True, text=True
|
| 150 |
+
)
|
| 151 |
+
return {"rc": r.returncode, "out": r.stdout, "err": r.stderr}
|
| 152 |
|
| 153 |
|
| 154 |
async def broadcast(msg: dict):
|
| 155 |
+
txt = json.dumps(msg, ensure_ascii=False)
|
| 156 |
dead = []
|
| 157 |
for ws in active_connections:
|
| 158 |
try:
|
|
|
|
| 180 |
stream_active = False
|
| 181 |
|
| 182 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 183 |
# ─── Action Handler ──────────────────────────────────
|
| 184 |
|
| 185 |
async def handle_action(ws: WebSocket, msg: dict):
|
|
|
|
| 187 |
data = msg.get("data", {})
|
| 188 |
|
| 189 |
async def send(obj):
|
| 190 |
+
await ws.send_text(json.dumps(obj, ensure_ascii=False))
|
| 191 |
|
| 192 |
+
async def auto_shot(label="", delay=0.5):
|
| 193 |
+
await asyncio.sleep(delay)
|
| 194 |
+
frame = capture_screen(scale=0.7, quality=70)
|
| 195 |
if frame:
|
| 196 |
await send({
|
| 197 |
"type": "screenshot",
|
|
|
|
| 207 |
frame = capture_screen(scale=0.8, quality=75)
|
| 208 |
await send({"type": "screenshot", "data": frame, "ts": int(time.time() * 1000)})
|
| 209 |
|
| 210 |
+
# ── TERMINAL — الأهم: ينتظر حتى ينتهي الأمر فعلاً ──
|
| 211 |
elif action == "terminal":
|
| 212 |
cmd = data.get("cmd", "")
|
| 213 |
+
timeout = int(data.get("timeout", 45))
|
| 214 |
+
if not cmd:
|
| 215 |
+
await send({"type": "terminal_result", "cmd": "", "stdout": "", "stderr": "no command", "returncode": -1})
|
| 216 |
+
return
|
| 217 |
+
|
| 218 |
+
# نفذ الأمر وانتظر
|
| 219 |
+
res = run_command(cmd, timeout=timeout)
|
| 220 |
+
|
| 221 |
+
# أرسل النتيجة فوراً
|
| 222 |
+
await send({
|
| 223 |
+
"type": "terminal_result",
|
| 224 |
+
"cmd": cmd,
|
| 225 |
+
"stdout": res["stdout"],
|
| 226 |
+
"stderr": res["stderr"],
|
| 227 |
+
"returncode": res["returncode"],
|
| 228 |
+
})
|
| 229 |
+
|
| 230 |
+
# screenshot تلقائي بعد الأمر (بدون تأخير كبير)
|
| 231 |
+
await auto_shot(f"بعد: {cmd[:40]}", delay=0.4)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 232 |
|
| 233 |
# ── MOUSE MOVE ──
|
| 234 |
elif action == "mouse_move":
|
|
|
|
| 249 |
else:
|
| 250 |
xdo(["click", btn_num])
|
| 251 |
await send({"type": "ack", "action": "mouse_click"})
|
| 252 |
+
await auto_shot("بعد النقر", delay=0.4)
|
|
|
|
|
|
|
| 253 |
|
| 254 |
# ── MOUSE DRAG ──
|
| 255 |
elif action == "mouse_drag":
|
|
|
|
| 269 |
if text:
|
| 270 |
xdo(["type", "--clearmodifiers", "--delay", "30", text])
|
| 271 |
await send({"type": "ack", "action": "keyboard_type"})
|
| 272 |
+
await auto_shot("بعد الكتابة", delay=0.3)
|
|
|
|
| 273 |
|
| 274 |
# ── KEYBOARD HOTKEY ──
|
| 275 |
elif action == "keyboard_hotkey":
|
| 276 |
keys = data.get("keys", [])
|
| 277 |
if keys:
|
| 278 |
+
xdo(["key", "--clearmodifiers", "+".join(keys)])
|
|
|
|
| 279 |
await send({"type": "ack", "action": "keyboard_hotkey"})
|
| 280 |
+
await auto_shot("بعد الاختصار", delay=0.4)
|
|
|
|
| 281 |
|
| 282 |
# ── KEYBOARD PRESS ──
|
| 283 |
elif action == "keyboard_press":
|
|
|
|
| 311 |
for _ in range(abs(clicks)):
|
| 312 |
xdo(["click", btn])
|
| 313 |
await send({"type": "ack", "action": "scroll"})
|
|
|
|
|
|
|
| 314 |
|
| 315 |
+
# ── OPEN APP — يستخدم terminal مباشرة ──
|
| 316 |
+
elif action == "open_app":
|
| 317 |
+
app_cmd = data.get("cmd", "")
|
| 318 |
+
if app_cmd:
|
| 319 |
+
subprocess.Popen(
|
| 320 |
+
app_cmd, shell=True,
|
| 321 |
+
env={**os.environ, "DISPLAY": DISPLAY},
|
| 322 |
+
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL
|
| 323 |
+
)
|
| 324 |
+
await send({"type": "ack", "action": "open_app", "cmd": app_cmd})
|
| 325 |
+
await auto_shot(f"بعد فتح: {app_cmd}", delay=3.0)
|
| 326 |
+
else:
|
| 327 |
+
await send({"type": "ack", "action": "open_app"})
|
| 328 |
|
| 329 |
# ── STREAM ──
|
| 330 |
elif action == "start_stream":
|
|
|
|
| 358 |
await send({"type": "screen_info", "width": w, "height": h,
|
| 359 |
"mouse_x": mx, "mouse_y": my})
|
| 360 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 361 |
else:
|
| 362 |
await send({"type": "error", "msg": f"Unknown action: {action}"})
|
| 363 |
|
|
|
|
| 377 |
except:
|
| 378 |
w, h = 1920, 1080
|
| 379 |
|
|
|
|
|
|
|
|
|
|
| 380 |
await ws.send_text(json.dumps({
|
| 381 |
"type": "connected",
|
| 382 |
"screen_width": w,
|
| 383 |
"screen_height": h,
|
| 384 |
+
"msg": "Z Computer Mode v4 — Terminal Optimized"
|
| 385 |
+
}, ensure_ascii=False))
|
|
|
|
| 386 |
|
| 387 |
+
# Initial screenshot
|
| 388 |
frame = capture_screen(scale=0.75, quality=72)
|
| 389 |
if frame:
|
| 390 |
await ws.send_text(json.dumps({
|
|
|
|
| 417 |
@app.post("/terminal")
|
| 418 |
async def rest_terminal(body: dict):
|
| 419 |
cmd = body.get("cmd", "")
|
| 420 |
+
res = run_command(cmd, timeout=body.get("timeout", 45))
|
| 421 |
return JSONResponse(res)
|
| 422 |
|
| 423 |
|
|
|
|
| 425 |
async def health():
|
| 426 |
res = run_command("xdotool getdisplaygeometry", timeout=4)
|
| 427 |
display_ok = res["returncode"] == 0
|
| 428 |
+
|
| 429 |
+
# Check curl works
|
| 430 |
+
curl_test = run_command(
|
| 431 |
+
"curl -s --max-time 5 'https://api.duckduckgo.com/?q=test&format=json&no_html=1' | python3 -c \"import sys,json;d=json.load(sys.stdin);print('OK',d.get('Type','?'))\"",
|
| 432 |
+
timeout=10
|
| 433 |
+
)
|
| 434 |
+
curl_ok = curl_test["returncode"] == 0
|
| 435 |
+
|
| 436 |
return {
|
| 437 |
"status": "ok",
|
| 438 |
"display": DISPLAY,
|
| 439 |
"display_working": display_ok,
|
| 440 |
+
"curl_working": curl_ok,
|
| 441 |
+
"version": "v4-terminal-optimized"
|
| 442 |
}
|
| 443 |
|
| 444 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 445 |
if __name__ == "__main__":
|
| 446 |
port = int(os.environ.get("PORT", 7860))
|
| 447 |
uvicorn.run("app:app", host="0.0.0.0", port=port, log_level="info")
|