// Bark 推送:运行器自己收尾时把结果发到手机。 // // 覆盖三类事件(都只在 headless 运行器里发,浏览器端油猴脚本不推送): // · 开始运行:「进程已经跑起来了」 // · 获得学分:每刷完一门有学分的课推一条 // · 收尾:正常刷完 / 长时间无进展 / 登录失败 // 手动 Ctrl+C 主动停止不推送:人就在键盘前,不需要再提醒一次。 // 通知是附加信息:发送失败只记告警,绝不影响退出码,也不阻塞下一次会话。 // // Bark 接口:GET https://api.day.app///<body>?group=<分组>[&ttl=<秒>](省略 ttl = 永久保留) import { formatCredit } from './study.mjs'; /** 单次请求超时:Bark 正常在 1 秒内返回,卡住就当失败,别拖慢收尾 */ export const BARK_TIMEOUT_MS = 8000; function withParam(url, key, val) { if (val === '' || val == null) return url; // 地址里已经写了同名参数(例如配置里直接粘了完整 curl 地址)就不再追加 if (new RegExp('[?&]' + key + '=').test(url)) return url; return url + (url.includes('?') ? '&' : '?') + key + '=' + encodeURIComponent(val); } /** * 拼 Bark 请求地址。 * base 可以是: * · 含设备 key 的根地址:https://api.day.app/KEY * · 带 {title}/{body} 占位符的完整模板:https://api.day.app/KEY/{title}/{body}?group=x */ export function buildBarkUrl(base, title, body, opts = {}) { let url = String(base || '').trim(); if (!url) return ''; const t = encodeURIComponent(title || ''); const b = encodeURIComponent(body || ''); if (/\{title\}|\{body\}/.test(url)) { url = url.replace(/\{title\}/g, t).replace(/\{body\}/g, b); } else { url = url.replace(/\/+$/, '') + '/' + t + '/' + b; } url = withParam(url, 'group', opts.group); url = withParam(url, 'ttl', opts.ttl ? String(opts.ttl) : ''); return url; } /** 收尾通知的标题与正文:把本次刷课的结论压缩成手机上能一眼看懂的两三行 */ export function buildFinishMessage(result) { const r = result || {}; const kind = r.kind || 'done'; const title = kind === 'login' ? '云学堂助手:登录失败' : kind === 'stalled' ? '云学堂助手:长时间无进展' : '云学堂助手:任务完成'; const lines = []; // 积分模式关闭时 snapshot 里仍是 0/24,直接贴出来会让人以为今天一条都没刷到 if (r.points && r.points.enabled === false) lines.push('每日积分模式:关'); else if (r.points && r.points.text) lines.push(String(r.points.text)); // 登录失败时还没开始刷,「完成 0 门 · 用时 0 秒」只会让人以为跑过一轮 if (kind !== 'login') { const secs = Number(r.elapsed) || 0; const used = secs >= 60 ? Math.floor(secs / 60) + ' 分 ' + (secs % 60) + ' 秒' : secs + ' 秒'; lines.push('完成 ' + (Number(r.completed) || 0) + ' 门 · 用时 ' + used); } if (r.finishReason) lines.push(String(r.finishReason)); return { title, body: lines.join('\n') }; } /** 启动通知:预检通过、浏览器即将启动时发一条,手机上能确认「程序真的跑起来了」 */ export function buildStartMessage(cfg) { const c = cfg || {}; const lines = ['正在启动浏览器并自动登录']; lines.push('模式:' + (c.POINTS_MODE ? '每日积分' : '普通刷课')); const budget = Number(c.BUDGET_MINUTES) || 0; lines.push('运行预算:' + (budget > 0 ? budget + ' 分钟' : '不限')); return { title: '云学堂助手:开始运行', body: lines.join('\n') }; } /** 学分通知:每刷完一门课发一条,带上本次累计学分与已完成门数 */ export function buildCreditMessage(event) { const e = event || {}; const title = '云学堂助手:获得 ' + formatCredit(e.credit) + ' 学分'; const lines = []; if (e.course) lines.push('课程「' + String(e.course) + '」'); let total = '本次累计 ' + formatCredit(e.total) + ' 学分'; if (e.completed != null) total += ' · 已完成 ' + (Number(e.completed) || 0) + ' 门'; lines.push(total); return { title, body: lines.join('\n') }; } /** * 发送 Bark 通知。永远不抛异常。 * @returns {Promise<{ok?:boolean, skipped?:boolean, status?:number}>} */ export async function sendBark(opts) { const o = opts || {}; const log = o.log || (() => {}); const warn = o.warn || (() => {}); const url = buildBarkUrl(o.url, o.title, o.body, { group: o.group, ttl: o.ttl }); if (!url) return { skipped: true }; if (typeof fetch !== 'function') { warn('当前 Node 没有全局 fetch(需要 Node 18+),跳过 Bark 通知'); return { skipped: true }; } try { const res = await fetch(url, { method: 'GET', signal: AbortSignal.timeout(o.timeoutMs || BARK_TIMEOUT_MS), }); let data = null; try { data = await res.json(); } catch (e) { /* 非 JSON 响应按状态码判断 */ } const code = data && data.code != null ? Number(data.code) : 200; if (!res.ok || code !== 200) { warn('Bark 通知发送失败:HTTP ' + res.status + (data && data.message ? '(' + data.message + ')' : '')); return { ok: false, status: res.status }; } log('已发送 Bark 通知:' + o.title); return { ok: true, status: res.status }; } catch (e) { warn('Bark 通知发送失败:' + (e && e.message ? e.message : e)); return { ok: false }; } } /** 按运行器配置发一条通知;没配 barkUrl 时是空操作 */ function notifyWith(cfg, msg, io) { if (!cfg || !cfg.BARK_URL) return Promise.resolve({ skipped: true }); return sendBark({ url: cfg.BARK_URL, group: cfg.BARK_GROUP, ttl: cfg.BARK_TTL, title: msg.title, body: msg.body, log: io && io.log, warn: io && io.warn, }); } /** 开始运行通知 */ export function notifyRunStarted(cfg, io) { return notifyWith(cfg, buildStartMessage(cfg), io); } /** 获得学分通知(每门刷完的课一条) */ export function notifyCreditEarned(cfg, event, io) { return notifyWith(cfg, buildCreditMessage(event), io); } /** 收尾通知 */ export function notifyRunFinished(cfg, result, io) { return notifyWith(cfg, buildFinishMessage(result), io); }