- hub: FastAPI backend (MCP server, ADB LAN controller, bridge, storage) - hub/web: Vue 3 admin console (device manager, screen mirror, chat workbench) - android: Kotlin shell app with WebView stage, OTA, telemetry, keep-alive - protocol: architecture, MCP schema, and WebSocket protocol specs
1058 lines
44 KiB
Python
1058 lines
44 KiB
Python
from __future__ import annotations
|
||
|
||
import asyncio
|
||
import base64
|
||
import io
|
||
import ipaddress
|
||
import os
|
||
import re
|
||
import shutil
|
||
import time
|
||
from collections.abc import AsyncIterator
|
||
from fractions import Fraction
|
||
from pathlib import Path
|
||
from typing import Any
|
||
|
||
from fastapi import HTTPException, Request, WebSocket
|
||
|
||
from app.adb_lan.fmp4_muxer import AnnexBAccessUnitFramer, ZeroLatencyFmp4Muxer
|
||
from app.storage.db import PulseWallDB
|
||
|
||
_SAFE_PACKAGE_RE = re.compile(r"^[A-Za-z0-9_.-]+(/[A-Za-z0-9_.$]+)?$")
|
||
_REPO_ROOT = Path(__file__).resolve().parents[3]
|
||
|
||
|
||
def is_private_ip(host: str | None) -> bool:
|
||
if not host:
|
||
return False
|
||
cleaned = host.strip()
|
||
if cleaned in ("localhost", "testclient"):
|
||
return True
|
||
if cleaned.startswith("::ffff:"):
|
||
cleaned = cleaned[len("::ffff:") :]
|
||
try:
|
||
ip = ipaddress.ip_address(cleaned)
|
||
return ip.is_loopback or ip.is_private or ip.is_link_local
|
||
except ValueError:
|
||
return False
|
||
|
||
|
||
def assert_lan_only_request(request: Request) -> None:
|
||
"""Hard security guard: LAN Developer Debug API MUST reject any non-LAN client or public proxy hop."""
|
||
client_host = request.client.host if request.client else None
|
||
if not is_private_ip(client_host):
|
||
raise HTTPException(
|
||
status_code=403,
|
||
detail=f"LAN Developer Debug API is strictly restricted to private LAN clients (got {client_host}).",
|
||
)
|
||
|
||
for hdr in ("x-forwarded-for", "x-real-ip", "cf-connecting-ip"):
|
||
val = request.headers.get(hdr)
|
||
if val:
|
||
parts = [p.strip() for p in val.split(",") if p.strip()]
|
||
if any(not is_private_ip(p) for p in parts):
|
||
raise HTTPException(
|
||
status_code=403,
|
||
detail=f"LAN Developer Debug API rejected public forwarded header '{hdr}'.",
|
||
)
|
||
|
||
|
||
def _norm_model(s: str) -> str:
|
||
return re.sub(r"[^a-z0-9]+", "", (s or "").lower())
|
||
|
||
|
||
def _extract_h264_codec_str(data: bytes) -> str | None:
|
||
idx = 0
|
||
n = len(data)
|
||
while idx < n - 4:
|
||
pos = data.find(b"\x00\x00\x01", idx)
|
||
if pos < 0:
|
||
return None
|
||
nal_start = pos + 3
|
||
if nal_start + 3 < n and (data[nal_start] & 0x1F) == 7:
|
||
return f"avc1.{data[nal_start + 1]:02x}{data[nal_start + 2]:02x}{data[nal_start + 3]:02x}"
|
||
idx = nal_start
|
||
return None
|
||
|
||
|
||
def _packet_has_idr(data: bytes) -> bool:
|
||
idx = 0
|
||
n = len(data)
|
||
while idx < n - 4:
|
||
pos = data.find(b"\x00\x00\x01", idx)
|
||
if pos < 0:
|
||
return False
|
||
nal_start = pos + 3
|
||
if nal_start < n and (data[nal_start] & 0x1F) == 5:
|
||
return True
|
||
idx = nal_start
|
||
return False
|
||
|
||
|
||
class _ChunkSink(io.RawIOBase):
|
||
def __init__(self) -> None:
|
||
self._chunks: list[bytes] = []
|
||
|
||
def writable(self) -> bool:
|
||
return True
|
||
|
||
def write(self, b: Any) -> int:
|
||
raw = bytes(b)
|
||
self._chunks.append(raw)
|
||
return len(raw)
|
||
|
||
def drain(self) -> bytes:
|
||
if not self._chunks:
|
||
return b""
|
||
out = b"".join(self._chunks)
|
||
self._chunks.clear()
|
||
return out
|
||
|
||
|
||
class _Fmp4StreamBroadcaster:
|
||
"""Zero-transcode, ZERO-BUFFERING H.264 broadcaster (1 hardware encoder per device).
|
||
|
||
Simultaneously fans out:
|
||
- Raw Annex-B H.264 Access Units (`format=h264`) for direct browser WebCodecs GPU decoding
|
||
- Zero-buffering fMP4 fragments (`format=fmp4`) for HTML5 <video> MSE GPU decoding fallback
|
||
"""
|
||
|
||
def __init__(
|
||
self,
|
||
controller: "LanAdbController",
|
||
device_id: str,
|
||
serial: str,
|
||
quality: str = "hd",
|
||
) -> None:
|
||
self.controller = controller
|
||
self.device_id = device_id
|
||
self.serial = serial
|
||
self.quality = quality
|
||
self.subscribers: set[asyncio.Queue[dict[str, Any] | bytes]] = set()
|
||
self.h264_subscribers: set[asyncio.Queue[dict[str, Any] | bytes]] = set()
|
||
self.mime: str = 'video/mp4; codecs="avc1.42c029"'
|
||
self.codec: str = "avc1.42c029"
|
||
self.width: int = 960
|
||
self.height: int = 540
|
||
self.init_segment: bytes | None = None
|
||
self.gop_fragments: list[bytes] = []
|
||
self.h264_gop_frames: list[bytes] = []
|
||
self._muxer = ZeroLatencyFmp4Muxer()
|
||
self._task: asyncio.Task[None] | None = None
|
||
self._idle_stop_task: asyncio.Task[None] | None = None
|
||
self._adb_proc: asyncio.subprocess.Process | None = None
|
||
self._stopped = False
|
||
|
||
def _has_subscribers(self) -> bool:
|
||
return bool(self.subscribers or self.h264_subscribers)
|
||
|
||
def configure(self, serial: str, quality: str) -> None:
|
||
changed = (serial != self.serial) or (quality != self.quality)
|
||
self.serial = serial
|
||
self.quality = quality
|
||
if changed:
|
||
self.init_segment = None
|
||
self.gop_fragments.clear()
|
||
self.h264_gop_frames.clear()
|
||
self._muxer = ZeroLatencyFmp4Muxer()
|
||
if self._task and not self._task.done():
|
||
self._kill_local_proc()
|
||
|
||
def subscribe(self, stream_format: str = "fmp4") -> asyncio.Queue[dict[str, Any] | bytes]:
|
||
if self._idle_stop_task and not self._idle_stop_task.done():
|
||
self._idle_stop_task.cancel()
|
||
self._idle_stop_task = None
|
||
q: asyncio.Queue[dict[str, Any] | bytes] = asyncio.Queue(maxsize=120)
|
||
if stream_format == "h264":
|
||
self.h264_subscribers.add(q)
|
||
if self._muxer.sps and self._muxer.pps:
|
||
self._enqueue(q, {"type": "init_h264", "codec": self.codec, "width": self.width, "height": self.height})
|
||
for raw_frame in self.h264_gop_frames:
|
||
self._enqueue(q, raw_frame)
|
||
else:
|
||
self.subscribers.add(q)
|
||
if self.init_segment is not None:
|
||
self._enqueue(q, {"type": "init", "mime": self.mime, "width": self.width, "height": self.height})
|
||
self._enqueue(q, self.init_segment)
|
||
for frag in self.gop_fragments:
|
||
self._enqueue(q, frag)
|
||
self._stopped = False
|
||
if self._task is None or self._task.done():
|
||
self._task = asyncio.create_task(self._run_producer())
|
||
return q
|
||
|
||
def unsubscribe(self, q: asyncio.Queue[dict[str, Any] | bytes]) -> None:
|
||
self.subscribers.discard(q)
|
||
self.h264_subscribers.discard(q)
|
||
if not self._has_subscribers() and not self._stopped:
|
||
if self._idle_stop_task and not self._idle_stop_task.done():
|
||
self._idle_stop_task.cancel()
|
||
self._idle_stop_task = asyncio.create_task(self._stop_after_grace())
|
||
|
||
async def _stop_after_grace(self) -> None:
|
||
try:
|
||
await asyncio.sleep(3.0)
|
||
if not self._has_subscribers():
|
||
self.stop_now()
|
||
except asyncio.CancelledError:
|
||
pass
|
||
|
||
def _kill_local_proc(self) -> None:
|
||
p = self._adb_proc
|
||
if p and p.returncode is None:
|
||
try:
|
||
p.kill()
|
||
except Exception:
|
||
pass
|
||
|
||
def stop_now(self) -> None:
|
||
self._stopped = True
|
||
if self._idle_stop_task and not self._idle_stop_task.done():
|
||
self._idle_stop_task.cancel()
|
||
self._kill_local_proc()
|
||
if self._task and not self._task.done():
|
||
self._task.cancel()
|
||
|
||
@staticmethod
|
||
def _enqueue(q: asyncio.Queue[dict[str, Any] | bytes], item: dict[str, Any] | bytes) -> None:
|
||
if q.full():
|
||
try:
|
||
q.get_nowait()
|
||
except asyncio.QueueEmpty:
|
||
pass
|
||
try:
|
||
q.put_nowait(item)
|
||
except asyncio.QueueFull:
|
||
pass
|
||
|
||
def _broadcast(self, item: dict[str, Any] | bytes) -> None:
|
||
for q in list(self.subscribers):
|
||
self._enqueue(q, item)
|
||
|
||
def _broadcast_h264(self, item: dict[str, Any] | bytes) -> None:
|
||
for q in list(self.h264_subscribers):
|
||
self._enqueue(q, item)
|
||
|
||
def _emit_access_units(self, aus: list[tuple[list[bytes], bool]]) -> None:
|
||
for nals, is_idr in aus:
|
||
new_init, frag = self._muxer.mux_access_unit(nals, is_idr)
|
||
if new_init is not None:
|
||
self.init_segment = new_init
|
||
self.mime = self._muxer.mime
|
||
if self._muxer.sps and len(self._muxer.sps) >= 4:
|
||
s = self._muxer.sps
|
||
self.codec = f"avc1.{s[1]:02x}{s[2]:02x}{s[3]:02x}"
|
||
self._broadcast({"type": "init", "mime": self.mime, "width": self.width, "height": self.height})
|
||
self._broadcast(new_init)
|
||
self._broadcast_h264({"type": "init_h264", "codec": self.codec, "width": self.width, "height": self.height})
|
||
self.gop_fragments.clear()
|
||
self.h264_gop_frames.clear()
|
||
if frag is not None:
|
||
if is_idr or len(self.gop_fragments) > 90:
|
||
self.gop_fragments = [frag]
|
||
else:
|
||
self.gop_fragments.append(frag)
|
||
self._broadcast(frag)
|
||
|
||
# Build raw Annex-B frame for direct browser WebCodecs GPU decoding:
|
||
# 1-byte header (0x01=keyframe, 0x00=delta) + Annex-B NALs (prepend SPS/PPS on IDR if absent)
|
||
out_nals = list(nals)
|
||
if is_idr:
|
||
types = {n[0] & 0x1F for n in out_nals if n}
|
||
prefix: list[bytes] = []
|
||
if 7 not in types and self._muxer.sps:
|
||
prefix.append(self._muxer.sps)
|
||
if 8 not in types and self._muxer.pps:
|
||
prefix.append(self._muxer.pps)
|
||
if prefix:
|
||
out_nals = prefix + out_nals
|
||
raw_pkt = (b"\x01" if is_idr else b"\x00") + b"".join(b"\x00\x00\x00\x01" + n for n in out_nals if n)
|
||
if is_idr or len(self.h264_gop_frames) > 90:
|
||
self.h264_gop_frames = [raw_pkt]
|
||
else:
|
||
self.h264_gop_frames.append(raw_pkt)
|
||
self._broadcast_h264(raw_pkt)
|
||
|
||
async def _cleanup_remote_screenrecord(self) -> None:
|
||
try:
|
||
await self.controller._run_adb(
|
||
["-s", self.serial, "shell", "killall screenrecord 2>/dev/null || pkill -x screenrecord 2>/dev/null || true"],
|
||
timeout=3.0,
|
||
)
|
||
except Exception:
|
||
pass
|
||
|
||
async def _run_producer(self) -> None:
|
||
adb_bin = self.controller._find_adb()
|
||
if not adb_bin:
|
||
return
|
||
|
||
try:
|
||
while not self._stopped and not self.controller._is_shutting_down() and self._has_subscribers():
|
||
await self._cleanup_remote_screenrecord()
|
||
size_str = self.controller._compute_stream_size(self.device_id, self.quality)
|
||
w_str, h_str = size_str.split("x")
|
||
self.width, self.height = int(w_str), int(h_str)
|
||
self._muxer.update_dimensions(self.width, self.height)
|
||
bitrate = "3500000" if self.quality == "fhd" else "2200000" if self.quality == "hd" else "1200000"
|
||
|
||
framer = AnnexBAccessUnitFramer()
|
||
|
||
adb_proc = await asyncio.create_subprocess_exec(
|
||
adb_bin,
|
||
"-s",
|
||
self.serial,
|
||
"exec-out",
|
||
"screenrecord",
|
||
"--output-format=h264",
|
||
"--size",
|
||
size_str,
|
||
"--bit-rate",
|
||
bitrate,
|
||
"--time-limit",
|
||
"175",
|
||
"-",
|
||
stdout=asyncio.subprocess.PIPE,
|
||
stderr=asyncio.subprocess.DEVNULL,
|
||
env=self.controller._adb_env(),
|
||
)
|
||
self._adb_proc = adb_proc
|
||
self.controller._active_stream_procs.add(adb_proc)
|
||
try:
|
||
assert adb_proc.stdout
|
||
while not self._stopped and not self.controller._is_shutting_down() and self._has_subscribers():
|
||
try:
|
||
# Short 45ms idle timeout immediately flushes the final frame of any UI tap/burst
|
||
chunk = await asyncio.wait_for(adb_proc.stdout.read(65536), timeout=0.045)
|
||
except asyncio.TimeoutError:
|
||
if adb_proc.returncode is not None:
|
||
break
|
||
flushed = framer.flush_idle()
|
||
if flushed:
|
||
self._emit_access_units(flushed)
|
||
continue
|
||
if not chunk:
|
||
flushed = framer.flush_idle()
|
||
if flushed:
|
||
self._emit_access_units(flushed)
|
||
break
|
||
|
||
aus = framer.feed(chunk)
|
||
if aus:
|
||
self._emit_access_units(aus)
|
||
finally:
|
||
self.controller._active_stream_procs.discard(adb_proc)
|
||
if self._adb_proc is adb_proc:
|
||
self._adb_proc = None
|
||
if adb_proc.returncode is None:
|
||
try:
|
||
adb_proc.kill()
|
||
except Exception:
|
||
pass
|
||
try:
|
||
await asyncio.wait_for(adb_proc.wait(), timeout=2.0)
|
||
except Exception:
|
||
pass
|
||
if not self._stopped and self._has_subscribers():
|
||
await asyncio.sleep(0.25)
|
||
except asyncio.CancelledError:
|
||
pass
|
||
finally:
|
||
if not self.controller._is_shutting_down():
|
||
await self._cleanup_remote_screenrecord()
|
||
|
||
|
||
class _DeviceStreamBroadcaster:
|
||
"""Maintains AT MOST ONE hardware H.264 screenrecord stream per Android device and fans out JPEG frames to all viewers."""
|
||
|
||
def __init__(
|
||
self,
|
||
controller: "LanAdbController",
|
||
device_id: str,
|
||
serial: str,
|
||
quality: str = "hd",
|
||
fps: int = 20,
|
||
) -> None:
|
||
self.controller = controller
|
||
self.device_id = device_id
|
||
self.serial = serial
|
||
self.quality = quality
|
||
self.fps = max(5, min(30, int(fps)))
|
||
self.subscribers: set[asyncio.Queue[bytes]] = set()
|
||
self.last_frame_jpeg: bytes | None = None
|
||
self._task: asyncio.Task[None] | None = None
|
||
self._idle_stop_task: asyncio.Task[None] | None = None
|
||
self._adb_proc: asyncio.subprocess.Process | None = None
|
||
self._stopped = False
|
||
|
||
def configure(self, serial: str, quality: str, fps: int) -> None:
|
||
fps = max(5, min(30, int(fps)))
|
||
changed = (serial != self.serial) or (quality != self.quality) or (fps != self.fps)
|
||
self.serial = serial
|
||
self.quality = quality
|
||
self.fps = fps
|
||
if changed and self._task and not self._task.done():
|
||
# Restart single producer with updated quality/fps while keeping subscribers attached
|
||
self._kill_local_proc()
|
||
|
||
def subscribe(self) -> asyncio.Queue[bytes]:
|
||
if self._idle_stop_task and not self._idle_stop_task.done():
|
||
self._idle_stop_task.cancel()
|
||
self._idle_stop_task = None
|
||
q: asyncio.Queue[bytes] = asyncio.Queue(maxsize=2)
|
||
self.subscribers.add(q)
|
||
if self.last_frame_jpeg is not None:
|
||
try:
|
||
q.put_nowait(self.last_frame_jpeg)
|
||
except asyncio.QueueFull:
|
||
pass
|
||
self._stopped = False
|
||
if self._task is None or self._task.done():
|
||
self._task = asyncio.create_task(self._run_producer())
|
||
return q
|
||
|
||
def unsubscribe(self, q: asyncio.Queue[bytes]) -> None:
|
||
self.subscribers.discard(q)
|
||
if not self.subscribers and not self._stopped:
|
||
if self._idle_stop_task and not self._idle_stop_task.done():
|
||
self._idle_stop_task.cancel()
|
||
self._idle_stop_task = asyncio.create_task(self._stop_after_grace())
|
||
|
||
async def _stop_after_grace(self) -> None:
|
||
try:
|
||
await asyncio.sleep(3.0)
|
||
if not self.subscribers:
|
||
self.stop_now()
|
||
except asyncio.CancelledError:
|
||
pass
|
||
|
||
def _kill_local_proc(self) -> None:
|
||
p = self._adb_proc
|
||
if p and p.returncode is None:
|
||
try:
|
||
p.kill()
|
||
except Exception:
|
||
pass
|
||
|
||
def stop_now(self) -> None:
|
||
self._stopped = True
|
||
if self._idle_stop_task and not self._idle_stop_task.done():
|
||
self._idle_stop_task.cancel()
|
||
self._kill_local_proc()
|
||
if self._task and not self._task.done():
|
||
self._task.cancel()
|
||
|
||
def _broadcast(self, jpg: bytes) -> None:
|
||
self.last_frame_jpeg = jpg
|
||
for q in list(self.subscribers):
|
||
if q.full():
|
||
try:
|
||
q.get_nowait()
|
||
except asyncio.QueueEmpty:
|
||
pass
|
||
try:
|
||
q.put_nowait(jpg)
|
||
except asyncio.QueueFull:
|
||
pass
|
||
|
||
async def _cleanup_remote_screenrecord(self) -> None:
|
||
try:
|
||
await self.controller._run_adb(
|
||
["-s", self.serial, "shell", "killall screenrecord 2>/dev/null || pkill -x screenrecord 2>/dev/null || true"],
|
||
timeout=3.0,
|
||
)
|
||
except Exception:
|
||
pass
|
||
|
||
async def _run_producer(self) -> None:
|
||
adb_bin = self.controller._find_adb()
|
||
if not adb_bin:
|
||
return
|
||
try:
|
||
import av # type: ignore
|
||
except ImportError:
|
||
return
|
||
|
||
# Instant initial frame via screencap if we have no cached frame yet
|
||
if self.last_frame_jpeg is None:
|
||
try:
|
||
size_w = int(self.controller._compute_stream_size(self.device_id, self.quality).split("x")[0])
|
||
code, png_raw, _ = await self.controller._run_adb(
|
||
["-s", self.serial, "exec-out", "screencap", "-p"], timeout=8.0, binary=True
|
||
)
|
||
if code == 0 and isinstance(png_raw, bytes) and len(png_raw) > 100:
|
||
first_jpg = self.controller._png_to_jpeg(png_raw, max_width=size_w)
|
||
if first_jpg:
|
||
self._broadcast(first_jpg)
|
||
except Exception:
|
||
pass
|
||
|
||
last_sent_at = 0.0
|
||
try:
|
||
while not self._stopped and not self.controller._is_shutting_down() and self.subscribers:
|
||
await self._cleanup_remote_screenrecord()
|
||
size_str = self.controller._compute_stream_size(self.device_id, self.quality)
|
||
bitrate = "3500000" if self.quality == "fhd" else "2200000" if self.quality == "hd" else "1200000"
|
||
jpeg_quality = 82 if self.quality == "fhd" else 76 if self.quality == "hd" else 68
|
||
min_frame_gap = 1.0 / float(self.fps)
|
||
|
||
codec = av.CodecContext.create("h264", "r")
|
||
adb_proc = await asyncio.create_subprocess_exec(
|
||
adb_bin,
|
||
"-s",
|
||
self.serial,
|
||
"exec-out",
|
||
"screenrecord",
|
||
"--output-format=h264",
|
||
"--size",
|
||
size_str,
|
||
"--bit-rate",
|
||
bitrate,
|
||
"--time-limit",
|
||
"175",
|
||
"-",
|
||
stdout=asyncio.subprocess.PIPE,
|
||
stderr=asyncio.subprocess.DEVNULL,
|
||
env=self.controller._adb_env(),
|
||
)
|
||
self._adb_proc = adb_proc
|
||
self.controller._active_stream_procs.add(adb_proc)
|
||
try:
|
||
assert adb_proc.stdout
|
||
while not self._stopped and not self.controller._is_shutting_down() and self.subscribers:
|
||
try:
|
||
chunk = await asyncio.wait_for(adb_proc.stdout.read(16384), timeout=0.6)
|
||
except asyncio.TimeoutError:
|
||
if adb_proc.returncode is not None:
|
||
break
|
||
continue
|
||
if not chunk:
|
||
break
|
||
for pkt in codec.parse(chunk):
|
||
try:
|
||
frames = codec.decode(pkt)
|
||
except Exception:
|
||
continue
|
||
for frame in frames:
|
||
now = time.monotonic()
|
||
if now - last_sent_at < min_frame_gap:
|
||
continue
|
||
last_sent_at = now
|
||
out = io.BytesIO()
|
||
frame.to_image().save(out, format="JPEG", quality=jpeg_quality)
|
||
self._broadcast(out.getvalue())
|
||
finally:
|
||
self.controller._active_stream_procs.discard(adb_proc)
|
||
if self._adb_proc is adb_proc:
|
||
self._adb_proc = None
|
||
if adb_proc.returncode is None:
|
||
try:
|
||
adb_proc.kill()
|
||
except Exception:
|
||
pass
|
||
try:
|
||
await asyncio.wait_for(adb_proc.wait(), timeout=2.0)
|
||
except Exception:
|
||
pass
|
||
if not self._stopped and self.subscribers:
|
||
await asyncio.sleep(0.35)
|
||
except asyncio.CancelledError:
|
||
pass
|
||
finally:
|
||
if not self.controller._is_shutting_down():
|
||
await self._cleanup_remote_screenrecord()
|
||
|
||
|
||
class LanAdbController:
|
||
"""Structured LAN-only ADB controller supporting Android 11 Wireless Debugging (mDNS TLS + TCP) & shared live stream."""
|
||
|
||
def __init__(self, db: PulseWallDB) -> None:
|
||
self.db = db
|
||
self._adb_cache_ts = 0.0
|
||
self._adb_cache: list[dict[str, str]] = []
|
||
self._shutdown_event: asyncio.Event | None = None
|
||
self._active_stream_procs: set[asyncio.subprocess.Process] = set()
|
||
self._broadcasters: dict[str, _DeviceStreamBroadcaster] = {}
|
||
self._fmp4_broadcasters: dict[str, _Fmp4StreamBroadcaster] = {}
|
||
self._input_shells: dict[str, asyncio.subprocess.Process] = {}
|
||
self._input_locks: dict[str, asyncio.Lock] = {}
|
||
self._ota_tasks: dict[str, asyncio.Task[None]] = {}
|
||
self._ota_status: dict[str, dict[str, Any]] = {}
|
||
|
||
# ---- ADB direct OTA install (used when device is reachable over wireless ADB) ----
|
||
def get_adb_ota_status(self, device_id: str) -> dict[str, Any]:
|
||
st = self._ota_status.get(device_id)
|
||
if not st:
|
||
return {"device_id": device_id, "state": "idle"}
|
||
return {"device_id": device_id, **st}
|
||
|
||
def start_adb_ota_install(self, device_id: str, serial: str, apk_path: Path, meta: dict[str, Any]) -> bool:
|
||
existing = self._ota_tasks.get(device_id)
|
||
if existing and not existing.done():
|
||
return False
|
||
self._ota_status[device_id] = {
|
||
"state": "installing",
|
||
"method": "adb",
|
||
"serial": serial,
|
||
"version_name": meta.get("version_name"),
|
||
"version_code": meta.get("version_code"),
|
||
"started_at_ms": int(time.time() * 1000),
|
||
"message": "正在通过 ADB 直接安装 APK…",
|
||
}
|
||
task = asyncio.create_task(self._run_adb_ota_install(device_id, serial, apk_path, meta))
|
||
self._ota_tasks[device_id] = task
|
||
return True
|
||
|
||
async def _run_adb_ota_install(self, device_id: str, serial: str, apk_path: Path, meta: dict[str, Any]) -> None:
|
||
st = self._ota_status[device_id]
|
||
t0 = time.monotonic()
|
||
try:
|
||
if not apk_path.exists():
|
||
raise RuntimeError(f"APK 不存在: {apk_path}")
|
||
code, out, err = await self._run_adb(["-s", serial, "install", "-r", str(apk_path)], timeout=300.0)
|
||
out_s = str(out)
|
||
if code != 0 or "Success" not in out_s:
|
||
raise RuntimeError((err or out_s or f"adb install exit {code}")[:400])
|
||
# Relaunch App right after the package replace kills the old process
|
||
await self._run_adb(["-s", serial, "shell", "am", "start", "-n", "com.pulsewall.app/.MainActivity"], timeout=15.0)
|
||
st.update(
|
||
state="success",
|
||
message=f"ADB 直装完成 v{meta.get('version_name')} ({meta.get('version_code')}),已自动重启 App",
|
||
duration_sec=round(time.monotonic() - t0, 1),
|
||
)
|
||
self.db.add_audit("ota", device_id, f"ADB 直装 OTA 成功 v{meta.get('version_name')} ({meta.get('version_code')})", {"serial": serial})
|
||
except asyncio.CancelledError:
|
||
st.update(state="cancelled", message="ADB 安装已取消")
|
||
raise
|
||
except Exception as exc:
|
||
detail = str(getattr(exc, "detail", exc))
|
||
st.update(state="failed", message=f"ADB 直装失败: {detail}", duration_sec=round(time.monotonic() - t0, 1))
|
||
self.db.add_audit("ota", device_id, f"ADB 直装 OTA 失败: {detail[:200]}", {"serial": serial})
|
||
finally:
|
||
st["finished_at_ms"] = int(time.time() * 1000)
|
||
|
||
def _is_shutting_down(self) -> bool:
|
||
return self._shutdown_event is not None and self._shutdown_event.is_set()
|
||
|
||
def bind_shutdown_event(self, ev: asyncio.Event) -> None:
|
||
self._shutdown_event = ev
|
||
|
||
def stop_all_streams(self) -> None:
|
||
for b in list(self._broadcasters.values()):
|
||
b.stop_now()
|
||
self._broadcasters.clear()
|
||
for fb in list(self._fmp4_broadcasters.values()):
|
||
fb.stop_now()
|
||
self._fmp4_broadcasters.clear()
|
||
for sh in list(self._input_shells.values()):
|
||
if sh.returncode is None:
|
||
try:
|
||
sh.kill()
|
||
except Exception:
|
||
pass
|
||
self._input_shells.clear()
|
||
for t in list(self._ota_tasks.values()):
|
||
if not t.done():
|
||
t.cancel()
|
||
self._ota_tasks.clear()
|
||
for p in list(self._active_stream_procs):
|
||
if p.returncode is None:
|
||
try:
|
||
p.kill()
|
||
except Exception:
|
||
pass
|
||
self._active_stream_procs.clear()
|
||
|
||
def _find_adb(self) -> str | None:
|
||
toolchain_adb = _REPO_ROOT / ".toolchain" / "android-sdk" / "platform-tools" / "adb"
|
||
if toolchain_adb.exists():
|
||
return str(toolchain_adb)
|
||
return shutil.which("adb")
|
||
|
||
def _find_ffmpeg(self) -> str | None:
|
||
sys_ff = shutil.which("ffmpeg")
|
||
if sys_ff:
|
||
return sys_ff
|
||
try:
|
||
import imageio_ffmpeg # type: ignore
|
||
|
||
return imageio_ffmpeg.get_ffmpeg_exe()
|
||
except Exception:
|
||
return None
|
||
|
||
def _adb_env(self) -> dict[str, str]:
|
||
env = dict(os.environ)
|
||
toolchain_home = _REPO_ROOT / ".toolchain" / "home"
|
||
if (toolchain_home / ".android" / "adbkey").exists():
|
||
env["HOME"] = str(toolchain_home)
|
||
return env
|
||
|
||
async def _run_adb(self, args: list[str], timeout: float = 15.0, binary: bool = False) -> tuple[int, bytes | str, str]:
|
||
adb_bin = self._find_adb()
|
||
if not adb_bin:
|
||
raise HTTPException(
|
||
status_code=503,
|
||
detail="adb binary is not installed on Hub host. Install android-tools-adb or platform-tools.",
|
||
)
|
||
proc = await asyncio.create_subprocess_exec(
|
||
adb_bin,
|
||
*args,
|
||
stdout=asyncio.subprocess.PIPE,
|
||
stderr=asyncio.subprocess.PIPE,
|
||
env=self._adb_env(),
|
||
)
|
||
try:
|
||
stdout, stderr = await asyncio.wait_for(proc.communicate(), timeout=timeout)
|
||
except asyncio.TimeoutError:
|
||
proc.kill()
|
||
raise HTTPException(status_code=504, detail="ADB command timed out.")
|
||
err_text = stderr.decode("utf-8", errors="replace").strip()
|
||
if binary:
|
||
return proc.returncode or 0, stdout, err_text
|
||
return proc.returncode or 0, stdout.decode("utf-8", errors="replace").strip(), err_text
|
||
|
||
async def list_live_adb_devices(self, force_refresh: bool = False) -> list[dict[str, str]]:
|
||
now = time.monotonic()
|
||
if not force_refresh and (now - self._adb_cache_ts) < 3.0:
|
||
return self._adb_cache
|
||
if not self._find_adb():
|
||
return []
|
||
try:
|
||
code, out, _ = await self._run_adb(["devices", "-l"], timeout=5.0)
|
||
if code != 0 or not isinstance(out, str):
|
||
return self._adb_cache
|
||
items: list[dict[str, str]] = []
|
||
for line in out.splitlines()[1:]:
|
||
line = line.strip()
|
||
if not line:
|
||
continue
|
||
parts = line.split()
|
||
if len(parts) < 2:
|
||
continue
|
||
serial, state = parts[0], parts[1]
|
||
meta: dict[str, str] = {"serial": serial, "state": state, "model": "", "device": "", "product": ""}
|
||
for tok in parts[2:]:
|
||
if ":" in tok:
|
||
k, v = tok.split(":", 1)
|
||
meta[k] = v
|
||
items.append(meta)
|
||
self._adb_cache = items
|
||
self._adb_cache_ts = now
|
||
return items
|
||
except Exception:
|
||
return self._adb_cache
|
||
|
||
def match_live_adb(self, dev: dict[str, Any], live_list: list[dict[str, str]]) -> dict[str, str] | None:
|
||
online_adb = [x for x in live_list if x.get("state") == "device"]
|
||
if not online_adb:
|
||
return None
|
||
target = (dev.get("adb_target") or "").strip()
|
||
if target:
|
||
for item in online_adb:
|
||
if item["serial"] == target:
|
||
return item
|
||
# Fallback: match by Android device model (e.g. "W2_Ultra" in "Google W2 Ultra")
|
||
dev_model_norm = _norm_model(dev.get("model", ""))
|
||
if dev_model_norm:
|
||
for item in online_adb:
|
||
adb_model_norm = _norm_model(item.get("model", ""))
|
||
if adb_model_norm and (adb_model_norm in dev_model_norm or dev_model_norm in adb_model_norm):
|
||
return item
|
||
return None
|
||
|
||
async def enrich_devices_with_adb(self, devices: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
||
live_list = await self.list_live_adb_devices()
|
||
enriched: list[dict[str, Any]] = []
|
||
for dev in devices:
|
||
matched = self.match_live_adb(dev, live_list)
|
||
copy_dev = dict(dev)
|
||
copy_dev["adb_connected"] = matched is not None
|
||
copy_dev["adb_serial"] = matched["serial"] if matched else ""
|
||
if matched and "adb_lan" not in copy_dev.get("capabilities", []):
|
||
copy_dev["capabilities"] = list(copy_dev.get("capabilities", [])) + ["adb_lan"]
|
||
enriched.append(copy_dev)
|
||
return enriched
|
||
|
||
def _is_valid_lan_adb_target(self, target: str) -> bool:
|
||
if target.endswith("._adb-tls-connect._tcp") or target.endswith("._adb._tcp"):
|
||
return True
|
||
host = target.split(":")[0]
|
||
return is_private_ip(host)
|
||
|
||
async def _resolve_target_serial(self, device_id: str, require_control_auth: bool = True) -> str:
|
||
dev = self.db.get_device(device_id)
|
||
if not dev:
|
||
raise HTTPException(status_code=404, detail=f"Device '{device_id}' not found.")
|
||
|
||
if require_control_auth:
|
||
cfg = self.db.get_config()
|
||
if not cfg.lan_debug_enabled:
|
||
raise HTTPException(status_code=403, detail="Global LAN developer debug switch is disabled in Hub config.")
|
||
if not dev.get("lan_debug_allowed"):
|
||
raise HTTPException(status_code=403, detail=f"LAN debug is not authorized for device '{device_id}'.")
|
||
|
||
live_list = await self.list_live_adb_devices()
|
||
matched = self.match_live_adb(dev, live_list)
|
||
if matched:
|
||
return matched["serial"]
|
||
|
||
adb_target = (dev.get("adb_target") or "").strip()
|
||
if not adb_target:
|
||
raise HTTPException(status_code=400, detail=f"Device '{device_id}' has no connected ADB serial or adb_target configured.")
|
||
if not self._is_valid_lan_adb_target(adb_target):
|
||
raise HTTPException(status_code=403, detail=f"ADB target '{adb_target}' must be on private LAN.")
|
||
|
||
if ":" in adb_target and not adb_target.endswith("._tcp"):
|
||
await self._run_adb(["connect", adb_target], timeout=8.0)
|
||
return adb_target
|
||
|
||
async def pair_wireless(self, pair_address: str, pairing_code: str, device_id: str | None = None) -> dict[str, Any]:
|
||
addr = pair_address.strip()
|
||
code = pairing_code.strip()
|
||
if ":" not in addr or not is_private_ip(addr.split(":")[0]):
|
||
raise HTTPException(status_code=400, detail="配对地址必须是局域网 IP:端口 格式(如 192.168.1.18:35239)")
|
||
if not re.fullmatch(r"\d{6}", code):
|
||
raise HTTPException(status_code=400, detail="WLAN 配对码应为 6 位数字")
|
||
|
||
rc, out, err = await self._run_adb(["pair", addr, code], timeout=20.0)
|
||
out_str = str(out)
|
||
ok = rc == 0 and "Successfully paired" in out_str
|
||
matched_serial = ""
|
||
if ok:
|
||
await asyncio.sleep(0.8)
|
||
live_list = await self.list_live_adb_devices(force_refresh=True)
|
||
online_adb = [x for x in live_list if x.get("state") == "device"]
|
||
if device_id:
|
||
dev = self.db.get_device(device_id)
|
||
matched = self.match_live_adb(dev, online_adb) if dev else None
|
||
if matched:
|
||
matched_serial = matched["serial"]
|
||
elif online_adb:
|
||
matched_serial = online_adb[-1]["serial"]
|
||
if matched_serial:
|
||
self.db.set_device_lan_debug(device_id, True, matched_serial)
|
||
self.db.add_audit("lan_adb_pair", device_id or "hub", f"Wireless ADB pair {addr}: ok={ok}", {"output": out_str, "error": err})
|
||
return {
|
||
"ok": ok,
|
||
"output": out_str,
|
||
"error": err,
|
||
"adb_serial": matched_serial,
|
||
"live_adb_devices": await self.list_live_adb_devices(force_refresh=True),
|
||
}
|
||
|
||
async def capture_screen_png(self, device_id: str) -> bytes:
|
||
serial = await self._resolve_target_serial(device_id, require_control_auth=False)
|
||
code, raw, err = await self._run_adb(["-s", serial, "exec-out", "screencap", "-p"], timeout=15.0, binary=True)
|
||
if code != 0 or not isinstance(raw, bytes) or len(raw) < 100:
|
||
raise HTTPException(status_code=502, detail=f"ADB 截屏失败: {err or 'Empty screencap'}")
|
||
return raw
|
||
|
||
def _compute_stream_size(self, device_id: str, quality: str = "hd") -> str:
|
||
max_long = 1280 if quality == "fhd" else 960 if quality == "hd" else 640
|
||
dev = self.db.get_device(device_id) or {}
|
||
prof = dev.get("display_profile") or {}
|
||
w = int(prof.get("width_px") or 1920)
|
||
h = int(prof.get("height_px") or 1080)
|
||
if w <= 0 or h <= 0:
|
||
return "960x540"
|
||
long_side = max(w, h)
|
||
scale = min(1.0, max_long / float(long_side))
|
||
tw = max(160, (int(w * scale) // 2) * 2)
|
||
th = max(160, (int(h * scale) // 2) * 2)
|
||
return f"{tw}x{th}"
|
||
|
||
@staticmethod
|
||
def _png_to_jpeg(png_bytes: bytes, max_width: int = 960) -> bytes | None:
|
||
try:
|
||
from PIL import Image # type: ignore
|
||
|
||
img = Image.open(io.BytesIO(png_bytes)).convert("RGB")
|
||
if img.width > max_width:
|
||
ratio = max_width / float(img.width)
|
||
img = img.resize((max_width, max(1, int(img.height * ratio))))
|
||
out = io.BytesIO()
|
||
img.save(out, format="JPEG", quality=80)
|
||
return out.getvalue()
|
||
except Exception:
|
||
return None
|
||
|
||
async def stream_mjpeg(
|
||
self,
|
||
device_id: str,
|
||
request: Request,
|
||
quality: str = "hd",
|
||
fps: int = 20,
|
||
) -> AsyncIterator[bytes]:
|
||
"""Subscribes to the single shared hardware H.264 -> PyAV broadcaster for this device."""
|
||
serial = await self._resolve_target_serial(device_id, require_control_auth=False)
|
||
broadcaster = self._broadcasters.get(device_id)
|
||
if broadcaster is None:
|
||
broadcaster = _DeviceStreamBroadcaster(self, device_id, serial, quality=quality, fps=fps)
|
||
self._broadcasters[device_id] = broadcaster
|
||
else:
|
||
broadcaster.configure(serial, quality=quality, fps=fps)
|
||
|
||
q = broadcaster.subscribe()
|
||
|
||
def _wrap_frame(jpg: bytes) -> bytes:
|
||
header = (
|
||
f"--frame\r\nContent-Type: image/jpeg\r\nContent-Length: {len(jpg)}\r\n\r\n"
|
||
).encode("ascii")
|
||
return header + jpg + b"\r\n"
|
||
|
||
try:
|
||
while not self._is_shutting_down() and not await request.is_disconnected():
|
||
try:
|
||
jpg = await asyncio.wait_for(q.get(), timeout=1.0)
|
||
yield _wrap_frame(jpg)
|
||
except asyncio.TimeoutError:
|
||
continue
|
||
except (asyncio.CancelledError, GeneratorExit):
|
||
pass
|
||
finally:
|
||
broadcaster.unsubscribe(q)
|
||
|
||
async def stream_fmp4_ws(
|
||
self,
|
||
device_id: str,
|
||
websocket: WebSocket,
|
||
quality: str = "hd",
|
||
stream_format: str = "fmp4",
|
||
) -> None:
|
||
"""Streams zero-transcode H.264 (raw Annex-B for WebCodecs GPU or fMP4 for MSE GPU) over WebSocket."""
|
||
serial = await self._resolve_target_serial(device_id, require_control_auth=False)
|
||
broadcaster = self._fmp4_broadcasters.get(device_id)
|
||
if broadcaster is None:
|
||
broadcaster = _Fmp4StreamBroadcaster(self, device_id, serial, quality=quality)
|
||
self._fmp4_broadcasters[device_id] = broadcaster
|
||
else:
|
||
broadcaster.configure(serial, quality=quality)
|
||
|
||
fmt = "h264" if stream_format == "h264" else "fmp4"
|
||
q = broadcaster.subscribe(stream_format=fmt)
|
||
last_sent = time.monotonic()
|
||
try:
|
||
while not self._is_shutting_down():
|
||
try:
|
||
item = await asyncio.wait_for(q.get(), timeout=1.0)
|
||
except asyncio.TimeoutError:
|
||
if time.monotonic() - last_sent >= 5.0:
|
||
await websocket.send_json({"type": "ping", "ts": int(time.time() * 1000)})
|
||
last_sent = time.monotonic()
|
||
continue
|
||
if isinstance(item, dict):
|
||
await websocket.send_json(item)
|
||
else:
|
||
await websocket.send_bytes(item)
|
||
last_sent = time.monotonic()
|
||
except Exception:
|
||
pass
|
||
finally:
|
||
broadcaster.unsubscribe(q)
|
||
|
||
async def _fast_input_cmd(self, serial: str, shell_cmd: str) -> tuple[int, str, str]:
|
||
"""Executes an Android input command over a persistent interactive `adb shell` session to avoid per-click TLS handshake overhead."""
|
||
adb_bin = self._find_adb()
|
||
if not adb_bin:
|
||
return await self._run_adb(["-s", serial, "shell", shell_cmd])
|
||
|
||
lock = self._input_locks.setdefault(serial, asyncio.Lock())
|
||
async with lock:
|
||
proc = self._input_shells.get(serial)
|
||
if proc is None or proc.returncode is not None or proc.stdin is None:
|
||
proc = await asyncio.create_subprocess_exec(
|
||
adb_bin,
|
||
"-s",
|
||
serial,
|
||
"shell",
|
||
stdin=asyncio.subprocess.PIPE,
|
||
stdout=asyncio.subprocess.DEVNULL,
|
||
stderr=asyncio.subprocess.DEVNULL,
|
||
env=self._adb_env(),
|
||
)
|
||
self._input_shells[serial] = proc
|
||
try:
|
||
assert proc.stdin is not None
|
||
proc.stdin.write(f"{shell_cmd} &\n".encode("utf-8"))
|
||
await asyncio.wait_for(proc.stdin.drain(), timeout=2.0)
|
||
return 0, "dispatched", ""
|
||
except Exception:
|
||
self._input_shells.pop(serial, None)
|
||
try:
|
||
proc.kill()
|
||
except Exception:
|
||
pass
|
||
return await self._run_adb(["-s", serial, "shell", shell_cmd])
|
||
|
||
async def execute_action(self, device_id: str, action: str, params: dict[str, Any] | None = None) -> dict[str, Any]:
|
||
params = params or {}
|
||
adb_target = await self._resolve_target_serial(device_id, require_control_auth=True)
|
||
self.db.add_audit("lan_adb", device_id, f"ADB action '{action}' on {adb_target}", {"action": action, "params": params})
|
||
|
||
if action == "status":
|
||
code, out, err = await self._run_adb(["-s", adb_target, "get-state"])
|
||
return {"ok": code == 0, "adb_target": adb_target, "state": out, "error": err}
|
||
|
||
if action == "tap":
|
||
x, y = int(params["x"]), int(params["y"])
|
||
code, out, err = await self._fast_input_cmd(adb_target, f"input tap {x} {y}")
|
||
return {"ok": code == 0, "output": out, "error": err}
|
||
|
||
if action == "swipe":
|
||
x1, y1, x2, y2 = int(params["x1"]), int(params["y1"]), int(params["x2"]), int(params["y2"])
|
||
dur = int(params.get("duration_ms", 300))
|
||
code, out, err = await self._fast_input_cmd(adb_target, f"input swipe {x1} {y1} {x2} {y2} {dur}")
|
||
return {"ok": code == 0, "output": out, "error": err}
|
||
|
||
if action == "text":
|
||
text = str(params.get("text", "")).replace(" ", "%s")
|
||
if len(text) > 200 or any(ch in text for ch in ";|&$`\n\r'\""):
|
||
raise HTTPException(status_code=400, detail="Unsupported characters or length in text input.")
|
||
code, out, err = await self._fast_input_cmd(adb_target, f"input text {text}")
|
||
return {"ok": code == 0, "output": out, "error": err}
|
||
|
||
if action == "keyevent":
|
||
key = str(params.get("key", "KEYCODE_HOME"))
|
||
if not re.fullmatch(r"[A-Z0-9_]+", key):
|
||
raise HTTPException(status_code=400, detail="Invalid keyevent name.")
|
||
code, out, err = await self._fast_input_cmd(adb_target, f"input keyevent {key}")
|
||
return {"ok": code == 0, "output": out, "error": err}
|
||
|
||
if action == "screen_wake":
|
||
code, out, err = await self._fast_input_cmd(adb_target, "input keyevent KEYCODE_WAKEUP")
|
||
return {"ok": code == 0, "output": out, "error": err}
|
||
|
||
if action == "screen_sleep":
|
||
code, out, err = await self._fast_input_cmd(adb_target, "input keyevent KEYCODE_SLEEP")
|
||
return {"ok": code == 0, "output": out, "error": err}
|
||
|
||
if action == "launch_app":
|
||
component = str(params.get("component", "")).strip()
|
||
if not _SAFE_PACKAGE_RE.fullmatch(component):
|
||
raise HTTPException(status_code=400, detail="Invalid Android package/component format.")
|
||
if "/" in component:
|
||
code, out, err = await self._run_adb(["-s", adb_target, "shell", "am", "start", "-n", component])
|
||
else:
|
||
code, out, err = await self._run_adb(
|
||
["-s", adb_target, "shell", "monkey", "-p", component, "-c", "android.intent.category.LAUNCHER", "1"]
|
||
)
|
||
return {"ok": code == 0, "output": out, "error": err}
|
||
|
||
if action == "screencap":
|
||
code, raw, err = await self._run_adb(["-s", adb_target, "exec-out", "screencap", "-p"], timeout=20.0, binary=True)
|
||
if code != 0 or not isinstance(raw, bytes) or not raw:
|
||
return {"ok": False, "error": err or "Empty screencap"}
|
||
return {
|
||
"ok": True,
|
||
"mime_type": "image/png",
|
||
"size_bytes": len(raw),
|
||
"image_base64": base64.b64encode(raw).decode("ascii"),
|
||
}
|
||
|
||
if action == "dumpsys_summary":
|
||
_, bat, _ = await self._run_adb(["-s", adb_target, "shell", "dumpsys", "battery"])
|
||
_, therm, _ = await self._run_adb(["-s", adb_target, "shell", "dumpsys", "thermalservice"])
|
||
return {"ok": True, "battery": bat[:2000], "thermal": therm[:2000]}
|
||
|
||
raise HTTPException(status_code=400, detail=f"Unsupported LAN ADB action: {action}")
|