gzist_01.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474
  1. // 广州理工学院(GZIST)拾光课程表适配脚本
  2. // 正方教务 v9 接口,参考案例 JSEI_01:
  3. // https://github.com/XingHeYuZhuan/shiguang_warehouse/tree/main/resources/JSEI
  4. // 非该校开发者适配,发现问题请提 issue 或 PR
  5. /** 基础域名:校园网直连 / WebVPN(按当前页面自动选择) */
  6. const BASE_URLS = {
  7. campus: "http://jw.gzist.edu.cn/jwglxt",
  8. webvpn: "https://webvpn.gzist.edu.cn/https/jw.gzist.edu.cn/jwglxt"
  9. };
  10. // 本校正方页面覆盖了原型方法且行为不符标准:filter 回调拿到的第一个参数是 index、trim 会删掉字符串内部空白,
  11. // 故下面两处改用不依赖原型的写法(for 循环 / 正则)。
  12. const safeTrim = (s) => String(s).replace(/^\s+|\s+$/g, "");
  13. function getBaseUrl() {
  14. const { origin, hostname, pathname } = window.location;
  15. // WebVPN:路径形如 /https/jw.gzist.edu.cn/jwglxt/...
  16. if (hostname.includes("webvpn")) {
  17. const matched = pathname.match(/\/https\/[^/]+\/jwglxt/);
  18. return origin + (matched ? matched[0] : "/https/jw.gzist.edu.cn/jwglxt");
  19. }
  20. // 校园网:从 /jwglxt 起截断
  21. const matched = pathname.match(/\/jwglxt(?=\/|$)/);
  22. if (matched) return origin + pathname.substring(0, matched.index + matched[0].length);
  23. return BASE_URLS.campus;
  24. }
  25. /** 节次与周次合并去重(取自上游 wiki:课程合并与去重函数) */
  26. function mergeAndDistinctCourses(courses) {
  27. if (!Array.isArray(courses) || courses.length <= 1) return courses;
  28. // 1. 深拷贝并规范周次数据,过滤无效项
  29. const list = courses.map(c => ({
  30. ...c,
  31. name: c.name || '',
  32. teacher: c.teacher || '',
  33. position: c.position || '',
  34. weeks: Array.isArray(c.weeks) ? [...c.weeks].sort((a, b) => a - b) : []
  35. }));
  36. // 阶段 1:合并连续节次与完全重复记录(前提:名称、教师、地点、星期、周次一致)
  37. list.sort((a, b) => {
  38. return a.name.localeCompare(b.name) ||
  39. a.teacher.localeCompare(b.teacher) ||
  40. a.position.localeCompare(b.position) ||
  41. (a.day || 0) - (b.day || 0) ||
  42. a.weeks.join(',').localeCompare(b.weeks.join(',')) ||
  43. (a.startSection || 0) - (b.startSection || 0);
  44. });
  45. const step1Merged = [];
  46. let current = list[0];
  47. for (let i = 1; i < list.length; i++) {
  48. const next = list[i];
  49. const isSameCourseAndWeeks =
  50. current.name === next.name &&
  51. current.teacher === next.teacher &&
  52. current.position === next.position &&
  53. current.day === next.day &&
  54. current.weeks.join(',') === next.weeks.join(',');
  55. const isContinuous = current.endSection + 1 === next.startSection;
  56. const isDuplicate = current.startSection === next.startSection && current.endSection === next.endSection;
  57. if (isSameCourseAndWeeks && isContinuous) {
  58. // 节次连续:延长结束节次 (如 1-2 节 + 3-4 节 -> 1-4 节)
  59. current.endSection = next.endSection;
  60. } else if (isSameCourseAndWeeks && isDuplicate) {
  61. // 完全重复:跳过
  62. continue;
  63. } else {
  64. step1Merged.push(current);
  65. current = next;
  66. }
  67. }
  68. step1Merged.push(current);
  69. // 阶段 2:合并同节次的周次(前提:名称、教师、地点、星期、开始/结束节次一致)
  70. step1Merged.sort((a, b) => {
  71. return a.name.localeCompare(b.name) ||
  72. a.teacher.localeCompare(b.teacher) ||
  73. a.position.localeCompare(b.position) ||
  74. (a.day || 0) - (b.day || 0) ||
  75. (a.startSection || 0) - (b.startSection || 0) ||
  76. (a.endSection || 0) - (b.endSection || 0);
  77. });
  78. const step2Merged = [];
  79. let cur = step1Merged[0];
  80. for (let i = 1; i < step1Merged.length; i++) {
  81. const nxt = step1Merged[i];
  82. const isSameCourseAndSection =
  83. cur.name === nxt.name &&
  84. cur.teacher === nxt.teacher &&
  85. cur.position === nxt.position &&
  86. cur.day === nxt.day &&
  87. cur.startSection === nxt.startSection &&
  88. cur.endSection === nxt.endSection;
  89. if (isSameCourseAndSection) {
  90. // 周次合并去重 (如 1-8 周 + 9-16 周 -> 1-16 周)
  91. cur.weeks = Array.from(new Set([...cur.weeks, ...nxt.weeks])).sort((a, b) => a - b);
  92. } else {
  93. step2Merged.push(cur);
  94. cur = nxt;
  95. }
  96. }
  97. step2Merged.push(cur);
  98. return step2Merged;
  99. }
  100. /** 解析周次字符串,处理单双周和周次范围 */
  101. function parseWeeks(weekStr) {
  102. if (!weekStr) return [];
  103. const cleaned = weekStr
  104. .replace(/周数[::]/g, '')
  105. .replace(/第/g, '')
  106. .replace(/周/g, '')
  107. .replace(/共\s*\d+\s*.*$/g, '');
  108. const segments = cleaned.split(/[,,、;;]/);
  109. const weeks = [];
  110. const segRegex = /(\d+)(?:\s*[-~]\s*(\d+))?\s*(?:[((]?\s*([单双])\s*周?\s*[))]?)?/g;
  111. for (const seg of segments) {
  112. const s = safeTrim(seg);
  113. if (!s) continue;
  114. segRegex.lastIndex = 0;
  115. let m;
  116. while ((m = segRegex.exec(s)) !== null) {
  117. if (m[0] === '') {
  118. segRegex.lastIndex++;
  119. continue;
  120. }
  121. const start = parseInt(m[1], 10);
  122. const end = m[2] ? parseInt(m[2], 10) : start;
  123. const flagStr = m[3] || '';
  124. let flag = 0;
  125. if (flagStr.includes('单')) flag = 1;
  126. else if (flagStr.includes('双')) flag = 2;
  127. for (let w = start; w <= end; w++) {
  128. if (flag === 1 && w % 2 === 0) continue;
  129. if (flag === 2 && w % 2 !== 0) continue;
  130. weeks.push(w);
  131. }
  132. }
  133. }
  134. return [...new Set(weeks)].sort((a, b) => a - b);
  135. }
  136. /** 解析课表接口返回的 JSON */
  137. function parseJsonData(jsonData) {
  138. if (!jsonData || !Array.isArray(jsonData.kbList)) return [];
  139. const initialCourseList = [];
  140. for (const raw of jsonData.kbList) {
  141. if (!raw.kcmc || !raw.xqj || !raw.jcs || !raw.zcd) continue;
  142. const weeksArray = parseWeeks(raw.zcd);
  143. if (weeksArray.length === 0) continue;
  144. const sectionParts = String(raw.jcs).split("-");
  145. const startSection = Number(sectionParts[0]);
  146. const endSection = Number(sectionParts[sectionParts.length - 1]);
  147. const day = Number(raw.xqj);
  148. if (isNaN(day) || isNaN(startSection) || isNaN(endSection) ||
  149. day < 1 || day > 7 || startSection > endSection) {
  150. continue;
  151. }
  152. initialCourseList.push({
  153. name: safeTrim(raw.kcmc),
  154. teacher: safeTrim(raw.xm || ""), // 无教师(如线上课)时传空串
  155. position: safeTrim(raw.cdmc || ""), // 无固定教室时传空串
  156. day: day,
  157. startSection: startSection,
  158. endSection: endSection,
  159. weeks: weeksArray
  160. });
  161. }
  162. return mergeAndDistinctCourses(initialCourseList);
  163. }
  164. async function promptUserToStart() {
  165. return await window.shiguangBridgePromise.showAlert(
  166. "广州理工学院课表导入",
  167. "导入前请确保已进入教务系统页面(本校学生请用统一身份认证登录,教务自身的账号密码不可用;校外请走 WebVPN)",
  168. "好的,开始导入"
  169. );
  170. }
  171. /** 获取学年学期选项;学年以选中项为中心取前后共 5 个 */
  172. async function fetchAcademicOptions() {
  173. const url = `${getBaseUrl()}/kbcx/xskbcx_cxXskbcxIndex.html?gnmkdm=N2151&layout=default`;
  174. try {
  175. const response = await fetch(url, {
  176. method: "GET",
  177. credentials: "include"
  178. });
  179. if (!response.ok) return null;
  180. const doc = new DOMParser().parseFromString(await response.text(), "text/html");
  181. const readOptions = (selector) => {
  182. const result = [];
  183. doc.querySelectorAll(selector).forEach(opt => {
  184. if (opt.value === "") return;
  185. result.push({
  186. value: opt.value,
  187. text: safeTrim(opt.textContent),
  188. selected: opt.selected
  189. });
  190. });
  191. return result;
  192. };
  193. const allYearOptions = readOptions("#xnm option");
  194. const semesterOptions = readOptions("#xqm option");
  195. if (allYearOptions.length === 0 || semesterOptions.length === 0) return null;
  196. const semesterIndex = semesterOptions.findIndex(opt => opt.selected);
  197. const defaultSemesterIndex = semesterIndex === -1 ? 0 : semesterIndex;
  198. const selectedIndex = allYearOptions.findIndex(opt => opt.selected);
  199. if (selectedIndex === -1) {
  200. return {
  201. yearOptions: allYearOptions.slice(0, 5),
  202. semesterOptions,
  203. defaultYearIndex: 0,
  204. defaultSemesterIndex
  205. };
  206. }
  207. const start = Math.max(0, selectedIndex - 2);
  208. const end = Math.min(allYearOptions.length, selectedIndex + 3);
  209. return {
  210. yearOptions: allYearOptions.slice(start, end),
  211. semesterOptions,
  212. defaultYearIndex: selectedIndex - start,
  213. defaultSemesterIndex
  214. };
  215. } catch (e) {
  216. return null;
  217. }
  218. }
  219. /** 提示用户选择学年和学期 */
  220. async function selectAcademicYearAndSemester() {
  221. const optionsData = await fetchAcademicOptions();
  222. if (!optionsData) {
  223. window.shiguangBridge.showToast("读取学年学期失败,请确认已登录教务系统。");
  224. return null;
  225. }
  226. const { yearOptions, semesterOptions, defaultYearIndex, defaultSemesterIndex } = optionsData;
  227. const yearIndex = await window.shiguangBridgePromise.showSingleSelection(
  228. "选择学年",
  229. JSON.stringify(yearOptions.map(item => item.text)),
  230. defaultYearIndex
  231. );
  232. if (yearIndex === null || yearIndex === undefined || yearIndex < 0) return null;
  233. const semesterIndex = await window.shiguangBridgePromise.showSingleSelection(
  234. "选择学期",
  235. JSON.stringify(semesterOptions.map(item => item.text)),
  236. defaultSemesterIndex
  237. );
  238. if (semesterIndex === null || semesterIndex === undefined || semesterIndex < 0) return null;
  239. return {
  240. academicYear: yearOptions[yearIndex].value,
  241. semesterCode: semesterOptions[semesterIndex].value
  242. };
  243. }
  244. /** 获取学期开学日期(失败返回 null,不影响主流程) */
  245. async function fetchSemesterStartDate(academicYear, semesterCode) {
  246. const url = `${getBaseUrl()}/kbcx/xskbcxZccx_cxZcByXnxq.html?gnmkdm=N2154`;
  247. const requestBody = `xnm=${academicYear}&xqm=${semesterCode}`;
  248. try {
  249. const response = await fetch(url, {
  250. method: "POST",
  251. headers: {
  252. "accept": "application/json, text/javascript, */*; q=0.01",
  253. "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8",
  254. "x-requested-with": "XMLHttpRequest"
  255. },
  256. body: requestBody,
  257. credentials: "include"
  258. });
  259. if (!response.ok) return null;
  260. const json = await response.json();
  261. if (!Array.isArray(json) || json.length === 0) return null;
  262. // 优先找第 1 周,否则取第一项
  263. const firstWeekObj = json.find(item => String(item.zs) === "1" || String(item.zsmc) === "1") || json[0];
  264. if (firstWeekObj.rq) {
  265. const startDateStr = firstWeekObj.rq.split('/')[0];
  266. if (/^\d{4}-\d{2}-\d{2}$/.test(startDateStr)) return startDateStr;
  267. }
  268. for (const field of ["zcrq", "ksrq"]) {
  269. const matched = firstWeekObj[field] && String(firstWeekObj[field]).match(/(\d{4}-\d{2}-\d{2})/);
  270. if (matched) return matched[1];
  271. }
  272. } catch (e) {
  273. // 开学日期获取失败不影响导入
  274. }
  275. return null;
  276. }
  277. /** 请求并解析课程数据 */
  278. async function fetchAndParseCourses(academicYear, semesterCode) {
  279. const requestBody = `xnm=${academicYear}&xqm=${semesterCode}&kzlx=ck&xsdm=&kclbdm=`;
  280. const targetUrl = `${getBaseUrl()}/kbcx/xskbcx_cxXsgrkb.html?gnmkdm=N2151`;
  281. try {
  282. // 并行获取课程数据与开学日期
  283. const [courseResponse, semesterStartDate] = await Promise.all([
  284. fetch(targetUrl, {
  285. method: "POST",
  286. headers: {
  287. "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8"
  288. },
  289. body: requestBody,
  290. credentials: "include"
  291. }),
  292. fetchSemesterStartDate(academicYear, semesterCode)
  293. ]);
  294. if (!courseResponse.ok) {
  295. window.shiguangBridge.showToast(`获取课表失败(HTTP ${courseResponse.status}),请稍后重试。`);
  296. return null;
  297. }
  298. const jsonText = await courseResponse.text();
  299. // 会话失效时正方返回 200 + 登录页,单独提示,避免被误认为网络问题
  300. if (/login_slogin|name=["']yhm["']/.test(jsonText)) {
  301. window.shiguangBridge.showToast("登录状态已失效,请重新登录教务系统后再导入。");
  302. return null;
  303. }
  304. const parsedCourses = parseJsonData(JSON.parse(jsonText));
  305. if (parsedCourses.length === 0) {
  306. window.shiguangBridge.showToast("该学期没有查询到课程,请确认所选学年学期是否正确。");
  307. return null;
  308. }
  309. return {
  310. courses: parsedCourses,
  311. config: {
  312. semesterStartDate: semesterStartDate,
  313. semesterTotalWeeks: 20
  314. }
  315. };
  316. } catch (e) {
  317. window.shiguangBridge.showToast("获取课表失败,请检查网络环境或登录状态。");
  318. return null;
  319. }
  320. }
  321. async function saveCourses(parsedCourses) {
  322. try {
  323. await window.shiguangBridgePromise.saveImportedCourses(JSON.stringify(parsedCourses));
  324. return true;
  325. } catch (error) {
  326. window.shiguangBridge.showToast(`课程保存失败:${error}`);
  327. return false;
  328. }
  329. }
  330. // 本校作息(学校作息表口径:每节 45 分钟 + 10 分钟课间)。
  331. // 本校按此口径导入作息(接口另有“每节 50 分钟、两节相连”的行政口径,经决定不采用)。
  332. const FALLBACK_TIME_SLOTS = [
  333. { number: 1, startTime: "08:20", endTime: "09:05" },
  334. { number: 2, startTime: "09:15", endTime: "10:00" },
  335. { number: 3, startTime: "10:20", endTime: "11:05" },
  336. { number: 4, startTime: "11:15", endTime: "12:00" },
  337. { number: 5, startTime: "14:00", endTime: "14:45" },
  338. { number: 6, startTime: "14:55", endTime: "15:40" },
  339. { number: 7, startTime: "16:00", endTime: "16:45" },
  340. { number: 8, startTime: "16:55", endTime: "17:40" },
  341. { number: 9, startTime: "18:40", endTime: "19:20" },
  342. { number: 10, startTime: "19:20", endTime: "20:00" },
  343. { number: 11, startTime: "20:20", endTime: "21:00" },
  344. { number: 12, startTime: "21:00", endTime: "21:40" }
  345. ];
  346. async function importPresetTimeSlots() {
  347. try {
  348. await window.shiguangBridgePromise.savePresetTimeSlots(JSON.stringify(FALLBACK_TIME_SLOTS));
  349. window.shiguangBridge.showToast("时间段导入成功!");
  350. return true;
  351. } catch (error) {
  352. window.shiguangBridge.showToast(`时间段导入失败:${error}`);
  353. return false;
  354. }
  355. }
  356. async function runImportFlow() {
  357. const alertConfirmed = await promptUserToStart();
  358. if (!alertConfirmed) {
  359. window.shiguangBridge.showToast("用户取消了导入。");
  360. return;
  361. }
  362. const selection = await selectAcademicYearAndSemester();
  363. if (!selection) {
  364. window.shiguangBridge.showToast("未选择学年学期,导入流程终止。");
  365. return;
  366. }
  367. const { academicYear, semesterCode } = selection;
  368. const result = await fetchAndParseCourses(academicYear, semesterCode);
  369. if (result === null) return;
  370. const { courses, config } = result;
  371. // 保存顺序对齐 JSEI_01:课程 → 作息 → 课表配置
  372. const saveResult = await saveCourses(courses);
  373. if (!saveResult) return;
  374. const timeSlotsSaved = await importPresetTimeSlots();
  375. try {
  376. await window.shiguangBridgePromise.saveCourseConfig(JSON.stringify(config));
  377. window.shiguangBridge.showToast(
  378. config.semesterStartDate
  379. ? `课表配置更新成功!开学日期:${config.semesterStartDate}`
  380. : "课表配置更新成功!"
  381. );
  382. } catch (error) {
  383. window.shiguangBridge.showToast(`课表配置保存失败:${error}`);
  384. }
  385. window.shiguangBridge.showToast(
  386. timeSlotsSaved
  387. ? `课程导入成功,共导入 ${courses.length} 门课程!`
  388. : `课程已导入 ${courses.length} 门,但作息时间未写入,请在「作息时间」中手动设置。`
  389. );
  390. window.shiguangBridge.notifyTaskCompletion();
  391. }
  392. runImportFlow();