2026-10-21 15:14:07 +08:00

218 lines
9.4 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"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";
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|ERROR):/.test(lines[i])) { ending = lines[i]; break; }
}
if (!ending) return {ok: false, reason: "脚本已退出,但本轮日志没有 END 或 ERROR 结果"};
var failed = /\bERROR:/.test(ending) || /异常|失败|未就绪|未完成|未能|尚未确认|连续无进展/.test(ending);
return {ok: !failed, reason: ending.replace(/^.*?\b(?:END|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.wasBlocked = false;
this.lastObserverError = "";
this.lastTask = "";
this.successes = 0;
this.failures = 0;
this.skipped = 0;
}
Scheduler.prototype.isBusy = function () {
return /^(?:waiting|running|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.active = null;
this.cancelled = false;
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;
// blocked 时依然允许重发停止请求,但绝不放行下一任务。
if (this.phase === "blocked" && this.active) {
try { this.adapter.stop(this.active.handle); } catch (ignore) {}
}
this.event("已请求停止整组,等待当前脚本完全退出");
};
Scheduler.prototype.finish = function (phase, message) {
this.phase = phase;
this.event(message);
};
Scheduler.prototype.beginStop = function (reason, now) {
this.active.stopReason = reason;
this.active.stopAt = now;
this.phase = "stopping";
try { this.adapter.stop(this.active.handle); }
catch (error) { this.active.stopError = String(error); }
this.event(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 + " 个任务");
return;
}
this.round++;
this.index = 0;
}
this.phase = "waiting";
this.readyAt = now + this.plan.gapSeconds * 1000;
this.event("下一项:" + 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 (this.attempt < task.retries) {
this.attempt++;
this.phase = "waiting";
this.readyAt = now + this.plan.gapSeconds * 1000;
this.event(task.name + "失败:" + reason + ";准备重试 " + 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 (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) 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, 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,
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};