qdhhc.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446
  1. // 青岛黄海学院(qdhhc.edu.cn) 拾光课程表适配脚本
  2. // 非该大学开发者适配,开发者无法及时发现问题
  3. // 出现问题请提issues或者提交pr更改,这更加快速
  4. /**
  5. * 节次与周次合并去重函数
  6. * @param {Array<Object>} courses 原始解析课程数组
  7. * @returns {Array<Object>} 合并去重后的课程数组
  8. */
  9. function mergeAndDistinctCourses(courses) {
  10. if (!Array.isArray(courses) || courses.length <= 1) return courses;
  11. // 1. 深拷贝并规范周次数据,过滤无效项
  12. const list = courses.map(c => ({
  13. ...c,
  14. name: c.name || '',
  15. teacher: c.teacher || '',
  16. position: c.position || '',
  17. weeks: Array.isArray(c.weeks) ? [...c.weeks].sort((a, b) => a - b) : []
  18. }));
  19. // 阶段 1:合并连续节次与完全重复记录(前提:名称、教师、地点、星期、周次一致)
  20. list.sort((a, b) => {
  21. return a.name.localeCompare(b.name) ||
  22. a.teacher.localeCompare(b.teacher) ||
  23. a.position.localeCompare(b.position) ||
  24. (a.day || 0) - (b.day || 0) ||
  25. a.weeks.join(',').localeCompare(b.weeks.join(',')) ||
  26. (a.startSection || 0) - (b.startSection || 0);
  27. });
  28. const step1Merged = [];
  29. let current = list[0];
  30. for (let i = 1; i < list.length; i++) {
  31. const next = list[i];
  32. const isSameCourseAndWeeks =
  33. current.name === next.name &&
  34. current.teacher === next.teacher &&
  35. current.position === next.position &&
  36. current.day === next.day &&
  37. current.weeks.join(',') === next.weeks.join(',');
  38. const isContinuous = current.endSection + 1 === next.startSection;
  39. const isDuplicate = current.startSection === next.startSection && current.endSection === next.endSection;
  40. if (isSameCourseAndWeeks && isContinuous) {
  41. // 节次连续:延长结束节次 (如 1-2 节 + 3-4 节 -> 1-4 节)
  42. current.endSection = next.endSection;
  43. } else if (isSameCourseAndWeeks && isDuplicate) {
  44. // 完全重复:跳过
  45. continue;
  46. } else {
  47. step1Merged.push(current);
  48. current = next;
  49. }
  50. }
  51. step1Merged.push(current);
  52. // 阶段 2:合并同节次的周次(前提:名称、教师、地点、星期、开始/结束节次一致)
  53. step1Merged.sort((a, b) => {
  54. return a.name.localeCompare(b.name) ||
  55. a.teacher.localeCompare(b.teacher) ||
  56. a.position.localeCompare(b.position) ||
  57. (a.day || 0) - (b.day || 0) ||
  58. (a.startSection || 0) - (b.startSection || 0) ||
  59. (a.endSection || 0) - (b.endSection || 0);
  60. });
  61. const step2Merged = [];
  62. let cur = step1Merged[0];
  63. for (let i = 1; i < step1Merged.length; i++) {
  64. const nxt = step1Merged[i];
  65. const isSameCourseAndSection =
  66. cur.name === nxt.name &&
  67. cur.teacher === nxt.teacher &&
  68. cur.position === nxt.position &&
  69. cur.day === nxt.day &&
  70. cur.startSection === nxt.startSection &&
  71. cur.endSection === nxt.endSection;
  72. if (isSameCourseAndSection) {
  73. // 周次合并去重 (如 1-8 周 + 9-16 周 -> 1-16 周)
  74. cur.weeks = Array.from(new Set([...cur.weeks, ...nxt.weeks])).sort((a, b) => a - b);
  75. } else {
  76. step2Merged.push(cur);
  77. cur = nxt;
  78. }
  79. }
  80. step2Merged.push(cur);
  81. return step2Merged;
  82. }
  83. /**
  84. * 解析周次字符串,处理单双周和周次范围。
  85. */
  86. function parseWeeks(weekStr) {
  87. if (!weekStr) return [];
  88. const weekSets = weekStr.split(',');
  89. let weeks = [];
  90. for (const set of weekSets) {
  91. const trimmedSet = set.trim();
  92. const rangeMatch = trimmedSet.match(/(\d+)-(\d+)周/);
  93. const singleMatch = trimmedSet.match(/^(\d+)周/); // 匹配以数字周结束的
  94. let start = 0;
  95. let end = 0;
  96. let processed = false;
  97. if (rangeMatch) { // 范围, 如 "1-5周"
  98. start = Number(rangeMatch[1]);
  99. end = Number(rangeMatch[2]);
  100. processed = true;
  101. } else if (singleMatch) { // 单个周, 如 "6周"
  102. start = end = Number(singleMatch[1]);
  103. processed = true;
  104. }
  105. if (processed) {
  106. // 确定单双周
  107. const isSingle = trimmedSet.includes('(单)');
  108. const isDouble = trimmedSet.includes('(双)');
  109. for (let w = start; w <= end; w++) {
  110. if (isSingle && w % 2 === 0) continue; // 单周跳过偶数
  111. if (isDouble && w % 2 !== 0) continue; // 双周跳过奇数
  112. weeks.push(w);
  113. }
  114. }
  115. }
  116. // 去重并排序
  117. return [...new Set(weeks)].sort((a, b) => a - b);
  118. }
  119. /**
  120. * 解析 API 返回的 JSON 数据。
  121. */
  122. function parseJsonData(jsonData) {
  123. console.log("JS: parseJsonData 正在解析 JSON 数据...");
  124. // 检查JSON结构:新的数据在 kbList 字段中
  125. if (!jsonData || !Array.isArray(jsonData.kbList)) {
  126. console.warn("JS: JSON 数据结构错误或缺少 kbList 字段。");
  127. return [];
  128. }
  129. const rawCourseList = jsonData.kbList;
  130. const initialCourseList = [];
  131. for (const rawCourse of rawCourseList) {
  132. // 关键字段检查: kcmc(课名), xm(教师), cdmc(教室), xqj(星期), jcs(节次范围), zcd(周次描述)
  133. if (!rawCourse.kcmc || !rawCourse.xm || !rawCourse.cdmc ||
  134. !rawCourse.xqj || !rawCourse.jcs || !rawCourse.zcd) {
  135. continue;
  136. }
  137. const weeksArray = parseWeeks(rawCourse.zcd);
  138. // 周次有效性检查
  139. if (weeksArray.length === 0) {
  140. continue;
  141. }
  142. // 解析节次范围,例如 "1-2"
  143. const sectionParts = rawCourse.jcs.split('-');
  144. const startSection = Number(sectionParts[0]);
  145. const endSection = Number(sectionParts[sectionParts.length - 1]);
  146. const day = Number(rawCourse.xqj); // xqj: 星期几 (周一为1, 周日为7)
  147. // 数字有效性检查
  148. if (isNaN(day) || isNaN(startSection) || isNaN(endSection) || day < 1 || day > 7 || startSection > endSection) {
  149. // console.warn(`JS: 课程 ${rawCourse.kcmc} 星期或节次数据无效,跳过。`);
  150. continue;
  151. }
  152. initialCourseList.push({
  153. name: rawCourse.kcmc.trim(),
  154. teacher: rawCourse.xm.trim(),
  155. position: rawCourse.cdmc.trim(),
  156. day: day,
  157. startSection: startSection,
  158. endSection: endSection,
  159. weeks: weeksArray
  160. });
  161. }
  162. // 调用合并与去重函数,整理连续节次与单双周周次
  163. const finalCourseList = mergeAndDistinctCourses(initialCourseList);
  164. console.log(`JS: JSON 数据解析与合并完成,整理后共 ${finalCourseList.length} 门课程。`);
  165. return finalCourseList;
  166. }
  167. function validateYearInput(input) {
  168. console.log("JS: validateYearInput 被调用,输入: " + input);
  169. if (/^[0-9]{4}$/.test(input)) {
  170. console.log("JS: validateYearInput 验证通过。");
  171. return false;
  172. } else {
  173. console.log("JS: validateYearInput 验证失败。");
  174. return "请输入四位数字的学年!";
  175. }
  176. }
  177. async function promptUserToStart() {
  178. console.log("JS: 流程开始:显示公告。");
  179. return await window.shiguangBridgePromise.showAlert(
  180. "教务系统课表导入",
  181. "导入前请确保您已在浏览器中成功登录教务系统",
  182. "好的,开始导入"
  183. );
  184. }
  185. async function getAcademicYear() {
  186. const currentYear = new Date().getFullYear().toString();
  187. console.log("JS: 提示用户输入学年。");
  188. return await window.shiguangBridgePromise.showPrompt(
  189. "选择学年",
  190. "请输入要导入课程的起始学年(例如 2025-2026 应输入2025):",
  191. currentYear,
  192. "validateYearInput"
  193. );
  194. }
  195. async function selectSemester() {
  196. const semesters = ["第一学期", "第二学期"];
  197. console.log("JS: 提示用户选择学期。");
  198. const semesterIndex = await window.shiguangBridgePromise.showSingleSelection(
  199. "选择学期",
  200. JSON.stringify(semesters),
  201. 0
  202. );
  203. return semesterIndex;
  204. }
  205. /**
  206. * 将选择索引转换为 API 所需的学期码。
  207. */
  208. function getSemesterCode(semesterIndex) {
  209. // semesterIndex 3 (第一学期), 12 (第二学期)
  210. return semesterIndex === 0 ? "3" : "12";
  211. }
  212. async function fetchSemesterStartDate(academicYear, semesterCode) {
  213. const url = "http://jwxt.qdhhc.edu.cn/jwglxt/kbcx/xskbcxZccx_cxZcByXnxq.html?gnmkdm=N2154";
  214. const requestBody = `xnm=${academicYear}&xqm=${semesterCode}`;
  215. try {
  216. const response = await fetch(url, {
  217. method: "POST",
  218. headers: {
  219. "accept": "application/json, text/javascript, */*; q=0.01",
  220. "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8",
  221. "x-requested-with": "XMLHttpRequest"
  222. },
  223. body: requestBody,
  224. credentials: "include"
  225. });
  226. if (response.ok) {
  227. const json = await response.json();
  228. if (Array.isArray(json) && json.length > 0) {
  229. const firstWeekObj = json.find(item => String(item.zs) === "1" || String(item.zsmc) === "1") || json[0];
  230. if (firstWeekObj.rq) {
  231. const startDateStr = firstWeekObj.rq.split('/')[0];
  232. if (/^\d{4}-\d{2}-\d{2}$/.test(startDateStr)) {
  233. return startDateStr;
  234. }
  235. }
  236. if (firstWeekObj.zcrq) {
  237. const match = firstWeekObj.zcrq.match(/(\d{4}-\d{2}-\d{2})/);
  238. if (match) return match[1];
  239. }
  240. }
  241. }
  242. } catch (e) {
  243. console.error("JS: 获取学期开学时间失败:", e);
  244. }
  245. return null;
  246. }
  247. async function fetchAndParseCourses(academicYear, semesterIndex) {
  248. const semesterCode = getSemesterCode(semesterIndex);
  249. const requestBody = `xnm=${academicYear}&xqm=${semesterCode}&kzlx=ck&xsdm=&kclbdm=`;
  250. const semesterStartDate = await fetchSemesterStartDate(academicYear, semesterCode);
  251. console.log("JS: 获取到的开学日期为:", semesterStartDate);
  252. const targetUrls = [
  253. "http://jwxt.qdhhc.edu.cn/jwglxt/kbcx/xskbcx_cxXsgrkb.html?gnmkdm=N2151"
  254. ];
  255. for (const url of targetUrls) {
  256. try {
  257. const response = await fetch(url, {
  258. method: "POST",
  259. headers: {
  260. "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8"
  261. },
  262. body: requestBody,
  263. credentials: "include"
  264. });
  265. if (response.ok) {
  266. const jsonText = await response.text();
  267. const jsonData = JSON.parse(jsonText);
  268. if (jsonData && jsonData.kbList) {
  269. const parsedCourses = parseJsonData(jsonData);
  270. if (parsedCourses.length > 0) {
  271. return {
  272. courses: parsedCourses,
  273. config: {
  274. semesterStartDate: semesterStartDate,
  275. semesterTotalWeeks: 20
  276. }
  277. };
  278. }
  279. }
  280. }
  281. } catch (e) {
  282. console.error(`JS: 接口请求失败: ${url}`, e);
  283. }
  284. }
  285. window.shiguangBridge.showToast("未能获取课表数据,请检查网络环境或登录状态。");
  286. return null;
  287. }
  288. async function saveCourses(parsedCourses) {
  289. window.shiguangBridge.showToast(`正在保存 ${parsedCourses.length} 门课程...`);
  290. console.log(`JS: 尝试保存 ${parsedCourses.length} 门课程...`);
  291. try {
  292. await window.shiguangBridgePromise.saveImportedCourses(JSON.stringify(parsedCourses, null, 2));
  293. console.log("JS: 课程保存成功!");
  294. return true;
  295. } catch (error) {
  296. window.shiguangBridge.showToast(`课程保存失败: ${error.message}`);
  297. console.error('JS: Save Courses Error:', error);
  298. return false;
  299. }
  300. }
  301. const TimeSlots = [
  302. { number: 1, startTime: "08:00", endTime: "08:45" },
  303. { number: 2, startTime: "08:50", endTime: "09:35" },
  304. { number: 3, startTime: "10:05", endTime: "10:50" },
  305. { number: 4, startTime: "10:55", endTime: "11:40" },
  306. { number: 5, startTime: "11:45", endTime: "12:30" },
  307. { number: 6, startTime: "14:00", endTime: "14:45" },
  308. { number: 7, startTime: "14:50", endTime: "15:35" },
  309. { number: 8, startTime: "16:05", endTime: "16:50" },
  310. { number: 9, startTime: "16:55", endTime: "17:40" },
  311. { number: 10, startTime: "19:10", endTime: "19:55" },
  312. { number: 11, startTime: "20:00", endTime: "20:45" }
  313. ];
  314. async function importPresetTimeSlots(timeSlots) {
  315. console.log(`JS: 准备导入 ${timeSlots.length} 个预设时间段。`);
  316. if (timeSlots.length > 0) {
  317. window.shiguangBridge.showToast(`正在导入 ${timeSlots.length} 个预设时间段...`);
  318. try {
  319. await window.shiguangBridgePromise.savePresetTimeSlots(JSON.stringify(timeSlots));
  320. window.shiguangBridge.showToast("预设时间段导入成功!");
  321. console.log("JS: 预设时间段导入成功。");
  322. } catch (error) {
  323. window.shiguangBridge.showToast("导入时间段失败: " + error.message);
  324. console.error('JS: Save Time Slots Error:', error);
  325. }
  326. } else {
  327. window.shiguangBridge.showToast("警告:时间段为空,未导入时间段信息。");
  328. console.warn("JS: 警告:传入时间段为空,未导入时间段信息。");
  329. }
  330. }
  331. async function runImportFlow() {
  332. const alertConfirmed = await promptUserToStart();
  333. if (!alertConfirmed) {
  334. window.shiguangBridge.showToast("用户取消了导入。");
  335. console.log("JS: 用户取消了导入流程。");
  336. return;
  337. }
  338. const academicYear = await getAcademicYear();
  339. if (academicYear === null) {
  340. window.shiguangBridge.showToast("导入已取消。");
  341. console.log("JS: 获取学年失败/取消,流程终止。");
  342. return;
  343. }
  344. console.log(`JS: 已选择学年: ${academicYear}`);
  345. const semesterIndex = await selectSemester();
  346. if (semesterIndex === null || semesterIndex === -1) {
  347. window.shiguangBridge.showToast("导入已取消。");
  348. console.log("JS: 选择学期失败/取消,流程终止。");
  349. return;
  350. }
  351. console.log(`JS: 已选择学期索引: ${semesterIndex}`);
  352. const result = await fetchAndParseCourses(academicYear, semesterIndex);
  353. if (result === null) {
  354. console.log("JS: 课程获取或解析失败,流程终止。");
  355. return;
  356. }
  357. const { courses, config } = result;
  358. const saveResult = await saveCourses(courses);
  359. if (!saveResult) {
  360. console.log("JS: 课程保存失败,流程终止。");
  361. return;
  362. }
  363. try {
  364. await window.shiguangBridgePromise.saveCourseConfig(JSON.stringify(config));
  365. let configMsg = `课表配置更新成功!`;
  366. if (config.semesterStartDate) {
  367. configMsg += `开学日期:${config.semesterStartDate}`;
  368. }
  369. window.shiguangBridge.showToast(configMsg);
  370. } catch (error) {
  371. window.shiguangBridge.showToast(`课表配置保存失败: ${error.message}`);
  372. console.error('JS: Save Config Error:', error);
  373. }
  374. await importPresetTimeSlots(TimeSlots);
  375. window.shiguangBridge.showToast(`课程导入成功,共导入 ${courses.length} 门课程!`);
  376. console.log("JS: 整个导入流程执行完毕并成功。");
  377. window.shiguangBridge.notifyTaskCompletion();
  378. }
  379. runImportFlow();