SHIEP.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405
  1. // resources/SUEP/SUEP_03.js
  2. // 上海电力大学 本科教务系统(eams / 上海树维)拾光课程表适配脚本 —— 接口探测版
  3. //
  4. // 本脚本改自本仓库中天津农学院 (TJAU) 的适配脚本(作者:星河欲转)。
  5. // 两者是同一套「树维 eams」系统,因此沿用它的整体思路:
  6. // - 用接口探测 ids / tagId,不依赖用户先打开「我的课表」页面;
  7. // - 用「按周建矩阵、再切连续节次块」的算法合并课程,能正确处理
  8. // 「同一门课不同周次占用不同节次」这种不规则情况。
  9. // 只把 URL、解析规则和节次时间换成了上海电力大学的实际情况。
  10. //
  11. // 导入页(adapters.yaml 的 import_url):https://jw.shiep.edu.cn/eams/index.action
  12. //
  13. // 前置条件:**只需登录**,不需要打开课表页。
  14. //
  15. // 与 SUEP_01.js / SUEP_02.js 的差别:
  16. // SUEP_01 读当前页面内联脚本;SUEP_02 已登录后调接口、但参数取自当前页面;
  17. // 本脚本连参数都由接口探测,因此对页面状态没有要求。
  18. const EAMS_BASE = "https://jw.shiep.edu.cn/eams";
  19. /**
  20. * 同一接口在短时间内被连续请求时,服务端会返回一个约 4 KB 的「精简版」页面
  21. * (不含工具栏,也不含 ids / tagId 等标记),间隔约 1 秒再请求就恢复正常。
  22. * 实测:14 次连发只有第 1 次完整;间隔 2 秒的 4 次请求则全部完整。
  23. * 这不是登录失效,所以收到这种响应应当退避重试,而不是直接报错。
  24. */
  25. const MAX_ATTEMPTS = 4;
  26. const RETRY_DELAY_MS = 1000;
  27. function powerSplit(paramsRaw) {
  28. const args = [];
  29. let current = "";
  30. let depth = 0;
  31. let inQuote = false;
  32. let quoteChar = "";
  33. for (let i = 0; i < paramsRaw.length; i++) {
  34. let char = paramsRaw[i];
  35. if ((char === '"' || char === "'") && (i === 0 || paramsRaw[i - 1] !== '\\')) {
  36. if (!inQuote) { inQuote = true; quoteChar = char; }
  37. else if (char === quoteChar) { inQuote = false; }
  38. }
  39. if (!inQuote) {
  40. if (char === '(' || char === '[' || char === '{') depth++;
  41. if (char === ')' || char === ']' || char === '}') depth--;
  42. }
  43. if (char === ',' && depth === 0 && !inQuote) {
  44. args.push(cleanArg(current));
  45. current = "";
  46. } else {
  47. current += char;
  48. }
  49. }
  50. args.push(cleanArg(current));
  51. return args;
  52. }
  53. function cleanArg(s) {
  54. s = s.trim();
  55. if (s === "null") return null;
  56. return s.replace(/^["']|["']$/g, "");
  57. }
  58. /**
  59. * 去掉课程名末尾的课程序号。
  60. * 教务返回的课程名形如 "高等数学A(1)(2800001.32)",末尾括号里是课程序号,
  61. * 展示时应去掉;课程名自带的括号要保留,例如 "体育1(篮球)"、
  62. * "大学英语C读写(1)"(全角括号)。
  63. * 注意不能简单地 split('(')[0] —— 那会把 "体育1(篮球)" 变成 "体育1"。
  64. */
  65. function stripCourseNo(courseName) {
  66. return String(courseName).replace(/\s*\(\s*\d+(?:\.\d+)?\s*\)\s*$/, "").trim();
  67. }
  68. /**
  69. * 全局课程合并逻辑(沿用 TJAU 脚本的算法)。
  70. * 按 (课程名|教师|地点|星期) 分组,再把课表打散成「每一周各占哪些节」的矩阵,
  71. * 最后把矩阵里形状相同的连续节次块聚合成一条课程,因此能正确处理
  72. * 例如「第 1-9 周上 1-2 节、第 10 周只上第 2 节」这类不规则安排。
  73. */
  74. function mergeContinuousLessons(lessons) {
  75. if (!lessons || lessons.length === 0) return [];
  76. const groups = {};
  77. lessons.forEach(l => {
  78. const key = `${l.name}|${l.teacher}|${l.position}|${l.day}`;
  79. if (!groups[key]) {
  80. groups[key] = {
  81. name: l.name,
  82. teacher: l.teacher,
  83. position: l.position,
  84. day: l.day,
  85. // 最多按 50 周预留:第 N 周对应哪些节次的矩阵
  86. weeksMatrix: Array.from({ length: 50 }, () => new Set())
  87. };
  88. }
  89. // 按「周」填入对应的「节」,Set 自动去重
  90. if (l.weeks && Array.isArray(l.weeks)) {
  91. l.weeks.forEach(w => {
  92. if (w >= 0 && w < 50) {
  93. for (let s = l.startSection; s <= l.endSection; s++) {
  94. groups[key].weeksMatrix[w].add(s);
  95. }
  96. }
  97. });
  98. }
  99. });
  100. const merged = [];
  101. for (const key in groups) {
  102. const group = groups[key];
  103. const matrix = group.weeksMatrix;
  104. // 记录相同的「连续节次块」出现在哪些周
  105. // 例如 blockMap["1-2"] = [1, 2, 3, ...];blockMap["2-2"] = [10]
  106. const blockMap = {};
  107. for (let w = 0; w < matrix.length; w++) {
  108. const sections = Array.from(matrix[w]).sort((a, b) => a - b);
  109. if (sections.length === 0) continue;
  110. let start = sections[0];
  111. let prev = sections[0];
  112. for (let i = 1; i < sections.length; i++) {
  113. const curr = sections[i];
  114. if (curr === prev + 1) {
  115. prev = curr;
  116. } else {
  117. const blockKey = `${start}-${prev}`;
  118. if (!blockMap[blockKey]) blockMap[blockKey] = [];
  119. blockMap[blockKey].push(w);
  120. start = curr;
  121. prev = curr;
  122. }
  123. }
  124. const blockKey = `${start}-${prev}`;
  125. if (!blockMap[blockKey]) blockMap[blockKey] = [];
  126. blockMap[blockKey].push(w);
  127. }
  128. for (const blockKey in blockMap) {
  129. const [startSec, endSec] = blockKey.split('-').map(Number);
  130. merged.push({
  131. name: group.name,
  132. teacher: group.teacher,
  133. position: group.position,
  134. day: group.day,
  135. startSection: startSec,
  136. endSection: endSec,
  137. weeks: blockMap[blockKey],
  138. isCustomTime: false,
  139. customStartTime: null,
  140. customEndTime: null
  141. });
  142. }
  143. }
  144. merged.sort((a, b) => {
  145. if (a.day !== b.day) return a.day - b.day;
  146. if (a.startSection !== b.startSection) return a.startSection - b.startSection;
  147. return a.name.localeCompare(b.name);
  148. });
  149. return merged;
  150. }
  151. /**
  152. * 解析课表 HTML。
  153. *
  154. * 上海电力的响应结构与天津农学院不同:**没有** `var teachers =` / `actTeachers`
  155. * 那套结构,教师姓名直接就在 TaskActivity 的参数里。所以这里改成按
  156. * 「activity = new TaskActivity」切块,教师取第 2 个参数。
  157. *
  158. * TaskActivity 七个参数(名称取自系统自己的 TaskActivity_New.js):
  159. * teacherId, teacherName, courseId, courseName, roomId, roomName, vaildWeeks
  160. */
  161. function parseTaskActivities(html) {
  162. const rawResults = [];
  163. const unitCountMatch = html.match(/unitCount\s*=\s*(\d+)/);
  164. const unitCount = unitCountMatch ? parseInt(unitCountMatch[1], 10) : 13;
  165. const blocks = html.split(/activity\s*=\s*new\s+TaskActivity/);
  166. for (let i = 1; i < blocks.length; i++) {
  167. const block = blocks[i];
  168. const argsMatch = block.match(/^\s*\(([\s\S]*?)\)\s*;/);
  169. if (!argsMatch) continue;
  170. const args = powerSplit(argsMatch[1]);
  171. if (args.length < 7) continue;
  172. const name = stripCourseNo(args[3] || "未知课程");
  173. const teacher = (args[1] || "").trim() || "未知教师";
  174. const position = (args[5] || "").trim() || "未知地点";
  175. const weeksBitmap = args[6] || "";
  176. // 周次位图:第 i 个字符(i 从 1 开始)为 "1" 表示第 i 周有课,
  177. // 第 0 位是占位符,恒为 "0",不能当成第 1 周。
  178. const weeks = [];
  179. for (let j = 1; j < weeksBitmap.length; j++) {
  180. if (weeksBitmap[j] === "1") weeks.push(j);
  181. }
  182. if (weeks.length === 0) continue;
  183. // index = 星期索引 * unitCount + 节次索引,反推即各自 +1
  184. const idxRegex = /index\s*=\s*(\d+)\s*\*\s*unitCount\s*\+\s*(\d+)\s*;/g;
  185. let m;
  186. while ((m = idxRegex.exec(block)) !== null) {
  187. const section = parseInt(m[2], 10) + 1;
  188. rawResults.push({
  189. name: name,
  190. teacher: teacher,
  191. position: position,
  192. day: parseInt(m[1], 10) + 1,
  193. startSection: section,
  194. endSection: section,
  195. weeks: weeks
  196. });
  197. }
  198. }
  199. return mergeContinuousLessons(rawResults);
  200. }
  201. async function request(url, options = {}) {
  202. const res = await fetch(url, { credentials: "include", ...options });
  203. if (!res.ok) throw new Error(`网络请求失败: ${res.status}`);
  204. return await res.text();
  205. }
  206. function sleep(ms) {
  207. return new Promise(resolve => setTimeout(resolve, ms));
  208. }
  209. function looksLikeLoginPage(html) {
  210. return /authserver|统一身份认证|应用未注册/.test(html);
  211. }
  212. /**
  213. * 带退避重试的请求:只有通过 validate 的响应才算拿到完整内容。
  214. * 传输错误和「响应不完整」都会重试,因为这个接口确实会间歇性地返回精简版页面。
  215. */
  216. async function requestValidated(url, options, validate, label) {
  217. let incompleteLength = -1;
  218. let lastError = null;
  219. for (let attempt = 1; attempt <= MAX_ATTEMPTS; attempt++) {
  220. try {
  221. const text = await request(url, options);
  222. if (looksLikeLoginPage(text)) {
  223. throw new Error("请求被重定向到统一身份认证,请先登录教务系统");
  224. }
  225. if (validate(text)) return text;
  226. incompleteLength = text.length;
  227. lastError = null;
  228. } catch (error) {
  229. lastError = error;
  230. }
  231. if (attempt < MAX_ATTEMPTS) {
  232. console.log(`[拾光] ${label} 第 ${attempt} 次未拿到完整响应,${RETRY_DELAY_MS}ms 后重试`);
  233. await sleep(RETRY_DELAY_MS);
  234. }
  235. }
  236. if (lastError) throw lastError;
  237. throw new Error(`${label}连续 ${MAX_ATTEMPTS} 次响应都不完整(最后一次 ${incompleteLength} 字节),请稍后重试`);
  238. }
  239. /**
  240. * 探测调用课表接口所需的参数。
  241. * 课表页把 ids(学生内部编号)写在 bg.form.addInput(form,"ids","...") 里,
  242. * 学期组件的 id 形如 semesterBarXXXSemester,当前学期的编号则写在
  243. * semesterCalendar({...value:"424"}) 里。
  244. */
  245. async function detectParameters() {
  246. // 精简版页面里没有这两个标记,所以必须校验后重试
  247. const validate = html => /bg\.form\.addInput\(form,"ids","\d+"\)/.test(html)
  248. && /id="semesterBar\d+Semester"/.test(html);
  249. const html = await requestValidated(
  250. `${EAMS_BASE}/courseTableForStd.action`, {}, validate, "探测课表参数"
  251. );
  252. const idsMatch = html.match(/bg\.form\.addInput\(form,"ids","(\d+)"\)/);
  253. const tagIdMatch = html.match(/id="(semesterBar\d+Semester)"/);
  254. const currentSemesterMatch = html.match(/semesterCalendar\(\{[^}]*value:"(\d+)"/);
  255. return {
  256. ids: idsMatch[1],
  257. tagId: tagIdMatch[1],
  258. currentSemesterId: currentSemesterMatch ? currentSemesterMatch[1] : ""
  259. };
  260. }
  261. /**
  262. * 解析学期列表。
  263. * 响应是一段 JS 对象字面量(不是标准 JSON,键没有引号):
  264. * {yearDom:"...", termDom:"...",
  265. * semesters:{y0:[{id:32,schoolYear:"2013-2014",name:"2"}], ...},
  266. * yearIndex:"13", termIndex:"0", semesterId:"424"}
  267. * 这里不 eval 它(不执行服务端返回的代码),只用正则抽取值;顺序天然按学年排列。
  268. */
  269. function parseSemesterList(text) {
  270. const pattern = /id:(\d+)\s*,\s*schoolYear:"([^"]*)"\s*,\s*name:"([^"]*)"/g;
  271. const list = [];
  272. let m;
  273. while ((m = pattern.exec(text)) !== null) {
  274. list.push({ id: m[1], name: `${m[2]}学年${m[3]}学期` });
  275. }
  276. return list;
  277. }
  278. async function getSelectedSemester(tagId, currentSemesterId) {
  279. const raw = await requestValidated(`${EAMS_BASE}/dataQuery.action`, {
  280. method: "POST",
  281. headers: { "Content-Type": "application/x-www-form-urlencoded" },
  282. body: `tagId=${encodeURIComponent(tagId)}&dataType=semesterCalendar`
  283. + `&value=${encodeURIComponent(currentSemesterId)}&empty=false`
  284. }, text => parseSemesterList(text).length > 0, "获取学期列表");
  285. const list = parseSemesterList(raw);
  286. if (list.length === 0) throw new Error("未解析到学期列表");
  287. // 默认选中当前学期,避免默认停在最早的学期上
  288. let defaultIndex = 0;
  289. for (let i = 0; i < list.length; i++) {
  290. if (list[i].id === currentSemesterId) defaultIndex = i;
  291. }
  292. const idx = await window.shiguangBridgePromise.showSingleSelection(
  293. "选择学期", JSON.stringify(list.map(s => s.name)), defaultIndex
  294. );
  295. return idx !== null ? list[idx] : null;
  296. }
  297. async function fetchAndParseCourses(semesterId, ids) {
  298. // 真正的课表响应一定含 "new CourseTable"(哪怕是空课表),
  299. // 精简版页面没有它 —— 用它区分「响应不完整要重试」和「这个学期确实没课」
  300. const html = await requestValidated(`${EAMS_BASE}/courseTableForStd!courseTable.action`, {
  301. method: "POST",
  302. headers: { "Content-Type": "application/x-www-form-urlencoded" },
  303. body: `ignoreHead=1&setting.kind=std&semester.id=${semesterId}&ids=${ids}`
  304. }, text => /new CourseTable/.test(text), "获取课表数据");
  305. if (!/new TaskActivity/.test(html)) {
  306. throw new Error("该学期没有课程数据(课表为空),请换一个学期再试");
  307. }
  308. return parseTaskActivities(html);
  309. }
  310. /**
  311. * 上海电力大学各节次起止时间(共 13 节)。
  312. * eams 只给节次编号、不给时间,所以按学校作息表写死。
  313. * 时间整理自公开资料,请以教务处公布的最新作息为准;如有出入直接改这里。
  314. */
  315. async function applyTimeSlots() {
  316. const slots = [
  317. { "number": 1, "startTime": "08:20", "endTime": "09:05" },
  318. { "number": 2, "startTime": "09:10", "endTime": "09:55" },
  319. { "number": 3, "startTime": "10:10", "endTime": "10:55" },
  320. { "number": 4, "startTime": "11:00", "endTime": "11:45" },
  321. { "number": 5, "startTime": "11:50", "endTime": "12:30" },
  322. { "number": 6, "startTime": "13:20", "endTime": "14:05" },
  323. { "number": 7, "startTime": "14:10", "endTime": "14:55" },
  324. { "number": 8, "startTime": "15:10", "endTime": "15:55" },
  325. { "number": 9, "startTime": "16:00", "endTime": "16:45" },
  326. { "number": 10, "startTime": "16:50", "endTime": "17:30" },
  327. { "number": 11, "startTime": "18:15", "endTime": "19:00" },
  328. { "number": 12, "startTime": "19:05", "endTime": "19:50" },
  329. { "number": 13, "startTime": "19:55", "endTime": "20:35" }
  330. ];
  331. return await window.shiguangBridgePromise.savePresetTimeSlots(JSON.stringify(slots));
  332. }
  333. async function runImportFlow() {
  334. try {
  335. window.shiguangBridge.showToast("开始探测教务参数...");
  336. const params = await detectParameters();
  337. const semester = await getSelectedSemester(params.tagId, params.currentSemesterId);
  338. if (!semester) return;
  339. window.shiguangBridge.showToast("正在同步课表...");
  340. const courses = await fetchAndParseCourses(semester.id, params.ids);
  341. if (!courses || courses.length === 0) throw new Error("未解析到课程数据");
  342. await applyTimeSlots();
  343. const saveResult = await window.shiguangBridgePromise.saveImportedCourses(JSON.stringify(courses));
  344. if (saveResult) {
  345. window.shiguangBridge.showToast(`成功导入 ${courses.length} 个课程条目`);
  346. window.shiguangBridge.notifyTaskCompletion();
  347. }
  348. } catch (e) {
  349. console.error(`[异常] ${e.message}`);
  350. window.shiguangBridge.showToast(e.message);
  351. }
  352. }
  353. runImportFlow();