// ==UserScript== // @name 中小学智慧教育平台每周任务积分助手-免费版 // @namespace https://basic.smartedu.cn/ // @version 1.1.9 // @description UI操作版:在当前标签页逐个打开真实课时页面,自动化点击页面上的真实按钮(播放/点赞/收藏/评分/存库/育小苗AI对话)完成每周积分任务,全程可见,约26.9分/周。支持脚本猫(ScriptCat)与油猴(Tampermonkey)。 // @author weekly-points // @match https://basic.smartedu.cn/* // @grant GM_setValue // @grant GM_getValue // @grant GM_deleteValue // @grant GM_xmlhttpRequest // @grant GM_addStyle // @connect ykt.eduyun.cn // @connect *.ykt.eduyun.cn // @connect x-incentive-service.ykt.eduyun.cn // @connect e-favorite-api.ykt.eduyun.cn // @connect ykt.cbern.com.cn // @connect *.ykt.cbern.com.cn // @connect s-file-1.ykt.cbern.com.cn // @connect s-file-2.ykt.cbern.com.cn // @connect api.ykt.cbern.com.cn // @run-at document-idle // @noframes // ==/UserScript== (function() { "use strict"; const CFG = { APP_ID: "e5649925-441d-4a53-b525-51a2f1c4e0a8", TOKEN_LS_KEY: "ND_UC_AUTH-e5649925-441d-4a53-b525-51a2f1c4e0a8&ncet-xedu&token", TARGETS: { browse: 5, play: 5, save: 5, like: 1, fav: 2, rate: 1, ai: 5 }, TEXTBOOKS: [ "fa60dc59-2eea-444d-80fb-f008d6b8d572" ], AI_PROMPTS: [ "你好,请简单介绍一下你自己", "请推荐一节适合预习的数学课程", "教师如何保存资源到我的资源库?", "我想找语文三年级下册的教材,怎么找?", "平台里怎么提交资源评价?", "请介绍一下平台的人工智能教育栏目", "如何查看我的积分明细?", "帮我找一节初中物理实验课" ], READY_TIMEOUT: 25e3, PLAY_MAX: 18e4, BROWSE_WAIT: 5e3, DELAY: [ 1500, 4e3 ] }; const API = { balance: "https://x-incentive-service.ykt.eduyun.cn/v1/incentives/my_package", history: "https://x-incentive-service.ykt.eduyun.cn/v1/incentives/actions/search", favors: "https://e-favorite-api.ykt.eduyun.cn/v1/user_favors", docList: "https://doc-center.ykt.eduyun.cn/v1.0/c/search/action/query_lately?$limit=({O},50)&$orderby=last_open+desc&scope=file", docDelete: "https://doc-center.ykt.eduyun.cn/v1.0/c/document/batch_delete?clear=true" }; const TASK_NAMES = { browse: "浏览资源", play: "播放视频", save: "存我的资源库", like: "点赞", fav: "收藏", rate: "提交评价", ai: "育小苗AI对话" }; const _SA = "swp#2026^fr"; const _SB = "ee!notice@x7Qz"; const _NB = [ "levcy4y117z3g9/DgZjOifv7h972narWnsvNlaa/2IaPsdr+gd2sitPuj//spMOMtcfmkeSV2oSL3//flf7L", "l8rPxKaY26Hwj9D9gK7Biv7JQzQRWNDv3pfN1MWHsde504/U7Yqd9FdMW1pVeUEBYA==" ]; const _HE1 = "efccbd5de25c4c0b4e025f32b1a633cc"; const _HE2 = "523c59bafb6477de8341bef4cebb01a8"; let _OK = null; function _dec(b64) { const tb = Uint8Array.from(atob(b64), c => c.charCodeAt(0)); const sb = (new TextEncoder).encode(_SA + _SB); const out = new Uint8Array(tb.length); for (let i = 0; i < tb.length; i++) out[i] = tb[i] ^ sb[i % sb.length]; return (new TextDecoder).decode(out); } async function _boot() { if (_OK !== null) return _OK; try { const n0 = _dec(_NB[0]); const n1 = _dec(_NB[1]); const data = (new TextEncoder).encode(n0 + "" + n1 + "" + _SA + _SB); const digest = await crypto.subtle.digest("SHA-256", data); const hex = [ ...new Uint8Array(digest) ].map(b => b.toString(16).padStart(2, "0")).join(""); const rhex = hex.split("").reverse().join(""); _OK = rhex === _HE2 + _HE1; if (!_OK) console.error("[积分助手] 完整性校验失败:插件信息被修改,已停止运行。请恢复原始脚本。"); } catch (e) { _OK = false; console.error("[积分助手] 完整性校验异常,已停止运行。"); } return _OK; } function _noticeHTML() { const n0 = _dec(_NB[0]); const n1 = _dec(_NB[1]); const i = n1.lastIndexOf(":"); const head = i >= 0 ? n1.slice(0, i + 1) : n1; const num = i >= 0 ? n1.slice(i + 1) : ""; const esc = s => s.replace(/&/g, "&").replace(//g, ">"); return `
${esc(n0)}
${esc(head)}${esc(num)}
`; } const sleep = ms => new Promise(r => setTimeout(r, ms)); const randDelay = () => sleep(CFG.DELAY[0] + Math.random() * (CFG.DELAY[1] - CFG.DELAY[0])); function weekKey(d = new Date) { const t = new Date(Date.UTC(d.getFullYear(), d.getMonth(), d.getDate())); const day = t.getUTCDay() || 7; t.setUTCDate(t.getUTCDate() + 4 - day); const y = t.getUTCFullYear(); const w = Math.ceil(((t - Date.UTC(y, 0, 1)) / 864e5 + 1) / 7); return `${y}-W${String(w).padStart(2, "0")}`; } function emptyWeek() { return { week: weekKey(), browse: [], play: [], save: [], like: [], fav: [], rate: [], ai: 0 }; } function loadState() { let s = GM_getValue("swp_state", null); if (!s || s.week !== weekKey()) { s = emptyWeek(); GM_setValue("swp_state", s); } return s; } function saveState(s) { GM_setValue("swp_state", s); } function pushOnce(state, k, id) { if (k === "ai") { state.ai += 1; return; } if (!state[k].includes(id)) state[k].push(id); } const doneCount = (state, k) => k === "ai" ? state.ai : state[k].length; function log(msg) { const line = `[${(new Date).toTimeString().slice(0, 8)}] ${msg}`; console.log("[积分助手]", msg); try { const buf = GM_getValue("swp_ui_log", []); buf.push(line); GM_setValue("swp_ui_log", buf.slice(-150)); } catch (e) {} if (logEl) { logEl.textContent += line + "\n"; logEl.scrollTop = logEl.scrollHeight; } } function getToken() { try { const win = typeof unsafeWindow !== "undefined" ? unsafeWindow : window; const raw = win.localStorage.getItem(CFG.TOKEN_LS_KEY); if (!raw) return null; return JSON.parse(JSON.parse(raw).value); } catch (e) { return null; } } async function macHeader(url, method, token) { const u = new URL(url); const chars = "123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; let r = ""; for (let i = 0; i < 8; i++) r += chars[Math.ceil(35 * Math.random())]; const nonce = Date.now() + parseInt(token.diff || 0, 10) + ":" + r; const normalized = nonce + "\n" + method.toUpperCase() + "\n" + u.pathname + u.search + "\n" + u.host + "\n"; const key = await crypto.subtle.importKey("raw", (new TextEncoder).encode(token.mac_key), { name: "HMAC", hash: "SHA-256" }, false, [ "sign" ]); const sig = await crypto.subtle.sign("HMAC", key, (new TextEncoder).encode(normalized)); const mac = btoa(String.fromCharCode(...new Uint8Array(sig))); return 'MAC id="' + token.access_token + '",nonce="' + nonce + '",mac="' + mac + '"'; } async function xFetch(url, {method: method = "GET", body: body = null, json: json = true, auth: auth = true, headers: extraHeaders = null} = {}) { const headers = Object.assign({ "sdp-app-id": CFG.APP_ID, Accept: "application/json, text/plain, */*" }, extraHeaders || {}); if ((json || body !== null && typeof body === "object") && !headers["Content-Type"]) headers["Content-Type"] = "application/json"; if (auth) { const token = getToken(); if (!token) throw new Error("未获取到登录令牌,请先在本站登录并刷新页面"); headers["Authorization"] = await macHeader(url, method, token); } const opts = { method: method, headers: headers }; if (body !== null) opts.body = typeof body === "string" ? body : JSON.stringify(body); try { const resp = await fetch(url, opts); const text = await resp.text(); if (!resp.ok) throw new Error(`HTTP ${resp.status}: ${text.slice(0, 120)}`); return json ? text ? JSON.parse(text) : null : text; } catch (fetchErr) { if (typeof GM_xmlhttpRequest !== "function") throw fetchErr; return await new Promise((resolve, reject) => { GM_xmlhttpRequest({ method: method, url: url, headers: opts.headers, data: opts.body, timeout: 3e4, onload: r => { if (r.status >= 400) return reject(new Error(`HTTP ${r.status}: ${(r.responseText || "").slice(0, 120)}`)); const t = r.responseText || ""; try { resolve(json ? t ? JSON.parse(t) : null : t); } catch (err) { resolve(t); } }, onerror: () => reject(new Error(`网络错误(fetch: ${fetchErr.message})`)), ontimeout: () => reject(new Error("请求超时")) }); }); } } async function getPool() { let cache = GM_getValue("swp_pool", null); if (cache && Date.now() - cache.t < 864e5 && cache.textbooks.join() === CFG.TEXTBOOKS.join()) return cache.ids; const ids = []; for (const tb of CFG.TEXTBOOKS) { try { const parts = await xFetch(`https://s-file-2.ykt.cbern.com.cn/zxx/ndrs/national_lesson/teachingmaterials/${tb}/resources/parts.json`, { auth: false }); for (const purl of parts || []) { const list = await xFetch(purl, { auth: false }); (list || []).forEach(r => { if (r.resource_type_code === "national_lesson" && r.id) ids.push(r.id); }); } } catch (e) { log(`拉取教材 ${tb} 课时列表失败:${e.message}`); } } if (ids.length) GM_setValue("swp_pool", { t: Date.now(), textbooks: CFG.TEXTBOOKS, ids: ids }); return ids; } async function getLesson(lessonId) { let cache = GM_getValue("swp_lesson_" + lessonId, null); if (cache && Date.now() - cache.t < 7 * 864e5) return cache.d; const j = await xFetch(`https://s-file-2.ykt.cbern.com.cn/zxx/ndrv2/national_lesson/resources/details/${lessonId}.json`, { auth: false }); const title = j.global_title && (j.global_title["zh-CN"] || Object.values(j.global_title)[0]) || "国家课程资源"; const hours = j.resource_structure && j.resource_structure.relations || []; const d = { id: lessonId, title: title, hourId: hours.length ? hours[0].id : "lesson_1" }; GM_setValue("swp_lesson_" + lessonId, { t: Date.now(), d: d }); return d; } async function pickLessons(state, keys, n) { const pool = await getPool(); if (!pool.length) throw new Error("资源池为空,请检查教材ID配置或网络"); const used = new Set; keys.forEach(k => (state[k] || []).forEach(id => used.add(id))); const out = []; for (const id of pool) { if (out.length >= n) break; if (!used.has(id) && !out.includes(id)) out.push(id); } for (const id of pool) { if (out.length >= n) break; if (!out.includes(id)) out.push(id); } return out; } const lessonUrl = L => `https://basic.smartedu.cn/syncClassroom/classActivity?activityId=${L.id}&classHourId=${L.hourId}`; const sleepBtn = () => sleep(1500); function pageReady() { return document.body && document.body.innerText.includes("存到我的资源库"); } async function waitReady() { const t0 = Date.now(); while (Date.now() - t0 < CFG.READY_TIMEOUT) { if (pageReady()) return true; await sleep(500); } return false; } function clickText(text) { const els = [ ...document.querySelectorAll("div,span,button") ].filter(e => (e.innerText || "").trim() === text); if (!els.length) return false; els[els.length - 1].click(); return true; } async function uiPlay() { if (!clickText("播放视频")) return false; await sleep(2e3); return await ensureVideoPlaying(); } async function ensureVideoPlaying() { let v = document.querySelector("video"); if (!v) return false; v.muted = true; try { if (v.paused) await v.play(); } catch (e) {} const t0 = v.currentTime; await sleep(2500); v = document.querySelector("video"); if (v && v.currentTime > t0 + .5) return true; try { if (v) { v.muted = true; await v.play(); } } catch (e) {} await sleep(2500); v = document.querySelector("video"); return !!(v && v.currentTime > t0 + .5); } function installHeartbeatCounter() { try { const win = typeof unsafeWindow !== "undefined" ? unsafeWindow : window; if (win.__swpHbWrapped) return; win.__swpHbWrapped = true; const oo = win.XMLHttpRequest.prototype.open; win.XMLHttpRequest.prototype.open = function(m, u) { if (String(m).toUpperCase() === "POST" && String(u).indexOf("study_details") >= 0) { GM_setValue("swp_hb_cnt", GM_getValue("swp_hb_cnt", 0) + 1); } return oo.apply(this, arguments); }; } catch (e) {} } const hbCount = () => GM_getValue("swp_hb_cnt", 0); function uiLike() { const el = document.querySelector('[class*="like-wrap"]'); if (!el) return false; if (/like-active/.test(el.className || "")) return "already"; el.click(); return true; } async function uiFav() { if (!clickText("收藏")) return document.body.innerText.includes("已收藏") ? "already" : false; await sleepBtn(); return true; } async function uiRate() { if (!clickText("评分")) return false; await sleep(1500); const stars = document.querySelectorAll("li.fish-rate-star"); if (stars.length < 5) return false; stars[4].click(); await sleep(800); return clickText("确认提交"); } function uiSave() { return clickText("存到我的资源库"); } async function libList() { const out = []; let offset = 0; while (true) { const j = await xFetch(API.docList.replace("{O}", offset)); const items = j && j.items || []; out.push(...items); offset += 50; if (!items.length || offset >= (j.total || 0)) break; } return out.map(i => ({ id: i.identifier, name: i.global_title && i.global_title["zh-CN"] || "" })); } async function libDelete(ids) { for (let i = 0; i < ids.length; i += 10) { await xFetch(API.docDelete, { method: "POST", body: { ids: ids.slice(i, i + 10) } }); await sleep(500); } return ids.length; } async function libCleanupLegacy() { try { const items = await libList(); const junk = items.filter(i => /\(\d+\)$/.test(i.name)); if (!junk.length) { log(" 资源库检查:无重复副本"); return; } const n = await libDelete(junk.map(i => i.id)); log(` 资源库清理:已删除 ${n} 个历史副本(释放容量)`); } catch (e) { log(" 资源库清理失败(不影响任务继续):" + e.message); } } async function libDeleteNewlyAdded(beforeIds) { try { const after = await libList(); const fresh = after.filter(i => !beforeIds.includes(i.id)); if (!fresh.length) return; await libDelete(fresh.map(i => i.id)); log(` 已自动删除刚存入的 ${fresh.length} 个副本(${fresh[0].name}…,容量不占用)`); } catch (e) { log(" 自动删除副本失败(不影响积分):" + e.message); } } function aiRoot() { return document.querySelector('[class*="ai-assistant2"]') || document; } function aiEditor() { return aiRoot().querySelector('.ck-editor__editable, [contenteditable="true"]'); } async function aiPanelOpen() { const ent = document.querySelector(".ai-assistant2-entrance") || document.querySelector('[class*="ai-assistant"][class*="entrance"]'); if (!ent) return false; ent.click(); await sleep(2500); const tip = [ ...document.querySelectorAll("div,span,button") ].filter(e => (e.innerText || "").trim() === "知道了").pop(); if (tip) { tip.click(); await sleep(800); } return !!aiEditor(); } async function aiType(text) { const ed = aiEditor(); if (!ed) return false; try { ed.focus(); if (ed.ckeditorInstance && typeof ed.ckeditorInstance.setData === "function") { ed.ckeditorInstance.setData("

" + text.replace(/[<>]/g, "") + "

"); } else { document.execCommand("selectAll", false, null); document.execCommand("insertText", false, text); ed.dispatchEvent(new InputEvent("input", { bubbles: true, data: text, inputType: "insertText" })); } } catch (e) { return false; } await sleep(600); const counter = (document.querySelector(".ai-assistant2-inputbox-editStatus-limit") || {}).innerText || ""; return (ed.textContent || "").trim().length > 0 && !counter.startsWith("0/"); } function aiSendBtn() { const icon = document.querySelector(".ai-assistant2-inputbox-editIcon"); if (icon) return icon; const root = aiRoot(); const byCls = root.querySelectorAll('[class*="send"], [class*="Send"]'); if (byCls.length) return byCls[byCls.length - 1]; const ed = aiEditor(); if (!ed) return null; const box = ed.closest('[class*="inputbox"], [class*="input-box"]') || ed.parentElement.parentElement; if (!box) return null; const icons = box.querySelectorAll('img,svg,i,button,[class*="icon"],[class*="Icon"]'); return icons.length ? icons[icons.length - 1] : null; } async function aiNewChat() { const btn = document.querySelector(".ai-assistant2-operator-newtalk-icon"); if (!btn) return false; if (!document.querySelector(".ai-assistant2-message-list")) return true; btn.click(); const t0 = Date.now(); while (Date.now() - t0 < 8e3) { await sleep(600); const home = !!document.querySelector(".ai-assistant2-homebox"); const gone = !document.querySelector(".ai-assistant2-message-list"); const counter = (document.querySelector(".ai-assistant2-inputbox-editStatus-limit") || {}).innerText || ""; if ((home || gone) && counter.indexOf("0/") === 0) return true; } return false; } async function runAiRoundsOnPage(state) { if (!await aiPanelOpen()) { log(" ✘ 未找到育小苗入口或面板未打开(请确认已登录)"); return; } while (state.ai < CFG.TARGETS.ai) { const q = CFG.AI_PROMPTS[state.ai % CFG.AI_PROMPTS.length]; const fresh = await aiNewChat(); if (!fresh) log(" ⚠ 未能新建对话,将继续当前对话"); if (!await aiType(q)) { log(` ✘ 第 ${state.ai + 1} 轮输入框写入失败,停止AI任务`); return; } const btn = aiSendBtn(); if (!btn) { log(" ✘ 未找到发送按钮,停止AI任务"); return; } btn.click(); pushOnce(state, "ai"); saveState(state); log(` 对话 ${state.ai}/${CFG.TARGETS.ai} ✓${fresh ? "(新对话)" : ""}:${q}`); if (state.ai < CFG.TARGETS.ai) await sleep(9e3 + Math.random() * 4e3); } log(" AI对话完成"); } function badge(text, stopBtn = true) { let b = document.getElementById("swp-ui-badge"); if (!b) { b = document.createElement("div"); b.id = "swp-ui-badge"; b.style.cssText = "position:fixed;left:16px;bottom:16px;z-index:999999;display:flex;align-items:center;gap:8px;" + "background:rgba(30,41,59,.92);color:#fff;padding:8px 12px;border-radius:8px;font-size:12px;box-shadow:0 4px 14px rgba(0,0,0,.3)"; document.body.appendChild(b); } b.innerHTML = `${text}` + (stopBtn ? `停止` : ""); const stop = b.querySelector("#swp-ui-stop"); if (stop) stop.addEventListener("click", () => { GM_deleteValue("swp_ui_job"); log("⏹ 已手动停止任务"); b.remove(); }); } function badgeRemove() { const b = document.getElementById("swp-ui-badge"); if (b) b.remove(); } const getJob = () => GM_getValue("swp_ui_job", null); const setJob = j => { j ? GM_setValue("swp_ui_job", j) : GM_deleteValue("swp_ui_job"); }; async function startJob(tasks) { if (!await _boot()) return; if (getJob()) { log("已有进行中的任务,请先「继续」或「停止」"); updateUI(); return; } const state = loadState(); const resTasks = tasks.filter(t => t !== "ai"); const aiNeeded = tasks.includes("ai") && state.ai < CFG.TARGETS.ai; const resNeed = Math.max(0, ...resTasks.map(t => Math.max(0, CFG.TARGETS[t] - doneCount(state, t)))); const need = Math.max(resNeed, aiNeeded ? 1 : 0); if (need <= 0) { log("本周所选任务均已完成,无需执行"); updateUI(); return; } const lessons = await pickLessons(state, resTasks.length ? resTasks : [ "ai" ], need); GM_setValue("swp_hb_cnt", 0); if (resTasks.includes("save")) { log("▶ 检查个人资源库容量…"); await libCleanupLegacy(); } let b0 = null; try { b0 = (await queryBalance()).balance; } catch (e) {} setJob({ tasks: resTasks, ai: aiNeeded, queue: lessons, idx: 0, origin: location.href, startedAt: Date.now(), b0: b0 }); log(`🚀 启动UI任务:共 ${lessons.length} 个课时页面${aiNeeded ? "(含育小苗AI对话)" : ""},将在本标签页依次打开真实页面操作`); const first = await getLesson(lessons[0]); location.href = lessonUrl(first); } async function runLessonWork(job) { if (!await _boot()) return; const lessonId = new URLSearchParams(location.search).get("activityId"); const state = loadState(); const remaining = {}; job.tasks.forEach(t => { remaining[t] = Math.max(0, CFG.TARGETS[t] - doneCount(state, t)); }); const tasksHere = job.tasks.filter(t => remaining[t] > 0); const aiHere = !!job.ai && job.idx === 0 && state.ai < CFG.TARGETS.ai; badge(`积分助手:正在处理课时 ${job.idx + 1}/${job.queue.length}`, true); log(`▶ 课时 ${job.idx + 1}/${job.queue.length}`); if (!tasksHere.length && !aiHere) { log(" 本课时无待办任务"); return advance(job); } if (!await waitReady()) { log(" ✘ 页面加载超时"); return advance(job); } if (aiHere) { badge(`积分助手:育小苗AI对话中 ${job.idx + 1}/${job.queue.length}`, true); log("▶ 育小苗AI对话(真实面板操作)"); await runAiRoundsOnPage(state); if (!getJob()) { badgeRemove(); log("⏹ 任务已停止,流程终止"); return; } } if (remaining.browse > 0) { badge(`积分助手:浏览页面中 ${job.idx + 1}/${job.queue.length}`, true); await sleep(CFG.BROWSE_WAIT); pushOnce(state, "browse", lessonId); saveState(state); log(" 浏览 ✓"); remaining.browse--; } let playStarted = false; if (remaining.play > 0) { if (await uiPlay()) { playStarted = true; pushOnce(state, "play", lessonId); saveState(state); log(" 播放 ✓(已静音,真实观看中)"); remaining.play--; const startHb = hbCount(); const targetHb = startHb + Math.max(1, remaining.play + 1); const t0 = Date.now(); while (Date.now() - t0 < CFG.PLAY_MAX) { if (!getJob()) { badgeRemove(); log("⏹ 任务已停止,流程终止"); return; } const hb = hbCount(); const left = Math.round((CFG.PLAY_MAX - (Date.now() - t0)) / 1e3); badge(`积分助手:观看中 ${job.idx + 1}/${job.queue.length} · 心跳 ${hb - startHb}/${targetHb - startHb} · 最长剩 ${left}s`, true); if (hb >= targetHb) { log(` 观看完成:新增心跳 ${hb - startHb} 次`); break; } await sleep(5e3); } } else log(" ✘ 未找到播放按钮或视频未播放"); } if (remaining.like > 0) { const r = uiLike(); if (r === "already") log(" 点赞:本课时已赞过,跳过"); else if (r) { pushOnce(state, "like", lessonId); saveState(state); log(" 点赞 ✓"); remaining.like--; } else log(" ✘ 未找到点赞按钮"); await randDelay(); } if (remaining.fav > 0) { const r = await uiFav(); if (r === "already") log(" 收藏:本课时已收藏过,跳过"); else if (r) { pushOnce(state, "fav", lessonId); saveState(state); log(" 收藏 ✓"); remaining.fav--; if (GM_getValue("swp_unfav", false)) { try { await xFetch(`${API.favors}?content_id=${lessonId}&content_type=national_lesson`, { method: "DELETE" }); log(" 已自动取消收藏"); } catch (e) { log(" 自动取消收藏失败(不影响积分)"); } } } else log(" ✘ 未找到收藏按钮"); await randDelay(); } if (remaining.rate > 0) { if (await uiRate()) { pushOnce(state, "rate", lessonId); saveState(state); log(" 评价 ✓(五星)"); remaining.rate--; } else log(" ✘ 评分流程未完成"); await randDelay(); } if (remaining.save > 0) { let before = []; try { before = (await libList()).map(i => i.id); } catch (e) {} if (uiSave()) { pushOnce(state, "save", lessonId); saveState(state); log(" 存库 ✓"); remaining.save--; await sleep(3e3); await libDeleteNewlyAdded(before); } else log(" ✘ 未找到存库按钮"); await sleep(2e3); } advance(job); } async function advance(job) { if (!getJob()) { badgeRemove(); log("⏹ 任务已停止,流程终止"); return; } job.idx += 1; if (job.idx < job.queue.length) { setJob(job); const next = await getLesson(job.queue[job.idx]); log(`↪ 跳转下一个课时:${next.title}`); location.href = lessonUrl(next); } else { const origin = job.origin; setJob(null); log("🎉 全部队列完成"); let summary = "积分助手:全部完成,正在返回…"; try { await sleep(4e3); const b1 = (await queryBalance()).balance; if (job.b0 != null && typeof b1 === "number") { const diff = b1 - job.b0; log(`💰 本次任务:积分 ${job.b0} → ${b1},本次共得 +${diff.toFixed(1)} 分`); summary = `积分助手:全部完成 · 本次共得 +${diff.toFixed(1)} 分`; } else { log(`💰 当前总积分:${b1}`); summary = `积分助手:全部完成 · 当前 ${b1} 分`; } const s = loadState(); s._balance = b1; saveState(s); if (balEl) balEl.textContent = `当前总积分:${b1}`; } catch (e) {} badge(summary, false); setTimeout(() => { location.href = origin; }, 3e3); } } async function queryBalance() { return await xFetch(API.balance); } async function queryHistory(n = 10) { const j = await xFetch(`${API.history}?page_size=${n}&page_no=0`); return (j.items || []).map(i => ({ t: (i.biz_date || "").slice(5, 16).replace("T", " "), amt: i.amount, rule: i.rule_id, remark: i.remark })); } GM_addStyle(`\n #swp-fab{position:fixed;right:16px;bottom:88px;z-index:999999;width:44px;height:44px;border-radius:50%;\n background:linear-gradient(135deg,#3b82f6,#6366f1);color:#fff;font-size:12px;line-height:44px;text-align:center;\n cursor:pointer;box-shadow:0 2px 10px rgba(0,0,0,.25);user-select:none;font-weight:600}\n #swp-panel{position:fixed;right:16px;bottom:140px;z-index:999999;width:320px;max-height:70vh;display:none;flex-direction:column;\n background:#fff;border-radius:10px;box-shadow:0 6px 24px rgba(0,0,0,.22);overflow:hidden;font-size:12px;color:#333}\n #swp-panel.open{display:flex}\n .swp-head{padding:8px 12px;background:#f0f5ff;font-weight:600;display:flex;justify-content:space-between;align-items:center}\n .swp-head span:last-child{cursor:pointer;color:#999;font-weight:400}\n .swp-notice{margin:6px 12px 0;padding:6px 8px;background:#fffbeb;border:1px solid #fde68a;border-radius:6px;color:#92400e;line-height:1.7;font-size:11px}\n .swp-balance{padding:6px 12px;color:#1d4ed8;font-weight:600}\n .swp-progress{padding:0 12px 4px;color:#666;line-height:1.7}\n .swp-progress b{color:#16a34a;font-weight:600}\n .swp-btns{display:grid;grid-template-columns:1fr 1fr;gap:6px;padding:8px 12px}\n .swp-btns button{border:1px solid #d1d5db;background:#f9fafb;border-radius:6px;padding:4px 2px;cursor:pointer;font-size:12px}\n .swp-btns button:hover{background:#eef2ff;border-color:#6366f1}\n .swp-btns button:disabled{opacity:.5;cursor:not-allowed}\n .swp-btn-all{grid-column:1/3;background:#4f46e5!important;color:#fff!important;border-color:#4f46e5!important;font-weight:600;padding:6px!important}\n .swp-btn-resume{grid-column:1/3;background:#f59e0b!important;color:#fff!important;border-color:#f59e0b!important;font-weight:600}\n .swp-opts{padding:0 12px 6px;color:#666;display:flex;justify-content:space-between;align-items:center}\n .swp-log{flex:1;overflow:auto;margin:0 12px 10px;border-top:1px solid #eee;padding-top:6px;white-space:pre-wrap;word-break:break-all;line-height:1.6;min-height:80px}\n `); let logEl, progEl, balEl, panel; function progressText(state) { const T = CFG.TARGETS; const n = k => doneCount(state, k); return `浏览 ${n("browse")}/${T.browse} | 播放 ${n("play")}/${T.play} | 存库 ${n("save")}/${T.save} | ` + `点赞 ${n("like")}/${T.like} | 收藏 ${n("fav")}/${T.fav} | 评价 ${n("rate")}/${T.rate} | AI ${n("ai")}/${T.ai}`; } function updateUI() { const state = loadState(); const job = getJob(); if (progEl) progEl.innerHTML = progressText(state); const resumeBtn = panel.querySelector('[data-act="resume"]'); if (resumeBtn) resumeBtn.remove(); if (job) { const btn = document.createElement("button"); btn.className = "swp-btn-resume"; btn.setAttribute("data-act", "resume"); btn.textContent = `任务进行中(${Math.min(job.idx + 1, job.queue.length)}/${job.queue.length})· 点击继续`; panel.querySelector(".swp-btns").appendChild(btn); } [ ...panel.querySelectorAll(".swp-btns button") ].forEach(b => { const act = b.getAttribute("data-act"); if (act !== "resume" && act !== "stop" && act !== "balance" && act !== "clearlog" && act !== "reset") b.disabled = !!job; }); const stopTask = panel.querySelector('[data-act="stop"]'); if (stopTask) stopTask.remove(); if (job) { const btn2 = document.createElement("button"); btn2.setAttribute("data-act", "stop"); btn2.textContent = "停止任务"; panel.querySelector(".swp-btns").appendChild(btn2); } } async function refreshBalance() { try { const b = await queryBalance(); const state = loadState(); state._balance = b.balance; saveState(state); if (balEl) balEl.textContent = `当前总积分:${b.balance}`; return b; } catch (e) { if (balEl) balEl.textContent = "积分查询失败:" + e.message; throw e; } } function buildPanel() { const fab = document.createElement("div"); fab.id = "swp-fab"; fab.textContent = "积分"; fab.title = "智慧教育平台每周任务积分助手(UI版)"; panel = document.createElement("div"); panel.id = "swp-panel"; panel.innerHTML = `\n
每周任务积分助手(UI版)✕
\n
\n
点击「查询积分」获取余额
\n
\n
\n \n \n \n \n \n \n
\n
${weekKey()}
\n
\n `; document.body.appendChild(fab); document.body.appendChild(panel); logEl = panel.querySelector('[data-role="log"]'); progEl = panel.querySelector('[data-role="prog"]'); balEl = panel.querySelector('[data-role="bal"]'); logEl.textContent = GM_getValue("swp_ui_log", []).join("\n") + "\n"; logEl.scrollTop = logEl.scrollHeight; const unfav = panel.querySelector('[data-act="unfav"]'); unfav.checked = !!GM_getValue("swp_unfav", false); unfav.addEventListener("change", () => GM_setValue("swp_unfav", unfav.checked)); panel.querySelector('[data-role="notice"]').innerHTML = _noticeHTML(); panel.classList.add("open"); fab.addEventListener("click", () => { panel.classList.toggle("open"); updateUI(); }); panel.querySelector('[data-act="close"]').addEventListener("click", () => panel.classList.remove("open")); panel.addEventListener("click", async e => { const act = e.target.getAttribute && e.target.getAttribute("data-act"); if (!act || act === "unfav" || act === "close") return; if (act === "balance") { try { await refreshBalance(); const h = await queryHistory(5); log("最近积分明细:"); h.forEach(i => log(` ${i.t} +${i.amt} [规则${i.rule}] ${i.remark.slice(0, 30)}`)); } catch (err) { log("查询失败:" + err.message); } return; } if (act === "clearlog") { GM_setValue("swp_ui_log", []); logEl.textContent = ""; log("日志已清空"); return; } if (act === "reset") { GM_setValue("swp_state", emptyWeek()); log("已清空本周本地进度(仅记账,不影响平台数据),可重新执行任务"); updateUI(); return; } if (act === "stop") { setJob(null); badgeRemove(); log("⏹ 任务已停止(已完成的部分照常计分)"); updateUI(); return; } if (act === "resume") { const job = getJob(); if (!job) { updateUI(); return; } if (job.idx >= job.queue.length) { setJob(null); updateUI(); return; } const next = await getLesson(job.queue[job.idx]); location.href = lessonUrl(next); return; } if (getJob()) { log("已有进行中的任务:可点橙色「继续」或「停止」"); updateUI(); return; } try { const bb = await queryBalance(); const s2 = loadState(); s2._balance = bb.balance; saveState(s2); if (balEl) balEl.textContent = `当前总积分:${bb.balance}`; } catch (e2) { log("查询积分失败:" + e2.message); } if (act === "all") startJob(Object.keys(TASK_NAMES)); else if (TASK_NAMES[act]) startJob([ act ]); }); updateUI(); } async function init() { if (!location.host.includes("basic.smartedu.cn")) return; if (!getToken()) { console.log("[积分助手] 未检测到登录令牌,登录后刷新页面即可使用"); return; } if (!await _boot()) return; installHeartbeatCounter(); buildPanel(); const job = getJob(); const isLessonPage = /syncClassroom\/classActivity/.test(location.pathname) && new URLSearchParams(location.search).get("activityId"); if (job && isLessonPage) { const target = job.queue[job.idx]; if (target && decodeURIComponent(isLessonPage) === target) { runLessonWork(job); return; } } if (job) { const remain = job.queue.length - job.idx; log(`UI任务进行中:还剩 ${remain} 个课时。可在任意页面打开面板点「继续」,或点「停止」`); } else if (!isLessonPage) { log("积分助手(UI版)已就绪:将在当前标签页打开真实课时页面操作"); } } if (document.readyState === "complete" || document.readyState === "interactive") init(); else window.addEventListener("DOMContentLoaded", init); })();