SHIEP.js 15 KB

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