From b0d4bbbc3b703a72928d0713af665d372de4450f Mon Sep 17 00:00:00 2001 From: xgh Date: Wed, 4 Nov 2026 17:48:42 +0800 Subject: [PATCH] =?UTF-8?q?=E5=A2=9E=E5=8A=A0=E5=BA=94=E7=94=A8=E5=88=97?= =?UTF-8?q?=E8=A1=A8=E6=8E=92=E5=BA=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- android-bridge/README.md | 14 +- .../java/com/cpagent/bridge/BridgeService.kt | 46 +++-- .../java/com/cpagent/bridge/MainActivity.kt | 79 ++++---- .../com/cpagent/bridge/agent/AtxDeployer.kt | 191 +++++++++++------- .../cpagent/bridge/handler/CommandRouter.kt | 72 ++++--- 5 files changed, 231 insertions(+), 171 deletions(-) diff --git a/android-bridge/README.md b/android-bridge/README.md index 1fbbd40..31ab634 100644 --- a/android-bridge/README.md +++ b/android-bridge/README.md @@ -25,17 +25,19 @@ ## 使用步骤 -1. **手机端准备 atx-agent**(非 root,需一次性 adb): +1. 在 Root 设备上安装并打开 CP Bridge APK,填写服务器地址(如 `ws://192.168.1.100:8000/ws/device`)、token(服务器启用时才需要)、设备名称并保存。 +2. 在启动桥接服务前,点击「部署 atx-agent(需 Root)」并在 Root 管理器中授权。APK 会将内置 atx-agent 复制到 `/data/local/tmp/atx-agent` 并启动它,以系统进程列表中能查到该进程作为部署成功条件。 +3. 点击「启动桥接服务」;状态卡显示「已连接服务器」即接入成功。 +4. 管理平台 Web 页面(http://服务器:8000)会出现该设备,可执行支持的设备操作。 + +没有 Root 时,可使用 ADB 手动推送并启动: ```bash adb push atx-agent /data/local/tmp/atx-agent adb shell chmod 755 /data/local/tmp/atx-agent - adb shell /data/local/tmp/atx-agent server -d # 启动 atx-agent + adb shell /data/local/tmp/atx-agent server -d ``` -2. 安装并打开 CP Bridge APK,填写服务器地址(如 `ws://192.168.1.100:8000/ws/device`)、token(服务器启用时才需要)、设备名称,保存 -3. 点击「启动桥接服务」;状态卡显示「已连接服务器」即接入成功 -4. 管理平台 Web 页面(http://服务器:8000)会出现该设备,可执行 Shell / 查看设备信息 -> 重启手机后 atx-agent 进程会丢失,需重新 `adb shell /data/local/tmp/atx-agent server -d`(root 设备可自行加入启动脚本)。 +Root 部署和 ADB 部署都使用 `/data/local/tmp/atx-agent`。文件只需安装一次;设备重启后进程会退出,重新点部署按钮(Root)或执行启动命令(ADB)即可。 ## 模块说明 diff --git a/android-bridge/app/src/main/java/com/cpagent/bridge/BridgeService.kt b/android-bridge/app/src/main/java/com/cpagent/bridge/BridgeService.kt index bdc7d8b..bcb25a5 100644 --- a/android-bridge/app/src/main/java/com/cpagent/bridge/BridgeService.kt +++ b/android-bridge/app/src/main/java/com/cpagent/bridge/BridgeService.kt @@ -10,12 +10,12 @@ import android.content.Intent import android.content.SharedPreferences import android.content.pm.ServiceInfo import android.os.Build +import android.os.PowerManager import android.provider.Settings import android.util.Log import androidx.core.app.NotificationCompat import androidx.core.app.ServiceCompat import com.cpagent.bridge.agent.AtxClient -import com.cpagent.bridge.agent.AtxDeployer import com.cpagent.bridge.agent.DeviceBasicInfo import com.cpagent.bridge.handler.CommandRouter import com.cpagent.bridge.monitor.HeartbeatMonitor @@ -28,7 +28,6 @@ import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.cancel import kotlinx.coroutines.launch -import kotlinx.coroutines.withContext import org.json.JSONObject /** @@ -78,21 +77,7 @@ class BridgeService : Service() { private var wsClient: BridgeWsClient? = null private var deviceId: String = "" private var atxClient: AtxClient? = null - private var deployer: AtxDeployer? = null - - /** 手动触发:root 检测 + 部署 + 启动 atx-agent,结果通过回调返回。 */ - fun deployAtxAgent(onResult: (Boolean, String) -> Unit) { - val atx = atxClient ?: AtxClient().also { atxClient = it } - val d = deployer ?: AtxDeployer(this).also { deployer = it } - scope.launch { - val ok = d.ensureRunning(atx) - val msg = if (ok) "atx-agent 已就绪" else "部署失败(无 root 或启动超时),详见日志 CpBridgeAtxDeploy" - if (ok) agentHealthy = true - notifyState() - withContext(Dispatchers.Main) { onResult(ok, msg) } - } - } - + private var wakeLock: PowerManager.WakeLock? = null override fun onCreate() { super.onCreate() instance = this @@ -119,8 +104,6 @@ class BridgeService : Service() { private fun startBridge() { Log.i(TAG, "startBridge() called, running=$running") if (running) return - running = true - lastError = "" ServiceCompat.startForeground( this, NOTIFICATION_ID, buildNotification("连接中..."), ServiceInfo.FOREGROUND_SERVICE_TYPE_CONNECTED_DEVICE, @@ -134,10 +117,14 @@ class BridgeService : Service() { if (serverUrl.isBlank()) { Log.e(TAG, "serverUrl 为空,服务不启动") lastError = "未配置服务器地址" - updateNotification("未配置服务器地址") + stopSelf() return } + running = true + lastError = "" + acquireWakeLock() + val basicInfo = DeviceBasicInfo.of(deviceId, deviceName) val atx = AtxClient().also { atxClient = it } @@ -194,6 +181,7 @@ class BridgeService : Service() { running = false instance = null wsClient?.close() + releaseWakeLock() scope.cancel() notifyState() super.onDestroy() @@ -201,6 +189,24 @@ class BridgeService : Service() { override fun onBind(intent: Intent?) = null + /** 屏幕关闭时维持 CPU 活跃,避免桥接心跳和 WebSocket 指令处理被深度休眠暂停。 */ + private fun acquireWakeLock() { + if (wakeLock?.isHeld == true) return + val powerManager = getSystemService(Context.POWER_SERVICE) as PowerManager + wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "$TAG:Bridge").apply { + setReferenceCounted(false) + acquire() + } + Log.i(TAG, "已获取部分唤醒锁") + } + + private fun releaseWakeLock() { + wakeLock?.let { lock -> + if (lock.isHeld) lock.release() + } + wakeLock = null + } + private fun buildNotification(text: String): Notification { val nm = getSystemService(NOTIFICATION_SERVICE) as NotificationManager if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { diff --git a/android-bridge/app/src/main/java/com/cpagent/bridge/MainActivity.kt b/android-bridge/app/src/main/java/com/cpagent/bridge/MainActivity.kt index 8dda267..2dd40e6 100644 --- a/android-bridge/app/src/main/java/com/cpagent/bridge/MainActivity.kt +++ b/android-bridge/app/src/main/java/com/cpagent/bridge/MainActivity.kt @@ -33,7 +33,6 @@ import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.BatteryAlert import androidx.compose.material.icons.filled.CheckCircle import androidx.compose.material.icons.filled.CloudOff -import androidx.compose.material.icons.filled.Memory import androidx.compose.material.icons.filled.PhoneAndroid import androidx.compose.material.icons.filled.PlayArrow import androidx.compose.material.icons.filled.Settings @@ -60,6 +59,7 @@ import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier @@ -69,8 +69,10 @@ import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.core.content.ContextCompat +import com.cpagent.bridge.agent.AtxDeployer import com.cpagent.bridge.ws.WsState import kotlinx.coroutines.delay +import kotlinx.coroutines.launch class MainActivity : ComponentActivity() { @@ -333,8 +335,9 @@ private fun ConfigCard( @Composable private fun ControlCard(context: Context) { val running = BridgeService.running + val scope = rememberCoroutineScope() var deploying by remember { mutableStateOf(false) } - var deployMsg by remember { mutableStateOf("") } + var deployMessage by remember { mutableStateOf("") } Card( shape = RoundedCornerShape(20.dp), colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surface), @@ -342,38 +345,45 @@ private fun ControlCard(context: Context) { ) { Column(Modifier.padding(20.dp), verticalArrangement = Arrangement.spacedBy(12.dp)) { Text("桥接服务", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.SemiBold) - if (running) { + if (!running) { OutlinedButton( + enabled = !deploying, onClick = { - if (deploying) return@OutlinedButton - deploying = true - deployMsg = "检测 root 并部署中..." - BridgeService.instance?.deployAtxAgent { ok, msg -> + scope.launch { + deploying = true + deployMessage = "正在请求 Root 并部署 atx-agent…" + val started = AtxDeployer(context.applicationContext).ensureRunning() + deployMessage = if (started) "atx-agent 进程已启动,可以启动桥接服务" + else "部署失败:请检查 Root 授权状态和应用日志;也可使用 ADB 手动启动" deploying = false - deployMsg = if (ok) "✓ $msg" else "✗ $msg" } }, - enabled = !deploying, modifier = Modifier.fillMaxWidth().height(48.dp), shape = RoundedCornerShape(14.dp), ) { - if (deploying) { - CircularProgressIndicator(Modifier.size(18.dp), strokeWidth = 2.dp) - } else { - Icon(Icons.Filled.Memory, null, Modifier.size(18.dp)) - } + if (deploying) CircularProgressIndicator(Modifier.size(18.dp), strokeWidth = 2.dp) + else Text("部署 atx-agent(需 Root)") + } + if (deployMessage.isNotBlank()) { + Text(deployMessage, style = MaterialTheme.typography.bodySmall, + color = if (deployMessage.startsWith("部署失败")) MaterialTheme.colorScheme.error + else MaterialTheme.colorScheme.onSurfaceVariant) + } + Button( + enabled = !deploying, + onClick = { + context.startForegroundService(Intent(context, BridgeService::class.java).apply { + action = BridgeService.ACTION_START + }) + }, + modifier = Modifier.fillMaxWidth().height(48.dp), + shape = RoundedCornerShape(14.dp), + ) { + Icon(Icons.Filled.PlayArrow, null, Modifier.size(18.dp)) Spacer(Modifier.width(6.dp)) - Text(if (deploying) "部署中..." else "部署 atx-agent(需 Root)") - } - if (deployMsg.isNotBlank()) { - Text( - deployMsg, - style = MaterialTheme.typography.bodySmall, - color = if (deployMsg.startsWith("✓")) MaterialTheme.colorScheme.primary - else if (deployMsg.startsWith("✗")) MaterialTheme.colorScheme.error - else MaterialTheme.colorScheme.onSurfaceVariant, - ) + Text("启动桥接服务") } + } else { Button( onClick = { context.startService(Intent(context, BridgeService::class.java).apply { @@ -389,20 +399,6 @@ private fun ControlCard(context: Context) { Spacer(Modifier.width(6.dp)) Text("停止服务", color = MaterialTheme.colorScheme.onErrorContainer) } - } else { - Button( - onClick = { - context.startForegroundService(Intent(context, BridgeService::class.java).apply { - action = BridgeService.ACTION_START - }) - }, - modifier = Modifier.fillMaxWidth().height(48.dp), - shape = RoundedCornerShape(14.dp), - ) { - Icon(Icons.Filled.PlayArrow, null, Modifier.size(18.dp)) - Spacer(Modifier.width(6.dp)) - Text("启动桥接服务") - } } } } @@ -428,6 +424,11 @@ private fun HintCard(context: Context) { else "建议加入电池优化白名单,防止服务被系统休眠时杀掉", style = MaterialTheme.typography.bodySmall, ) + Text( + "桥接服务运行时会保持 CPU 唤醒,以便屏幕关闭后继续收发指令;持续运行会增加耗电。", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSecondaryContainer.copy(alpha = 0.7f), + ) if (!ignoring) { OutlinedButton( onClick = { @@ -441,7 +442,7 @@ private fun HintCard(context: Context) { } } Text( - "Root 设备可在上方「桥接服务」中一键部署 atx-agent;非 Root 设备需 adb 手动启动:adb shell /data/local/tmp/atx-agent server -d", + "Root 设备可先点“部署 atx-agent(需 Root)”,授权后会从 APK 安装并启动,并确认进程已运行;没有 Root 时,可按 README 中的 ADB 命令手动启动。设备重启后需重新启动 atx-agent。", style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSecondaryContainer.copy(alpha = 0.7f), ) diff --git a/android-bridge/app/src/main/java/com/cpagent/bridge/agent/AtxDeployer.kt b/android-bridge/app/src/main/java/com/cpagent/bridge/agent/AtxDeployer.kt index b826bd8..ab22a7d 100644 --- a/android-bridge/app/src/main/java/com/cpagent/bridge/agent/AtxDeployer.kt +++ b/android-bridge/app/src/main/java/com/cpagent/bridge/agent/AtxDeployer.kt @@ -3,103 +3,142 @@ package com.cpagent.bridge.agent import android.content.Context import android.util.Log import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.delay import kotlinx.coroutines.withContext -import kotlinx.coroutines.withTimeoutOrNull import java.io.File +import java.util.concurrent.TimeUnit -/** - * root 设备上自动部署并启动 atx-agent: - * 1. 探活 7912,在线则跳过 - * 2. 无 root 则跳过(需手动 adb 启动) - * 3. 从 assets 释放二进制到 /data/local/tmp/atx-agent(chmod 755) - * 4. su 启动 `atx-agent server -d`,轮询等待就绪 - */ +/** Root deployment of the APK-bundled atx-agent. */ class AtxDeployer(private val context: Context) { companion object { private const val TAG = "CpBridgeAtxDeploy" private const val TARGET = "/data/local/tmp/atx-agent" private const val ASSET = "atx-agent" + private const val COMMAND_TIMEOUT_SECONDS = 25L + private const val EXIT_MARKER = "CP_BRIDGE_SHELL_EXIT=" } - data class SuResult(val ok: Boolean, val output: String) + private data class SuResult(val exitCode: Int?, val output: String, val timedOut: Boolean = false) { + val ok get() = exitCode == 0 && !timedOut + } - private fun su(cmd: String): SuResult = try { - val p = Runtime.getRuntime().exec(arrayOf("su", "-c", cmd)) - val out = buildString { - p.inputStream.bufferedReader().use { append(it.readText()) } - p.errorStream.bufferedReader().use { append(it.readText()) } + private fun findSu(): String? = listOf("/system/bin/su", "/system/xbin/su", "/sbin/su") + .firstOrNull { File(it).exists() } + + /** Some su implementations execute argv directly; give scripts to an explicit shell via stdin. */ + private fun su(binary: String, command: String): SuResult { + val process = try { + ProcessBuilder(binary, "-c", "/system/bin/sh") + .redirectErrorStream(true) + .start() + } catch (e: Exception) { + return SuResult(null, e.message ?: e.javaClass.simpleName) + } + val output = StringBuffer() + val reader = Thread { + // Closing the stream after a timeout must not raise an uncaught thread exception. + runCatching { + process.inputStream.bufferedReader(Charsets.UTF_8).use { input -> + val buffer = CharArray(2048) + while (true) { + val count = input.read(buffer) + if (count < 0) break + synchronized(output) { + output.append(buffer, 0, count) + if (output.length > 65536) output.delete(0, output.length - 65536) + } + } + } + } + }.apply { isDaemon = true; start() } + + return try { + process.outputStream.bufferedWriter(Charsets.UTF_8).use { input -> + // EXIT also catches explicit exit and set -e failures in deployment scripts. + input.write("trap 'cp_bridge_status=\$?; printf \"\\n${EXIT_MARKER}%s\\n\" \"\$cp_bridge_status\"' EXIT\n") + input.write(command) + input.write("\n") + } + if (!process.waitFor(COMMAND_TIMEOUT_SECONDS, TimeUnit.SECONDS)) { + process.destroyForcibly() + SuResult(null, output.toString().trim(), timedOut = true) + } else { + reader.join(1000) + val lines = output.toString().lines() + val shellExit = lines.lastOrNull { it.startsWith(EXIT_MARKER) } + ?.removePrefix(EXIT_MARKER)?.trim()?.toIntOrNull() + val commandOutput = lines.filterNot { it.startsWith(EXIT_MARKER) }.joinToString("\n").trim() + if (shellExit == null) { + SuResult(null, "Root shell 未返回执行结果,su exit=${process.exitValue()}: $commandOutput") + } else { + SuResult(shellExit, commandOutput) + } + } + } catch (e: Exception) { + process.destroyForcibly() + SuResult(null, e.message ?: e.javaClass.simpleName) + } finally { + runCatching { process.outputStream.close() } + runCatching { process.inputStream.close() } + runCatching { process.errorStream.close() } } - SuResult(p.waitFor() == 0, out.trim()) - } catch (e: Exception) { - SuResult(false, e.message ?: e.javaClass.simpleName) } - fun hasRoot(): Boolean { - val r = su("id") - return r.ok && r.output.contains("uid=0") - } + /** Deploy before BridgeService starts; success means the OS reports an atx-agent process. */ + suspend fun ensureRunning(): Boolean = withContext(Dispatchers.IO) { + val suBinary = findSu() + if (suBinary == null) { + Log.w(TAG, "未找到 su 文件,无法 Root 部署") + return@withContext false + } - /** atx-agent 已在线返回 true;否则 root 部署+启动;失败/无 root 返回 false。 */ - suspend fun ensureRunning(atx: AtxClient): Boolean = withContext(Dispatchers.IO) { - if (atx.ping()) { - Log.i(TAG, "atx-agent 已在线,跳过部署") + val existing = su(suBinary, "pidof atx-agent") + if (existing.timedOut || existing.exitCode == null || existing.exitCode !in 0..1) { + Log.e(TAG, "Root shell 进程查询失败,exit=${existing.exitCode}, timeout=${existing.timedOut}: ${existing.output}") + return@withContext false + } + if (existing.ok && existing.output.isNotBlank()) { + Log.i(TAG, "atx-agent 进程已运行,PID=${existing.output}") return@withContext true } - if (!hasRoot()) { - Log.i(TAG, "无 root 权限,跳过自动部署(需手动启动 atx-agent)") - return@withContext false - } - Log.i(TAG, "检测到 root,开始自动部署 atx-agent") - if (su("pidof atx-agent").output.isNotBlank()) { - // 进程在但 7912 不通:杀掉重装 - Log.w(TAG, "atx-agent 进程存在但端口不通,重启") - su("pkill -f atx-agent") - delay(1000) - } - - if (!install()) { - Log.e(TAG, "atx-agent 安装失败") - return@withContext false - } - - val start = su("nohup $TARGET server -d >/dev/null 2>&1 &") - if (!start.ok) { - Log.e(TAG, "atx-agent 启动失败: ${start.output}") - return@withContext false - } - Log.i(TAG, "atx-agent 启动命令已执行,等待 7912 就绪...") - - val ready = withTimeoutOrNull(20_000) { - while (true) { - if (atx.ping()) return@withTimeoutOrNull true - delay(500) - } - @Suppress("UNREACHABLE_CODE") false - } - if (ready == true) { - Log.i(TAG, "atx-agent 自动部署成功并已就绪") - } else { - Log.e(TAG, "atx-agent 启动后 20s 内未就绪") - } - ready == true - } - - private fun install(): Boolean { - val stage = File(context.cacheDir, "atx-agent-stage") - return try { + val stage = File(context.cacheDir, ASSET) + try { context.assets.open(ASSET).use { input -> - stage.outputStream().use { input.copyTo(it) } + stage.outputStream().use { output -> input.copyTo(output) } } - stage.setReadable(true, false) - stage.setExecutable(true, false) - val r = su("cp '${stage.absolutePath}' $TARGET && chmod 755 $TARGET") - stage.delete() - if (!r.ok) Log.e(TAG, "复制到 $TARGET 失败: ${r.output}") - r.ok } catch (e: Exception) { - Log.e(TAG, "释放 assets 失败: ${e.message}") + Log.e(TAG, "读取 APK 内 atx-agent 失败", e) + return@withContext false + } + + val stagedPath = stage.absolutePath.replace("'", "'\\''") + val installCommand = "set -e; id; cp '$stagedPath' '$TARGET'; chmod 755 '$TARGET'; " + + "test -f '$TARGET'; test -x '$TARGET'; echo CP_BRIDGE_INSTALL_OK; ls -l '$TARGET'" + val install = su(suBinary, installCommand) + if (!install.ok || !install.output.contains("CP_BRIDGE_INSTALL_OK")) { + val reason = if (install.timedOut) "su 部署命令超时" else "su 部署失败,exit=${install.exitCode},目标文件校验未通过" + Log.e(TAG, "$reason: ${install.output}") + return@withContext false + } + Log.i(TAG, "已在设备上验证 atx-agent 文件存在且可执行: ${install.output}") + + val start = su(suBinary, "'$TARGET' server -d >/dev/null 2>&1 2048 || '\\' in path || path.startsWith("/")) throw IllegalArgumentException("只能访问 /sdcard/Download") + if (path.length > 2048 || '\\' in path || path.startsWith("/")) throw IllegalArgumentException("只能访问 /sdcard") if (path.any { it.code < 32 || it.code == 127 }) throw IllegalArgumentException("文件路径包含控制字符") if (path.isEmpty() && allowRoot) return "" if (path.isBlank()) throw IllegalArgumentException("文件路径不能为空") @@ -181,7 +181,7 @@ class CommandRouter( private fun shellQuote(value: String): String = "'" + value.replace("'", "'\\''") + "'" - private fun remotePath(relative: String): String = if (relative.isEmpty()) DOWNLOAD_ROOT else "$DOWNLOAD_ROOT/$relative" + private fun remotePath(relative: String): String = if (relative.isEmpty()) SD_CARD_ROOT else "$SD_CARD_ROOT/$relative" private suspend fun canonicalPath(path: String): String { val result = atx.shell("readlink -f ${shellQuote(path)}", 10) @@ -189,23 +189,23 @@ class CommandRouter( return result.output.trim().lineSequence().last() } - /** 校验设备上的真实解析路径,拦截 Download 中指向外部目录的符号链接。 */ - private suspend fun requireInsideDownload(path: String, allowMissingLeaf: Boolean = false): String { - val root = canonicalPath(DOWNLOAD_ROOT).trimEnd('/') - if (path == DOWNLOAD_ROOT) return root - val candidate = remotePath(path.removePrefix("/sdcard/Download/").takeIf { path.startsWith("/sdcard/Download/") } ?: path) + /** 校验设备上的真实解析路径,拦截 /sdcard 中指向外部目录的符号链接。 */ + private suspend fun requireInsideSdCard(path: String, allowMissingLeaf: Boolean = false): String { + val root = canonicalPath(SD_CARD_ROOT).trimEnd('/') + if (path == SD_CARD_ROOT) return root + val candidate = remotePath(path) val actual = if (allowMissingLeaf) { val existing = atx.shell("test -e ${shellQuote(candidate)} || test -L ${shellQuote(candidate)}", 5).exitCode == 0 if (existing) { canonicalPath(candidate) } else { - val parent = candidate.substringBeforeLast('/', DOWNLOAD_ROOT) - val leaf = candidate.substringAfterLast('/') - val canonicalParent = canonicalPath(parent).trimEnd('/') - "$canonicalParent/$leaf" + val parent = candidate.substringBeforeLast('/', SD_CARD_ROOT) + val leaf = candidate.substringAfterLast('/') + val canonicalParent = canonicalPath(parent).trimEnd('/') + "$canonicalParent/$leaf" } } else canonicalPath(candidate) - if (actual != root && !actual.startsWith("$root/")) throw IllegalArgumentException("只能访问 /sdcard/Download") + if (actual != root && !actual.startsWith("$root/")) throw IllegalArgumentException("只能访问 /sdcard") return actual } @@ -232,7 +232,7 @@ class CommandRouter( private fun handleFileList(envelope: Envelope) = scope.launch { try { val relative = relativePath(envelope.str("path"), allowRoot = true) - val dir = requireInsideDownload(relative) + val dir = requireInsideSdCard(relative) val result = atx.shell("ls -1A ${shellQuote(dir)}", 20) checkShell(result, "读取目录失败") val names = result.output.lineSequence().map(String::trimEnd).filter { it.isNotEmpty() } @@ -242,7 +242,7 @@ class CommandRouter( for (name in names) { try { val childRel = if (relative.isEmpty()) name else "$relative/$name" - val childAbs = requireInsideDownload(childRel) + val childAbs = requireInsideSdCard(childRel) val info = try { json.parseToJsonElement(atx.get("/finfo/${encodedPath(childAbs)}")).jsonObject } catch (_: Exception) { @@ -261,7 +261,7 @@ class CommandRouter( put("modifiedAt", modifiedAt) } } catch (_: Exception) { - // Skip entries that disappear or resolve outside Download while listing. + // Skip entries that disappear or resolve outside /sdcard while listing. } } send(Proto.response(envelope.id, envelope.action, Proto.STATUS_SUCCESS, buildJsonObject { @@ -278,16 +278,16 @@ class CommandRouter( private fun handleFileMutation(envelope: Envelope, operation: String) = scope.launch { try { val relative = relativePath(envelope.str("path")) - val actual = requireInsideDownload(relative, allowMissingLeaf = operation == "mkdir") + val actual = requireInsideSdCard(relative, allowMissingLeaf = operation == "mkdir") val result = when (operation) { "mkdir" -> atx.shell("mkdir ${shellQuote(actual)}", 15) "delete" -> { - if (actual == canonicalPath(DOWNLOAD_ROOT)) throw IllegalArgumentException("不能删除 Download 根目录") + if (actual == canonicalPath(SD_CARD_ROOT)) throw IllegalArgumentException("不能删除 /sdcard 根目录") atx.shell("rm -rf ${shellQuote(actual)}", 30) } "rename" -> { val newRelative = relativePath(envelope.str("newPath")) - val destination = requireInsideDownload(newRelative, allowMissingLeaf = true) + val destination = requireInsideSdCard(newRelative, allowMissingLeaf = true) atx.shell("mv ${shellQuote(actual)} ${shellQuote(destination)}", 30) } else -> throw IllegalArgumentException("不支持的文件操作") @@ -306,7 +306,7 @@ class CommandRouter( cleanTransfers() val id = transferId(envelope) val relative = relativePath(envelope.str("path")) - requireInsideDownload(relative, allowMissingLeaf = true) + requireInsideSdCard(relative, allowMissingLeaf = true) val size = envelope.str("size")?.toLongOrNull() ?: throw IllegalArgumentException("文件大小无效") if (size !in 0..MAX_TRANSFER_SIZE) throw IllegalArgumentException("文件不能超过 512 MiB") val file = File(transferDir, "$id.upload.part") @@ -354,7 +354,7 @@ class CommandRouter( if (transfer.received != transfer.size || transfer.file.length() != transfer.size) throw IllegalArgumentException("上传文件长度不匹配") if (sha256(transfer.file) != expectedSha256) throw IllegalArgumentException("上传文件 SHA-256 校验失败") } - val target = requireInsideDownload(transfer.relativePath, allowMissingLeaf = true) + val target = requireInsideSdCard(transfer.relativePath, allowMissingLeaf = true) val name = target.substringAfterLast('/') val response = atx.uploadFile("/upload/${encodedPath(target.removePrefix("/"))}", transfer.file, name, readTimeoutSec = 300) val body = json.parseToJsonElement(response.ifBlank { "{}" }) @@ -375,7 +375,7 @@ class CommandRouter( val id = transferId(envelope) if (downloads.containsKey(id) || uploads.containsKey(id)) throw IllegalArgumentException("传输 ID 已存在") val relative = relativePath(envelope.str("path")) - val remote = requireInsideDownload(relative) + val remote = requireInsideSdCard(relative) if (atx.shell("test -f ${shellQuote(remote)}", 5).exitCode != 0) throw IllegalArgumentException("目标不是普通文件") transferDir.mkdirs() val file = File(transferDir, "$id.download.part") @@ -431,7 +431,7 @@ class CommandRouter( try { val relative = relativePath(envelope.str("path")) if (!relative.lowercase().endsWith(".apk")) throw IllegalArgumentException("只能安装 APK 文件") - val apk = requireInsideDownload(relative) + val apk = requireInsideSdCard(relative) if (atx.shell("test -f ${shellQuote(apk)}", 5).exitCode != 0) throw IllegalArgumentException("APK 文件不存在") val result = atx.shell("pm install -r ${shellQuote(apk)}", 180) val success = result.exitCode == 0 && result.output.contains("Success", ignoreCase = true) @@ -681,13 +681,18 @@ class CommandRouter( } .map { info -> val pkg = info.activityInfo.packageName - val ver = try { - val pi = pm.getPackageInfo(pkg, 0) - (pi.versionName ?: "") to (pi.longVersionCode.toInt()) + val packageInfo = try { + pm.getPackageInfo(pkg, 0) } catch (_: Exception) { - "" to 0 + null } - AppEntry(pkg, info.loadLabel(pm).toString(), ver.first, ver.second) + AppEntry( + pkg, + info.loadLabel(pm).toString(), + packageInfo?.versionName ?: "", + packageInfo?.longVersionCode?.toInt() ?: 0, + packageInfo?.firstInstallTime ?: 0L, + ) } .distinctBy { it.packageName } .sortedBy { it.label.lowercase() } @@ -698,6 +703,7 @@ class CommandRouter( put("name", app.label) put("versionName", app.versionName) put("versionCode", app.versionCode) + put("firstInstallTime", app.firstInstallTime) } } } @@ -708,7 +714,13 @@ class CommandRouter( } } - private data class AppEntry(val packageName: String, val label: String, val versionName: String, val versionCode: Int) + private data class AppEntry( + val packageName: String, + val label: String, + val versionName: String, + val versionCode: Int, + val firstInstallTime: Long, + ) private fun handleAppLaunch(envelope: Envelope) = scope.launch { val pkg = envelope.str("package") ?: ""