"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(
'' +
'' +
'' +
'' +
'' +
'' +
'' +
'' +
'' +
'' +
'' +
'' +
'' +
'' +
'' +
'' +
'' +
'' +
'' +
'' +
'' +
'' +
'' +
'' +
'' +
'' +
'' +
'' +
'' +
'' +
'' +
'' +
'' +
''
);
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, "'");
}
function renderRows() {
ui.taskRows.removeAllViews();
rowControls = [];
plan.tasks.forEach(function (task, index) {
var row = ui.inflate('' +
'' +
'' +
'' +
'' +
'' +
'' +
'' +
'', 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('' +
'' +
'' +
'' +
'' +
'' +
'' +
'' +
'' +
'');
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 showFloating() {
if (!plan.floating) return;
floatingWindow = floaty.rawWindow('' +
'' +
'');
floatingWindow.setPosition(0, Math.round(device.height * 0.25));
floatingWindow.stopQueue.on("click", guard(function () { scheduler.requestStop(); }));
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: "正在执行", 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 + " 个任务" : "还未启动任务");
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);
rowControls.forEach(function (controls) { controls.forEach(function (view) { view.setEnabled(!busy); }); });
if (floatingWindow) {
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.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);