gdouyj.js 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812
  1. /**
  2. * 广东海洋大学阳江校区教务适配
  3. * @date 2026-7-30
  4. * @author Mccurtain (原始 GDOU 适配)
  5. * @adapted-by Yihe-ng (阳江校区作息与适配)
  6. * @version 1.2
  7. *
  8. * @note 教务系统已关闭外网直连,现行入口为学校提供的零信任地址
  9. * (https://wfw.gdou.edu.cn/https://jw.gdou.edu.cn/),校内外均可访问。
  10. * 接口地址改为运行时推导,
  11. */
  12. (function () {
  13. /**
  14. * 节次与周次合并去重函数。
  15. * @param {Array<Object>} courses 原始解析课程数组
  16. * @returns {Array<Object>} 合并去重后的课程数组
  17. */
  18. function mergeAndDistinctCourses(courses) {
  19. if (!Array.isArray(courses) || courses.length <= 1) return courses;
  20. const list = courses.map(course => ({
  21. ...course,
  22. name: course.name || '',
  23. teacher: course.teacher || '',
  24. position: course.position || '',
  25. weeks: Array.isArray(course.weeks) ? [...course.weeks].sort((a, b) => a - b) : []
  26. }));
  27. // 阶段 1:合并相同课程、星期、周次下的连续节次和重复记录。
  28. list.sort((a, b) =>
  29. a.name.localeCompare(b.name) ||
  30. a.teacher.localeCompare(b.teacher) ||
  31. a.position.localeCompare(b.position) ||
  32. (a.day || 0) - (b.day || 0) ||
  33. a.weeks.join(',').localeCompare(b.weeks.join(',')) ||
  34. (a.startSection || 0) - (b.startSection || 0)
  35. );
  36. const sectionMerged = [];
  37. let current = list[0];
  38. for (let i = 1; i < list.length; i++) {
  39. const next = list[i];
  40. const sameCourseAndWeeks =
  41. current.name === next.name &&
  42. current.teacher === next.teacher &&
  43. current.position === next.position &&
  44. current.day === next.day &&
  45. current.weeks.join(',') === next.weeks.join(',');
  46. const isContinuous = current.endSection + 1 === next.startSection;
  47. const isDuplicate = current.startSection === next.startSection &&
  48. current.endSection === next.endSection;
  49. if (sameCourseAndWeeks && isContinuous) {
  50. current.endSection = next.endSection;
  51. } else if (sameCourseAndWeeks && isDuplicate) {
  52. continue;
  53. } else {
  54. sectionMerged.push(current);
  55. current = next;
  56. }
  57. }
  58. sectionMerged.push(current);
  59. // 阶段 2:合并相同节次下分段返回的周次。
  60. sectionMerged.sort((a, b) =>
  61. a.name.localeCompare(b.name) ||
  62. a.teacher.localeCompare(b.teacher) ||
  63. a.position.localeCompare(b.position) ||
  64. (a.day || 0) - (b.day || 0) ||
  65. (a.startSection || 0) - (b.startSection || 0) ||
  66. (a.endSection || 0) - (b.endSection || 0)
  67. );
  68. const result = [];
  69. let currentCourse = sectionMerged[0];
  70. for (let i = 1; i < sectionMerged.length; i++) {
  71. const nextCourse = sectionMerged[i];
  72. const sameCourseAndSection =
  73. currentCourse.name === nextCourse.name &&
  74. currentCourse.teacher === nextCourse.teacher &&
  75. currentCourse.position === nextCourse.position &&
  76. currentCourse.day === nextCourse.day &&
  77. currentCourse.startSection === nextCourse.startSection &&
  78. currentCourse.endSection === nextCourse.endSection;
  79. if (sameCourseAndSection) {
  80. currentCourse.weeks = Array.from(new Set([
  81. ...currentCourse.weeks,
  82. ...nextCourse.weeks
  83. ])).sort((a, b) => a - b);
  84. } else {
  85. result.push(currentCourse);
  86. currentCourse = nextCourse;
  87. }
  88. }
  89. result.push(currentCourse);
  90. return result;
  91. }
  92. /**
  93. * 解析周次字符串,处理单双周和周次范围。
  94. * 兼容格式:"1-16周"、"6周"、"第6周"、"1-8周(单)"、"1-10周(双)"、"1-5周,9周"
  95. */
  96. function parseWeeks(weekStr) {
  97. if (!weekStr) return [];
  98. const normalizedWeekStr = String(weekStr).replace(/,/g, ',');
  99. const weekSets = normalizedWeekStr.split(',');
  100. let weeks = [];
  101. for (const set of weekSets) {
  102. const trimmedSet = set.trim();
  103. const rangeMatch = trimmedSet.match(/(\d+)\s*-\s*(\d+)\s*周?/);
  104. const singleMatch = trimmedSet.match(/^(?:第\s*)?(\d+)\s*周?/); // 匹配单个周次,包括调课返回的“第N周”
  105. let start = 0;
  106. let end = 0;
  107. let processed = false;
  108. if (rangeMatch) { // 范围, 如 "1-5周"
  109. start = Number(rangeMatch[1]);
  110. end = Number(rangeMatch[2]);
  111. processed = true;
  112. } else if (singleMatch) { // 单个周, 如 "6周"
  113. start = end = Number(singleMatch[1]);
  114. processed = true;
  115. }
  116. if (processed && start >= 1 && end >= start) {
  117. // 确定单双周
  118. const isSingle = trimmedSet.includes('(单)');
  119. const isDouble = trimmedSet.includes('(双)');
  120. for (let w = start; w <= end; w++) {
  121. if (isSingle && w % 2 === 0) continue; // 单周跳过偶数
  122. if (isDouble && w % 2 !== 0) continue; // 双周跳过奇数
  123. weeks.push(w);
  124. }
  125. }
  126. }
  127. // 去重并排序
  128. return [...new Set(weeks)].sort((a, b) => a - b);
  129. }
  130. /**
  131. * 解析节次字符串,例如 "1-2"、"1-2节" 或单节 "3"。
  132. * 返回 null 表示接口返回了无法识别的节次格式。
  133. */
  134. function parseSectionRange(sectionStr) {
  135. const sectionText = sectionStr == null ? '' : String(sectionStr);
  136. const sectionMatch = sectionText.match(/^\s*(?:第)?(\d+)\s*(?:-\s*(\d+))?\s*节?\s*$/);
  137. if (!sectionMatch) {
  138. return null;
  139. }
  140. const startSection = Number(sectionMatch[1]);
  141. const endSection = Number(sectionMatch[2] || sectionMatch[1]);
  142. if (!Number.isInteger(startSection) || !Number.isInteger(endSection) ||
  143. startSection < 1 || endSection < startSection) {
  144. return null;
  145. }
  146. return { startSection, endSection };
  147. }
  148. /**
  149. * 阳江校区其他场地(非慎思楼)的作息。
  150. * 只有第 3、4 节在校区作息表中是不同的连续时间块,使用自定义时间表示。
  151. */
  152. const OTHER_VENUE_SECTION_3_4_TIME = { startTime: "10:10", endTime: "11:40" };
  153. function getOtherVenueCustomTime(position, startSection, endSection) {
  154. const positionText = position == null ? '' : String(position);
  155. if (!positionText || positionText.includes("慎思楼")) {
  156. return null;
  157. }
  158. if (startSection !== 3 || endSection !== 4) {
  159. return null;
  160. }
  161. return OTHER_VENUE_SECTION_3_4_TIME;
  162. }
  163. function applyOtherVenueCustomTime(courses) {
  164. return courses.map(course => {
  165. const customTime = getOtherVenueCustomTime(
  166. course.position,
  167. course.startSection,
  168. course.endSection
  169. );
  170. if (!customTime) return course;
  171. return {
  172. ...course,
  173. isCustomTime: true,
  174. customStartTime: customTime.startTime,
  175. customEndTime: customTime.endTime
  176. };
  177. });
  178. }
  179. /**
  180. * 解析正方 v9 课表查询接口返回的 JSON 数据。
  181. */
  182. function parseJsonData(jsonData) {
  183. console.log("JS: parseJsonData 正在解析 JSON 数据...");
  184. // 正方 v9 个人课表数据放在 kbList 字段中
  185. if (!jsonData || !Array.isArray(jsonData.kbList)) {
  186. console.warn("JS: JSON 数据结构错误或缺少 kbList 字段。");
  187. return [];
  188. }
  189. const rawCourseList = jsonData.kbList;
  190. const initialCourseList = [];
  191. for (const rawCourse of rawCourseList) {
  192. if (!rawCourse || typeof rawCourse !== 'object') {
  193. continue;
  194. }
  195. // 课程名、星期、节次和周次是解析所必需的;教师或教室为空时仍保留课程。
  196. if (!rawCourse.kcmc || rawCourse.xqj == null ||
  197. rawCourse.jcs == null || rawCourse.zcd == null) {
  198. continue;
  199. }
  200. const weeksArray = parseWeeks(rawCourse.zcd);
  201. // 周次有效性检查
  202. if (weeksArray.length === 0) {
  203. continue;
  204. }
  205. const sectionRange = parseSectionRange(rawCourse.jcs);
  206. if (!sectionRange) {
  207. console.warn(`JS: 跳过无法解析节次的课程:${rawCourse.kcmc}`);
  208. continue;
  209. }
  210. const day = Number(rawCourse.xqj); // xqj: 星期几 (周一为1, 周日为7)
  211. // 数字有效性检查
  212. if (isNaN(day) || day < 1 || day > 7) {
  213. continue;
  214. }
  215. initialCourseList.push({
  216. name: String(rawCourse.kcmc).trim(),
  217. teacher: rawCourse.xm == null ? '' : String(rawCourse.xm).trim(),
  218. position: rawCourse.cdmc == null ? '' : String(rawCourse.cdmc).trim(),
  219. day: day,
  220. startSection: sectionRange.startSection,
  221. endSection: sectionRange.endSection,
  222. weeks: weeksArray
  223. });
  224. }
  225. const mergedCourses = mergeAndDistinctCourses(initialCourseList);
  226. const finalCourseList = applyOtherVenueCustomTime(mergedCourses);
  227. finalCourseList.sort((a, b) =>
  228. a.day - b.day ||
  229. a.startSection - b.startSection ||
  230. a.name.localeCompare(b.name)
  231. );
  232. console.log(`JS: JSON 数据解析与合并完成,共找到 ${finalCourseList.length} 门课程。`);
  233. return finalCourseList;
  234. }
  235. async function promptUserToStart() {
  236. console.log("JS: 流程开始:显示公告。");
  237. return await window.shiguangBridgePromise.showAlert(
  238. "广东海洋大学阳江校区教务系统课表导入",
  239. "请确认页面上的学年和学期,再按提示导入课程。\n\n如果登录后页面显示不全,下次登录前可点右上角菜单,选择“电脑模式”。",
  240. "好的,开始导入"
  241. );
  242. }
  243. /**
  244. * 从 select 元素解析学年和学期选项。
  245. * 默认索引优先使用当前 select.value,确保跟随用户在页面上的实际选择。
  246. */
  247. function parseSelectOptions(selectElement) {
  248. if (!selectElement || typeof selectElement.querySelectorAll !== "function") {
  249. return { options: [], defaultIndex: 0 };
  250. }
  251. const options = [];
  252. let defaultIndex = 0;
  253. Array.from(selectElement.querySelectorAll("option")).forEach(option => {
  254. const value = String(option.value || "").trim();
  255. if (!value) return;
  256. const text = String(option.textContent || "").trim() || value;
  257. if (option.selected) defaultIndex = options.length;
  258. options.push({ value, text });
  259. });
  260. const currentValue = String(selectElement.value || "").trim();
  261. const currentIndex = options.findIndex(option => option.value === currentValue);
  262. if (currentIndex !== -1) defaultIndex = currentIndex;
  263. return { options, defaultIndex };
  264. }
  265. function parseAcademicOptionsFromDocument(doc) {
  266. if (!doc || typeof doc.querySelector !== "function") return null;
  267. const yearData = parseSelectOptions(doc.querySelector("#xnm"));
  268. const semesterData = parseSelectOptions(doc.querySelector("#xqm"));
  269. if (yearData.options.length === 0 || semesterData.options.length === 0) return null;
  270. return {
  271. yearOptions: yearData.options,
  272. semesterOptions: semesterData.options,
  273. defaultYearIndex: yearData.defaultIndex,
  274. defaultSemesterIndex: semesterData.defaultIndex
  275. };
  276. }
  277. function isOnTimetablePage() {
  278. const pathname = typeof window !== "undefined" && window.location
  279. ? window.location.pathname
  280. : "";
  281. return typeof pathname === "string" && pathname.includes("xskbcx_cxXskbcxIndex.html");
  282. }
  283. function getCurrentPageAcademicOptions() {
  284. const frame = typeof document !== "undefined"
  285. ? document.getElementById("gdouyj-timetable-frame")
  286. : null;
  287. if (frame) {
  288. try {
  289. return parseAcademicOptionsFromDocument(frame.contentDocument);
  290. } catch (error) {
  291. return null;
  292. }
  293. }
  294. if (!isOnTimetablePage() || typeof document === "undefined" || !document.querySelector) {
  295. return null;
  296. }
  297. return parseAcademicOptionsFromDocument(document);
  298. }
  299. /**
  300. * WFW 移动门户生成的代理前缀会使页面资源跳转到登录页。
  301. * 只修正本校 WFW 前缀,保留学校原页面和原查询逻辑。
  302. */
  303. function normalizeWfwPageHtml(html, origin) {
  304. const prefix = `${origin}/https://jw.gdou.edu.cn`;
  305. const escapedPrefix = prefix.replace(/\//g, "\\/");
  306. const escapedOrigin = origin.replace(/\//g, "\\/");
  307. return html.split(prefix).join(origin).split(escapedPrefix).join(escapedOrigin);
  308. }
  309. async function prepareWfwTimetableHtml(html, origin) {
  310. const page = new DOMParser().parseFromString(normalizeWfwPageHtml(html, origin), "text/html");
  311. for (const existing of Array.from(page.querySelectorAll("base"))) existing.remove();
  312. const base = page.createElement("base");
  313. base.href = `${origin}/kbcx/xskbcx_cxXskbcxIndex.html?gnmkdm=N2151&layout=default`;
  314. page.head.prepend(base);
  315. // 顺序获取原站依赖,避免 WFW 同时加载大量资源时返回 503 后留下半成品页面。
  316. for (const script of Array.from(page.querySelectorAll("script[src]"))) {
  317. const url = new URL(script.getAttribute("src"), `${origin}/`);
  318. if (url.origin !== origin) throw new Error("课表页包含非同源脚本,已停止打开");
  319. let response;
  320. for (let attempt = 0; attempt < 3; attempt++) {
  321. response = await fetch(url.href, { credentials: "include", cache: "no-store" });
  322. if (response.status !== 503) break;
  323. if (attempt < 2) await new Promise(resolve => setTimeout(resolve, 500));
  324. }
  325. if (!response.ok) throw new Error(`页面资源加载失败:${url.pathname},HTTP ${response.status}`);
  326. const type = response.headers.get("content-type") || "";
  327. if (!/(?:javascript|ecmascript)/i.test(type)) {
  328. throw new Error("页面资源未返回脚本,请重新登录");
  329. }
  330. const code = normalizeWfwPageHtml(await response.text(), origin);
  331. script.removeAttribute("src");
  332. script.removeAttribute("async");
  333. script.removeAttribute("defer");
  334. script.textContent = code.replace(/<\/script/gi, "<\\/script");
  335. }
  336. return `<!doctype html>\n${page.documentElement.outerHTML}`;
  337. }
  338. async function openTimetableFromMobilePortal() {
  339. if (window.location.hostname !== "wfw.gdou.edu.cn" ||
  340. window.location.pathname !== "/xtgl/index_cxAllApp.html" ||
  341. document.getElementById("gdouyj-timetable-frame")) {
  342. return false;
  343. }
  344. const confirmed = await window.shiguangBridgePromise.showAlert(
  345. "打开课表",
  346. "这里暂时看不到课表。点“打开课表”后,请确认页面上的学年和学期,再点一次拾光的“导入”按钮保存课程。",
  347. "打开课表"
  348. );
  349. if (!confirmed) return true;
  350. try {
  351. const url = buildScheduleUrl("xskbcx_cxXskbcxIndex.html", "gnmkdm=N2151&layout=default");
  352. const response = await fetch(url, { credentials: "include" });
  353. if (!response.ok) throw new Error(`HTTP ${response.status}`);
  354. const html = await response.text();
  355. const parsed = new DOMParser().parseFromString(html, "text/html");
  356. if (!parseAcademicOptionsFromDocument(parsed)) {
  357. throw new Error("未取得个人课表页面,请重新登录;必要时在登录前切换电脑模式");
  358. }
  359. window.shiguangBridge.showToast("正在加载个人课表页面,请稍候...");
  360. const preparedHtml = await prepareWfwTimetableHtml(html, window.location.origin);
  361. const panel = document.createElement("div");
  362. panel.id = "gdouyj-timetable-panel";
  363. panel.style.cssText = "position:fixed;inset:0;z-index:2147483647;display:flex;flex-direction:column;background:white";
  364. const toolbar = document.createElement("div");
  365. toolbar.style.cssText = "display:flex;align-items:center;justify-content:space-between;padding:8px 12px;background:#087ebc;color:white;font:16px sans-serif";
  366. const label = document.createElement("span");
  367. label.textContent = "确认学年学期后,再点“导入”";
  368. const close = document.createElement("button");
  369. close.textContent = "返回";
  370. close.type = "button";
  371. const previousTitle = document.title;
  372. close.onclick = () => {
  373. panel.remove();
  374. document.title = previousTitle;
  375. };
  376. toolbar.append(label, close);
  377. const frame = document.createElement("iframe");
  378. frame.id = "gdouyj-timetable-frame";
  379. frame.title = "广东海洋大学个人课表查询";
  380. frame.style.cssText = "flex:1;min-height:0;width:100%;border:0;background:white";
  381. frame.srcdoc = preparedHtml;
  382. panel.append(toolbar, frame);
  383. document.body.appendChild(panel);
  384. document.title = "个人课表查询";
  385. } catch (error) {
  386. window.shiguangBridge.showToast(`打开课表页面失败:${error.message}`);
  387. }
  388. return true;
  389. }
  390. /**
  391. * 推导教务系统接口前缀:
  392. * 直接访问:pathname 形如 /kbcx/xskbcx_cxXsgrkb.html → 前缀为 ""
  393. * 反代·拼接态:pathname 形如 /https://jw.gdou.edu.cn/kbcx/xskbcx_...html → 前缀为 "/https://jw.gdou.edu.cn"
  394. * 反代·哈希态:pathname 形如 /http/<hash>/kbcx/xskbcx_...html → 前缀为 "/http/<hash>"
  395. * 以 "/kbcx/" 为锚点即可同时覆盖以上三种情况。
  396. */
  397. function getScheduleBase() {
  398. const path = (window.location && window.location.pathname) || "";
  399. const kbIndex = path.indexOf("/kbcx/");
  400. if (kbIndex >= 0) return path.slice(0, kbIndex);
  401. // 兜底:停留在教务系统非课表页(例如首页)时,直接识别反代前缀。
  402. const proxyPrefix = path.match(/^\/(?:https?:\/\/[^/]+|(?:http|https|https-443)\/[^/]+)/i);
  403. return proxyPrefix ? proxyPrefix[0] : "";
  404. }
  405. /**
  406. * 拼接教务系统接口地址,自动带上直连/反代前缀。
  407. * @param {string} modulePath 接口文件名,例如 "xskbcx_cxXsgrkb.html"
  408. * @param {string} query 可选查询串,例如 "gnmkdm=N2151"
  409. */
  410. function buildScheduleUrl(modulePath, query) {
  411. const base = getScheduleBase();
  412. const queryString = query ? `?${query}` : "";
  413. return `${window.location.origin}${base}/kbcx/${modulePath}${queryString}`;
  414. }
  415. /**
  416. * 从正方课表页读取学年和学期选项。
  417. * 学期码直接使用教务系统返回的 value,例如第一学期为 3、第二学期为 12。
  418. */
  419. async function fetchAcademicOptions() {
  420. const currentPageOptions = getCurrentPageAcademicOptions();
  421. if (currentPageOptions) {
  422. console.log("JS: 使用当前课表页的学年学期选项。");
  423. return currentPageOptions;
  424. }
  425. const url = buildScheduleUrl("xskbcx_cxXskbcxIndex.html", "gnmkdm=N2151&layout=default");
  426. try {
  427. const response = await fetch(url, {
  428. method: "GET",
  429. credentials: "include"
  430. });
  431. if (!response.ok) return null;
  432. const htmlText = await response.text();
  433. const doc = new DOMParser().parseFromString(htmlText, "text/html");
  434. const optionsData = parseAcademicOptionsFromDocument(doc);
  435. if (!optionsData) return null;
  436. const selectedYearIndex = optionsData.defaultYearIndex;
  437. const start = Math.max(0, selectedYearIndex - 2);
  438. const end = Math.min(optionsData.yearOptions.length, selectedYearIndex + 3);
  439. return {
  440. ...optionsData,
  441. yearOptions: optionsData.yearOptions.slice(start, end),
  442. defaultYearIndex: selectedYearIndex - start
  443. };
  444. } catch (error) {
  445. console.warn("JS: 读取学年学期选项失败:", error);
  446. return null;
  447. }
  448. }
  449. /**
  450. * 使用教务系统返回的选项让用户选择学年和学期。
  451. * 学年和学期码直接使用 option 的 value,避免本地手动映射。
  452. */
  453. async function selectAcademicYearAndSemester() {
  454. const optionsData = await fetchAcademicOptions();
  455. if (!optionsData) {
  456. window.shiguangBridge.showToast("从教务系统读取学年学期失败,请确保登录状态。");
  457. return null;
  458. }
  459. const { yearOptions, semesterOptions, defaultYearIndex, defaultSemesterIndex } = optionsData;
  460. const yearTexts = yearOptions.map(option => option.text);
  461. const yearIndex = await window.shiguangBridgePromise.showSingleSelection(
  462. "选择学年",
  463. JSON.stringify(yearTexts),
  464. defaultYearIndex
  465. );
  466. if (yearIndex === null || yearIndex === -1 || !yearOptions[yearIndex]) return null;
  467. const selectedYearCode = yearOptions[yearIndex].value;
  468. const semesterTexts = semesterOptions.map(option => option.text);
  469. const semesterIndex = await window.shiguangBridgePromise.showSingleSelection(
  470. "选择学期",
  471. JSON.stringify(semesterTexts),
  472. defaultSemesterIndex
  473. );
  474. if (semesterIndex === null || semesterIndex === -1 || !semesterOptions[semesterIndex]) return null;
  475. const selectedSemesterCode = semesterOptions[semesterIndex].value;
  476. return {
  477. academicYear: selectedYearCode,
  478. semesterCode: selectedSemesterCode
  479. };
  480. }
  481. /**
  482. * 将正方返回的日期字段规范为 yyyy-MM-dd。
  483. */
  484. function normalizeStartDate(value) {
  485. const match = String(value || "").match(/(\d{4})[-\/.年](\d{1,2})[-\/.月](\d{1,2})/);
  486. if (!match) return null;
  487. return `${match[1]}-${match[2].padStart(2, "0")}-${match[3].padStart(2, "0")}`;
  488. }
  489. /**
  490. * 从正方校历响应中查找第一周日期。
  491. * 兼容顶层数组、data/list/rows 等包装对象,以及 zrq/zcrq/rq/ksrq 字段。
  492. */
  493. function findSemesterStartDate(value) {
  494. if (value == null) return null;
  495. if (typeof value !== "object") {
  496. return normalizeStartDate(value);
  497. }
  498. if (Array.isArray(value)) {
  499. const firstWeek = value.find(item =>
  500. item && typeof item === "object" &&
  501. (String(item.zs) === "1" || String(item.zsmc) === "1")
  502. ) || value[0];
  503. const firstWeekDate = findSemesterStartDate(firstWeek);
  504. if (firstWeekDate) return firstWeekDate;
  505. for (const item of value) {
  506. const date = findSemesterStartDate(item);
  507. if (date) return date;
  508. }
  509. return null;
  510. }
  511. for (const field of ["zrq", "zcrq", "rq", "ksrq"]) {
  512. const date = normalizeStartDate(value[field]);
  513. if (date) return date;
  514. }
  515. for (const item of Object.values(value)) {
  516. const date = findSemesterStartDate(item);
  517. if (date) return date;
  518. }
  519. return null;
  520. }
  521. /**
  522. * 获取所选学期的第一周开学日期。
  523. * 日期接口失败时返回 null,不阻断课表导入。
  524. */
  525. async function fetchSemesterStartDate(academicYear, semesterCode) {
  526. const url = buildScheduleUrl("xskbcxZccx_cxZcByXnxq.html", "gnmkdm=N2154");
  527. const requestBody = `xnm=${encodeURIComponent(academicYear)}&xqm=${encodeURIComponent(semesterCode)}`;
  528. try {
  529. const response = await fetch(url, {
  530. method: "POST",
  531. headers: {
  532. "accept": "application/json, text/javascript, */*; q=0.01",
  533. "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8",
  534. "x-requested-with": "XMLHttpRequest"
  535. },
  536. body: requestBody,
  537. credentials: "include"
  538. });
  539. if (!response.ok) {
  540. console.warn(`JS: 开学日期接口请求失败:HTTP ${response.status}`);
  541. return null;
  542. }
  543. const responseText = await response.text();
  544. let json;
  545. try {
  546. json = JSON.parse(responseText);
  547. } catch (error) {
  548. console.warn("JS: 开学日期接口未返回 JSON,可能登录已过期。", error);
  549. return null;
  550. }
  551. const startDate = findSemesterStartDate(json);
  552. if (!startDate) console.warn("JS: 校历响应中未找到第 1 周开学日期。");
  553. return startDate;
  554. } catch (error) {
  555. console.warn("JS: 获取学期开学日期失败:", error);
  556. }
  557. return null;
  558. }
  559. /**
  560. * 请求正方 v9 课表接口并解析课程数据。
  561. */
  562. async function fetchAndParseCourses(academicYear, semesterCode) {
  563. const requestBody = `xnm=${encodeURIComponent(academicYear)}&xqm=${encodeURIComponent(semesterCode)}&kzlx=ck&xsdm=&kclbdm=`;
  564. // 广东海洋大学正方教务 v9 个人课表查询接口
  565. const targetUrl = buildScheduleUrl("xskbcx_cxXsgrkb.html", "gnmkdm=N2151");
  566. try {
  567. // 课表和校历互不依赖,并行请求以减少导入等待时间。
  568. const [courseResponse, semesterStartDate] = await Promise.all([
  569. fetch(targetUrl, {
  570. method: "POST",
  571. headers: {
  572. "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8"
  573. },
  574. body: requestBody,
  575. credentials: "include"
  576. }),
  577. fetchSemesterStartDate(academicYear, semesterCode)
  578. ]);
  579. if (!courseResponse.ok) {
  580. window.shiguangBridge.showToast(`课表请求失败:HTTP ${courseResponse.status}`);
  581. console.error(`JS: 接口返回非 200 状态码:${courseResponse.status}`);
  582. return null;
  583. }
  584. const jsonText = await courseResponse.text();
  585. const jsonData = JSON.parse(jsonText);
  586. if (!jsonData || !Array.isArray(jsonData.kbList) || jsonData.kbList.length === 0) {
  587. window.shiguangBridge.showToast("未查询到课表数据,请检查学年/学期是否选择正确,或确认已登录教务系统。");
  588. return null;
  589. }
  590. const parsedCourses = parseJsonData(jsonData);
  591. if (parsedCourses.length === 0) {
  592. window.shiguangBridge.showToast("课表数据为空或解析失败,请确认所选学年学期。");
  593. return null;
  594. }
  595. return {
  596. courses: parsedCourses,
  597. // CourseConfigJsonModel(wiki 1.3):所有字段可选,未提供则用默认值。
  598. // GDOU 各节课间隔不统一,因此用 TimeSlot 节次表达时间。
  599. config: {
  600. semesterStartDate,
  601. semesterTotalWeeks: 20
  602. }
  603. };
  604. } catch (e) {
  605. console.error("JS: 获取课表失败:", e);
  606. window.shiguangBridge.showToast("获取课表失败:请确认已在教务系统登录并停留在个人课表页,且登录状态未过期。");
  607. return null;
  608. }
  609. }
  610. async function saveCourses(parsedCourses) {
  611. window.shiguangBridge.showToast(`正在保存 ${parsedCourses.length} 门课程...`);
  612. console.log(`JS: 尝试保存 ${parsedCourses.length} 门课程...`);
  613. try {
  614. await window.shiguangBridgePromise.saveImportedCourses(JSON.stringify(parsedCourses, null, 2));
  615. console.log("JS: 课程保存成功!");
  616. return true;
  617. } catch (error) {
  618. window.shiguangBridge.showToast(`课程保存失败: ${error.message}`);
  619. console.error('JS: Save Courses Error:', error);
  620. return false;
  621. }
  622. }
  623. // 阳江校区慎思楼上课时间(根据用户提供的校区作息表)
  624. const TimeSlots = [
  625. { number: 1, startTime: "08:10", endTime: "08:55" },
  626. { number: 2, startTime: "09:05", endTime: "09:50" },
  627. { number: 3, startTime: "10:20", endTime: "11:05" },
  628. { number: 4, startTime: "11:15", endTime: "12:00" },
  629. { number: 5, startTime: "14:30", endTime: "15:15" },
  630. { number: 6, startTime: "15:20", endTime: "16:05" },
  631. { number: 7, startTime: "16:20", endTime: "17:05" },
  632. { number: 8, startTime: "17:10", endTime: "17:55" },
  633. { number: 9, startTime: "19:30", endTime: "20:15" },
  634. { number: 10, startTime: "20:25", endTime: "21:10" }
  635. ];
  636. async function importPresetTimeSlots(timeSlots) {
  637. console.log(`JS: 准备导入 ${timeSlots.length} 个预设时间段。`);
  638. if (timeSlots.length > 0) {
  639. window.shiguangBridge.showToast(`正在导入 ${timeSlots.length} 个预设时间段...`);
  640. try {
  641. await window.shiguangBridgePromise.savePresetTimeSlots(JSON.stringify(timeSlots));
  642. window.shiguangBridge.showToast("预设时间段导入成功!");
  643. console.log("JS: 预设时间段导入成功。");
  644. } catch (error) {
  645. window.shiguangBridge.showToast("导入时间段失败: " + error.message);
  646. console.error('JS: Save Time Slots Error:', error);
  647. }
  648. } else {
  649. window.shiguangBridge.showToast("警告:时间段为空,未导入时间段信息。");
  650. console.warn("JS: 警告:传入时间段为空,未导入时间段信息。");
  651. }
  652. }
  653. async function runImportFlow() {
  654. // 首次在异常移动门户执行时只打开查询页,保留用户核对与选择学期的机会。
  655. if (await openTimetableFromMobilePortal()) return;
  656. const alertConfirmed = await promptUserToStart();
  657. if (!alertConfirmed) {
  658. window.shiguangBridge.showToast("用户取消了导入。");
  659. console.log("JS: 用户取消了导入流程。");
  660. return;
  661. }
  662. const selection = await selectAcademicYearAndSemester();
  663. if (!selection) {
  664. window.shiguangBridge.showToast("导入已取消。");
  665. console.log("JS: 获取学年学期失败/取消,流程终止。");
  666. return;
  667. }
  668. const { academicYear, semesterCode } = selection;
  669. console.log(`JS: 已确定学年学期:${academicYear},学期码:${semesterCode}`);
  670. const result = await fetchAndParseCourses(academicYear, semesterCode);
  671. if (result === null) {
  672. console.log("JS: 课程获取或解析失败,流程终止。");
  673. return;
  674. }
  675. const { courses, config } = result;
  676. const saveResult = await saveCourses(courses);
  677. if (!saveResult) {
  678. console.log("JS: 课程保存失败,流程终止。");
  679. return;
  680. }
  681. try {
  682. await window.shiguangBridgePromise.saveCourseConfig(JSON.stringify(config));
  683. const configMessage = config.semesterStartDate
  684. ? `课表配置更新成功!总周数:${config.semesterTotalWeeks}周,开学日期:${config.semesterStartDate}。`
  685. : `课表配置更新成功!总周数:${config.semesterTotalWeeks}周,未获取到开学日期,已继续导入。`;
  686. window.shiguangBridge.showToast(configMessage);
  687. } catch (error) {
  688. window.shiguangBridge.showToast(`课表配置保存失败: ${error.message}`);
  689. console.error('JS: Save Config Error:', error);
  690. return;
  691. }
  692. await importPresetTimeSlots(TimeSlots);
  693. window.shiguangBridge.showToast(`课程导入成功,共导入 ${courses.length} 门课程!`);
  694. console.log("JS: 整个导入流程执行完毕并成功。");
  695. window.shiguangBridge.notifyTaskCompletion();
  696. }
  697. // 脚本执行入口
  698. runImportFlow();
  699. })();