225 lines
8.8 KiB
JavaScript
225 lines
8.8 KiB
JavaScript
/*
|
||
* AutoJS 6:列出今天首次安装的应用,再逐个执行 pm uninstall。
|
||
* 不需要无障碍、截图或 OCR;卸载需要 Root 权限。
|
||
* 注意:默认真实卸载并删除应用数据。只看列表时将 dryRun 改为 true。
|
||
*/
|
||
var CONFIG = {
|
||
dryRun: false,
|
||
shellRoot: true,
|
||
commandTimeoutMs: 30000,
|
||
progressIntervalMs: 5000,
|
||
// 不希望卸载的应用包名,例如 "com.tencent.android.qqdownloader"。
|
||
keepPackages: []
|
||
};
|
||
|
||
function report(message) {
|
||
console.log("[uninstall_today_apps] " + message);
|
||
}
|
||
|
||
function getDayRange(now) {
|
||
var start = new Date(now.getTime());
|
||
start.setHours(0, 0, 0, 0);
|
||
var end = new Date(start.getTime());
|
||
// 按本地自然日计算,不能简单加 24 小时(兼容夏令时)。
|
||
end.setDate(end.getDate() + 1);
|
||
return { start: start.getTime(), end: end.getTime() };
|
||
}
|
||
|
||
function isValidPackageName(name) {
|
||
return /^[A-Za-z_][A-Za-z0-9_]*(\.[A-Za-z_][A-Za-z0-9_]*)*$/.test(name);
|
||
}
|
||
|
||
function isEligible(info, range, selfPackage) {
|
||
var name = String(info.packageName);
|
||
var installedAt = Number(info.firstInstallTime);
|
||
if (!isValidPackageName(name) || name === selfPackage ||
|
||
CONFIG.keepPackages.indexOf(name) !== -1) {
|
||
return false;
|
||
}
|
||
// FLAG_SYSTEM=1,FLAG_UPDATED_SYSTEM_APP=128;两类系统应用均不处理。
|
||
if (!info.applicationInfo || (Number(info.applicationInfo.flags) & (1 | 128)) !== 0) {
|
||
return false;
|
||
}
|
||
// 用首次安装时间,不把今天更新的老应用算作今天安装。
|
||
return installedAt >= range.start && installedAt < range.end;
|
||
}
|
||
|
||
function collectPackages(pm, range, selfPackage) {
|
||
// 不含 GET_UNINSTALLED_PACKAGES:仅扫描当前用户已安装且对 AutoJS 可见的应用。
|
||
var installed = pm.getInstalledPackages(0);
|
||
var result = [];
|
||
var seen = {};
|
||
for (var i = 0; i < installed.size(); i++) {
|
||
var info = installed.get(i);
|
||
var name = String(info.packageName);
|
||
if (isEligible(info, range, selfPackage) && !seen["$" + name]) {
|
||
seen["$" + name] = true;
|
||
result.push(name);
|
||
}
|
||
}
|
||
result.sort();
|
||
return result;
|
||
}
|
||
|
||
function quoteShell(value) {
|
||
return "'" + String(value).replace(/'/g, "'\\''") + "'";
|
||
}
|
||
|
||
function monotonicMillis() {
|
||
return Number(android.os.SystemClock.elapsedRealtime());
|
||
}
|
||
|
||
function createOutputFile() {
|
||
return java.io.File.createTempFile("uninstall_today_", ".log", context.getCacheDir());
|
||
}
|
||
|
||
function startCommandProcess(command, outputPath) {
|
||
// 不调用 AutoJS shell(),也不 readLine()/waitFor():避免 mus 或输出管道无限等待。
|
||
// 在外层 sh 重定向,连 mus 自身的授权错误也写入文件,不等待子进程关闭输出管道。
|
||
// 使用已确认的绝对路径,不依赖 AutoJS 进程的 PATH。
|
||
var executable = CONFIG.shellRoot ? "/system/xbin/mus" : "/system/bin/sh";
|
||
var script = "exec " + executable + " -c " + quoteShell(command) +
|
||
" > " + quoteShell(outputPath) + " 2>&1";
|
||
var args = java.lang.reflect.Array.newInstance(java.lang.String, 3);
|
||
args[0] = "/system/bin/sh";
|
||
args[1] = "-c";
|
||
args[2] = script;
|
||
return new java.lang.ProcessBuilder(args).start();
|
||
}
|
||
|
||
function runCommand(command) {
|
||
if (!(CONFIG.commandTimeoutMs > 0) || !(CONFIG.progressIntervalMs > 0)) {
|
||
throw new Error("命令超时和进度间隔必须大于 0");
|
||
}
|
||
var outputFile = createOutputFile();
|
||
var outputPath = String(outputFile.getAbsolutePath());
|
||
var process = null;
|
||
var started = monotonicMillis();
|
||
var nextProgress = CONFIG.progressIntervalMs;
|
||
try {
|
||
process = startCommandProcess(command, outputPath);
|
||
while (true) {
|
||
var code = null;
|
||
try {
|
||
code = Number(process.exitValue());
|
||
} catch (running) {
|
||
// Java Process.exitValue() 在进程仍运行时抛 IllegalThreadStateException。
|
||
}
|
||
if (code !== null) {
|
||
return { code: code, result: String(files.read(outputPath)), error: "" };
|
||
}
|
||
var elapsed = monotonicMillis() - started;
|
||
if (elapsed >= CONFIG.commandTimeoutMs) {
|
||
var partialOutput;
|
||
try {
|
||
partialOutput = String(files.read(outputPath)).slice(-4000);
|
||
} catch (readError) {
|
||
partialOutput = "无法读取输出:" + String(readError);
|
||
}
|
||
var timeout = new Error("命令超时(" + Math.floor(elapsed / 1000) +
|
||
" 秒):" + command + ";输出=" + partialOutput);
|
||
timeout.commandTimedOut = true;
|
||
throw timeout;
|
||
}
|
||
if (elapsed >= nextProgress) {
|
||
report("等待命令完成(" + Math.floor(elapsed / 1000) + " 秒):" + command);
|
||
nextProgress = elapsed + CONFIG.progressIntervalMs;
|
||
}
|
||
sleep(200);
|
||
}
|
||
} finally {
|
||
if (process !== null) {
|
||
try { process.destroy(); } catch (ignoreDestroy) {}
|
||
}
|
||
try { outputFile.delete(); } catch (ignoreDelete) {}
|
||
}
|
||
}
|
||
|
||
function checkCommandPermission() {
|
||
report("检查执行身份(" + (CONFIG.shellRoot ? "/system/xbin/mus -c id" : "sh -c id") +
|
||
"),最长等待 " + Math.ceil(CONFIG.commandTimeoutMs / 1000) + " 秒");
|
||
var identity = runCommand("id");
|
||
var output = String(identity.result).trim();
|
||
report("执行身份:" + output);
|
||
if (identity.code !== 0 || (CONFIG.shellRoot && !/(^|\s)uid=0\b/.test(output))) {
|
||
throw new Error("未获得 Root 执行身份,请检查 /system/xbin/mus 是否可从 AutoJS 进程使用及其 Root 权限;" +
|
||
"code=" + identity.code + " 输出=" + output);
|
||
}
|
||
}
|
||
|
||
function uninstallPackage(name) {
|
||
// 即使单独调用,也不允许未校验的包名拼进命令。
|
||
if (!isValidPackageName(name)) {
|
||
throw new Error("非法包名:" + name);
|
||
}
|
||
var command = "pm uninstall " + name;
|
||
report("执行:" + command);
|
||
var result = runCommand(command);
|
||
var stdout = result && result.result != null ? String(result.result).trim() : "";
|
||
var stderr = result && result.error != null ? String(result.error).trim() : "";
|
||
// 不能只看退出码,部分 ROM 的 pm 失败时退出码仍可能为 0。
|
||
if (!result || Number(result.code) !== 0 || !/^Success$/m.test(stdout)) {
|
||
throw new Error("code=" + (result ? result.code : "无结果") +
|
||
" stdout=" + stdout + " stderr=" + stderr);
|
||
}
|
||
}
|
||
|
||
function main() {
|
||
var selfPackage = String(context.getPackageName());
|
||
if (!isValidPackageName(selfPackage)) {
|
||
throw new Error("无法获取 AutoJS 自身包名,已停止以防误卸载");
|
||
}
|
||
var now = new Date();
|
||
var range = getDayRange(now);
|
||
var pm = context.getPackageManager();
|
||
var packages = collectPackages(pm, range, selfPackage);
|
||
report("设备本地日期:" + now.toLocaleDateString() + ";按首次安装时间筛选");
|
||
// 必须先完成扫描并输出整个列表,再开始卸载。
|
||
report("当天安装的待卸载包名列表(已过滤保护项):" + JSON.stringify(packages));
|
||
report("共 " + packages.length + " 个;已跳过系统应用、AutoJS 自身和保留名单");
|
||
if (CONFIG.dryRun) {
|
||
report("仅查看模式,不执行卸载");
|
||
return;
|
||
}
|
||
if (packages.length === 0) {
|
||
report("没有需要卸载的应用");
|
||
return;
|
||
}
|
||
// 先用无副作用的 id 检查提权,避免每个包都等待一次 mus 提权超时。
|
||
checkCommandPermission();
|
||
var succeeded = 0;
|
||
var failed = [];
|
||
var unprocessed = [];
|
||
for (var i = 0; i < packages.length; i++) {
|
||
var name = packages[i];
|
||
try {
|
||
uninstallPackage(name);
|
||
succeeded++;
|
||
report("卸载成功:" + name);
|
||
} catch (error) {
|
||
failed.push(name);
|
||
report("卸载失败:" + name + ";" + String(error));
|
||
if (error.commandTimedOut) {
|
||
// destroy() 不保证终止 mus 派生的所有子进程,不能并发继续或自动重试。
|
||
unprocessed = packages.slice(i + 1);
|
||
report("上一条卸载结果未知,已停止本批任务;请核实安装状态后再运行");
|
||
break;
|
||
}
|
||
}
|
||
}
|
||
report("处理完毕:成功 " + succeeded + " 个,失败/状态未知 " + failed.length + " 个");
|
||
if (failed.length > 0) {
|
||
report("失败/状态未知包名列表:" + JSON.stringify(failed));
|
||
}
|
||
if (unprocessed.length > 0) {
|
||
report("尚未处理包名列表:" + JSON.stringify(unprocessed));
|
||
}
|
||
}
|
||
|
||
try {
|
||
main();
|
||
} catch (error) {
|
||
report("脚本失败:" + String(error.stack || error));
|
||
throw error;
|
||
}
|