jsei_01.js 18 KB

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