lyu.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249
  1. // 临沂大学(lyu.edu.cn) 拾光课程表适配脚本
  2. // 基于正方教务系统接口适配(webvpn版)
  3. function mergeAndDistinctCourses(courses) {
  4. if (!Array.isArray(courses) || courses.length <= 1) return courses;
  5. const list = courses.map(c => ({
  6. ...c,
  7. name: c.name || '',
  8. teacher: c.teacher || '',
  9. position: c.position || '',
  10. weeks: Array.isArray(c.weeks) ? [...c.weeks].sort((a, b) => a - b) : []
  11. }));
  12. list.sort((a, b) => {
  13. return a.name.localeCompare(b.name) || a.teacher.localeCompare(b.teacher) ||
  14. a.position.localeCompare(b.position) || (a.day || 0) - (b.day || 0) ||
  15. a.weeks.join(',').localeCompare(b.weeks.join(',')) || (a.startSection || 0) - (b.startSection || 0);
  16. });
  17. const step1Merged = [];
  18. let current = list[0];
  19. for (let i = 1; i < list.length; i++) {
  20. const next = list[i];
  21. const isSame = current.name === next.name && current.teacher === next.teacher &&
  22. current.position === next.position && current.day === next.day &&
  23. current.weeks.join(',') === next.weeks.join(',');
  24. if (isSame && current.endSection + 1 === next.startSection) {
  25. current.endSection = next.endSection;
  26. } else if (isSame && current.startSection === next.startSection && current.endSection === next.endSection) {
  27. continue;
  28. } else {
  29. step1Merged.push(current);
  30. current = next;
  31. }
  32. }
  33. step1Merged.push(current);
  34. step1Merged.sort((a, b) => {
  35. return a.name.localeCompare(b.name) || a.teacher.localeCompare(b.teacher) ||
  36. a.position.localeCompare(b.position) || (a.day || 0) - (b.day || 0) ||
  37. (a.startSection || 0) - (b.startSection || 0) || (a.endSection || 0) - (b.endSection || 0);
  38. });
  39. const step2Merged = [];
  40. let cur = step1Merged[0];
  41. for (let i = 1; i < step1Merged.length; i++) {
  42. const nxt = step1Merged[i];
  43. if (cur.name === nxt.name && cur.teacher === nxt.teacher && cur.position === nxt.position &&
  44. cur.day === nxt.day && cur.startSection === nxt.startSection && cur.endSection === nxt.endSection) {
  45. cur.weeks = Array.from(new Set([...cur.weeks, ...nxt.weeks])).sort((a, b) => a - b);
  46. } else {
  47. step2Merged.push(cur);
  48. cur = nxt;
  49. }
  50. }
  51. step2Merged.push(cur);
  52. return step2Merged;
  53. }
  54. function parseWeeks(weekStr) {
  55. if (!weekStr) return [];
  56. const weekSets = weekStr.split(',');
  57. let weeks = [];
  58. for (const set of weekSets) {
  59. const trimmedSet = set.trim();
  60. const rangeMatch = trimmedSet.match(/(\d+)-(\d+)周/);
  61. const singleMatch = trimmedSet.match(/^(\d+)周/);
  62. let start = 0, end = 0, processed = false;
  63. if (rangeMatch) { start = Number(rangeMatch[1]); end = Number(rangeMatch[2]); processed = true; }
  64. else if (singleMatch) { start = end = Number(singleMatch[1]); processed = true; }
  65. if (processed) {
  66. const isSingle = trimmedSet.includes('(单)');
  67. const isDouble = trimmedSet.includes('(双)');
  68. for (let w = start; w <= end; w++) {
  69. if (isSingle && w % 2 === 0) continue;
  70. if (isDouble && w % 2 !== 0) continue;
  71. weeks.push(w);
  72. }
  73. }
  74. }
  75. return [...new Set(weeks)].sort((a, b) => a - b);
  76. }
  77. function parseJsonData(jsonData) {
  78. if (!jsonData || !Array.isArray(jsonData.kbList)) return [];
  79. const initialCourseList = [];
  80. for (const rawCourse of jsonData.kbList) {
  81. if (!rawCourse.kcmc || !rawCourse.xm || !rawCourse.cdmc ||
  82. !rawCourse.xqj || !rawCourse.jcs || !rawCourse.zcd) continue;
  83. const weeksArray = parseWeeks(rawCourse.zcd);
  84. if (weeksArray.length === 0) continue;
  85. const sectionParts = rawCourse.jcs.split('-');
  86. const startSection = Number(sectionParts[0]);
  87. const endSection = Number(sectionParts[sectionParts.length - 1]);
  88. const day = Number(rawCourse.xqj);
  89. if (isNaN(day) || isNaN(startSection) || isNaN(endSection) ||
  90. day < 1 || day > 7 || startSection > endSection) continue;
  91. initialCourseList.push({
  92. name: rawCourse.kcmc.trim(),
  93. teacher: rawCourse.xm.trim(),
  94. position: rawCourse.cdmc.trim(),
  95. day: day,
  96. startSection: startSection,
  97. endSection: endSection,
  98. weeks: weeksArray
  99. });
  100. }
  101. return mergeAndDistinctCourses(initialCourseList);
  102. }
  103. async function promptUserToStart() {
  104. return await window.shiguangBridgePromise.showAlert(
  105. "教务系统课表导入",
  106. "导入前请确保您已在浏览器中成功登录教务系统",
  107. "好的,开始导入"
  108. );
  109. }
  110. async function fetchAcademicOptions() {
  111. const url = "/jwglxt/kbcx/xskbcx_cxXskbcxIndex.html?gnmkdm=N2151&enlink-vpn";
  112. try {
  113. const response = await fetch(url, { method: "GET", credentials: "include" });
  114. if (!response.ok) return null;
  115. const htmlText = await response.text();
  116. const parser = new DOMParser();
  117. const doc = parser.parseFromString(htmlText, "text/html");
  118. const allYearOptions = Array.from(doc.querySelectorAll("#xnm option"))
  119. .filter(opt => opt.value !== "")
  120. .map(opt => ({ value: opt.value, text: opt.textContent.trim(), selected: opt.hasAttribute("selected") }));
  121. const semesterOptions = Array.from(doc.querySelectorAll("#xqm option"))
  122. .filter(opt => opt.value !== "")
  123. .map(opt => ({ value: opt.value, text: opt.textContent.trim(), selected: opt.hasAttribute("selected") }));
  124. if (allYearOptions.length === 0 || semesterOptions.length === 0) return null;
  125. const selectedIndex = allYearOptions.findIndex(opt => opt.selected);
  126. if (selectedIndex === -1) {
  127. return {
  128. yearOptions: allYearOptions.slice(0, 5), semesterOptions,
  129. defaultYearIndex: 0,
  130. defaultSemesterIndex: semesterOptions.findIndex(opt => opt.selected) !== -1 ? semesterOptions.findIndex(opt => opt.selected) : 0
  131. };
  132. }
  133. const start = Math.max(0, selectedIndex - 2);
  134. const end = Math.min(allYearOptions.length, selectedIndex + 3);
  135. return {
  136. yearOptions: allYearOptions.slice(start, end), semesterOptions,
  137. defaultYearIndex: selectedIndex - start,
  138. defaultSemesterIndex: semesterOptions.findIndex(opt => opt.selected) !== -1 ? semesterOptions.findIndex(opt => opt.selected) : 0
  139. };
  140. } catch (e) { return null; }
  141. }
  142. async function selectAcademicYearAndSemester() {
  143. const optionsData = await fetchAcademicOptions();
  144. if (!optionsData) {
  145. window.shiguangBridge.showToast("从教务系统读取学年学期失败,请确保登录状态。");
  146. return null;
  147. }
  148. const { yearOptions, semesterOptions, defaultYearIndex, defaultSemesterIndex } = optionsData;
  149. const yearIndex = await window.shiguangBridgePromise.showSingleSelection(
  150. "选择学年", JSON.stringify(yearOptions.map(item => item.text)), defaultYearIndex
  151. );
  152. if (yearIndex === null || yearIndex === -1) return null;
  153. const semesterIndex = await window.shiguangBridgePromise.showSingleSelection(
  154. "选择学期", JSON.stringify(semesterOptions.map(item => item.text)), defaultSemesterIndex
  155. );
  156. if (semesterIndex === null || semesterIndex === -1) return null;
  157. return { academicYear: yearOptions[yearIndex].value, semesterCode: semesterOptions[semesterIndex].value };
  158. }
  159. async function fetchSemesterStartDate(academicYear, semesterCode) {
  160. const url = "/jwglxt/kbcx/xskbcxZccx_cxZcByXnxq.html?gnmkdm=N2154&enlink-vpn";
  161. try {
  162. const response = await fetch(url, {
  163. method: "POST",
  164. headers: {
  165. "accept": "application/json, text/javascript, */*; q=0.01",
  166. "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8",
  167. "x-requested-with": "XMLHttpRequest"
  168. },
  169. body: `xnm=${academicYear}&xqm=${semesterCode}`,
  170. credentials: "include"
  171. });
  172. if (response.ok) {
  173. const json = await response.json();
  174. if (Array.isArray(json) && json.length > 0) {
  175. const firstWeekObj = json.find(item => String(item.zs) === "1" || String(item.zsmc) === "1") || json[0];
  176. if (firstWeekObj.rq) {
  177. const startDateStr = firstWeekObj.rq.split('/')[0];
  178. if (/^\d{4}-\d{2}-\d{2}$/.test(startDateStr)) return startDateStr;
  179. }
  180. if (firstWeekObj.zcrq) {
  181. const match = firstWeekObj.zcrq.match(/(\d{4}-\d{2}-\d{2})/);
  182. if (match) return match[1];
  183. }
  184. }
  185. }
  186. } catch (e) {}
  187. return null;
  188. }
  189. async function fetchAndParseCourses(academicYear, semesterCode) {
  190. const targetUrl = "/jwglxt/kbcx/xskbcx_cxXsgrkb.html?gnmkdm=N2151&enlink-vpn";
  191. const [courseResponse, semesterStartDate] = await Promise.all([
  192. fetch(targetUrl, {
  193. method: "POST",
  194. headers: { "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8" },
  195. body: `xnm=${academicYear}&xqm=${semesterCode}&kzlx=ck&xsdm=&kclbdm=`,
  196. credentials: "include"
  197. }),
  198. fetchSemesterStartDate(academicYear, semesterCode)
  199. ]);
  200. try {
  201. if (courseResponse.ok) {
  202. const jsonData = await courseResponse.json();
  203. if (jsonData && jsonData.kbList) {
  204. const parsedCourses = parseJsonData(jsonData);
  205. if (parsedCourses.length > 0) {
  206. return { courses: parsedCourses, config: { semesterStartDate: semesterStartDate, semesterTotalWeeks: 20 } };
  207. }
  208. }
  209. }
  210. } catch (e) {}
  211. window.shiguangBridge.showToast("未能获取课表数据,请检查网络环境或登录状态。");
  212. return null;
  213. }
  214. async function saveCourses(parsedCourses) {
  215. try {
  216. await window.shiguangBridgePromise.saveImportedCourses(JSON.stringify(parsedCourses));
  217. return true;
  218. } catch (error) {
  219. window.shiguangBridge.showToast("课程保存失败: " + error.message);
  220. return false;
  221. }
  222. }
  223. async function runImportFlow() {
  224. const alertConfirmed = await promptUserToStart();
  225. if (!alertConfirmed) { window.shiguangBridge.showToast("用户取消了导入。"); return; }
  226. const selection = await selectAcademicYearAndSemester();
  227. if (!selection) { window.shiguangBridge.showToast("未选择学年学期,导入流程终止。"); return; }
  228. const { academicYear, semesterCode } = selection;
  229. const result = await fetchAndParseCourses(academicYear, semesterCode);
  230. if (result === null) return;
  231. const { courses, config } = result;
  232. const saveResult = await saveCourses(courses);
  233. if (!saveResult) return;
  234. try { await window.shiguangBridgePromise.saveCourseConfig(JSON.stringify(config)); } catch (e) {}
  235. window.shiguangBridge.showToast("课程导入成功,共导入 " + courses.length + " 门课程!");
  236. window.shiguangBridge.notifyTaskCompletion();
  237. }
  238. runImportFlow();