350 lines
20 KiB
JavaScript
350 lines
20 KiB
JavaScript
"ui";
|
||
|
||
// AutoJs6 可视化串行任务管理器。将本文件与 lib 目录放在同一个文件夹。
|
||
var ENTRY = String(engines.myEngine().getSource());
|
||
var BASE = parentDirectory(files.path(ENTRY));
|
||
var DATA = files.join(BASE, "data");
|
||
var PLAN_FILE = files.join(DATA, "plan.json");
|
||
var LOG_FILE = files.join(DATA, "manager.log");
|
||
var STATUS_FILE = files.join(DATA, "status.json");
|
||
var core = require(files.join(BASE, "lib/scheduler.js"));
|
||
var createAdapter = require(files.join(BASE, "lib/autojs-adapter.js")).createAdapter;
|
||
var adapter = null;
|
||
var scheduler = null;
|
||
var floatingWindow = null;
|
||
var closing = false;
|
||
var recentLogs = [];
|
||
var rowControls = [];
|
||
|
||
function canonical(path) { return String(new java.io.File(String(path)).getCanonicalPath()); }
|
||
// AutoJs6 的 files 模块没有 dirname;统一通过 Android 的 Java File 取父目录。
|
||
function parentDirectory(path) {
|
||
var parent = new java.io.File(String(path)).getParent();
|
||
return parent === null ? "/" : String(parent);
|
||
}
|
||
function guard(action) {
|
||
return function () {
|
||
try { return action.apply(null, arguments); }
|
||
catch (error) { toast(String(error.message || error)); log(String(error)); }
|
||
};
|
||
}
|
||
function ensureIdle() {
|
||
if (scheduler && scheduler.isBusy()) throw new Error("请先停止整组,确认当前脚本退出后再修改任务");
|
||
}
|
||
function chooseExisting(paths) {
|
||
for (var i = 0; i < paths.length; i++) if (files.exists(paths[i])) return paths[i];
|
||
return paths[0];
|
||
}
|
||
function defaultPlan() {
|
||
return {version: 1, loops: 1, gapSeconds: 3, floating: true, tasks: [
|
||
{id: "fanqie", name: "番茄小说", enabled: true, times: 1, timeoutMinutes: 480, retries: 0, onFailure: "skip",
|
||
path: chooseExisting(["/sdcard/脚本/番茄/fanqie-daily.auto.js", "/sdcard/脚本/fanqie-daily.auto.js", "/sdcard/Download/fanqie-daily.auto.js"])},
|
||
{id: "hongguo", name: "红果免费短剧", enabled: true, times: 1, timeoutMinutes: 120, retries: 0, onFailure: "skip",
|
||
path: chooseExisting(["/sdcard/脚本/红果/hongguo-daily.auto.js", "/sdcard/脚本/hongguo-daily.auto.js", "/sdcard/Download/hongguo-daily.auto.js"])}
|
||
]};
|
||
}
|
||
function loadPlan() {
|
||
if (!files.exists(PLAN_FILE)) return core.normalizePlan(defaultPlan());
|
||
try { return core.normalizePlan(JSON.parse(files.read(PLAN_FILE))); }
|
||
catch (error) {
|
||
var backup = PLAN_FILE + ".broken-" + Date.now();
|
||
if (!files.copy(PLAN_FILE, backup)) throw new Error("配置损坏且无法保留副本,请检查:" + PLAN_FILE);
|
||
toast("旧配置无法读取,已保留副本;当前使用默认任务");
|
||
return core.normalizePlan(defaultPlan());
|
||
}
|
||
}
|
||
function atomicWrite(path, text) {
|
||
files.ensureDir(DATA + "/");
|
||
files.write(path + ".tmp", text);
|
||
if (!new java.io.File(path + ".tmp").renameTo(new java.io.File(path))) throw new Error("保存失败:" + path);
|
||
}
|
||
function appendLog(message, state) {
|
||
var line = new Date().toISOString() + " " + message;
|
||
recentLogs.push(line);
|
||
if (recentLogs.length > 6) recentLogs.shift();
|
||
files.append(LOG_FILE, line + "\n");
|
||
if (state) atomicWrite(STATUS_FILE, JSON.stringify({updatedAt: new Date().toISOString(), state: state}, null, 2));
|
||
log(line);
|
||
}
|
||
|
||
// 第二次打开时保留原管理器及它正在运行的任务,不强停旧实例。
|
||
var duplicate = engines.all().some(function (engine) {
|
||
return engine.id !== engines.myEngine().id && /(?:^|\/)task-manager\.auto\.js$/.test(String(engine.getSource()));
|
||
});
|
||
if (duplicate) {
|
||
toast("任务管理器已经运行,请从最近任务切回原界面");
|
||
activity.finish();
|
||
exit();
|
||
}
|
||
|
||
files.ensureDir(DATA + "/");
|
||
if (files.exists(LOG_FILE) && new java.io.File(LOG_FILE).length() > 1024 * 1024) {
|
||
if (files.copy(LOG_FILE, LOG_FILE + ".previous")) files.write(LOG_FILE, "");
|
||
}
|
||
var plan = loadPlan();
|
||
ui.layout(
|
||
'<vertical bg="#F3F5F8">' +
|
||
'<vertical padding="18 16" bg="#173B71">' +
|
||
'<text text="脚本任务管理器" textSize="23sp" textColor="#FFFFFF" textStyle="bold"/>' +
|
||
'<text text="按顺序运行 · 等待结束 · 自动循环" textSize="13sp" textColor="#D9E6FF" marginTop="5"/>' +
|
||
'</vertical>' +
|
||
'<scroll w="*" h="0" layout_weight="1"><vertical padding="16">' +
|
||
'<vertical padding="14" bg="#FFFFFF">' +
|
||
'<text id="phaseText" text="尚未开始" textSize="19sp" textColor="#173B71" textStyle="bold"/>' +
|
||
'<text id="progressText" textSize="14sp" textColor="#344054" marginTop="8"/>' +
|
||
'<text id="messageText" textSize="13sp" textColor="#667085" marginTop="5"/>' +
|
||
'</vertical>' +
|
||
'<text text="整组设置" textSize="17sp" textColor="#172B4D" marginTop="18" textStyle="bold"/>' +
|
||
'<horizontal gravity="center_vertical" marginTop="8">' +
|
||
'<vertical w="0" layout_weight="1"><text text="循环次数 · 0 为无限" textSize="13sp"/>' +
|
||
'<input id="loopsInput" inputType="number" singleLine="true" textSize="17sp"/></vertical>' +
|
||
'<vertical w="0" layout_weight="1" marginLeft="12"><text text="任务间隔 · 秒" textSize="13sp"/>' +
|
||
'<input id="gapInput" inputType="number" singleLine="true" textSize="17sp"/></vertical>' +
|
||
'</horizontal>' +
|
||
'<Switch id="floatSwitch" text="运行时显示悬浮状态和停止按钮" textSize="14sp" padding="0 8"/>' +
|
||
'<text text="暂停会结束当前脚本;继续时从下一次未执行项接着运行。管理器需保持运行,界面可以退到后台。" textSize="12sp" textColor="#667085"/>' +
|
||
'<horizontal gravity="center_vertical" marginTop="16">' +
|
||
'<text text="任务顺序" textSize="17sp" textStyle="bold" textColor="#172B4D" w="0" layout_weight="1"/>' +
|
||
'<button id="addButton" text="添加脚本" textSize="14sp"/>' +
|
||
'</horizontal>' +
|
||
'<vertical id="taskRows"/>' +
|
||
'<text text="最近记录" textSize="17sp" textStyle="bold" textColor="#172B4D" marginTop="18"/>' +
|
||
'<text id="logText" text="等待开始" textSize="12sp" textColor="#667085" textIsSelectable="true" padding="0 8"/>' +
|
||
'</vertical></scroll>' +
|
||
'<horizontal padding="10 6" bg="#FFFFFF">' +
|
||
'<button id="saveButton" text="保存" w="0" layout_weight="1"/>' +
|
||
'<button id="startButton" text="开始整组" w="0" layout_weight="2" textColor="#173B71"/>' +
|
||
'<button id="pauseButton" text="暂停" w="0" layout_weight="2" textColor="#173B71"/>' +
|
||
'<button id="stopButton" text="停止整组" w="0" layout_weight="2" textColor="#B42318"/>' +
|
||
'</horizontal>' +
|
||
'</vertical>'
|
||
);
|
||
ui.loopsInput.setText(String(plan.loops));
|
||
ui.gapInput.setText(String(plan.gapSeconds));
|
||
ui.floatSwitch.setChecked(plan.floating);
|
||
|
||
function settingsPlan() {
|
||
return core.normalizePlan({tasks: plan.tasks, loops: String(ui.loopsInput.text()),
|
||
gapSeconds: String(ui.gapInput.text()), floating: ui.floatSwitch.isChecked()});
|
||
}
|
||
function persist() {
|
||
var next = settingsPlan();
|
||
atomicWrite(PLAN_FILE, JSON.stringify(next, null, 2));
|
||
plan = next;
|
||
}
|
||
function commitTasks(edit) {
|
||
ensureIdle();
|
||
var next = settingsPlan();
|
||
edit(next.tasks);
|
||
next = core.normalizePlan(next);
|
||
atomicWrite(PLAN_FILE, JSON.stringify(next, null, 2));
|
||
plan = next;
|
||
renderRows();
|
||
}
|
||
function escapeXml(text) {
|
||
return String(text).replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">")
|
||
.replace(/"/g, """).replace(/'/g, "'");
|
||
}
|
||
function renderRows() {
|
||
ui.taskRows.removeAllViews();
|
||
rowControls = [];
|
||
plan.tasks.forEach(function (task, index) {
|
||
var row = ui.inflate('<vertical bg="#FFFFFF" padding="10" marginTop="8">' +
|
||
'<horizontal gravity="center_vertical"><checkbox id="enabledBox"/>' +
|
||
'<text text="' + escapeXml((index + 1) + ". " + task.name) + '" w="0" layout_weight="1" textSize="16sp" textStyle="bold"/></horizontal>' +
|
||
'<text text="' + escapeXml(task.path) + '" textSize="12sp" textColor="#667085"/>' +
|
||
'<text text="' + escapeXml(task.times + " 次 · 每次 " + task.timeoutMinutes + " 分钟超时 · 重试 " + task.retries + " 次 · 失败" +
|
||
(task.onFailure === "skip" ? "跳过" : "停止整组")) + '" textSize="12sp" textColor="#344054" marginTop="4"/>' +
|
||
'<horizontal marginTop="4"><button id="upButton" text="上移" w="0" layout_weight="1" textSize="13sp"/>' +
|
||
'<button id="downButton" text="下移" w="0" layout_weight="1" textSize="13sp"/>' +
|
||
'<button id="editButton" text="编辑" w="0" layout_weight="1" textSize="13sp"/>' +
|
||
'<button id="deleteButton" text="删除" w="0" layout_weight="1" textSize="13sp"/></horizontal></vertical>', ui.taskRows, false);
|
||
row.enabledBox.setChecked(task.enabled);
|
||
row.enabledBox.on("check", function (checked) {
|
||
guard(function () { commitTasks(function (tasks) { tasks[index].enabled = checked; }); })();
|
||
// 保存失败也恢复为已保存的勾选状态。
|
||
renderRows();
|
||
});
|
||
row.upButton.on("click", guard(function () { if (!index) return;
|
||
commitTasks(function (tasks) { var previous = tasks[index - 1]; tasks[index - 1] = tasks[index]; tasks[index] = previous; }); }));
|
||
row.downButton.on("click", guard(function () { if (index + 1 >= plan.tasks.length) return;
|
||
commitTasks(function (tasks) { var next = tasks[index + 1]; tasks[index + 1] = tasks[index]; tasks[index] = next; }); }));
|
||
row.editButton.on("click", guard(function () { ensureIdle(); editTask(index); }));
|
||
row.deleteButton.on("click", guard(function () {
|
||
ensureIdle();
|
||
dialogs.confirm("移除任务", "从列表移除“" + task.name + "”?手机里的脚本文件会保留。", function (yes) {
|
||
if (yes) guard(function () { commitTasks(function (tasks) { tasks.splice(index, 1); }); })();
|
||
});
|
||
}));
|
||
ui.taskRows.addView(row);
|
||
rowControls.push([row.enabledBox, row.upButton, row.downButton, row.editButton, row.deleteButton]);
|
||
});
|
||
}
|
||
|
||
function browseScript(directory, callback) {
|
||
if (!files.isDir(directory)) directory = "/sdcard/";
|
||
var names = files.listDir(directory, function (name) {
|
||
var path = files.join(directory, name);
|
||
return files.isDir(path) || /\.js$/i.test(name);
|
||
}) || [];
|
||
names.sort(function (a, b) {
|
||
var aDir = files.isDir(files.join(directory, a));
|
||
var bDir = files.isDir(files.join(directory, b));
|
||
return aDir !== bDir ? (aDir ? -1 : 1) : a.localeCompare(b);
|
||
});
|
||
var labels = names.map(function (name) { return (files.isDir(files.join(directory, name)) ? "文件夹 " : "脚本 ") + name; });
|
||
labels.unshift("上一级文件夹");
|
||
dialogs.select("选择脚本 · " + directory, labels, function (index) {
|
||
guard(function () {
|
||
if (index < 0) return;
|
||
if (index === 0) { browseScript(parentDirectory(directory.replace(/\/$/, "")), callback); return; }
|
||
var path = files.join(directory, names[index - 1]);
|
||
if (files.isDir(path)) browseScript(path, callback);
|
||
else callback(path);
|
||
})();
|
||
});
|
||
}
|
||
|
||
function editTask(index) {
|
||
var task = index < 0 ? {name: "", path: "", times: 1, timeoutMinutes: 120, retries: 0, onFailure: "skip", enabled: true} : plan.tasks[index];
|
||
var form = ui.inflate('<scroll><vertical padding="18">' +
|
||
'<text text="任务名称"/><input id="taskName" singleLine="true"/>' +
|
||
'<text text="脚本完整路径"/><input id="taskPath" textSize="13sp" singleLine="false"/>' +
|
||
'<button id="browseButton" text="浏览手机脚本"/>' +
|
||
'<text text="每轮执行次数"/><input id="timesInput" inputType="number" singleLine="true"/>' +
|
||
'<text text="单次超时(分钟)"/><input id="timeoutInput" inputType="number" singleLine="true"/>' +
|
||
'<text text="失败后额外重试次数"/><input id="retryInput" inputType="number" singleLine="true"/>' +
|
||
'<text text="重试耗尽后"/><spinner id="policyInput" entries="跳过此任务|停止整组"/>' +
|
||
'<text text="跳过会略过此任务在本轮的剩余次数,继续下一个任务。" textSize="12sp" textColor="#667085"/>' +
|
||
'</vertical></scroll>');
|
||
form.taskName.setText(task.name); form.taskPath.setText(task.path);
|
||
form.timesInput.setText(String(task.times)); form.timeoutInput.setText(String(task.timeoutMinutes));
|
||
form.retryInput.setText(String(task.retries)); form.policyInput.setSelection(task.onFailure === "stop" ? 1 : 0);
|
||
form.browseButton.on("click", guard(function () {
|
||
browseScript(files.exists("/sdcard/脚本") ? "/sdcard/脚本" : "/sdcard/Download", function (path) {
|
||
form.taskPath.setText(path);
|
||
if (!String(form.taskName.text()).trim()) form.taskName.setText(files.getName(path));
|
||
});
|
||
}));
|
||
var dialog = dialogs.build({title: index < 0 ? "添加脚本" : "编辑任务", customView: form,
|
||
positive: "保存任务", negative: "取消", autoDismiss: false});
|
||
dialog.on("negative", function () { dialog.dismiss(); });
|
||
dialog.on("positive", guard(function () {
|
||
ensureIdle();
|
||
var edited = {id: task.id || "task-" + Date.now(), enabled: task.enabled, name: String(form.taskName.text()),
|
||
path: String(form.taskPath.text()).trim(), times: String(form.timesInput.text()),
|
||
timeoutMinutes: String(form.timeoutInput.text()), retries: String(form.retryInput.text()),
|
||
onFailure: form.policyInput.getSelectedItemPosition() === 1 ? "stop" : "skip"};
|
||
if (!files.exists(edited.path) || files.isDir(edited.path)) throw new Error("找不到该脚本,请检查完整路径");
|
||
if (/task-manager\.auto\.js$/i.test(edited.path)) throw new Error("管理器不能把自身加入任务列表");
|
||
var normalized = core.normalizePlan({tasks: [edited], loops: 1, gapSeconds: 0}).tasks[0];
|
||
commitTasks(function (tasks) { if (index < 0) tasks.push(normalized); else tasks[index] = normalized; });
|
||
dialog.dismiss();
|
||
}));
|
||
dialog.show();
|
||
}
|
||
|
||
function closeFloating() {
|
||
if (floatingWindow) { floatingWindow.close(); floatingWindow = null; }
|
||
}
|
||
function togglePause() {
|
||
if (scheduler.pauseRequested) scheduler.requestResume(Date.now());
|
||
else scheduler.requestPause(Date.now());
|
||
updateScreen();
|
||
}
|
||
function showFloating() {
|
||
if (!plan.floating) return;
|
||
floatingWindow = floaty.rawWindow('<vertical padding="8" bg="#E6173B71" w="152">' +
|
||
'<text id="statusLabel" text="整组运行中 · 拖动可移动" textSize="12sp" textColor="#FFFFFF" padding="0 5"/>' +
|
||
'<button id="pauseQueue" text="暂停" h="44" textSize="13sp"/>' +
|
||
'<button id="stopQueue" text="停止整组" h="44" textSize="13sp"/></vertical>');
|
||
floatingWindow.setPosition(0, Math.round(device.height * 0.25));
|
||
floatingWindow.stopQueue.on("click", guard(function () { scheduler.requestStop(); }));
|
||
floatingWindow.pauseQueue.on("click", guard(togglePause));
|
||
var drag = null;
|
||
floatingWindow.statusLabel.setOnTouchListener(new android.view.View.OnTouchListener({onTouch: function (view, event) {
|
||
if (!floatingWindow) return false;
|
||
if (event.getAction() === 0) drag = {x: event.getRawX(), y: event.getRawY(), left: floatingWindow.getX(), top: floatingWindow.getY()};
|
||
else if (event.getAction() === 2 && drag) {
|
||
floatingWindow.setPosition(Math.max(0, Math.min(device.width - floatingWindow.getWidth(), drag.left + event.getRawX() - drag.x)),
|
||
Math.max(0, Math.min(device.height - floatingWindow.getHeight(), drag.top + event.getRawY() - drag.y)));
|
||
}
|
||
return true;
|
||
}}));
|
||
}
|
||
|
||
function updateScreen() {
|
||
if (!scheduler || closing) return;
|
||
var state = scheduler.status(Date.now());
|
||
var names = {idle: "尚未开始", waiting: "等待下一次执行", running: "正在执行", pausing: "正在结束当前脚本", paused: "整组已暂停", stopping: "正在停止", blocked: "停止待确认",
|
||
completed: "整组已结束", stopped: "整组已停止", failed: "因失败停止"};
|
||
ui.phaseText.setText(names[state.phase]);
|
||
ui.progressText.setText(state.taskCount ? "第 " + state.round + "/" + (state.loops || "∞") + " 轮 · " + state.taskName +
|
||
"\n本轮第 " + Math.min(state.index, state.taskCount) + "/" + state.taskCount + " 个任务 · 第 " + state.repetition + "/" + (state.times || "—") +
|
||
" 次 · 已运行 " + state.elapsedSeconds + " 秒\n成功 " + state.successes + " 次 · 失败尝试 " + state.failures + " 次 · 跳过 " + state.skipped + " 个任务" +
|
||
(state.interrupted ? " · 暂停结束 " + state.interrupted + " 次" : "") : "还未启动任务");
|
||
ui.messageText.setText(state.message + (state.observerError ? "\n运行记录保存失败:" + state.observerError : ""));
|
||
ui.logText.setText(recentLogs.join("\n") || "等待开始");
|
||
var busy = scheduler.isBusy();
|
||
[ui.startButton, ui.saveButton, ui.addButton, ui.loopsInput, ui.gapInput, ui.floatSwitch].forEach(function (view) { view.setEnabled(!busy); });
|
||
ui.stopButton.setEnabled(busy);
|
||
ui.pauseButton.setEnabled(scheduler.canTogglePause());
|
||
ui.pauseButton.setText(state.pauseRequested ? "继续" : "暂停");
|
||
rowControls.forEach(function (controls) { controls.forEach(function (view) { view.setEnabled(!busy); }); });
|
||
if (floatingWindow) {
|
||
floatingWindow.pauseQueue.setEnabled(scheduler.canTogglePause());
|
||
floatingWindow.pauseQueue.setText(state.pauseRequested ? "继续" : "暂停");
|
||
floatingWindow.statusLabel.setText(state.taskName + "\n第 " + state.round + " 轮 · " + state.repetition + "/" + state.times + " 次\n" + names[state.phase]);
|
||
if (!busy) closeFloating();
|
||
}
|
||
}
|
||
|
||
try {
|
||
adapter = createAdapter({engines: engines, files: files, parentDirectory: parentDirectory});
|
||
scheduler = new core.Scheduler(adapter, function (message, state) { appendLog(message, state); });
|
||
} catch (initialError) { toastLog(String(initialError)); throw initialError; }
|
||
|
||
ui.addButton.on("click", guard(function () { ensureIdle(); editTask(-1); }));
|
||
ui.saveButton.on("click", guard(function () { ensureIdle(); persist(); toast("配置已保存"); }));
|
||
ui.stopButton.on("click", guard(function () { scheduler.requestStop(); updateScreen(); }));
|
||
ui.pauseButton.on("click", guard(togglePause));
|
||
ui.startButton.on("click", guard(function () {
|
||
ensureIdle();
|
||
var candidate = settingsPlan();
|
||
candidate.tasks.filter(function (task) { return task.enabled; }).forEach(function (task) {
|
||
if (!files.exists(task.path) || files.isDir(task.path)) throw new Error("脚本不存在,请先编辑路径:" + task.path);
|
||
if (canonical(task.path) === canonical(ENTRY) || /task-manager\.auto\.js$/i.test(task.path)) throw new Error("不能运行管理器自身");
|
||
});
|
||
var otherEngines = engines.all().filter(function (engine) { return engine.id !== engines.myEngine().id; });
|
||
if (otherEngines.length) throw new Error("请先结束其他运行中的脚本,避免同时操作手机:" + otherEngines[0].getSource());
|
||
if (candidate.floating && !floaty.hasPermission()) {
|
||
toast("请允许 AutoJs6 悬浮窗权限后再点开始,也可以关闭悬浮状态开关");
|
||
floaty.requestPermission(); return;
|
||
}
|
||
plan = candidate; persist();
|
||
try { showFloating(); scheduler.start(plan, Date.now() + 500); }
|
||
catch (error) { closeFloating(); throw error; }
|
||
updateScreen();
|
||
activity.moveTaskToBack(true);
|
||
}));
|
||
|
||
ui.emitter.on("back_pressed", function (event) {
|
||
if (scheduler && scheduler.isBusy()) { event.consumed = true; activity.moveTaskToBack(true); }
|
||
});
|
||
events.on("exit", function () {
|
||
closing = true;
|
||
if (adapter) adapter.close();
|
||
try { closeFloating(); } catch (ignore) {}
|
||
});
|
||
renderRows();
|
||
updateScreen();
|
||
setInterval(function () {
|
||
if (closing) return;
|
||
try { scheduler.tick(Date.now()); updateScreen(); }
|
||
catch (error) {
|
||
// 意外异常时停止当前引擎;保留 active 等待销毁确认,不能直接启动下一任务。
|
||
scheduler.requestStop();
|
||
toastLog("管理器异常,正在停止整组:" + error);
|
||
}
|
||
}, 500);
|