jsei_01.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557
  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 weekSets = weekStr.split(',');
  111. let weeks = [];
  112. for (const set of weekSets) {
  113. const trimmedSet = set.trim();
  114. const rangeMatch = trimmedSet.match(/(\d+)-(\d+)周/);
  115. const singleMatch = trimmedSet.match(/^(\d+)周/);
  116. let start = 0;
  117. let end = 0;
  118. let processed = false;
  119. if (rangeMatch) {
  120. start = Number(rangeMatch[1]);
  121. end = Number(rangeMatch[2]);
  122. processed = true;
  123. } else if (singleMatch) {
  124. start = end = Number(singleMatch[1]);
  125. processed = true;
  126. }
  127. if (processed) {
  128. const isSingle = trimmedSet.includes('(单)');
  129. const isDouble = trimmedSet.includes('(双)');
  130. for (let w = start; w <= end; w++) {
  131. if (isSingle && w % 2 === 0) continue;
  132. if (isDouble && w % 2 !== 0) continue;
  133. weeks.push(w);
  134. }
  135. }
  136. }
  137. return [...new Set(weeks)].sort((a, b) => a - b);
  138. }
  139. /**
  140. * 解析 API 返回的 JSON 数据
  141. */
  142. function parseJsonData(jsonData) {
  143. if (!jsonData || !Array.isArray(jsonData.kbList)) {
  144. return [];
  145. }
  146. const rawCourseList = jsonData.kbList;
  147. const initialCourseList = [];
  148. for (const rawCourse of rawCourseList) {
  149. if (!rawCourse.kcmc || !rawCourse.xm || !rawCourse.cdmc ||
  150. !rawCourse.xqj || !rawCourse.jcs || !rawCourse.zcd) {
  151. continue;
  152. }
  153. const weeksArray = parseWeeks(rawCourse.zcd);
  154. if (weeksArray.length === 0) {
  155. continue;
  156. }
  157. const sectionParts = rawCourse.jcs.split('-');
  158. const startSection = Number(sectionParts[0]);
  159. const endSection = Number(sectionParts[sectionParts.length - 1]);
  160. const day = Number(rawCourse.xqj);
  161. if (isNaN(day) || isNaN(startSection) || isNaN(endSection) ||
  162. day < 1 || day > 7 || startSection > endSection) {
  163. continue;
  164. }
  165. initialCourseList.push({
  166. name: rawCourse.kcmc.trim(),
  167. teacher: rawCourse.xm.trim(),
  168. position: rawCourse.cdmc.trim(),
  169. day: day,
  170. startSection: startSection,
  171. endSection: endSection,
  172. weeks: weeksArray
  173. });
  174. }
  175. return mergeAndDistinctCourses(initialCourseList);
  176. }
  177. async function promptUserToStart() {
  178. return await window.shiguangBridgePromise.showAlert(
  179. "教务系统课表导入",
  180. "导入前请确保您已在浏览器中成功登录教务系统",
  181. "好的,开始导入"
  182. );
  183. }
  184. /**
  185. * 从教务系统获取学年学期选项
  186. * 学年:以选中项为中心,取前2年+后2年,共5个选项
  187. */
  188. async function fetchAcademicOptions() {
  189. const url = `${getBaseUrl()}/kbcx/xskbcx_cxXskbcxIndex.html?gnmkdm=N2151&layout=default`;
  190. try {
  191. const response = await fetch(url, {
  192. method: "GET",
  193. credentials: "include"
  194. });
  195. if (!response.ok) return null;
  196. const htmlText = await response.text();
  197. const parser = new DOMParser();
  198. const doc = parser.parseFromString(htmlText, "text/html");
  199. const allYearOptions = Array.from(doc.querySelectorAll("#xnm option"))
  200. .filter(opt => opt.value !== "")
  201. .map(opt => ({
  202. value: opt.value,
  203. text: opt.textContent.trim(),
  204. selected: opt.selected
  205. }));
  206. const semesterOptions = Array.from(doc.querySelectorAll("#xqm option"))
  207. .filter(opt => opt.value !== "")
  208. .map(opt => ({
  209. value: opt.value,
  210. text: opt.textContent.trim(),
  211. selected: opt.selected
  212. }));
  213. if (allYearOptions.length === 0 || semesterOptions.length === 0) {
  214. return null;
  215. }
  216. const selectedIndex = allYearOptions.findIndex(opt => opt.selected);
  217. if (selectedIndex === -1) {
  218. return {
  219. yearOptions: allYearOptions.slice(0, 5),
  220. semesterOptions,
  221. defaultYearIndex: 0,
  222. defaultSemesterIndex: semesterOptions.findIndex(opt => opt.selected) !== -1
  223. ? semesterOptions.findIndex(opt => opt.selected)
  224. : 0
  225. };
  226. }
  227. const start = Math.max(0, selectedIndex - 2);
  228. const end = Math.min(allYearOptions.length, selectedIndex + 3);
  229. const yearOptions = allYearOptions.slice(start, end);
  230. const newDefaultIndex = selectedIndex - start;
  231. const defaultSemesterIndex = semesterOptions.findIndex(opt => opt.selected);
  232. return {
  233. yearOptions,
  234. semesterOptions,
  235. defaultYearIndex: newDefaultIndex,
  236. defaultSemesterIndex: defaultSemesterIndex !== -1 ? defaultSemesterIndex : 0
  237. };
  238. } catch (e) {
  239. return null;
  240. }
  241. }
  242. /**
  243. * 提示用户选择学年和学期
  244. */
  245. async function selectAcademicYearAndSemester() {
  246. const optionsData = await fetchAcademicOptions();
  247. if (!optionsData) {
  248. window.shiguangBridge.showToast("从教务系统读取学年学期失败,请确保登录状态。");
  249. return null;
  250. }
  251. const { yearOptions, semesterOptions, defaultYearIndex, defaultSemesterIndex } = optionsData;
  252. const yearTexts = yearOptions.map(item => item.text);
  253. const yearIndex = await window.shiguangBridgePromise.showSingleSelection(
  254. "选择学年",
  255. JSON.stringify(yearTexts),
  256. defaultYearIndex
  257. );
  258. if (yearIndex === null || yearIndex === -1) return null;
  259. const selectedYearCode = yearOptions[yearIndex].value;
  260. const semesterTexts = semesterOptions.map(item => item.text);
  261. const semesterIndex = await window.shiguangBridgePromise.showSingleSelection(
  262. "选择学期",
  263. JSON.stringify(semesterTexts),
  264. defaultSemesterIndex
  265. );
  266. if (semesterIndex === null || semesterIndex === -1) return null;
  267. const selectedSemesterCode = semesterOptions[semesterIndex].value;
  268. return {
  269. academicYear: selectedYearCode,
  270. semesterCode: selectedSemesterCode
  271. };
  272. }
  273. /**
  274. * 获取学期开学日期
  275. */
  276. async function fetchSemesterStartDate(academicYear, semesterCode) {
  277. const url = `${getBaseUrl()}/kbcx/xskbcxZccx_cxZcByXnxq.html?gnmkdm=N2154`;
  278. const requestBody = `xnm=${academicYear}&xqm=${semesterCode}`;
  279. try {
  280. const response = await fetch(url, {
  281. method: "POST",
  282. headers: {
  283. "accept": "application/json, text/javascript, */*; q=0.01",
  284. "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8",
  285. "x-requested-with": "XMLHttpRequest"
  286. },
  287. body: requestBody,
  288. credentials: "include"
  289. });
  290. if (response.ok) {
  291. const json = await response.json();
  292. if (Array.isArray(json) && json.length > 0) {
  293. // 优先找第1周,否则取第一项
  294. const firstWeekObj = json.find(item => String(item.zs) === "1" || String(item.zsmc) === "1") || json[0];
  295. if (firstWeekObj.rq) {
  296. const startDateStr = firstWeekObj.rq.split('/')[0];
  297. if (/^\d{4}-\d{2}-\d{2}$/.test(startDateStr)) {
  298. return startDateStr;
  299. }
  300. }
  301. if (firstWeekObj.zcrq) {
  302. const match = firstWeekObj.zcrq.match(/(\d{4}-\d{2}-\d{2})/);
  303. if (match) return match[1];
  304. }
  305. // 某些系统用 ksrq 字段
  306. if (firstWeekObj.ksrq) {
  307. const match = firstWeekObj.ksrq.match(/(\d{4}-\d{2}-\d{2})/);
  308. if (match) return match[1];
  309. }
  310. }
  311. }
  312. } catch (e) {
  313. // 获取失败不影响主流程
  314. }
  315. return null;
  316. }
  317. /**
  318. * 从教务系统获取作息时间表(节次时间)
  319. * @param {string} academicYear 学年
  320. * @param {string} semesterCode 学期代码
  321. * @returns {Promise<Array<{number: number, startTime: string, endTime: string}>>}
  322. */
  323. async function fetchTimeSlots(academicYear, semesterCode) {
  324. const url = `${getBaseUrl()}/jzgl/skxxMobile_cxRsdjc.html?gnmkdm=N2154`;
  325. const requestBody = `xnm=${academicYear}&xqm=${semesterCode}&xqh_id=1`;
  326. try {
  327. const response = await fetch(url, {
  328. method: "POST",
  329. headers: {
  330. "accept": "*/*",
  331. "content-type": "application/x-www-form-urlencoded;charset=UTF-8",
  332. "x-requested-with": "XMLHttpRequest"
  333. },
  334. body: requestBody,
  335. credentials: "include"
  336. });
  337. if (!response.ok) return null;
  338. const json = await response.json();
  339. if (!Array.isArray(json)) return null;
  340. // 过滤有效节次并转换格式
  341. const timeSlots = json
  342. .filter(item => item.jcmc && item.qssj && item.jssj)
  343. .map(item => ({
  344. number: Number(item.jcmc),
  345. startTime: item.qssj.substring(0, 5), // "08:30:00" -> "08:30"
  346. endTime: item.jssj.substring(0, 5)
  347. }))
  348. .sort((a, b) => a.number - b.number);
  349. return timeSlots.length > 0 ? timeSlots : null;
  350. } catch (e) {
  351. return null;
  352. }
  353. }
  354. /**
  355. * 请求和解析课程数据
  356. */
  357. async function fetchAndParseCourses(academicYear, semesterCode) {
  358. const requestBody = `xnm=${academicYear}&xqm=${semesterCode}&kzlx=ck&xsdm=&kclbdm=`;
  359. const targetUrl = `${getBaseUrl()}/kbcx/xskbcx_cxXsgrkb.html?gnmkdm=N2151`;
  360. // 并行获取课程数据、开学日期、作息时间
  361. const [courseResponse, semesterStartDate, fetchedTimeSlots] = await Promise.all([
  362. fetch(targetUrl, {
  363. method: "POST",
  364. headers: {
  365. "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8"
  366. },
  367. body: requestBody,
  368. credentials: "include"
  369. }),
  370. fetchSemesterStartDate(academicYear, semesterCode),
  371. fetchTimeSlots(academicYear, semesterCode)
  372. ]);
  373. try {
  374. if (courseResponse.ok) {
  375. const jsonText = await courseResponse.text();
  376. const jsonData = JSON.parse(jsonText);
  377. if (jsonData && jsonData.kbList) {
  378. const parsedCourses = parseJsonData(jsonData);
  379. if (parsedCourses.length > 0) {
  380. return {
  381. courses: parsedCourses,
  382. config: {
  383. semesterStartDate: semesterStartDate,
  384. semesterTotalWeeks: 20
  385. },
  386. timeSlots: fetchedTimeSlots
  387. };
  388. }
  389. }
  390. }
  391. } catch (e) {
  392. // 请求失败
  393. }
  394. window.shiguangBridge.showToast("未能获取课表数据,请检查网络环境或登录状态。");
  395. return null;
  396. }
  397. async function saveCourses(parsedCourses) {
  398. try {
  399. await window.shiguangBridgePromise.saveImportedCourses(JSON.stringify(parsedCourses));
  400. return true;
  401. } catch (error) {
  402. window.shiguangBridge.showToast(`课程保存失败: ${error.message}`);
  403. return false;
  404. }
  405. }
  406. // 优先使用从教务系统接口动态获取的作息时间,获取失败时回退到此表
  407. const FALLBACK_TIME_SLOTS = [
  408. { number: 1, startTime: "08:30", endTime: "09:15" },
  409. { number: 2, startTime: "09:20", endTime: "10:05" },
  410. { number: 3, startTime: "10:20", endTime: "11:05" },
  411. { number: 4, startTime: "11:10", endTime: "11:55" },
  412. { number: 5, startTime: "14:00", endTime: "14:45" },
  413. { number: 6, startTime: "14:50", endTime: "15:35" },
  414. { number: 7, startTime: "15:50", endTime: "16:35" },
  415. { number: 8, startTime: "16:40", endTime: "17:25" },
  416. { number: 9, startTime: "17:30", endTime: "18:15" },
  417. { number: 10, startTime: "19:00", endTime: "19:45" },
  418. { number: 11, startTime: "19:55", endTime: "20:40" }
  419. ];
  420. async function importPresetTimeSlots(timeSlots) {
  421. let finalTimeSlots = timeSlots;
  422. let usedFallback = false;
  423. if (!finalTimeSlots || finalTimeSlots.length === 0) {
  424. // 动态获取失败,回退到硬编码保底方案
  425. finalTimeSlots = FALLBACK_TIME_SLOTS;
  426. usedFallback = true;
  427. }
  428. try {
  429. await window.shiguangBridgePromise.savePresetTimeSlots(JSON.stringify(finalTimeSlots));
  430. if (usedFallback) {
  431. window.shiguangBridge.showToast("未获取到教务系统作息,已使用内置保底作息时间导入。");
  432. } else {
  433. window.shiguangBridge.showToast("预设时间段导入成功!");
  434. }
  435. } catch (error) {
  436. window.shiguangBridge.showToast("导入时间段失败: " + error.message);
  437. }
  438. }
  439. async function runImportFlow() {
  440. const alertConfirmed = await promptUserToStart();
  441. if (!alertConfirmed) {
  442. window.shiguangBridge.showToast("用户取消了导入。");
  443. return;
  444. }
  445. const selection = await selectAcademicYearAndSemester();
  446. if (!selection) {
  447. window.shiguangBridge.showToast("未选择学年学期,导入流程终止。");
  448. return;
  449. }
  450. const { academicYear, semesterCode } = selection;
  451. const result = await fetchAndParseCourses(academicYear, semesterCode);
  452. if (result === null) {
  453. return;
  454. }
  455. const { courses, config, timeSlots } = result;
  456. const saveResult = await saveCourses(courses);
  457. if (!saveResult) {
  458. return;
  459. }
  460. try {
  461. await window.shiguangBridgePromise.saveCourseConfig(JSON.stringify(config));
  462. let configMsg = "课表配置更新成功!";
  463. if (config.semesterStartDate) {
  464. configMsg += ` 开学日期:${config.semesterStartDate}`;
  465. }
  466. window.shiguangBridge.showToast(configMsg);
  467. } catch (error) {
  468. window.shiguangBridge.showToast(`课表配置保存失败: ${error.message}`);
  469. }
  470. await importPresetTimeSlots(timeSlots);
  471. window.shiguangBridge.showToast(`课程导入成功,共导入 ${courses.length} 门课程!`);
  472. window.shiguangBridge.notifyTaskCompletion();
  473. }
  474. runImportFlow();