xjie_01.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403
  1. // 新疆工程学院(xjie.edu.cn) 拾光课程表适配脚本
  2. // 非该大学开发者适配,开发者无法及时发现问题
  3. // 出现问题请提联系开发者或者提交pr更改,这更加快速
  4. const BASE_URL = "https://jwxt.xjie.edu.cn";
  5. const URL_SEMESTER = `${BASE_URL}/jsxsd/jxzl/jxzl_query`; // 教学周历(学期列表 + 开学日期 + 最大周次)
  6. const URL_COURSE = `${BASE_URL}/jsxsd/xskb/xskb_list.do`; // 课表查询
  7. // 工具函数
  8. function parseWeeks(weekStr) {
  9. const weeks = [];
  10. if (!weekStr) return weeks;
  11. const pureWeekData = weekStr.split('(')[0];
  12. pureWeekData.split(',').forEach(seg => {
  13. if (seg.includes('-')) {
  14. const [s, e] = seg.split('-').map(Number);
  15. if (!isNaN(s) && !isNaN(e)) {
  16. for (let i = s; i <= e; i++) weeks.push(i);
  17. }
  18. } else {
  19. const w = parseInt(seg);
  20. if (!isNaN(w)) weeks.push(w);
  21. }
  22. });
  23. return [...new Set(weeks)].sort((a, b) => a - b);
  24. }
  25. /**
  26. * 节次与周次合并去重函数
  27. * @param {Array<Object>} courses 原始解析课程数组
  28. * @returns {Array<Object>} 合并去重后的课程数组
  29. */
  30. function mergeAndDistinctCourses(courses) {
  31. if (!Array.isArray(courses) || courses.length <= 1) return courses;
  32. const list = courses.map(c => ({
  33. ...c,
  34. name: c.name || '',
  35. teacher: c.teacher || '',
  36. position: c.position || '',
  37. weeks: Array.isArray(c.weeks) ? [...c.weeks].sort((a, b) => a - b) : []
  38. }));
  39. // 阶段 1:合并连续节次与完全重复记录
  40. list.sort((a, b) => {
  41. return a.name.localeCompare(b.name) ||
  42. a.teacher.localeCompare(b.teacher) ||
  43. a.position.localeCompare(b.position) ||
  44. (a.day || 0) - (b.day || 0) ||
  45. a.weeks.join(',').localeCompare(b.weeks.join(',')) ||
  46. (a.startSection || 0) - (b.startSection || 0);
  47. });
  48. const step1Merged = [];
  49. let current = list[0];
  50. for (let i = 1; i < list.length; i++) {
  51. const next = list[i];
  52. const isSameCourseAndWeeks =
  53. current.name === next.name &&
  54. current.teacher === next.teacher &&
  55. current.position === next.position &&
  56. current.day === next.day &&
  57. current.weeks.join(',') === next.weeks.join(',');
  58. const isContinuous = current.endSection + 1 === next.startSection;
  59. const isDuplicate = current.startSection === next.startSection && current.endSection === next.endSection;
  60. if (isSameCourseAndWeeks && isContinuous) {
  61. current.endSection = next.endSection;
  62. } else if (isSameCourseAndWeeks && isDuplicate) {
  63. continue;
  64. } else {
  65. step1Merged.push(current);
  66. current = next;
  67. }
  68. }
  69. step1Merged.push(current);
  70. // 阶段 2:合并同节次的周次
  71. step1Merged.sort((a, b) => {
  72. return a.name.localeCompare(b.name) ||
  73. a.teacher.localeCompare(b.teacher) ||
  74. a.position.localeCompare(b.position) ||
  75. (a.day || 0) - (b.day || 0) ||
  76. (a.startSection || 0) - (b.startSection || 0) ||
  77. (a.endSection || 0) - (b.endSection || 0);
  78. });
  79. const step2Merged = [];
  80. let cur = step1Merged[0];
  81. for (let i = 1; i < step1Merged.length; i++) {
  82. const nxt = step1Merged[i];
  83. const isSameCourseAndSection =
  84. cur.name === nxt.name &&
  85. cur.teacher === nxt.teacher &&
  86. cur.position === nxt.position &&
  87. cur.day === nxt.day &&
  88. cur.startSection === nxt.startSection &&
  89. cur.endSection === nxt.endSection;
  90. if (isSameCourseAndSection) {
  91. cur.weeks = Array.from(new Set([...cur.weeks, ...nxt.weeks])).sort((a, b) => a - b);
  92. } else {
  93. step2Merged.push(cur);
  94. cur = nxt;
  95. }
  96. }
  97. step2Merged.push(cur);
  98. return step2Merged;
  99. }
  100. // 核心解析逻辑
  101. function parseTimetableToModel(doc) {
  102. const timetable = doc.getElementById('timetable');
  103. if (!timetable) return [];
  104. const results = [];
  105. const rows = Array.from(timetable.querySelectorAll('tr')).slice(1);
  106. rows.forEach(row => {
  107. const cells = row.querySelectorAll('td');
  108. if (cells.length < 7) return;
  109. // 遍历周一到周日
  110. cells.forEach((cell, dayIndex) => {
  111. const day = dayIndex + 1;
  112. const detailDiv = cell.querySelector('div.kbcontent[style*="none"]');
  113. if (detailDiv) {
  114. const rawHtml = detailDiv.innerHTML.trim();
  115. if (rawHtml === "" || rawHtml === "&nbsp;") return;
  116. // 拆分可能存在的多个课程块
  117. const courseBlocks = rawHtml.split(/---------------------|----------------------/);
  118. courseBlocks.forEach(block => {
  119. if (block.replace(/&nbsp;|<br\/?>/g, '').trim() === "") return;
  120. const tempDiv = document.createElement('div');
  121. tempDiv.innerHTML = block;
  122. // 提取课程名
  123. let name = "";
  124. for (let node of tempDiv.childNodes) {
  125. if (node.nodeType === 3 && node.textContent.trim() !== "") {
  126. name = node.textContent.trim();
  127. break;
  128. } else if (node.tagName === "BR" && name !== "") {
  129. break;
  130. } else if (node.nodeType === 3) {
  131. name += node.textContent.trim();
  132. }
  133. }
  134. // 提取教师、周次(节次)、地点
  135. const teacherRaw = tempDiv.querySelector('font[title="教师"], font[title="老师"]')?.innerText || "未知教师";
  136. const teacher = teacherRaw.replace("任课教师:", "").trim();
  137. const weekStr = tempDiv.querySelector('font[title="周次(节次)"]')?.innerText || "";
  138. const position = tempDiv.querySelector('font[title="教室"]')?.innerText || "未知地点";
  139. let startSection = 0, endSection = 0;
  140. if (weekStr) {
  141. const secMatch = weekStr.match(/\[([\d\-,\s]+?)节\]/);
  142. if (secMatch && secMatch[1]) {
  143. const nums = secMatch[1]
  144. .split(/[^\d]+/)
  145. .map(Number)
  146. .filter(n => !isNaN(n) && n > 0);
  147. if (nums.length > 0) {
  148. startSection = Math.min(...nums);
  149. endSection = Math.max(...nums);
  150. }
  151. }
  152. }
  153. if (name && weekStr && startSection > 0) {
  154. results.push({
  155. "name": name,
  156. "teacher": teacher,
  157. "weeks": parseWeeks(weekStr),
  158. "position": position,
  159. "day": day,
  160. "startSection": startSection,
  161. "endSection": endSection
  162. });
  163. }
  164. });
  165. }
  166. });
  167. });
  168. return mergeAndDistinctCourses(results);
  169. }
  170. // 网络请求封装
  171. /**
  172. * GET 教学周历页面(用于获取学期列表)
  173. */
  174. async function requestSemesterPage() {
  175. const response = await fetch(URL_SEMESTER, {
  176. method: "GET",
  177. credentials: "include"
  178. });
  179. return await response.text();
  180. }
  181. /**
  182. * POST 教学周历页面(用于获取指定学期的开学日期与最大周次)
  183. * @param {string} semesterId 形如 "2025-2026-2"
  184. */
  185. async function requestSemesterDetailPage(semesterId) {
  186. const response = await fetch(URL_SEMESTER, {
  187. method: "POST",
  188. headers: { "Content-Type": "application/x-www-form-urlencoded" },
  189. body: `xnxq01id=${semesterId}`,
  190. credentials: "include"
  191. });
  192. return await response.text();
  193. }
  194. /**
  195. * POST 课表页面(用于获取课程数据)
  196. * @param {string} semesterId 形如 "2025-2026-2"
  197. */
  198. async function requestCoursePage(semesterId) {
  199. const response = await fetch(URL_COURSE, {
  200. method: "POST",
  201. headers: { "Content-Type": "application/x-www-form-urlencoded" },
  202. body: `jx0404id=&cj0701id=&zc=&demo=&xnxq01id=${semesterId}`,
  203. credentials: "include"
  204. });
  205. return await response.text();
  206. }
  207. // 业务逻辑
  208. /**
  209. * 获取学期列表,以 selected 为原点上下各取 3 个
  210. * @returns {Promise<{list: Array<{value:string,label:string}>, defaultIndex:number}>}
  211. */
  212. async function fetchSemesterList() {
  213. const html = await requestSemesterPage();
  214. const doc = new DOMParser().parseFromString(html, "text/html");
  215. const select = doc.getElementById("xnxq01id");
  216. if (!select) return { list: [], defaultIndex: -1 };
  217. const allOptions = Array.from(select.querySelectorAll("option")).map(opt => ({
  218. value: opt.value,
  219. label: opt.textContent.trim(),
  220. selected: opt.hasAttribute("selected")
  221. }));
  222. let selectedIndex = allOptions.findIndex(o => o.selected);
  223. if (selectedIndex === -1) selectedIndex = 0;
  224. const start = Math.max(0, selectedIndex - 3);
  225. const end = Math.min(allOptions.length, selectedIndex + 4);
  226. const list = allOptions.slice(start, end);
  227. const defaultIndex = selectedIndex - start;
  228. return { list, defaultIndex };
  229. }
  230. /**
  231. * 获取指定学期的开学日期 + 最大周次
  232. * @param {string} semesterId 形如 "2025-2026-2"
  233. * @returns {Promise<{startDate: string|null, totalWeeks: number|null}>}
  234. */
  235. async function fetchSemesterInfo(semesterId) {
  236. const html = await requestSemesterDetailPage(semesterId);
  237. const doc = new DOMParser().parseFromString(html, "text/html");
  238. const timetable = doc.getElementById("kbtable");
  239. if (!timetable) return { startDate: null, totalWeeks: null };
  240. const rows = Array.from(timetable.querySelectorAll("tr")).filter(r => r.querySelector("td"));
  241. if (rows.length === 0) return { startDate: null, totalWeeks: null };
  242. const firstDateCell = rows[0].querySelector("td[title]");
  243. const title = firstDateCell?.getAttribute("title") || "";
  244. const match = title.match(/^(\d{4})年(\d{2})月(\d{2})$/);
  245. const startDate = match ? `${match[1]}-${match[2]}-${match[3]}` : null;
  246. // 最大周次:所有行第一个 td 中能解析为整数的最大值
  247. let totalWeeks = null;
  248. for (const row of rows) {
  249. const firstTd = row.querySelector("td");
  250. if (!firstTd) continue;
  251. const n = parseInt(firstTd.textContent.trim(), 10);
  252. if (!isNaN(n) && n > 0) {
  253. if (totalWeeks === null || n > totalWeeks) totalWeeks = n;
  254. }
  255. }
  256. return { startDate, totalWeeks };
  257. }
  258. /**
  259. * 获取并解析指定学期的课程
  260. * @param {string} semesterId 形如 "2025-2026-2"
  261. * @returns {Promise<Array<Object>>}
  262. */
  263. async function fetchCourses(semesterId) {
  264. const html = await requestCoursePage(semesterId);
  265. return parseTimetableToModel(new DOMParser().parseFromString(html, "text/html"));
  266. }
  267. // 配置保存
  268. async function saveAppConfig(semesterStartDate, totalWeeks) {
  269. const config = {
  270. "semesterTotalWeeks": totalWeeks || 20,
  271. "firstDayOfWeek": 1
  272. };
  273. if (semesterStartDate) {
  274. config.semesterStartDate = semesterStartDate;
  275. }
  276. return await window.shiguangBridgePromise.saveCourseConfig(JSON.stringify(config));
  277. }
  278. /**
  279. * 统一作息(新疆工程学院)
  280. */
  281. async function saveAppTimeSlots() {
  282. const unifiedSlots = [
  283. { "number": 1, "startTime": "10:00", "endTime": "10:45" },
  284. { "number": 2, "startTime": "10:55", "endTime": "11:40" },
  285. { "number": 3, "startTime": "11:55", "endTime": "12:40" },
  286. { "number": 4, "startTime": "12:50", "endTime": "13:35" },
  287. { "number": 5, "startTime": "13:45", "endTime": "14:30" },
  288. { "number": 6, "startTime": "16:00", "endTime": "16:45" },
  289. { "number": 7, "startTime": "16:55", "endTime": "17:40" },
  290. { "number": 8, "startTime": "17:55", "endTime": "18:40" },
  291. { "number": 9, "startTime": "18:50", "endTime": "19:35" },
  292. { "number": 10, "startTime": "19:50", "endTime": "20:35" },
  293. { "number": 11, "startTime": "20:45", "endTime": "21:30" }
  294. ];
  295. return await window.shiguangBridgePromise.savePresetTimeSlots(JSON.stringify(unifiedSlots));
  296. }
  297. // 流程编排
  298. async function runImportFlow() {
  299. try {
  300. // 1. 用户确认
  301. const confirmed = await window.shiguangBridgePromise.showAlert(
  302. "提示", "请确保已成功登录教务系统。是否开始导入?", "开始"
  303. );
  304. if (!confirmed) return;
  305. // 2. 获取学期列表
  306. window.shiguangBridge.showToast("正在获取学期列表...");
  307. const { list: semesters, defaultIndex } = await fetchSemesterList();
  308. if (!semesters || semesters.length === 0) {
  309. window.shiguangBridge.showToast("未获取到学期列表,请检查登录状态。");
  310. return;
  311. }
  312. // 3. 用户选择学期
  313. const labels = semesters.map(s => s.label);
  314. const selectedIndex = await window.shiguangBridgePromise.showSingleSelection(
  315. "选择学期", JSON.stringify(labels), defaultIndex
  316. );
  317. if (selectedIndex === null) return;
  318. const semesterId = semesters[selectedIndex].value;
  319. // 4. 获取开学日期 + 最大周次
  320. window.shiguangBridge.showToast("正在获取学期信息...");
  321. const { startDate: semesterStartDate, totalWeeks } = await fetchSemesterInfo(semesterId);
  322. // 5. 获取课程
  323. window.shiguangBridge.showToast("正在请求课程数据...");
  324. const finalCourses = await fetchCourses(semesterId);
  325. if (finalCourses.length === 0) {
  326. window.shiguangBridge.showToast("未发现课程,请检查学期选择或登录状态。");
  327. return;
  328. }
  329. // 6. 保存配置(含开学日期 + 最大周次)/ 作息 / 课程
  330. await saveAppConfig(semesterStartDate, totalWeeks);
  331. await saveAppTimeSlots();
  332. await window.shiguangBridgePromise.saveImportedCourses(JSON.stringify(finalCourses));
  333. // 7. 完成
  334. window.shiguangBridge.showToast(`成功导入 ${finalCourses.length} 门课程`);
  335. window.shiguangBridge.notifyTaskCompletion();
  336. } catch (error) {
  337. window.shiguangBridge.showToast("异常: " + error.message);
  338. }
  339. }
  340. // 启动导入流程
  341. runImportFlow();