jsei_01.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534
  1. // 江苏电子信息职业学院(jsei.edu.cn) 拾光课程表适配脚本
  2. // 基于正方教务系统接口适配
  3. // 非该大学开发者适配,开发者无法及时发现问题
  4. // 出现问题请提issues或者提交pr更改,这更加快速
  5. /**
  6. * 节次与周次合并去重函数
  7. * @param {Array<Object>} courses 原始解析课程数组
  8. * @returns {Array<Object>} 合并去重后的课程数组
  9. */
  10. function mergeAndDistinctCourses(courses) {
  11. if (!Array.isArray(courses) || courses.length <= 1) return courses;
  12. // 1. 深拷贝并规范周次数据,过滤无效项
  13. const list = courses.map(c => ({
  14. ...c,
  15. name: c.name || '',
  16. teacher: c.teacher || '',
  17. position: c.position || '',
  18. weeks: Array.isArray(c.weeks) ? [...c.weeks].sort((a, b) => a - b) : []
  19. }));
  20. // 阶段 1:合并连续节次与完全重复记录(前提:名称、教师、地点、星期、周次一致)
  21. list.sort((a, b) => {
  22. return a.name.localeCompare(b.name) ||
  23. a.teacher.localeCompare(b.teacher) ||
  24. a.position.localeCompare(b.position) ||
  25. (a.day || 0) - (b.day || 0) ||
  26. a.weeks.join(',').localeCompare(b.weeks.join(',')) ||
  27. (a.startSection || 0) - (b.startSection || 0);
  28. });
  29. const step1Merged = [];
  30. let current = list[0];
  31. for (let i = 1; i < list.length; i++) {
  32. const next = list[i];
  33. const isSameCourseAndWeeks =
  34. current.name === next.name &&
  35. current.teacher === next.teacher &&
  36. current.position === next.position &&
  37. current.day === next.day &&
  38. current.weeks.join(',') === next.weeks.join(',');
  39. const isContinuous = current.endSection + 1 === next.startSection;
  40. const isDuplicate = current.startSection === next.startSection && current.endSection === next.endSection;
  41. if (isSameCourseAndWeeks && isContinuous) {
  42. // 节次连续:延长结束节次 (如 1-2 节 + 3-4 节 -> 1-4 节)
  43. current.endSection = next.endSection;
  44. } else if (isSameCourseAndWeeks && isDuplicate) {
  45. // 完全重复:跳过
  46. continue;
  47. } else {
  48. step1Merged.push(current);
  49. current = next;
  50. }
  51. }
  52. step1Merged.push(current);
  53. // 阶段 2:合并同节次的周次(前提:名称、教师、地点、星期、开始/结束节次一致)
  54. step1Merged.sort((a, b) => {
  55. return a.name.localeCompare(b.name) ||
  56. a.teacher.localeCompare(b.teacher) ||
  57. a.position.localeCompare(b.position) ||
  58. (a.day || 0) - (b.day || 0) ||
  59. (a.startSection || 0) - (b.startSection || 0) ||
  60. (a.endSection || 0) - (b.endSection || 0);
  61. });
  62. const step2Merged = [];
  63. let cur = step1Merged[0];
  64. for (let i = 1; i < step1Merged.length; i++) {
  65. const nxt = step1Merged[i];
  66. const isSameCourseAndSection =
  67. cur.name === nxt.name &&
  68. cur.teacher === nxt.teacher &&
  69. cur.position === nxt.position &&
  70. cur.day === nxt.day &&
  71. cur.startSection === nxt.startSection &&
  72. cur.endSection === nxt.endSection;
  73. if (isSameCourseAndSection) {
  74. // 周次合并去重 (如 1-8 周 + 9-16 周 -> 1-16 周)
  75. cur.weeks = Array.from(new Set([...cur.weeks, ...nxt.weeks])).sort((a, b) => a - b);
  76. } else {
  77. step2Merged.push(cur);
  78. cur = nxt;
  79. }
  80. }
  81. step2Merged.push(cur);
  82. return step2Merged;
  83. }
  84. /**
  85. * 解析周次字符串,处理单双周和周次范围
  86. */
  87. function parseWeeks(weekStr) {
  88. if (!weekStr) return [];
  89. const weekSets = weekStr.split(',');
  90. let weeks = [];
  91. for (const set of weekSets) {
  92. const trimmedSet = set.trim();
  93. const rangeMatch = trimmedSet.match(/(\d+)-(\d+)周/);
  94. const singleMatch = trimmedSet.match(/^(\d+)周/);
  95. let start = 0;
  96. let end = 0;
  97. let processed = false;
  98. if (rangeMatch) {
  99. start = Number(rangeMatch[1]);
  100. end = Number(rangeMatch[2]);
  101. processed = true;
  102. } else if (singleMatch) {
  103. start = end = Number(singleMatch[1]);
  104. processed = true;
  105. }
  106. if (processed) {
  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. return [...new Set(weeks)].sort((a, b) => a - b);
  117. }
  118. /**
  119. * 解析 API 返回的 JSON 数据
  120. */
  121. function parseJsonData(jsonData) {
  122. if (!jsonData || !Array.isArray(jsonData.kbList)) {
  123. return [];
  124. }
  125. const rawCourseList = jsonData.kbList;
  126. const initialCourseList = [];
  127. for (const rawCourse of rawCourseList) {
  128. if (!rawCourse.kcmc || !rawCourse.xm || !rawCourse.cdmc ||
  129. !rawCourse.xqj || !rawCourse.jcs || !rawCourse.zcd) {
  130. continue;
  131. }
  132. const weeksArray = parseWeeks(rawCourse.zcd);
  133. if (weeksArray.length === 0) {
  134. continue;
  135. }
  136. const sectionParts = rawCourse.jcs.split('-');
  137. const startSection = Number(sectionParts[0]);
  138. const endSection = Number(sectionParts[sectionParts.length - 1]);
  139. const day = Number(rawCourse.xqj);
  140. if (isNaN(day) || isNaN(startSection) || isNaN(endSection) ||
  141. day < 1 || day > 7 || startSection > endSection) {
  142. continue;
  143. }
  144. initialCourseList.push({
  145. name: rawCourse.kcmc.trim(),
  146. teacher: rawCourse.xm.trim(),
  147. position: rawCourse.cdmc.trim(),
  148. day: day,
  149. startSection: startSection,
  150. endSection: endSection,
  151. weeks: weeksArray
  152. });
  153. }
  154. return mergeAndDistinctCourses(initialCourseList);
  155. }
  156. async function promptUserToStart() {
  157. return await window.shiguangBridgePromise.showAlert(
  158. "教务系统课表导入",
  159. "导入前请确保您已在浏览器中成功登录教务系统",
  160. "好的,开始导入"
  161. );
  162. }
  163. /**
  164. * 从教务系统获取学年学期选项
  165. * 学年:以选中项为中心,取前2年+后2年,共5个选项
  166. */
  167. async function fetchAcademicOptions() {
  168. const url = "https://jwpd-443.webvpn.jsei.edu.cn/jwglxt/kbcx/xskbcx_cxXskbcxIndex.html?gnmkdm=N2151&layout=default";
  169. try {
  170. const response = await fetch(url, {
  171. method: "GET",
  172. credentials: "include"
  173. });
  174. if (!response.ok) return null;
  175. const htmlText = await response.text();
  176. const parser = new DOMParser();
  177. const doc = parser.parseFromString(htmlText, "text/html");
  178. const allYearOptions = Array.from(doc.querySelectorAll("#xnm option"))
  179. .filter(opt => opt.value !== "")
  180. .map(opt => ({
  181. value: opt.value,
  182. text: opt.textContent.trim(),
  183. selected: opt.selected
  184. }));
  185. const semesterOptions = Array.from(doc.querySelectorAll("#xqm option"))
  186. .filter(opt => opt.value !== "")
  187. .map(opt => ({
  188. value: opt.value,
  189. text: opt.textContent.trim(),
  190. selected: opt.selected
  191. }));
  192. if (allYearOptions.length === 0 || semesterOptions.length === 0) {
  193. return null;
  194. }
  195. const selectedIndex = allYearOptions.findIndex(opt => opt.selected);
  196. if (selectedIndex === -1) {
  197. return {
  198. yearOptions: allYearOptions.slice(0, 5),
  199. semesterOptions,
  200. defaultYearIndex: 0,
  201. defaultSemesterIndex: semesterOptions.findIndex(opt => opt.selected) !== -1
  202. ? semesterOptions.findIndex(opt => opt.selected)
  203. : 0
  204. };
  205. }
  206. const start = Math.max(0, selectedIndex - 2);
  207. const end = Math.min(allYearOptions.length, selectedIndex + 3);
  208. const yearOptions = allYearOptions.slice(start, end);
  209. const newDefaultIndex = selectedIndex - start;
  210. const defaultSemesterIndex = semesterOptions.findIndex(opt => opt.selected);
  211. return {
  212. yearOptions,
  213. semesterOptions,
  214. defaultYearIndex: newDefaultIndex,
  215. defaultSemesterIndex: defaultSemesterIndex !== -1 ? defaultSemesterIndex : 0
  216. };
  217. } catch (e) {
  218. return null;
  219. }
  220. }
  221. /**
  222. * 提示用户选择学年和学期
  223. */
  224. async function selectAcademicYearAndSemester() {
  225. const optionsData = await fetchAcademicOptions();
  226. if (!optionsData) {
  227. window.shiguangBridge.showToast("从教务系统读取学年学期失败,请确保登录状态。");
  228. return null;
  229. }
  230. const { yearOptions, semesterOptions, defaultYearIndex, defaultSemesterIndex } = optionsData;
  231. const yearTexts = yearOptions.map(item => item.text);
  232. const yearIndex = await window.shiguangBridgePromise.showSingleSelection(
  233. "选择学年",
  234. JSON.stringify(yearTexts),
  235. defaultYearIndex
  236. );
  237. if (yearIndex === null || yearIndex === -1) return null;
  238. const selectedYearCode = yearOptions[yearIndex].value;
  239. const semesterTexts = semesterOptions.map(item => item.text);
  240. const semesterIndex = await window.shiguangBridgePromise.showSingleSelection(
  241. "选择学期",
  242. JSON.stringify(semesterTexts),
  243. defaultSemesterIndex
  244. );
  245. if (semesterIndex === null || semesterIndex === -1) return null;
  246. const selectedSemesterCode = semesterOptions[semesterIndex].value;
  247. return {
  248. academicYear: selectedYearCode,
  249. semesterCode: selectedSemesterCode
  250. };
  251. }
  252. /**
  253. * 获取学期开学日期
  254. */
  255. async function fetchSemesterStartDate(academicYear, semesterCode) {
  256. const url = "https://jwpd-443.webvpn.jsei.edu.cn/jwglxt/kbcx/xskbcxZccx_cxZcByXnxq.html?gnmkdm=N2154";
  257. const requestBody = `xnm=${academicYear}&xqm=${semesterCode}`;
  258. try {
  259. const response = await fetch(url, {
  260. method: "POST",
  261. headers: {
  262. "accept": "application/json, text/javascript, */*; q=0.01",
  263. "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8",
  264. "x-requested-with": "XMLHttpRequest"
  265. },
  266. body: requestBody,
  267. credentials: "include"
  268. });
  269. if (response.ok) {
  270. const json = await response.json();
  271. if (Array.isArray(json) && json.length > 0) {
  272. // 优先找第1周,否则取第一项
  273. const firstWeekObj = json.find(item => String(item.zs) === "1" || String(item.zsmc) === "1") || json[0];
  274. if (firstWeekObj.rq) {
  275. const startDateStr = firstWeekObj.rq.split('/')[0];
  276. if (/^\d{4}-\d{2}-\d{2}$/.test(startDateStr)) {
  277. return startDateStr;
  278. }
  279. }
  280. if (firstWeekObj.zcrq) {
  281. const match = firstWeekObj.zcrq.match(/(\d{4}-\d{2}-\d{2})/);
  282. if (match) return match[1];
  283. }
  284. // 某些系统用 ksrq 字段
  285. if (firstWeekObj.ksrq) {
  286. const match = firstWeekObj.ksrq.match(/(\d{4}-\d{2}-\d{2})/);
  287. if (match) return match[1];
  288. }
  289. }
  290. }
  291. } catch (e) {
  292. // 获取失败不影响主流程
  293. }
  294. return null;
  295. }
  296. /**
  297. * 从教务系统获取作息时间表(节次时间)
  298. * @param {string} academicYear 学年
  299. * @param {string} semesterCode 学期代码
  300. * @returns {Promise<Array<{number: number, startTime: string, endTime: string}>>}
  301. */
  302. async function fetchTimeSlots(academicYear, semesterCode) {
  303. const url = "https://jwpd-443.webvpn.jsei.edu.cn/jwglxt/jzgl/skxxMobile_cxRsdjc.html?gnmkdm=N2154";
  304. const requestBody = `xnm=${academicYear}&xqm=${semesterCode}&xqh_id=1`;
  305. try {
  306. const response = await fetch(url, {
  307. method: "POST",
  308. headers: {
  309. "accept": "*/*",
  310. "content-type": "application/x-www-form-urlencoded;charset=UTF-8",
  311. "x-requested-with": "XMLHttpRequest"
  312. },
  313. body: requestBody,
  314. credentials: "include"
  315. });
  316. if (!response.ok) return null;
  317. const json = await response.json();
  318. if (!Array.isArray(json)) return null;
  319. // 过滤有效节次并转换格式
  320. const timeSlots = json
  321. .filter(item => item.jcmc && item.qssj && item.jssj)
  322. .map(item => ({
  323. number: Number(item.jcmc),
  324. startTime: item.qssj.substring(0, 5), // "08:30:00" -> "08:30"
  325. endTime: item.jssj.substring(0, 5)
  326. }))
  327. .sort((a, b) => a.number - b.number);
  328. return timeSlots.length > 0 ? timeSlots : null;
  329. } catch (e) {
  330. return null;
  331. }
  332. }
  333. /**
  334. * 请求和解析课程数据
  335. */
  336. async function fetchAndParseCourses(academicYear, semesterCode) {
  337. const requestBody = `xnm=${academicYear}&xqm=${semesterCode}&kzlx=ck&xsdm=&kclbdm=`;
  338. const targetUrl = "https://jwpd-443.webvpn.jsei.edu.cn/jwglxt/kbcx/xskbcx_cxXsgrkb.html?gnmkdm=N2151";
  339. // 并行获取课程数据、开学日期、作息时间
  340. const [courseResponse, semesterStartDate, fetchedTimeSlots] = await Promise.all([
  341. fetch(targetUrl, {
  342. method: "POST",
  343. headers: {
  344. "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8"
  345. },
  346. body: requestBody,
  347. credentials: "include"
  348. }),
  349. fetchSemesterStartDate(academicYear, semesterCode),
  350. fetchTimeSlots(academicYear, semesterCode)
  351. ]);
  352. try {
  353. if (courseResponse.ok) {
  354. const jsonText = await courseResponse.text();
  355. const jsonData = JSON.parse(jsonText);
  356. if (jsonData && jsonData.kbList) {
  357. const parsedCourses = parseJsonData(jsonData);
  358. if (parsedCourses.length > 0) {
  359. return {
  360. courses: parsedCourses,
  361. config: {
  362. semesterStartDate: semesterStartDate,
  363. semesterTotalWeeks: 20
  364. },
  365. timeSlots: fetchedTimeSlots
  366. };
  367. }
  368. }
  369. }
  370. } catch (e) {
  371. // 请求失败
  372. }
  373. window.shiguangBridge.showToast("未能获取课表数据,请检查网络环境或登录状态。");
  374. return null;
  375. }
  376. async function saveCourses(parsedCourses) {
  377. try {
  378. await window.shiguangBridgePromise.saveImportedCourses(JSON.stringify(parsedCourses));
  379. return true;
  380. } catch (error) {
  381. window.shiguangBridge.showToast(`课程保存失败: ${error.message}`);
  382. return false;
  383. }
  384. }
  385. // 优先使用从教务系统接口动态获取的作息时间,获取失败时回退到此表
  386. const FALLBACK_TIME_SLOTS = [
  387. { number: 1, startTime: "08:30", endTime: "09:15" },
  388. { number: 2, startTime: "09:20", endTime: "10:05" },
  389. { number: 3, startTime: "10:20", endTime: "11:05" },
  390. { number: 4, startTime: "11:10", endTime: "11:55" },
  391. { number: 5, startTime: "14:00", endTime: "14:45" },
  392. { number: 6, startTime: "14:50", endTime: "15:35" },
  393. { number: 7, startTime: "15:50", endTime: "16:35" },
  394. { number: 8, startTime: "16:40", endTime: "17:25" },
  395. { number: 9, startTime: "17:30", endTime: "18:15" },
  396. { number: 10, startTime: "19:00", endTime: "19:45" },
  397. { number: 11, startTime: "19:55", endTime: "20:40" }
  398. ];
  399. async function importPresetTimeSlots(timeSlots) {
  400. let finalTimeSlots = timeSlots;
  401. let usedFallback = false;
  402. if (!finalTimeSlots || finalTimeSlots.length === 0) {
  403. // 动态获取失败,回退到硬编码保底方案
  404. finalTimeSlots = FALLBACK_TIME_SLOTS;
  405. usedFallback = true;
  406. }
  407. try {
  408. await window.shiguangBridgePromise.savePresetTimeSlots(JSON.stringify(finalTimeSlots));
  409. if (usedFallback) {
  410. window.shiguangBridge.showToast("未获取到教务系统作息,已使用内置保底作息时间导入。");
  411. } else {
  412. window.shiguangBridge.showToast("预设时间段导入成功!");
  413. }
  414. } catch (error) {
  415. window.shiguangBridge.showToast("导入时间段失败: " + error.message);
  416. }
  417. }
  418. async function runImportFlow() {
  419. const alertConfirmed = await promptUserToStart();
  420. if (!alertConfirmed) {
  421. window.shiguangBridge.showToast("用户取消了导入。");
  422. return;
  423. }
  424. const selection = await selectAcademicYearAndSemester();
  425. if (!selection) {
  426. window.shiguangBridge.showToast("未选择学年学期,导入流程终止。");
  427. return;
  428. }
  429. const { academicYear, semesterCode } = selection;
  430. const result = await fetchAndParseCourses(academicYear, semesterCode);
  431. if (result === null) {
  432. return;
  433. }
  434. const { courses, config, timeSlots } = result;
  435. const saveResult = await saveCourses(courses);
  436. if (!saveResult) {
  437. return;
  438. }
  439. try {
  440. await window.shiguangBridgePromise.saveCourseConfig(JSON.stringify(config));
  441. let configMsg = "课表配置更新成功!";
  442. if (config.semesterStartDate) {
  443. configMsg += ` 开学日期:${config.semesterStartDate}`;
  444. }
  445. window.shiguangBridge.showToast(configMsg);
  446. } catch (error) {
  447. window.shiguangBridge.showToast(`课表配置保存失败: ${error.message}`);
  448. }
  449. await importPresetTimeSlots(timeSlots);
  450. window.shiguangBridge.showToast(`课程导入成功,共导入 ${courses.length} 门课程!`);
  451. window.shiguangBridge.notifyTaskCompletion();
  452. }
  453. runImportFlow();