gdou2.js 34 KB

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