gdouyj.js 31 KB

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