|
| 1 | +""" |
| 2 | +Live device control endpoints — GPS, battery, network type, proxy. |
| 3 | +
|
| 4 | +These apply instantly to a running emulator via the emulator console (telnet) |
| 5 | +or ADB shell, without touching the stored fingerprint. To persist a change, |
| 6 | +use PUT /api/fingerprint/{id} afterwards. |
| 7 | +
|
| 8 | +Routes |
| 9 | +------ |
| 10 | +POST /api/devices/{id}/gps — set GPS coordinates live |
| 11 | +POST /api/devices/{id}/battery — set battery level + charging state live |
| 12 | +POST /api/devices/{id}/network-type — set simulated network type live |
| 13 | +POST /api/devices/{id}/proxy/apply — re-apply current proxy settings to device |
| 14 | +""" |
| 15 | +from __future__ import annotations |
| 16 | + |
| 17 | +import logging |
| 18 | +from typing import Optional |
| 19 | + |
| 20 | +from fastapi import APIRouter, Depends, HTTPException |
| 21 | +from pydantic import BaseModel, Field |
| 22 | +from sqlalchemy import select |
| 23 | +from sqlalchemy.ext.asyncio import AsyncSession |
| 24 | + |
| 25 | +from api.deps import get_db, get_current_user |
| 26 | +from db.models import Device, DeviceStatus, User |
| 27 | +from core.fingerprint.spoofer import FingerprintSpoofer |
| 28 | +from core.tools.adb import ADBTool |
| 29 | + |
| 30 | +router = APIRouter(prefix="/devices", tags=["device-controls"]) |
| 31 | +adb_tool = ADBTool() |
| 32 | +spoofer = FingerprintSpoofer() |
| 33 | +logger = logging.getLogger(__name__) |
| 34 | + |
| 35 | + |
| 36 | +# --------------------------------------------------------------------------- |
| 37 | +# Helpers |
| 38 | +# --------------------------------------------------------------------------- |
| 39 | + |
| 40 | +async def _running_device(device_id: int, db: AsyncSession, user: User) -> Device: |
| 41 | + r = await db.execute(select(Device).where(Device.id == device_id)) |
| 42 | + device = r.scalar_one_or_none() |
| 43 | + if not device: |
| 44 | + raise HTTPException(404, "Device not found") |
| 45 | + if device.owner_id != user.id and user.role.value != "admin": |
| 46 | + raise HTTPException(403, "Access denied") |
| 47 | + if device.status != DeviceStatus.running or not device.adb_serial: |
| 48 | + raise HTTPException(400, "Device must be running with ADB serial") |
| 49 | + return device |
| 50 | + |
| 51 | + |
| 52 | +# --------------------------------------------------------------------------- |
| 53 | +# GPS |
| 54 | +# --------------------------------------------------------------------------- |
| 55 | + |
| 56 | +class GpsBody(BaseModel): |
| 57 | + latitude: float = Field(..., ge=-90, le=90) |
| 58 | + longitude: float = Field(..., ge=-180, le=180) |
| 59 | + altitude: float = Field(0.0) |
| 60 | + accuracy: float = Field(12.0, ge=0) |
| 61 | + persist: bool = Field( |
| 62 | + False, |
| 63 | + description="If true, also update the stored fingerprint latitude/longitude/altitude", |
| 64 | + ) |
| 65 | + |
| 66 | + |
| 67 | +@router.post("/{device_id}/gps") |
| 68 | +async def set_gps_live( |
| 69 | + device_id: int, |
| 70 | + body: GpsBody, |
| 71 | + db: AsyncSession = Depends(get_db), |
| 72 | + user: User = Depends(get_current_user), |
| 73 | +): |
| 74 | + """ |
| 75 | + Set the device GPS location instantly via the emulator console (`geo fix`). |
| 76 | +
|
| 77 | + Works on Google AVD only (requires `console_port`). Does NOT require root. |
| 78 | + The coordinate is applied at the emulator-hardware level, so all apps that |
| 79 | + read GPS via `LocationManager` will see it immediately. |
| 80 | +
|
| 81 | + Pass ``persist=true`` to also update the fingerprint row in the database. |
| 82 | + """ |
| 83 | + device = await _running_device(device_id, db, user) |
| 84 | + if not device.console_port: |
| 85 | + raise HTTPException(400, "Device has no console_port — GPS control requires AVD emulator") |
| 86 | + |
| 87 | + ok = await spoofer._telnet_command( |
| 88 | + device.console_port, |
| 89 | + f"geo fix {body.longitude} {body.latitude} {body.altitude}", |
| 90 | + ) |
| 91 | + if not ok: |
| 92 | + raise HTTPException(502, "geo fix command failed — check emulator console connectivity") |
| 93 | + |
| 94 | + if body.persist: |
| 95 | + from db.models import DeviceFingerprint |
| 96 | + r2 = await db.execute(select(DeviceFingerprint).where(DeviceFingerprint.device_id == device_id)) |
| 97 | + fp = r2.scalar_one_or_none() |
| 98 | + if fp: |
| 99 | + fp.latitude = body.latitude |
| 100 | + fp.longitude = body.longitude |
| 101 | + fp.altitude = body.altitude |
| 102 | + await db.flush() |
| 103 | + |
| 104 | + return { |
| 105 | + "success": True, |
| 106 | + "applied": f"geo fix {body.longitude} {body.latitude} {body.altitude}", |
| 107 | + "persisted": body.persist, |
| 108 | + } |
| 109 | + |
| 110 | + |
| 111 | +# --------------------------------------------------------------------------- |
| 112 | +# Battery |
| 113 | +# --------------------------------------------------------------------------- |
| 114 | + |
| 115 | +class BatteryBody(BaseModel): |
| 116 | + level: int = Field(..., ge=0, le=100, description="Battery percentage 0–100") |
| 117 | + charging: bool = Field(False, description="True = AC charging; False = discharging") |
| 118 | + temperature_celsius: float = Field(32.0, ge=0, le=60) |
| 119 | + |
| 120 | + |
| 121 | +@router.post("/{device_id}/battery") |
| 122 | +async def set_battery_live( |
| 123 | + device_id: int, |
| 124 | + body: BatteryBody, |
| 125 | + db: AsyncSession = Depends(get_db), |
| 126 | + user: User = Depends(get_current_user), |
| 127 | +): |
| 128 | + """ |
| 129 | + Set battery level, charging state, and temperature via emulator console. |
| 130 | + """ |
| 131 | + device = await _running_device(device_id, db, user) |
| 132 | + if not device.console_port: |
| 133 | + raise HTTPException(400, "Device has no console_port") |
| 134 | + |
| 135 | + cmds = [ |
| 136 | + f"power capacity {body.level}", |
| 137 | + "power status ac" if body.charging else "power status discharging", |
| 138 | + f"power health good", |
| 139 | + f"power temp {int(body.temperature_celsius * 10)}", |
| 140 | + ] |
| 141 | + applied = [] |
| 142 | + failed = [] |
| 143 | + for cmd in cmds: |
| 144 | + ok = await spoofer._telnet_command(device.console_port, cmd) |
| 145 | + (applied if ok else failed).append(cmd) |
| 146 | + |
| 147 | + return { |
| 148 | + "success": len(failed) == 0, |
| 149 | + "applied": applied, |
| 150 | + "failed": failed, |
| 151 | + } |
| 152 | + |
| 153 | + |
| 154 | +# --------------------------------------------------------------------------- |
| 155 | +# Network type |
| 156 | +# --------------------------------------------------------------------------- |
| 157 | + |
| 158 | +_NETWORK_SPEED_MAP = { |
| 159 | + "WIFI": "full", |
| 160 | + "LTE": "lte", |
| 161 | + "5G": "5g", |
| 162 | + "3G": "umts", |
| 163 | + "2G": "gprs", |
| 164 | + "EDGE": "edge", |
| 165 | + "HSPA": "hsdpa", |
| 166 | + "NONE": "full", |
| 167 | +} |
| 168 | + |
| 169 | + |
| 170 | +class NetworkTypeBody(BaseModel): |
| 171 | + network_type: str = Field( |
| 172 | + ..., |
| 173 | + description="One of: WIFI, LTE, 5G, 3G, 2G, EDGE, HSPA", |
| 174 | + ) |
| 175 | + persist: bool = False |
| 176 | + |
| 177 | + |
| 178 | +@router.post("/{device_id}/network-type") |
| 179 | +async def set_network_type_live( |
| 180 | + device_id: int, |
| 181 | + body: NetworkTypeBody, |
| 182 | + db: AsyncSession = Depends(get_db), |
| 183 | + user: User = Depends(get_current_user), |
| 184 | +): |
| 185 | + """ |
| 186 | + Change the simulated network type/speed via emulator console. |
| 187 | + Also updates ``ro.telephony.default_network_type`` via setprop for label spoofing. |
| 188 | + """ |
| 189 | + device = await _running_device(device_id, db, user) |
| 190 | + nt = body.network_type.upper() |
| 191 | + if nt not in _NETWORK_SPEED_MAP: |
| 192 | + raise HTTPException(400, f"Unknown network_type {nt!r}. Valid: {sorted(_NETWORK_SPEED_MAP)}") |
| 193 | + |
| 194 | + results: dict = {"applied": [], "failed": []} |
| 195 | + |
| 196 | + if device.console_port: |
| 197 | + speed = _NETWORK_SPEED_MAP[nt] |
| 198 | + ok = await spoofer._telnet_command(device.console_port, f"network speed {speed}") |
| 199 | + (results["applied"] if ok else results["failed"]).append(f"network speed {speed}") |
| 200 | + |
| 201 | + # Also spoof the label via setprop |
| 202 | + label_map = {"WIFI": "1", "LTE": "11", "5G": "20", "3G": "3", "2G": "1"} |
| 203 | + label = label_map.get(nt, "11") |
| 204 | + try: |
| 205 | + await adb_tool.shell(device.adb_serial, f"setprop ro.telephony.default_network_type {label}") |
| 206 | + results["applied"].append(f"setprop ro.telephony.default_network_type={label}") |
| 207 | + except Exception as exc: |
| 208 | + results["failed"].append(f"setprop: {exc}") |
| 209 | + |
| 210 | + if body.persist: |
| 211 | + from db.models import DeviceFingerprint |
| 212 | + r2 = await db.execute(select(DeviceFingerprint).where(DeviceFingerprint.device_id == device_id)) |
| 213 | + fp = r2.scalar_one_or_none() |
| 214 | + if fp: |
| 215 | + fp.network_type = nt |
| 216 | + await db.flush() |
| 217 | + |
| 218 | + return {"success": len(results["failed"]) == 0, **results, "persisted": body.persist} |
0 commit comments