Support shell commands in batch runner (adb shell/pm/cmd formats)
This commit is contained in:
parent
e371a0c3be
commit
b2c4de90d6
4 changed files with 147 additions and 16 deletions
8
api.php
8
api.php
|
|
@ -299,6 +299,14 @@ try {
|
|||
$result = adb_send_text($ip, $text);
|
||||
} elseif ($cmdType === 'launch_home') {
|
||||
$result = adb_send_key($ip, 'KEYCODE_HOME');
|
||||
} elseif ($cmdType === 'shell') {
|
||||
$raw = (string) ($input['shell'] ?? $input['cmd'] ?? $input['text'] ?? '');
|
||||
$shellCmd = normalize_adb_shell_command($raw);
|
||||
if ($shellCmd === '') {
|
||||
json_out(['ok' => false, 'error' => 'Empty or comment-only shell command.'], 400);
|
||||
}
|
||||
$res = adb_run_shell_command($ip, $shellCmd, 30);
|
||||
$result = ['ok' => $res['ok'], 'output' => $res['output'], 'command_line' => $shellCmd];
|
||||
} else {
|
||||
json_out(['ok' => false, 'error' => 'Unsupported command type.'], 400);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -478,6 +478,34 @@
|
|||
}
|
||||
}
|
||||
|
||||
function parseBatchLine(line) {
|
||||
let cmd = String(line || '').trim();
|
||||
if (!cmd || cmd.startsWith('#')) return null;
|
||||
|
||||
// Strip inline comment
|
||||
const hashIdx = cmd.indexOf(' #');
|
||||
if (hashIdx !== -1) cmd = cmd.slice(0, hashIdx).trim();
|
||||
if (!cmd || cmd.startsWith('#')) return null;
|
||||
|
||||
// Strip adb prefixes
|
||||
let shell = cmd;
|
||||
const adbShellMatch = shell.match(/^adb\s+-s\s+\S+\s+shell\s+(.+)$/i) || shell.match(/^adb\s+shell\s+(.+)$/i);
|
||||
if (adbShellMatch) {
|
||||
shell = adbShellMatch[1].trim();
|
||||
}
|
||||
|
||||
// Keycode if single token and looks like keycode
|
||||
const isSingleToken = !/\s/.test(shell);
|
||||
const keyCandidate = normalizeKeycode(shell);
|
||||
if (isSingleToken && /^KEYCODE_[A-Z0-9_]+$/.test(keyCandidate)) {
|
||||
// If original had adb shell prefix, treat as shell command unless clearly a keycode intent? No - "adb shell input keyevent KEYCODE_HOME" is shell.
|
||||
// But our stripped shell would be "input keyevent KEYCODE_HOME" (has spaces) so won't hit here. Good.
|
||||
return { type: 'key', value: keyCandidate, label: keyCandidate };
|
||||
}
|
||||
|
||||
return { type: 'shell', value: shell, label: shell };
|
||||
}
|
||||
|
||||
async function runBatch() {
|
||||
const device = getSelectedDevice();
|
||||
if (!device) {
|
||||
|
|
@ -485,10 +513,7 @@
|
|||
return;
|
||||
}
|
||||
const lines = String(els.batchInput.value || '').split(/\r?\n/);
|
||||
const commands = lines
|
||||
.map(l => l.trim())
|
||||
.filter(l => l && !l.startsWith('#'))
|
||||
.map(normalizeKeycode);
|
||||
const commands = lines.map(parseBatchLine).filter(Boolean);
|
||||
|
||||
if (!commands.length) {
|
||||
setAlert(els.commandAlert, 'Enter at least one command (one per line).', 'warning');
|
||||
|
|
@ -501,23 +526,25 @@
|
|||
let failCount = 0;
|
||||
|
||||
for (let i = 0; i < commands.length; i++) {
|
||||
const key = commands[i];
|
||||
els.scanMeta.textContent = `Batch: ${i + 1}/${commands.length} ${key}`;
|
||||
const cmd = commands[i];
|
||||
els.scanMeta.textContent = `Batch: ${i + 1}/${commands.length} ${cmd.label}`;
|
||||
try {
|
||||
const data = await api('command', { ip: device.ip, command: 'key', keycode: key }, 'POST');
|
||||
if (data.ok) {
|
||||
okCount++;
|
||||
log(`BATCH ${i + 1}/${commands.length} ${key} -> ${device.ip}: ok`);
|
||||
let data;
|
||||
if (cmd.type === 'key') {
|
||||
data = await api('command', { ip: device.ip, command: 'key', keycode: cmd.value }, 'POST');
|
||||
} else {
|
||||
failCount++;
|
||||
log(`BATCH ${i + 1}/${commands.length} ${key} -> ${device.ip}: ${data.error || data.output || 'failed'}`);
|
||||
data = await api('command', { ip: device.ip, command: 'shell', shell: cmd.value }, 'POST');
|
||||
}
|
||||
const ok = !!data.ok;
|
||||
if (ok) okCount++; else failCount++;
|
||||
const detail = data.output ? ` | ${String(data.output).slice(0, 200)}` : '';
|
||||
log(`BATCH ${i + 1}/${commands.length} [${cmd.type}] ${cmd.label} -> ${device.ip}: ${ok ? 'ok' : (data.error || 'failed')}${detail}`);
|
||||
} catch (e) {
|
||||
failCount++;
|
||||
log(`BATCH ${i + 1}/${commands.length} ${key} -> ${device.ip}: ${e.message}`);
|
||||
log(`BATCH ${i + 1}/${commands.length} [${cmd.type}] ${cmd.label} -> ${device.ip}: ${e.message}`);
|
||||
}
|
||||
if (i < commands.length - 1) {
|
||||
await new Promise(r => setTimeout(r, 250));
|
||||
await new Promise(r => setTimeout(r, 300));
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -136,8 +136,8 @@ declare(strict_types=1);
|
|||
<p class="section-title">Batch Commands</p>
|
||||
<div class="field">
|
||||
<label for="batchInput">Paste commands (one per line)</label>
|
||||
<textarea id="batchInput" rows="6" placeholder="KEYCODE_HOME KEYCODE_DPAD_DOWN KEYCODE_DPAD_CENTER"></textarea>
|
||||
<p class="hint">Runs keycodes in order, one per line. Lines starting with <code>#</code> and empty lines are ignored. Only whitelisted keycodes are accepted.</p>
|
||||
<textarea id="batchInput" rows="7" placeholder="adb shell pm uninstall -k --user 0 com.example.app pm disable-user --user 0 com.example.app KEYCODE_HOME"></textarea>
|
||||
<p class="hint">Runs commands in order. Supports keycodes (<code>KEYCODE_HOME</code>), shell commands (<code>pm ...</code>), and full <code>adb shell ...</code> lines. Lines starting with <code>#</code> and inline <code> # comments</code> are ignored.</p>
|
||||
</div>
|
||||
<div class="actions no-margin-top">
|
||||
<button type="button" class="button button-primary button-small" id="runBatchBtn">Run Batch</button>
|
||||
|
|
|
|||
96
lib/adb.php
96
lib/adb.php
|
|
@ -90,6 +90,55 @@ function run_cmd(string $cmd, int $timeout = 10): array
|
|||
];
|
||||
}
|
||||
|
||||
function run_cmd_array(array $args, int $timeout = 15): array
|
||||
{
|
||||
$descriptors = [
|
||||
0 => ['pipe', 'r'],
|
||||
1 => ['pipe', 'w'],
|
||||
2 => ['pipe', 'w'],
|
||||
];
|
||||
$proc = proc_open($args, $descriptors, $pipes, null, null);
|
||||
if (!is_resource($proc)) {
|
||||
return ['ok' => false, 'code' => 1, 'stdout' => '', 'stderr' => 'Failed to start process', 'timed_out' => false];
|
||||
}
|
||||
fclose($pipes[0]);
|
||||
stream_set_blocking($pipes[1], false);
|
||||
stream_set_blocking($pipes[2], false);
|
||||
$stdout = '';
|
||||
$stderr = '';
|
||||
$start = microtime(true);
|
||||
$timedOut = false;
|
||||
while (true) {
|
||||
$status = proc_get_status($proc);
|
||||
$stdout .= stream_get_contents($pipes[1]);
|
||||
$stderr .= stream_get_contents($pipes[2]);
|
||||
if (!$status['running']) {
|
||||
break;
|
||||
}
|
||||
if ((microtime(true) - $start) > $timeout) {
|
||||
$timedOut = true;
|
||||
proc_terminate($proc, 9);
|
||||
break;
|
||||
}
|
||||
usleep(50000);
|
||||
}
|
||||
$stdout .= stream_get_contents($pipes[1]);
|
||||
$stderr .= stream_get_contents($pipes[2]);
|
||||
fclose($pipes[1]);
|
||||
fclose($pipes[2]);
|
||||
$code = proc_close($proc);
|
||||
if ($timedOut) {
|
||||
$code = 124;
|
||||
}
|
||||
return [
|
||||
'ok' => $code === 0 && !$timedOut,
|
||||
'code' => $code,
|
||||
'stdout' => trim($stdout),
|
||||
'stderr' => trim($stderr),
|
||||
'timed_out' => $timedOut,
|
||||
];
|
||||
}
|
||||
|
||||
function adb_connect(string $ip): array
|
||||
{
|
||||
$target = adb_target($ip);
|
||||
|
|
@ -240,6 +289,53 @@ function adb_send_text(string $ip, string $text): array
|
|||
return ['ok' => $res['ok'], 'output' => $out];
|
||||
}
|
||||
|
||||
function normalize_adb_shell_command(string $line): string
|
||||
{
|
||||
$cmd = trim($line);
|
||||
if ($cmd === '' || str_starts_with($cmd, '#')) {
|
||||
return '';
|
||||
}
|
||||
|
||||
// Strip inline comment (simple heuristic: " #...")
|
||||
$hashPos = strpos($cmd, ' #');
|
||||
if ($hashPos !== false) {
|
||||
$cmd = trim(substr($cmd, 0, $hashPos));
|
||||
}
|
||||
if (str_starts_with($cmd, '#')) {
|
||||
return '';
|
||||
}
|
||||
|
||||
// Strip common prefixes
|
||||
if (preg_match('/^adb\s+-s\s+\S+\s+shell\s+(.+)$/i', $cmd, $m)) {
|
||||
$cmd = trim($m[1]);
|
||||
} elseif (preg_match('/^adb\s+shell\s+(.+)$/i', $cmd, $m)) {
|
||||
$cmd = trim($m[1]);
|
||||
}
|
||||
|
||||
return trim($cmd);
|
||||
}
|
||||
|
||||
function adb_run_shell_command(string $ip, string $command, int $timeout = 20): array
|
||||
{
|
||||
$command = trim($command);
|
||||
if ($command === '') {
|
||||
return ['ok' => false, 'code' => 1, 'stdout' => '', 'stderr' => 'Empty command', 'timed_out' => false, 'output' => 'Empty command'];
|
||||
}
|
||||
// Basic guardrails: no newlines, limit length
|
||||
if (preg_match('/[\r\n\0]/', $command)) {
|
||||
return ['ok' => false, 'code' => 1, 'stdout' => '', 'stderr' => 'Invalid command', 'timed_out' => false, 'output' => 'Invalid command'];
|
||||
}
|
||||
if (strlen($command) > 500) {
|
||||
return ['ok' => false, 'code' => 1, 'stdout' => '', 'stderr' => 'Command too long', 'timed_out' => false, 'output' => 'Command too long (max 500 chars)'];
|
||||
}
|
||||
|
||||
$target = adb_target($ip);
|
||||
$res = run_cmd_array([adb_bin(), '-s', $target, 'shell', $command], $timeout);
|
||||
$out = trim($res['stdout'] . "\n" . $res['stderr']);
|
||||
$res['output'] = $out;
|
||||
return $res;
|
||||
}
|
||||
|
||||
function devices_path(): string
|
||||
{
|
||||
return __DIR__ . '/../data/devices.json';
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue