276 lines
12 KiB
JavaScript
276 lines
12 KiB
JavaScript
"use strict";
|
||
|
||
// 不依赖 Android;时钟和脚本引擎由外层提供,便于验证顺序、停止和重试。
|
||
function integer(value, name, min, max) {
|
||
if (!/^\d+$/.test(String(value)) || Number(value) < min || Number(value) > max) {
|
||
throw new Error(name + "须为 " + min + "~" + max + " 的整数");
|
||
}
|
||
return Number(value);
|
||
}
|
||
|
||
function knownResultLog(path) {
|
||
if (/\/fanqie-daily\.auto\.js$/i.test(path)) return "/sdcard/Download/fanqie-daily-run.log";
|
||
if (/\/hongguo-daily\.auto\.js$/i.test(path)) return "/sdcard/Download/hongguo-daily-run.log";
|
||
if (/\/qimao-daily\.auto\.js$/i.test(path)) return "/sdcard/Download/qimao-daily-run.log";
|
||
return "";
|
||
}
|
||
|
||
function normalizePlan(plan) {
|
||
if (!plan || !Array.isArray(plan.tasks)) throw new Error("任务配置格式无效");
|
||
var tasks = plan.tasks.map(function (task, index) {
|
||
var path = String(task.path || "").trim();
|
||
if (path.charAt(0) !== "/" || !/\.js$/i.test(path)) throw new Error("任务 " + (index + 1) + " 须填写 .js 脚本的完整路径");
|
||
var policy = task.onFailure || "skip";
|
||
if (policy !== "skip" && policy !== "stop") throw new Error("失败策略无效");
|
||
return {
|
||
id: String(task.id || "task-" + index), name: String(task.name || "").trim() || path.split("/").pop(), path: path,
|
||
enabled: task.enabled !== false,
|
||
times: integer(task.times, "脚本执行次数", 1, 100000),
|
||
timeoutMinutes: integer(task.timeoutMinutes, "单次超时(分钟)", 1, 1440),
|
||
retries: integer(task.retries, "失败重试次数", 0, 10), onFailure: policy,
|
||
resultLog: knownResultLog(path)
|
||
};
|
||
});
|
||
return {version: 1, loops: integer(plan.loops, "整组循环次数(0 为无限)", 0, 1000000),
|
||
gapSeconds: integer(plan.gapSeconds, "执行间隔(秒)", 0, 3600), floating: plan.floating === true, tasks: tasks};
|
||
}
|
||
|
||
function resultFromLog(before, after) {
|
||
if (!after || after === before) return {ok: false, reason: "未生成本轮结果日志"};
|
||
var lines = String(after).trim().split(/\r?\n/);
|
||
var ending = "";
|
||
for (var i = lines.length - 1; i >= 0; i--) {
|
||
if (/\b(?:END(?: INCOMPLETE)?|ERROR):/.test(lines[i])) { ending = lines[i]; break; }
|
||
}
|
||
if (!ending) return {ok: false, reason: "脚本已退出,但本轮日志没有 END、END INCOMPLETE 或 ERROR 结果"};
|
||
var failed = /\[NO_RETRY\]/.test(ending) || /\b(?:ERROR|END INCOMPLETE):/.test(ending) || /异常|失败|未就绪|未完成|未能|尚未确认|连续无进展/.test(ending);
|
||
return {ok: !failed, reason: ending.replace(/^.*?\b(?:END(?: INCOMPLETE)?|ERROR):\s*/, "")};
|
||
}
|
||
|
||
function Scheduler(adapter, onEvent, options) {
|
||
this.adapter = adapter;
|
||
this.onEvent = onEvent || function () {};
|
||
this.stopGraceMs = (options && options.stopGraceMs) || 15000;
|
||
this.phase = "idle";
|
||
this.message = "设置任务后点击开始";
|
||
this.active = null;
|
||
this.cancelled = false;
|
||
this.pauseRequested = false;
|
||
this.pauseRemainingMs = 0;
|
||
this.wasBlocked = false;
|
||
this.lastObserverError = "";
|
||
this.lastTask = "";
|
||
this.successes = 0;
|
||
this.failures = 0;
|
||
this.skipped = 0;
|
||
this.interrupted = 0;
|
||
}
|
||
|
||
Scheduler.prototype.isBusy = function () {
|
||
return /^(?:waiting|running|pausing|paused|stopping|blocked)$/.test(this.phase);
|
||
};
|
||
|
||
Scheduler.prototype.event = function (message) {
|
||
this.message = message;
|
||
// 日志或界面更新失败不等于脚本启动失败,尤其不能因此重复启动同一任务。
|
||
try { this.onEvent(message, this.status()); }
|
||
catch (error) { this.lastObserverError = String(error); }
|
||
};
|
||
|
||
Scheduler.prototype.start = function (plan, now) {
|
||
if (this.isBusy()) throw new Error("当前任务尚未完全停止,不能启动另一组");
|
||
var normalized = normalizePlan(plan);
|
||
normalized.tasks = normalized.tasks.filter(function (task) { return task.enabled; });
|
||
if (!normalized.tasks.length) throw new Error("请至少启用一个任务");
|
||
this.plan = normalized;
|
||
this.round = 1;
|
||
this.index = 0;
|
||
this.repetition = 1;
|
||
this.attempt = 0;
|
||
this.successes = 0;
|
||
this.failures = 0;
|
||
this.skipped = 0;
|
||
this.interrupted = 0;
|
||
this.active = null;
|
||
this.cancelled = false;
|
||
this.pauseRequested = false;
|
||
this.pauseRemainingMs = 0;
|
||
this.wasBlocked = false;
|
||
this.lastObserverError = "";
|
||
this.lastTask = "";
|
||
this.phase = "waiting";
|
||
this.readyAt = now;
|
||
this.event("整组开始:共 " + normalized.tasks.length + " 个任务");
|
||
};
|
||
|
||
Scheduler.prototype.requestStop = function () {
|
||
if (!this.isBusy()) return;
|
||
this.cancelled = true;
|
||
this.pauseRequested = false;
|
||
if (this.active && this.active.stopReason === "pause") {
|
||
this.active.stopReason = "user";
|
||
if (this.phase !== "blocked") this.phase = "stopping";
|
||
}
|
||
// blocked 时依然允许重发停止请求,但绝不放行下一任务。
|
||
if (this.phase === "blocked" && this.active) {
|
||
try { this.adapter.stop(this.active.handle); } catch (ignore) {}
|
||
}
|
||
this.event("已请求停止整组,等待当前脚本完全退出");
|
||
};
|
||
|
||
Scheduler.prototype.canTogglePause = function () {
|
||
return !this.cancelled && /^(?:waiting|running|pausing|paused)$/.test(this.phase);
|
||
};
|
||
|
||
// 暂停结束当前这次执行;确认引擎退出后保留下一次尚未执行的位置。
|
||
Scheduler.prototype.requestPause = function (now) {
|
||
if (!this.canTogglePause() || this.pauseRequested) return;
|
||
this.pauseRequested = true;
|
||
if (this.active) {
|
||
if (this.active.stopReason === "pause") this.event("已请求暂停,等待当前脚本完全退出");
|
||
else this.beginStop("pause", now);
|
||
} else {
|
||
this.pauseRemainingMs = Math.max(0, this.readyAt - now);
|
||
this.phase = "paused";
|
||
this.event("整组已暂停,点击继续后运行后续任务");
|
||
}
|
||
};
|
||
|
||
Scheduler.prototype.requestResume = function (now) {
|
||
if (!this.canTogglePause() || !this.pauseRequested) return;
|
||
this.pauseRequested = false;
|
||
if (this.active) {
|
||
this.event("已请求继续,等待当前脚本完全退出后运行下一次未执行项");
|
||
return;
|
||
}
|
||
this.phase = "waiting";
|
||
this.readyAt = now + this.pauseRemainingMs;
|
||
this.pauseRemainingMs = 0;
|
||
this.event("已继续整组,保持原任务顺序和执行次数");
|
||
};
|
||
|
||
Scheduler.prototype.waitForNext = function (now) {
|
||
this.readyAt = now + this.plan.gapSeconds * 1000;
|
||
this.phase = this.pauseRequested ? "paused" : "waiting";
|
||
if (this.pauseRequested) this.pauseRemainingMs = this.plan.gapSeconds * 1000;
|
||
};
|
||
|
||
Scheduler.prototype.finish = function (phase, message) {
|
||
this.phase = phase;
|
||
this.pauseRequested = false;
|
||
this.pauseRemainingMs = 0;
|
||
this.event(message);
|
||
};
|
||
|
||
Scheduler.prototype.beginStop = function (reason, now) {
|
||
this.active.stopReason = reason;
|
||
this.active.stopAt = now;
|
||
this.phase = reason === "pause" ? "pausing" : "stopping";
|
||
try { this.adapter.stop(this.active.handle); }
|
||
catch (error) { this.active.stopError = String(error); }
|
||
this.event(reason === "pause" ? "正在暂停:结束当前脚本,退出后暂停后续任务" :
|
||
reason === "user" ? "正在停止当前脚本,停止后结束整组" : reason + ";等待旧脚本退出");
|
||
};
|
||
|
||
Scheduler.prototype.advance = function (skipTask, now) {
|
||
if (skipTask || this.repetition >= this.plan.tasks[this.index].times) {
|
||
this.index++;
|
||
this.repetition = 1;
|
||
} else this.repetition++;
|
||
this.attempt = 0;
|
||
if (this.index >= this.plan.tasks.length) {
|
||
if (this.plan.loops !== 0 && this.round >= this.plan.loops) {
|
||
this.finish("completed", "整组执行结束:成功 " + this.successes + " 次,跳过 " + this.skipped + " 个任务" +
|
||
(this.interrupted ? ",因暂停结束 " + this.interrupted + " 次" : ""));
|
||
return;
|
||
}
|
||
this.round++;
|
||
this.index = 0;
|
||
}
|
||
this.waitForNext(now);
|
||
this.event((this.pauseRequested ? "整组已暂停;" : "") + "下一项:" + this.plan.tasks[this.index].name + ";间隔 " + this.plan.gapSeconds + " 秒");
|
||
};
|
||
|
||
Scheduler.prototype.failAttempt = function (reason, now) {
|
||
this.failures++;
|
||
var task = this.plan.tasks[this.index];
|
||
if (/\[NO_RETRY\]/.test(reason)) {
|
||
this.finish("failed", task.name + "失败:" + reason + ";停止整组,不自动重试");
|
||
} else if (this.attempt < task.retries) {
|
||
this.attempt++;
|
||
this.waitForNext(now);
|
||
this.event(task.name + "失败:" + reason + (this.pauseRequested ? ";已暂停,继续后重试 " : ";准备重试 ") + this.attempt + "/" + task.retries);
|
||
} else if (task.onFailure === "skip") {
|
||
this.skipped++;
|
||
this.event(task.name + "失败:" + reason + ";跳过该任务的剩余次数");
|
||
this.advance(true, now);
|
||
} else this.finish("failed", task.name + "失败:" + reason + ";按设置停止整组");
|
||
};
|
||
|
||
Scheduler.prototype.tick = function (now) {
|
||
if (!this.isBusy()) return;
|
||
if (!this.active) {
|
||
if (this.cancelled) { this.finish("stopped", "整组已停止"); return; }
|
||
if (this.phase === "paused") return;
|
||
if (now < this.readyAt) return;
|
||
var task = this.plan.tasks[this.index];
|
||
this.lastTask = task.name;
|
||
try {
|
||
this.active = {handle: this.adapter.launch(task, now), startedAt: now};
|
||
this.phase = "running";
|
||
this.event("启动 " + task.name + ":第 " + this.repetition + "/" + task.times + " 次" +
|
||
(this.attempt ? ",重试 " + this.attempt + "/" + task.retries : ""));
|
||
} catch (error) { this.failAttempt(String(error), now); }
|
||
return;
|
||
}
|
||
var active = this.active;
|
||
var report;
|
||
try { report = this.adapter.poll(active.handle, now); }
|
||
catch (error) {
|
||
if (!active.stopReason) this.beginStop("引擎状态检查失败:" + error, now);
|
||
report = {done: false};
|
||
}
|
||
if (report.done) {
|
||
this.active = null;
|
||
this.adapter.release(active.handle);
|
||
if (this.cancelled || this.wasBlocked || active.stopReason === "user") {
|
||
this.finish("stopped", "当前脚本已退出,整组已停止");
|
||
} else if (active.stopReason === "pause") {
|
||
this.interrupted++;
|
||
this.event(this.lastTask + "已按暂停要求结束,本次执行不重跑");
|
||
this.advance(false, now);
|
||
} else if (active.stopReason) this.failAttempt(active.stopReason, now);
|
||
else if (!report.ok) this.failAttempt(report.reason || "脚本异常退出", now);
|
||
else {
|
||
this.successes++;
|
||
this.event(this.lastTask + "已结束" + (report.reason ? ":" + report.reason : ""));
|
||
this.advance(false, now);
|
||
}
|
||
return;
|
||
}
|
||
if (!active.stopReason) {
|
||
if (this.cancelled) this.beginStop("user", now);
|
||
else if (now - active.startedAt >= this.plan.tasks[this.index].timeoutMinutes * 60000) {
|
||
this.beginStop("单次运行超时", now);
|
||
}
|
||
}
|
||
if (active.stopReason && now - active.stopAt >= this.stopGraceMs && this.phase !== "blocked") {
|
||
this.wasBlocked = true;
|
||
this.finish("blocked", "未能确认旧脚本退出,已停止后续调度。可再次点停止,或在 AutoJs6 运行列表结束该脚本。");
|
||
}
|
||
};
|
||
|
||
Scheduler.prototype.status = function (now) {
|
||
var task = this.plan && this.plan.tasks[this.index];
|
||
return {phase: this.phase, message: this.message, pauseRequested: this.pauseRequested, taskName: task ? task.name : this.lastTask,
|
||
round: this.round || 0, loops: this.plan ? this.plan.loops : 0,
|
||
index: (this.index || 0) + 1, taskCount: this.plan ? this.plan.tasks.length : 0,
|
||
repetition: this.repetition || 0, times: task ? task.times : 0, attempt: this.attempt || 0,
|
||
successes: this.successes, failures: this.failures, skipped: this.skipped, interrupted: this.interrupted,
|
||
elapsedSeconds: this.active && now ? Math.floor((now - this.active.startedAt) / 1000) : 0,
|
||
observerError: this.lastObserverError || ""};
|
||
};
|
||
|
||
module.exports = {normalizePlan: normalizePlan, knownResultLog: knownResultLog,
|
||
resultFromLog: resultFromLog, Scheduler: Scheduler};
|