gdouyj.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398
  1. /**
  2. * 广东海洋大学阳江校区教务适配
  3. * @date 2026-7-30
  4. * @author Mccurtain (原始 GDOU 适配)
  5. * @adapted-by Yihe-ng (阳江校区作息与适配)
  6. * @version 1.1
  7. */
  8. /**
  9. * 解析周次字符串,处理单双周和周次范围。
  10. * 兼容格式:"1-16周"、"6周"、"1-8周(单)"、"1-10周(双)"、"1-5周,9周"
  11. */
  12. function parseWeeks(weekStr) {
  13. if (!weekStr) return [];
  14. const normalizedWeekStr = String(weekStr).replace(/,/g, ',');
  15. const weekSets = normalizedWeekStr.split(',');
  16. let weeks = [];
  17. for (const set of weekSets) {
  18. const trimmedSet = set.trim();
  19. const rangeMatch = trimmedSet.match(/(\d+)\s*-\s*(\d+)\s*周?/);
  20. const singleMatch = trimmedSet.match(/^(\d+)\s*周?/); // 匹配单个周次
  21. let start = 0;
  22. let end = 0;
  23. let processed = false;
  24. if (rangeMatch) { // 范围, 如 "1-5周"
  25. start = Number(rangeMatch[1]);
  26. end = Number(rangeMatch[2]);
  27. processed = true;
  28. } else if (singleMatch) { // 单个周, 如 "6周"
  29. start = end = Number(singleMatch[1]);
  30. processed = true;
  31. }
  32. if (processed && start >= 1 && end >= start) {
  33. // 确定单双周
  34. const isSingle = trimmedSet.includes('(单)');
  35. const isDouble = trimmedSet.includes('(双)');
  36. for (let w = start; w <= end; w++) {
  37. if (isSingle && w % 2 === 0) continue; // 单周跳过偶数
  38. if (isDouble && w % 2 !== 0) continue; // 双周跳过奇数
  39. weeks.push(w);
  40. }
  41. }
  42. }
  43. // 去重并排序
  44. return [...new Set(weeks)].sort((a, b) => a - b);
  45. }
  46. /**
  47. * 解析节次字符串,例如 "1-2"、"1-2节" 或单节 "3"。
  48. * 返回 null 表示接口返回了无法识别的节次格式。
  49. */
  50. function parseSectionRange(sectionStr) {
  51. const sectionText = sectionStr == null ? '' : String(sectionStr);
  52. const sectionMatch = sectionText.match(/^\s*(?:第)?(\d+)\s*(?:-\s*(\d+))?\s*节?\s*$/);
  53. if (!sectionMatch) {
  54. return null;
  55. }
  56. const startSection = Number(sectionMatch[1]);
  57. const endSection = Number(sectionMatch[2] || sectionMatch[1]);
  58. if (!Number.isInteger(startSection) || !Number.isInteger(endSection) ||
  59. startSection < 1 || endSection < startSection) {
  60. return null;
  61. }
  62. return { startSection, endSection };
  63. }
  64. /**
  65. * 阳江校区其他场地(非慎思楼)的作息。
  66. * 只有第 3、4 节在校区作息表中是不同的连续时间块,使用自定义时间表示。
  67. */
  68. const OTHER_VENUE_SECTION_3_4_TIME = { startTime: "10:10", endTime: "11:40" };
  69. function getOtherVenueCustomTime(position, startSection, endSection) {
  70. const positionText = position == null ? '' : String(position);
  71. if (!positionText || positionText.includes("慎思楼")) {
  72. return null;
  73. }
  74. if (startSection !== 3 || endSection !== 4) {
  75. return null;
  76. }
  77. return OTHER_VENUE_SECTION_3_4_TIME;
  78. }
  79. /**
  80. * 解析正方 v9 课表查询接口返回的 JSON 数据。
  81. */
  82. function parseJsonData(jsonData) {
  83. console.log("JS: parseJsonData 正在解析 JSON 数据...");
  84. // 正方 v9 个人课表数据放在 kbList 字段中
  85. if (!jsonData || !Array.isArray(jsonData.kbList)) {
  86. console.warn("JS: JSON 数据结构错误或缺少 kbList 字段。");
  87. return [];
  88. }
  89. const rawCourseList = jsonData.kbList;
  90. const finalCourseList = [];
  91. for (const rawCourse of rawCourseList) {
  92. if (!rawCourse || typeof rawCourse !== 'object') {
  93. continue;
  94. }
  95. // 课程名、星期、节次和周次是解析所必需的;教师或教室为空时仍保留课程。
  96. if (!rawCourse.kcmc || rawCourse.xqj == null ||
  97. rawCourse.jcs == null || rawCourse.zcd == null) {
  98. continue;
  99. }
  100. const weeksArray = parseWeeks(rawCourse.zcd);
  101. // 周次有效性检查
  102. if (weeksArray.length === 0) {
  103. continue;
  104. }
  105. const sectionRange = parseSectionRange(rawCourse.jcs);
  106. if (!sectionRange) {
  107. console.warn(`JS: 跳过无法解析节次的课程:${rawCourse.kcmc}`);
  108. continue;
  109. }
  110. const day = Number(rawCourse.xqj); // xqj: 星期几 (周一为1, 周日为7)
  111. // 数字有效性检查
  112. if (isNaN(day) || day < 1 || day > 7) {
  113. continue;
  114. }
  115. const course = {
  116. name: String(rawCourse.kcmc).trim(),
  117. teacher: rawCourse.xm == null ? '' : String(rawCourse.xm).trim(),
  118. position: rawCourse.cdmc == null ? '' : String(rawCourse.cdmc).trim(),
  119. day: day,
  120. startSection: sectionRange.startSection,
  121. endSection: sectionRange.endSection,
  122. weeks: weeksArray
  123. };
  124. const customTime = getOtherVenueCustomTime(
  125. course.position,
  126. course.startSection,
  127. course.endSection
  128. );
  129. if (customTime) {
  130. course.isCustomTime = true;
  131. course.customStartTime = customTime.startTime;
  132. course.customEndTime = customTime.endTime;
  133. }
  134. finalCourseList.push(course);
  135. }
  136. finalCourseList.sort((a, b) =>
  137. a.day - b.day ||
  138. a.startSection - b.startSection ||
  139. a.name.localeCompare(b.name)
  140. );
  141. console.log(`JS: JSON 数据解析完成,共找到 ${finalCourseList.length} 门课程。`);
  142. return finalCourseList;
  143. }
  144. /**
  145. * showPrompt 的校验函数:限定四位数字学年。
  146. */
  147. function validateYearInput(input) {
  148. console.log("JS: validateYearInput 被调用,输入: " + input);
  149. if (/^[0-9]{4}$/.test(input)) {
  150. console.log("JS: validateYearInput 验证通过。");
  151. return false;
  152. } else {
  153. console.log("JS: validateYearInput 验证失败。");
  154. return "请输入四位数字的学年!";
  155. }
  156. }
  157. /**
  158. * 根据当前日期推断学年起始年份。
  159. * 中国高校通常在 9 月开始新学年,因此 1-8 月默认使用上一年。
  160. */
  161. function getDefaultAcademicYear(date = new Date()) {
  162. const currentYear = date.getFullYear();
  163. const academicYearStart = date.getMonth() >= 8 ? currentYear : currentYear - 1;
  164. return academicYearStart.toString();
  165. }
  166. async function promptUserToStart() {
  167. console.log("JS: 流程开始:显示公告。");
  168. return await window.shiguangBridgePromise.showAlert(
  169. "广东海洋大学阳江校区教务系统课表导入",
  170. "导入前请确保您已在浏览器中成功登录广东海洋大学教务系统(jw.gdou.edu.cn)。\n本脚本将通过接口直接获取阳江校区课表,无需停留在特定页面。",
  171. "好的,开始导入"
  172. );
  173. }
  174. async function getAcademicYear() {
  175. const currentYear = getDefaultAcademicYear();
  176. console.log("JS: 提示用户输入学年。");
  177. return await window.shiguangBridgePromise.showPrompt(
  178. "选择学年",
  179. "请输入要导入课程的起始学年(例如 2025-2026 应输入 2025):",
  180. currentYear,
  181. "validateYearInput"
  182. );
  183. }
  184. async function selectSemester() {
  185. const semesters = ["第一学期", "第二学期"];
  186. console.log("JS: 提示用户选择学期。");
  187. const semesterIndex = await window.shiguangBridgePromise.showSingleSelection(
  188. "选择学期",
  189. JSON.stringify(semesters),
  190. 0
  191. );
  192. return semesterIndex;
  193. }
  194. /**
  195. * 将选择索引转换为正方教务接口所需的学期码。
  196. * 正方 v9:第一学期 = "3",第二学期 = "12"
  197. */
  198. function getSemesterCode(semesterIndex) {
  199. return semesterIndex === 0 ? "3" : "12";
  200. }
  201. /**
  202. * 请求正方 v9 课表接口并解析课程数据。
  203. */
  204. async function fetchAndParseCourses(academicYear, semesterIndex) {
  205. const semesterCode = getSemesterCode(semesterIndex);
  206. const requestBody = `xnm=${academicYear}&xqm=${semesterCode}&kzlx=ck&xsdm=&kclbdm=`;
  207. // 广东海洋大学正方教务 v9 个人课表查询接口
  208. const targetUrl = "https://jw.gdou.edu.cn/kbcx/xskbcx_cxXsgrkb.html?gnmkdm=N2151";
  209. try {
  210. const response = await fetch(targetUrl, {
  211. method: "POST",
  212. headers: {
  213. "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8"
  214. },
  215. body: requestBody,
  216. credentials: "include"
  217. });
  218. if (!response.ok) {
  219. window.shiguangBridge.showToast(`课表请求失败:HTTP ${response.status}`);
  220. console.error(`JS: 接口返回非 200 状态码:${response.status}`);
  221. return null;
  222. }
  223. const jsonText = await response.text();
  224. const jsonData = JSON.parse(jsonText);
  225. if (!jsonData || !Array.isArray(jsonData.kbList) || jsonData.kbList.length === 0) {
  226. window.shiguangBridge.showToast("未查询到课表数据,请检查学年/学期是否选择正确,或确认已登录教务系统。");
  227. return null;
  228. }
  229. const parsedCourses = parseJsonData(jsonData);
  230. if (parsedCourses.length === 0) {
  231. window.shiguangBridge.showToast("课表数据为空或解析失败,请确认所选学年学期。");
  232. return null;
  233. }
  234. return {
  235. courses: parsedCourses,
  236. // CourseConfigJsonModel(wiki 1.3):所有字段可选,未提供则用默认值。
  237. // GDOU 各节课间隔不统一,因此用 TimeSlot 节次表达时间,此处仅设置总周数。
  238. config: {
  239. semesterStartDate: null, // 未提供校历日期,App 不会按日期计算当前周
  240. semesterTotalWeeks: 20 // 本学期总周数
  241. }
  242. };
  243. } catch (e) {
  244. console.error("JS: 获取课表失败:", e);
  245. window.shiguangBridge.showToast("获取课表失败,请确认已登录教务系统且网络可访问 jw.gdou.edu.cn。");
  246. return null;
  247. }
  248. }
  249. async function saveCourses(parsedCourses) {
  250. window.shiguangBridge.showToast(`正在保存 ${parsedCourses.length} 门课程...`);
  251. console.log(`JS: 尝试保存 ${parsedCourses.length} 门课程...`);
  252. try {
  253. await window.shiguangBridgePromise.saveImportedCourses(JSON.stringify(parsedCourses, null, 2));
  254. console.log("JS: 课程保存成功!");
  255. return true;
  256. } catch (error) {
  257. window.shiguangBridge.showToast(`课程保存失败: ${error.message}`);
  258. console.error('JS: Save Courses Error:', error);
  259. return false;
  260. }
  261. }
  262. // 阳江校区慎思楼上课时间(根据用户提供的校区作息表)
  263. const TimeSlots = [
  264. { number: 1, startTime: "08:10", endTime: "08:55" },
  265. { number: 2, startTime: "09:05", endTime: "09:50" },
  266. { number: 3, startTime: "10:20", endTime: "11:05" },
  267. { number: 4, startTime: "11:15", endTime: "12:00" },
  268. { number: 5, startTime: "14:30", endTime: "15:15" },
  269. { number: 6, startTime: "15:20", endTime: "16:05" },
  270. { number: 7, startTime: "16:20", endTime: "17:05" },
  271. { number: 8, startTime: "17:10", endTime: "17:55" },
  272. { number: 9, startTime: "19:30", endTime: "20:15" },
  273. { number: 10, startTime: "20:25", endTime: "21:10" }
  274. ];
  275. async function importPresetTimeSlots(timeSlots) {
  276. console.log(`JS: 准备导入 ${timeSlots.length} 个预设时间段。`);
  277. if (timeSlots.length > 0) {
  278. window.shiguangBridge.showToast(`正在导入 ${timeSlots.length} 个预设时间段...`);
  279. try {
  280. await window.shiguangBridgePromise.savePresetTimeSlots(JSON.stringify(timeSlots));
  281. window.shiguangBridge.showToast("预设时间段导入成功!");
  282. console.log("JS: 预设时间段导入成功。");
  283. } catch (error) {
  284. window.shiguangBridge.showToast("导入时间段失败: " + error.message);
  285. console.error('JS: Save Time Slots Error:', error);
  286. }
  287. } else {
  288. window.shiguangBridge.showToast("警告:时间段为空,未导入时间段信息。");
  289. console.warn("JS: 警告:传入时间段为空,未导入时间段信息。");
  290. }
  291. }
  292. async function runImportFlow() {
  293. const alertConfirmed = await promptUserToStart();
  294. if (!alertConfirmed) {
  295. window.shiguangBridge.showToast("用户取消了导入。");
  296. console.log("JS: 用户取消了导入流程。");
  297. return;
  298. }
  299. const academicYear = await getAcademicYear();
  300. if (academicYear === null) {
  301. window.shiguangBridge.showToast("导入已取消。");
  302. console.log("JS: 获取学年失败/取消,流程终止。");
  303. return;
  304. }
  305. console.log(`JS: 已选择学年: ${academicYear}`);
  306. const semesterIndex = await selectSemester();
  307. if (semesterIndex === null || semesterIndex === -1) {
  308. window.shiguangBridge.showToast("导入已取消。");
  309. console.log("JS: 选择学期失败/取消,流程终止。");
  310. return;
  311. }
  312. console.log(`JS: 已选择学期索引: ${semesterIndex}`);
  313. const result = await fetchAndParseCourses(academicYear, semesterIndex);
  314. if (result === null) {
  315. console.log("JS: 课程获取或解析失败,流程终止。");
  316. return;
  317. }
  318. const { courses, config } = result;
  319. const saveResult = await saveCourses(courses);
  320. if (!saveResult) {
  321. console.log("JS: 课程保存失败,流程终止。");
  322. return;
  323. }
  324. try {
  325. await window.shiguangBridgePromise.saveCourseConfig(JSON.stringify(config));
  326. window.shiguangBridge.showToast(`课表配置更新成功!总周数:${config.semesterTotalWeeks}周。`);
  327. } catch (error) {
  328. window.shiguangBridge.showToast(`课表配置保存失败: ${error.message}`);
  329. console.error('JS: Save Config Error:', error);
  330. return;
  331. }
  332. await importPresetTimeSlots(TimeSlots);
  333. window.shiguangBridge.showToast(`课程导入成功,共导入 ${courses.length} 门课程!`);
  334. console.log("JS: 整个导入流程执行完毕并成功。");
  335. window.shiguangBridge.notifyTaskCompletion();
  336. }
  337. // 脚本执行入口
  338. runImportFlow();