neuq.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346
  1. /**
  2. * 东北大学秦皇岛校区(树维教务系统)课表导入适配脚本
  3. *
  4. * 树维教务系统特点:
  5. * 1. 课表以空 HTML 表格返回,课程数据通过 JavaScript 脚本动态注入
  6. * 2. 脚本中包含 `new TaskActivity(...)` 构造函数调用来定义课程
  7. * 3. 需要从脚本文本中直接提取课程信息,而不是解析 DOM
  8. *
  9. * 适用于使用树维教务系统的其他高校(需修改 BASE 地址)
  10. */
  11. (function () {
  12. const BASE = "https://jwxt.neuq.edu.cn";
  13. function truncateText(value, maxLen) {
  14. const text = String(value == null ? "" : value);
  15. if (text.length <= maxLen) return text;
  16. return `${text.slice(0, maxLen)}...`;
  17. }
  18. // 保留用于解析失败时输出关键诊断信息
  19. function extractCourseHtmlDebugInfo(courseHtml) {
  20. const text = String(courseHtml || "");
  21. const hasTaskActivity = /new\s+TaskActivity\s*\(/i.test(text);
  22. const hasUnitCount = /\bvar\s+unitCount\s*=\s*\d+/i.test(text);
  23. return {
  24. responseLength: text.length,
  25. hasTaskActivity,
  26. hasUnitCount
  27. };
  28. }
  29. async function requestText(url, options) {
  30. const requestOptions = { credentials: "include", ...options };
  31. const res = await fetch(url, requestOptions);
  32. if (!res.ok) {
  33. throw new Error(`网络请求失败: ${res.status}`);
  34. }
  35. return await res.text();
  36. }
  37. // 从入口页面 HTML 中提取学生 ID 和学期选择组件的 tagId
  38. function parseEntryParams(entryHtml) {
  39. const idsMatch = entryHtml.match(/bg\.form\.addInput\(form,"ids","(\d+)"\)/);
  40. const tagIdMatch = entryHtml.match(/id="(semesterBar\d+Semester)"/);
  41. return {
  42. studentId: idsMatch ? idsMatch[1] : "",
  43. tagId: tagIdMatch ? tagIdMatch[1] : ""
  44. };
  45. }
  46. // 解析学期列表
  47. function parseSemesterResponse(rawText) {
  48. let data;
  49. try {
  50. data = Function(`return (${String(rawText || "").trim()});`)();
  51. } catch (parseError) {
  52. throw new Error("学期数据解析失败");
  53. }
  54. const semesters = [];
  55. if (!data || !data.semesters || typeof data.semesters !== "object") {
  56. return semesters;
  57. }
  58. Object.keys(data.semesters).forEach((k) => {
  59. const arr = data.semesters[k];
  60. if (!Array.isArray(arr)) return;
  61. arr.forEach((s) => {
  62. if (!s || !s.id) return;
  63. semesters.push({
  64. id: String(s.id),
  65. name: `${s.schoolYear || ""} ${s.name || ""}学期`.trim()
  66. });
  67. });
  68. });
  69. return semesters;
  70. }
  71. // 清除课程名后面的课程序号
  72. function cleanCourseName(name) {
  73. return String(name || "").replace(/\(\d{10}\.\d{2}\)\s*$/, "").trim();
  74. }
  75. // 解析周次位图字符串
  76. function parseValidWeeksBitmap(bitmap) {
  77. if (!bitmap || typeof bitmap !== "string") return [];
  78. const weeks = [];
  79. for (let i = 0; i < bitmap.length; i++) {
  80. if (bitmap[i] === "1" && i >= 1) weeks.push(i-1);
  81. }
  82. return weeks;
  83. }
  84. function normalizeWeeks(weeks) {
  85. const list = Array.from(new Set((weeks || []).filter((w) => Number.isInteger(w) && w > 0)));
  86. list.sort((a, b) => a - b);
  87. return list;
  88. }
  89. function mapSectionToTimeSlotNumber(section) {
  90. const mapping = { 1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7, 8: 8 };
  91. return mapping[section] || section;
  92. }
  93. // 反引号化 JavaScript 字面量字符串
  94. function unquoteJsLiteral(token) {
  95. const text = String(token || "").trim();
  96. if (!text) return "";
  97. if (text === "null" || text === "undefined") return "";
  98. if ((text.startsWith("\"") && text.endsWith("\"")) || (text.startsWith("'") && text.endsWith("'"))) {
  99. }
  100. if (text.includes('+') && /^[a-zA-Z_$][\w$]*\s*\+/.test(text)) {
  101. const varName = text.split('+')[0].trim();
  102. return varName;
  103. }
  104. return text;
  105. }
  106. // 分割 JavaScript 函数参数字符串
  107. function splitJsArgs(argsText) {
  108. const args = [];
  109. let curr = "";
  110. let inQuote = "";
  111. let escaped = false;
  112. for (let i = 0; i < argsText.length; i++) {
  113. const ch = argsText[i];
  114. if (escaped) { curr += ch; escaped = false; continue; }
  115. if (ch === "\\") { curr += ch; escaped = true; continue; }
  116. if (inQuote) { curr += ch; if (ch === inQuote) inQuote = ""; continue; }
  117. if (ch === "\"" || ch === "'") { curr += ch; inQuote = ch; continue; }
  118. if (ch === ",") { args.push(curr.trim()); curr = ""; continue; }
  119. curr += ch;
  120. }
  121. if (curr.trim() || argsText.endsWith(",")) { args.push(curr.trim()); }
  122. return args;
  123. }
  124. // 核心:从脚本中解析 TaskActivity
  125. function parseCoursesFromTaskActivityScript(htmlText) {
  126. const text = String(htmlText || "");
  127. if (!text) return [];
  128. const unitCountMatch = text.match(/\bvar\s+unitCount\s*=\s*(\d+)\s*;/);
  129. const unitCount = unitCountMatch ? parseInt(unitCountMatch[1], 10) : 0;
  130. if (!Number.isInteger(unitCount) || unitCount <= 0) return [];
  131. const courses = [];
  132. const blockRe = /activity\s*=\s*new\s+TaskActivity\(([^]*?)\)\s*;\s*index\s*=\s*(?:(\d+)\s*\*\s*unitCount\s*\+\s*(\d+)|(\d+))\s*;\s*table\d+\.activities\[index\]/g;
  133. let match;
  134. while ((match = blockRe.exec(text)) !== null) {
  135. const argsText = match[1] || "";
  136. const args = splitJsArgs(argsText);
  137. if (args.length < 7) continue;
  138. const dayPart = match[2];
  139. const sectionPart = match[3];
  140. const directIndexPart = match[4];
  141. let indexValue = -1;
  142. if (dayPart != null && sectionPart != null) {
  143. indexValue = parseInt(dayPart, 10) * unitCount + parseInt(sectionPart, 10);
  144. } else if (directIndexPart != null) {
  145. indexValue = parseInt(directIndexPart, 10);
  146. }
  147. if (!Number.isInteger(indexValue) || indexValue < 0) continue;
  148. const day = Math.floor(indexValue / unitCount) + 1;
  149. let section = (indexValue % unitCount) + 1;
  150. section = mapSectionToTimeSlotNumber(section);
  151. if (day < 1 || day > 7 || section < 1 || section > 16) continue;
  152. let teacher = unquoteJsLiteral(args[1]);
  153. if (teacher && !/^['"]/.test(String(args[1]).trim()) && /join\s*\(/.test(String(args[1]))) {
  154. const resolved = resolveTeachersForTaskActivityBlock(text, match.index);
  155. if (resolved) { teacher = resolved; }
  156. }
  157. let name = unquoteJsLiteral(args[3]);
  158. if (name && !/^['"]/.test(String(args[3]).trim()) && /^\w+\s*\+\s*["']/.test(String(args[3]))) {
  159. const varMatch = String(args[3]).match(/^(\w+)\s*\+/);
  160. if (varMatch && varMatch[1] === "courseName") {
  161. const resolved = resolveCourseNameForTaskActivityBlock(text, match.index);
  162. if (resolved) {
  163. const suffixMatch = String(args[3]).match(/\+\s*["']([^)]+)["']$/);
  164. const suffix = suffixMatch ? suffixMatch[1] : "";
  165. name = resolved + (suffix ? `(${suffix})` : "");
  166. }
  167. }
  168. }
  169. name = cleanCourseName(name);
  170. const position = unquoteJsLiteral(args[5]);
  171. const weekBitmap = unquoteJsLiteral(args[6]);
  172. const weeks = normalizeWeeks(parseValidWeeksBitmap(weekBitmap));
  173. if (!name) continue;
  174. courses.push({ name, teacher, position, day, startSection: section, endSection: section+1, weeks });
  175. }
  176. return mergeContiguousSections(courses);
  177. }
  178. function resolveTeachersForTaskActivityBlock(fullText, blockStartIndex) {
  179. const start = Math.max(0, blockStartIndex - 2200);
  180. const segment = fullText.slice(start, blockStartIndex);
  181. const re = /var\s+actTeachers\s*=\s*\[([^]*?)\]\s*;/g;
  182. let m; let last = null;
  183. while ((m = re.exec(segment)) !== null) { last = m[1]; }
  184. if (!last) return "";
  185. const names = [];
  186. const nameRe = /name\s*:\s*(?:"([^"]*)"|'([^']*)')/g;
  187. let nm;
  188. while ((nm = nameRe.exec(last)) !== null) {
  189. const name = (nm[1] || nm[2] || "").trim();
  190. if (name) names.push(name);
  191. }
  192. if (names.length === 0) return "";
  193. return Array.from(new Set(names)).join(",");
  194. }
  195. function resolveCourseNameForTaskActivityBlock(fullText, blockStartIndex) {
  196. const start = Math.max(0, blockStartIndex - 3000);
  197. const segment = fullText.slice(start, blockStartIndex);
  198. const re = /(?:var\s+)?courseName\s*=\s*(?:"([^"]*)"|'([^']*)')(?:\s*;)?/gi;
  199. let match; const values = [];
  200. while ((match = re.exec(segment)) !== null) {
  201. const value = (match[1] || match[2] || "").trim();
  202. if (value) { values.push(value); }
  203. }
  204. return values.length > 0 ? values[values.length - 1] : null;
  205. }
  206. function mergeContiguousSections(courses) {
  207. const list = (courses || [])
  208. .filter((c) => c && c.name && Number.isInteger(c.day) && Number.isInteger(c.startSection) && Number.isInteger(c.endSection))
  209. .map((c) => ({ ...c, weeks: normalizeWeeks(c.weeks) }));
  210. list.sort((a, b) => {
  211. const ak = `${a.name}|${a.teacher}|${a.position}|${a.day}|${JSON.stringify(a.weeks)}`;
  212. const bk = `${b.name}|${b.teacher}|${b.position}|${b.day}|${JSON.stringify(b.weeks)}`;
  213. if (ak < bk) return -1; if (ak > bk) return 1;
  214. return a.startSection - b.startSection;
  215. });
  216. const merged = [];
  217. for (const item of list) {
  218. const prev = merged[merged.length - 1];
  219. const sameCourse = prev
  220. && prev.name === item.name
  221. && prev.teacher === item.teacher
  222. && prev.position === item.position
  223. && prev.day === item.day
  224. && JSON.stringify(prev.weeks) === JSON.stringify(item.weeks);
  225. const isContiguous = sameCourse && prev.endSection + 1 === item.startSection;
  226. if (isContiguous) { prev.endSection = item.endSection; }
  227. else { merged.push({ ...item }); }
  228. }
  229. return merged;
  230. }
  231. function getPresetTimeSlots() {
  232. return [
  233. { number: 1, startTime: "08:00", endTime: "08:45" },
  234. { number: 2, startTime: "08:50", endTime: "09:35" },
  235. { number: 3, startTime: "10:05", endTime: "10:50" },
  236. { number: 4, startTime: "10:55", endTime: "11:40" },
  237. { number: 5, startTime: "14:00", endTime: "14:45" },
  238. { number: 6, startTime: "14:50", endTime: "15:35" },
  239. { number: 7, startTime: "16:05", endTime: "16:50" },
  240. { number: 8, startTime: "16:55", endTime: "17:40" }
  241. ];
  242. }
  243. async function runImportFlow() {
  244. // 确保桥接可用
  245. if (!window.AndroidBridgePromise) {
  246. throw new Error("AndroidBridgePromise 不可用,无法进行导入交互。");
  247. }
  248. AndroidBridge.showToast("开始自动探测东北大学秦皇岛校区教务参数...");
  249. // 1. 探测学生 ID 和学期组件 tagId
  250. const entryUrl = `${BASE}/eams/courseTableForStd.action?&sf_request_type=ajax`;
  251. const entryHtml = await requestText(entryUrl, {
  252. method: "GET",
  253. headers: { "x-requested-with": "XMLHttpRequest" }
  254. });
  255. const params = parseEntryParams(entryHtml);
  256. if (!params.studentId || !params.tagId) {
  257. await window.AndroidBridgePromise.showAlert(
  258. "参数探测失败",
  259. "未能识别学生 ID 或学期组件 tagId,请确认已登录后重试。",
  260. "确定"
  261. );
  262. return;
  263. }
  264. // 2. 获取学期列表并让用户选择
  265. const semesterRaw = await requestText(`${BASE}/eams/dataQuery.action?sf_request_type=ajax`, {
  266. method: "POST",
  267. headers: { "content-type": "application/x-www-form-urlencoded; charset=UTF-8" },
  268. body: `tagId=${encodeURIComponent(params.tagId)}&dataType=semesterCalendar`
  269. });
  270. const allSemesters = parseSemesterResponse(semesterRaw);
  271. if (allSemesters.length === 0) {
  272. throw new Error("学期列表为空,无法继续导入。");
  273. }
  274. const recentSemesters = allSemesters;
  275. const selectIndex = await window.AndroidBridgePromise.showSingleSelection(
  276. "请选择导入学期",
  277. JSON.stringify(recentSemesters.map((s) => s.name || s.id)),
  278. recentSemesters.length - 1
  279. );
  280. if (selectIndex === null) {
  281. AndroidBridge.showToast("已取消导入");
  282. return;
  283. }
  284. const selectedSemester = recentSemesters[selectIndex];
  285. AndroidBridge.showToast("正在获取课表数据...");
  286. // 3. 拉取并解析课表
  287. const courseHtml = await requestText(`${BASE}/eams/courseTableForStd!courseTable.action?sf_request_type=ajax`, {
  288. method: "POST",
  289. headers: { "content-type": "application/x-www-form-urlencoded; charset=UTF-8" },
  290. body: [
  291. "ignoreHead=1",
  292. "setting.kind=std",
  293. "startWeek=",
  294. `semester.id=${encodeURIComponent(selectedSemester.id)}`,
  295. `ids=${encodeURIComponent(params.studentId)}`
  296. ].join("&")
  297. });
  298. const courses = parseCoursesFromTaskActivityScript(courseHtml);
  299. if (courses.length === 0) {
  300. const debugInfo = extractCourseHtmlDebugInfo(courseHtml);
  301. await window.AndroidBridgePromise.showAlert(
  302. "解析失败",
  303. `未能从课表响应中识别到课程。\n响应长度: ${debugInfo.responseLength}\n包含 TaskActivity: ${debugInfo.hasTaskActivity}`,
  304. "确定"
  305. );
  306. return;
  307. }
  308. // 4. 保存结果
  309. await window.AndroidBridgePromise.saveImportedCourses(JSON.stringify(courses));
  310. await window.AndroidBridgePromise.savePresetTimeSlots(JSON.stringify(getPresetTimeSlots()));
  311. AndroidBridge.showToast(`导入成功,共 ${courses.length} 条课程`);
  312. AndroidBridge.notifyTaskCompletion();
  313. }
  314. (async function bootstrap() {
  315. try {
  316. await runImportFlow();
  317. } catch (error) {
  318. console.error("导入流程失败:", error);
  319. AndroidBridge.showToast("自动探测失败,请检查教务连接");
  320. }
  321. })();
  322. })();