myschool.js 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462
  1. // 西安工业大学(http://jwgl2018.xatu.edu.cn) 拾光课程表适配脚本,基于天津农学院适配脚本
  2. // 本校开发者适配,出现问题请提issues或者提交pr更改,这更加快速
  3. //感谢XingHeYuZhuan、aryunm、jursin...等的帮助,感谢trae的辅助
  4. function powerSplit(paramsRaw) {
  5. const args = [];
  6. let current = "";
  7. let depth = 0;
  8. let inQuote = false;
  9. let quoteChar = "";
  10. for (let i = 0; i < paramsRaw.length; i++) {
  11. let char = paramsRaw[i];
  12. if ((char === '"' || char === "'") && (i === 0 || paramsRaw[i - 1] !== '\\')) {
  13. if (!inQuote) { inQuote = true; quoteChar = char; }
  14. else if (char === quoteChar) { inQuote = false; }
  15. }
  16. if (!inQuote) {
  17. if (char === '(' || char === '[' || char === '{') depth++;
  18. if (char === ')' || char === ']' || char === '}') depth--;
  19. }
  20. if (char === ',' && depth === 0 && !inQuote) {
  21. args.push(cleanArg(current));
  22. current = "";
  23. } else {
  24. current += char;
  25. }
  26. }
  27. args.push(cleanArg(current));
  28. return args;
  29. }
  30. function cleanArg(s) {
  31. s = s.trim();
  32. if (s === "null") return null;
  33. return s.replace(/^["']|["']$/g, "");
  34. }
  35. /**
  36. * 全局课程合并逻辑
  37. */
  38. function mergeContinuousLessons(lessons) {
  39. if (!lessons || lessons.length === 0) return [];
  40. // 1. 建立基于 (课程名|教师|地点|星期几) 的分组
  41. const groups = {};
  42. lessons.forEach(l => {
  43. const key = `${l.courseSequence || ""}|${l.name}|${l.teacher}|${l.position}|${l.day}`;
  44. if (!groups[key]) {
  45. groups[key] = {
  46. name: l.name,
  47. teacher: l.teacher,
  48. position: l.position,
  49. day: l.day,
  50. isTeachingBuilding3: l.isTeachingBuilding3,
  51. credit: l.credit,
  52. // 假设大学最多 50 周,构建一个:第 N 周对应哪些节次的矩阵
  53. weeksMatrix: Array.from({ length: 50 }, () => new Set())
  54. };
  55. }
  56. // 将系统传来的凌乱数据彻底打散,按“周”填入对应的“节”中,Set自动去重
  57. if (l.weeks && Array.isArray(l.weeks)) {
  58. l.weeks.forEach(w => {
  59. if (w >= 0 && w < 50) {
  60. for (let s = l.startSection; s <= l.endSection; s++) {
  61. groups[key].weeksMatrix[w].add(s);
  62. }
  63. }
  64. });
  65. }
  66. });
  67. const merged = [];
  68. // 2. 根据矩阵重新组装绝对精确的课程块
  69. for (const key in groups) {
  70. const group = groups[key];
  71. const matrix = group.weeksMatrix;
  72. // 用于记录相同的“连续节次块”分布在哪些周次
  73. // 例如 blockMap["1-2"] = [1, 2, 3, 4, 5, 6, 7, 8, 9]
  74. // 例如 blockMap["2-2"] = [10]
  75. const blockMap = {};
  76. for (let w = 0; w < matrix.length; w++) {
  77. const sections = Array.from(matrix[w]).sort((a, b) => a - b);
  78. if (sections.length === 0) continue;
  79. // 寻找当前周的连续节次块
  80. let start = sections[0];
  81. let prev = sections[0];
  82. for (let i = 1; i < sections.length; i++) {
  83. const curr = sections[i];
  84. if (curr === prev + 1) {
  85. prev = curr; // 节次连续,继续延伸
  86. } else {
  87. // 节次断开,结算上一个块
  88. const blockKey = `${start}-${prev}`;
  89. if (!blockMap[blockKey]) blockMap[blockKey] = [];
  90. blockMap[blockKey].push(w);
  91. // 开启新块
  92. start = curr;
  93. prev = curr;
  94. }
  95. }
  96. // 结算每周最后一个块
  97. const blockKey = `${start}-${prev}`;
  98. if (!blockMap[blockKey]) blockMap[blockKey] = [];
  99. blockMap[blockKey].push(w);
  100. }
  101. // 3. 将聚合好的 blockMap 转换为最终的 JSON 对象
  102. for (const blockKey in blockMap) {
  103. const [startSec, endSec] = blockKey.split('-').map(Number);
  104. merged.push({
  105. name: group.name,
  106. teacher: group.teacher,
  107. position: group.position,
  108. day: group.day,
  109. startSection: startSec,
  110. endSection: endSec,
  111. weeks: blockMap[blockKey],
  112. isTeachingBuilding3: group.isTeachingBuilding3,
  113. ...(group.credit !== undefined ? { credit: group.credit } : {})
  114. });
  115. }
  116. }
  117. // 4. 排序以便输出整洁美观
  118. merged.sort((a, b) => {
  119. if (a.day !== b.day) return a.day - b.day;
  120. if (a.startSection !== b.startSection) return a.startSection - b.startSection;
  121. return a.name.localeCompare(b.name);
  122. });
  123. return merged;
  124. }
  125. function isTeachingBuilding3(position) {
  126. return /教3/.test(position);
  127. }
  128. /** 从同一课表响应的课程列表中读取学分,按课程序号匹配,避免同名课程混淆。 */
  129. function parseCourseCredits(html) {
  130. const doc = new DOMParser().parseFromString(html, "text/html");
  131. const credits = new Map();
  132. for (const table of doc.querySelectorAll("table")) {
  133. const header = Array.from(table.rows).find(row =>
  134. Array.from(row.cells).some(cell => cell.tagName === "TH" && cell.textContent.trim() === "学分"));
  135. if (!header) continue;
  136. const headers = Array.from(header.cells).map(cell => cell.textContent.trim());
  137. const creditIndex = headers.indexOf("学分");
  138. const sequenceIndex = headers.indexOf("课程序号");
  139. if (sequenceIndex < 0) continue;
  140. for (const row of table.rows) {
  141. if (row === header || row.closest("table") !== table) continue;
  142. const sequence = row.cells[sequenceIndex]?.textContent.trim();
  143. const text = row.cells[creditIndex]?.textContent.trim();
  144. if (!sequence || !text || !/^\d+(?:\.\d+)?$/.test(text)) continue;
  145. const credit = Number(text);
  146. if (!Number.isFinite(credit)) continue;
  147. // 同一序号出现矛盾值时不猜测;合法的 0 学分需要保留。
  148. if (credits.has(sequence) && credits.get(sequence) !== credit) credits.set(sequence, undefined);
  149. else if (!credits.has(sequence)) credits.set(sequence, credit);
  150. }
  151. }
  152. return credits;
  153. }
  154. function parseTaskActivities(html) {
  155. const credits = parseCourseCredits(html);
  156. const rawResults = [];
  157. const blocks = html.split(/var\s+teachers\s*=/);
  158. for (let i = 1; i < blocks.length; i++) {
  159. const block = blocks[i];
  160. let teacherName = "未知教师";
  161. const tMatch = block.match(/actTeachers\s*=\s*\[\s*\{[\s\S]*?name:\s*"(.*?)"/);
  162. if (tMatch) teacherName = tMatch[1];
  163. const activityMatch = block.match(/new\s+TaskActivity\(([\s\S]*?)\);/);
  164. if (!activityMatch) continue;
  165. const args = powerSplit(activityMatch[1]);
  166. const courseSequence = (args[2] || "").match(/\(([^()]*)\)$/)?.[1] || "";
  167. const credit = credits.get(courseSequence);
  168. const courseName = (args[3] || "未知课程").split('(')[0];
  169. const position = (args[5] || "未知地点").replace(/\(.*?\)/g, "");
  170. const weeksBitmap = args[6] || "";
  171. const weeks = [];
  172. for (let j = 0; j < weeksBitmap.length; j++) {
  173. if (weeksBitmap[j] === '1') weeks.push(j);
  174. }
  175. const unitCountMatch = html.match(/unitCount\s*=\s*(\d+)/);
  176. const unitCount = unitCountMatch ? parseInt(unitCountMatch[1]) : 14;
  177. const idxRegex = /index\s*=\s*(\d+)\s*\*\s*unitCount\s*\+\s*(\d+);/g;
  178. let m;
  179. while ((m = idxRegex.exec(block)) !== null) {
  180. const day = parseInt(m[1]) + 1;
  181. const section = parseInt(m[2]) + 1;
  182. rawResults.push({
  183. "name": courseName,
  184. "courseSequence": courseSequence,
  185. ...(credit !== undefined ? { credit } : {}),
  186. "teacher": teacherName,
  187. "position": position,
  188. "day": day,
  189. "startSection": section,
  190. "endSection": section,
  191. "weeks": weeks,
  192. "isTeachingBuilding3": isTeachingBuilding3(position)
  193. });
  194. }
  195. }
  196. // 执行全局合并逻辑
  197. return mergeContinuousLessons(rawResults);
  198. }
  199. async function requestResponse(url, options = {}) {
  200. const res = await fetch(url, { credentials: "include", ...options });
  201. if (!res.ok) throw new Error(`网络请求失败: ${res.status}`);
  202. return res;
  203. }
  204. async function request(url, options = {}) {
  205. return await (await requestResponse(url, options)).text();
  206. }
  207. /** 根据教务首页的当前教学周,推算第一教学周的周一(北京时间)。 */
  208. function inferCurrentSemester(html, referenceTime) {
  209. const doc = new DOMParser().parseFromString(html, "text/html");
  210. const label = Array.from(doc.querySelectorAll("strong"))
  211. .find(el => el.textContent.trim() === "当前教学周");
  212. const weekText = label?.parentElement?.querySelector("span")?.textContent.trim();
  213. const totalMatch = label?.parentElement?.querySelector("i")?.textContent.match(/\/\s*(\d+)/);
  214. if (!weekText || !/^\d+$/.test(weekText) || !totalMatch) return null;
  215. const week = Number(weekText);
  216. const totalWeeks = Number(totalMatch[1]);
  217. if (week < 1 || week > totalWeeks || totalWeeks > 53 || !Number.isFinite(referenceTime)) return null;
  218. // 用 UTC 方法处理已平移到北京时间的日期,避免设备时区和夏令时影响。
  219. const start = new Date(referenceTime + 8 * 60 * 60 * 1000);
  220. start.setUTCHours(0, 0, 0, 0);
  221. const daysSinceMonday = (start.getUTCDay() + 6) % 7;
  222. start.setUTCDate(start.getUTCDate() - daysSinceMonday - (week - 1) * 7);
  223. // 学期选择器没有起止日期;按推算出的起始月份识别本校的秋季/春季学期。
  224. const isAutumn = start.getUTCMonth() >= 6;
  225. const schoolYearStart = start.getUTCFullYear() - (isAutumn ? 0 : 1);
  226. return {
  227. schoolYear: `${schoolYearStart}-${schoolYearStart + 1}`,
  228. term: isAutumn ? "1" : "2",
  229. semesterStartDate: start.toISOString().slice(0, 10),
  230. semesterTotalWeeks: totalWeeks
  231. };
  232. }
  233. async function getCurrentSemesterConfig(semester) {
  234. try {
  235. const res = await requestResponse("http://jwgl2018.xatu.edu.cn/eams/homeExt!main.action?sf_request_type=ajax");
  236. const serverTime = Date.parse(res.headers.get("Date") || "");
  237. const current = inferCurrentSemester(await res.text(), Number.isFinite(serverTime) ? serverTime : Date.now());
  238. if (!current) throw new Error("未能识别当前教学周");
  239. if (semester.schoolYear !== current.schoolYear || semester.term !== current.term) {
  240. window.shiguangBridge.showToast("历史或其他学期开学日期请手动设置");
  241. return null;
  242. }
  243. return {
  244. semesterStartDate: current.semesterStartDate,
  245. semesterTotalWeeks: current.semesterTotalWeeks
  246. };
  247. } catch (e) {
  248. console.warn(`[开学日期推算] ${e.message}`);
  249. window.shiguangBridge.showToast("无法推算开学日期,请在导入后手动设置");
  250. return null;
  251. }
  252. }
  253. async function detectParameters() {
  254. const html = await request("http://jwgl2018.xatu.edu.cn/eams/courseTableForStd.action?sf_request_type=ajax");
  255. const idsMatch = html.match(/bg\.form\.addInput\(form,"ids","(\d+)"\)/);
  256. const tagIdMatch = html.match(/id="(semesterBar\d+Semester)"/);
  257. if (!idsMatch || !tagIdMatch) return null;
  258. return { ids: idsMatch[1], tagId: tagIdMatch[1] };
  259. }
  260. async function getSelectedSemester(tagId) {
  261. const raw = await request(`http://jwgl2018.xatu.edu.cn/eams/dataQuery.action?sf_request_type=ajax`, {
  262. method: "POST",
  263. headers: { "Content-Type": "application/x-www-form-urlencoded" },
  264. body: `tagId=${encodeURIComponent(tagId)}&dataType=semesterCalendar`
  265. });
  266. const data = Function(`return (${raw});`)();
  267. const list = [];
  268. for (let key in data.semesters) {
  269. data.semesters[key].forEach(s => list.push({
  270. id: s.id,
  271. schoolYear: s.schoolYear,
  272. term: String(s.name),
  273. name: `${s.schoolYear} ${s.name}学期`
  274. }));
  275. }
  276. const idx = await window.shiguangBridgePromise.showSingleSelection("选择学期", JSON.stringify(list.map(s => s.name)), -1);
  277. return idx !== null ? list[idx] : null;
  278. }
  279. async function fetchAndParseCourses(semesterId, ids) {
  280. const html = await request(`http://jwgl2018.xatu.edu.cn/eams/courseTableForStd!courseTable.action?sf_request_type=ajax`, {
  281. method: "POST",
  282. headers: { "Content-Type": "application/x-www-form-urlencoded" },
  283. body: `ignoreHead=1&setting.kind=std&semester.id=${semesterId}&ids=${ids}`
  284. });
  285. return parseTaskActivities(html);
  286. }
  287. /** 将已排定考试转换成单次自定义时间课程;未排定、无效或超出学期的记录不导入。 */
  288. function parseExamCourses(html, config) {
  289. const doc = new DOMParser().parseFromString(html, "text/html");
  290. const startTime = Date.parse(`${config.semesterStartDate}T00:00:00Z`);
  291. const exams = [];
  292. const seen = new Set();
  293. let foundTable = false;
  294. for (const table of doc.querySelectorAll("table")) {
  295. const header = Array.from(table.rows).find(row =>
  296. Array.from(row.cells).some(cell => cell.tagName === "TH" && cell.textContent.trim() === "考试日期"));
  297. if (!header) continue;
  298. const headers = Array.from(header.cells).map(cell => cell.textContent.trim());
  299. const get = (row, name) => row.cells[headers.indexOf(name)]?.textContent.trim() || "";
  300. if (!["课程名称", "课程序号", "考试安排", "考试地点"].every(name => headers.includes(name))) continue;
  301. foundTable = true;
  302. for (const row of table.rows) {
  303. if (row === header || row.closest("table") !== table) continue;
  304. const dateText = get(row, "考试日期");
  305. const timeMatch = get(row, "考试安排").match(/^(\d{1,2}:\d{2})\s*[~~--]\s*(\d{1,2}:\d{2})$/);
  306. if (!/^\d{4}-\d{2}-\d{2}$/.test(dateText) || !timeMatch) continue;
  307. const date = new Date(`${dateText}T00:00:00Z`);
  308. if (!Number.isFinite(date.getTime()) || date.toISOString().slice(0, 10) !== dateText) continue;
  309. const times = timeMatch.slice(1).map(time => time.padStart(5, "0"));
  310. if (!times.every(time => /^(?:[01]\d|2[0-3]):[0-5]\d$/.test(time)) || times[0] >= times[1]) continue;
  311. const week = Math.floor((date.getTime() - startTime) / (7 * 86400000)) + 1;
  312. const name = get(row, "课程名称");
  313. if (!name || !Number.isInteger(week) || week < 1 || week > config.semesterTotalWeeks) continue;
  314. const seat = get(row, "考场座位号");
  315. const room = get(row, "考试地点");
  316. const position = `${room === "无" ? "" : room}${seat ? `(座位 ${seat})` : ""}`;
  317. const key = JSON.stringify([get(row, "课程序号"), dateText, times, position]);
  318. if (seen.has(key)) continue;
  319. seen.add(key);
  320. exams.push({
  321. name: `【考试】${name}`,
  322. teacher: "",
  323. position,
  324. day: date.getUTCDay() || 7,
  325. weeks: [week],
  326. isCustomTime: true,
  327. customStartTime: times[0],
  328. customEndTime: times[1]
  329. });
  330. }
  331. }
  332. if (!foundTable) throw new Error("未识别到考试安排表");
  333. return exams;
  334. }
  335. async function getOptionalExamCourses(semester, config) {
  336. // 历史学期没有可靠的开学日期,无法将考试日期换算成对应教学周。
  337. if (!config) return [];
  338. const choice = await window.shiguangBridgePromise.showSingleSelection(
  339. "是否同时导入考试安排", JSON.stringify(["仅导入课程", "同时导入已排定考试(单次课程)"]), 0);
  340. if (choice !== 1) return [];
  341. try {
  342. const html = await request(`http://jwgl2018.xatu.edu.cn/eams/stdExamTable!examTable.action?semester.id=${encodeURIComponent(semester.id)}&examBatch.id=0`);
  343. const exams = parseExamCourses(html, config);
  344. window.shiguangBridge.showToast(exams.length ? `已读取 ${exams.length} 场考试` : "当前学期暂无可导入的已排定考试");
  345. return exams;
  346. } catch (e) {
  347. console.warn(`[考试导入] ${e.message}`);
  348. window.shiguangBridge.showToast("考试安排读取失败,仅导入课程");
  349. return [];
  350. }
  351. }
  352. async function applyTimeSlots() {
  353. const slots = [
  354. { "number": 1, "startTime": "08:20", "endTime": "09:05" },
  355. { "number": 2, "startTime": "09:15", "endTime": "10:00" },
  356. { "number": 3, "startTime": "10:20", "endTime": "11:05" },
  357. { "number": 4, "startTime": "11:15", "endTime": "12:00" },
  358. { "number": 5, "startTime": "14:00", "endTime": "14:45" },
  359. { "number": 6, "startTime": "14:55", "endTime": "15:40" },
  360. { "number": 7, "startTime": "16:00", "endTime": "16:45" },
  361. { "number": 8, "startTime": "16:55", "endTime": "17:40" },
  362. { "number": 9, "startTime": "18:10", "endTime": "18:55" },
  363. { "number": 10, "startTime": "19:05", "endTime": "19:50" },
  364. { "number": 11, "startTime": "20:00", "endTime": "20:45" },
  365. { "number": 12, "startTime": "20:55", "endTime": "21:40" },
  366. ];
  367. return await window.shiguangBridgePromise.savePresetTimeSlots(JSON.stringify(slots));
  368. }
  369. function adjustTeachingBuilding3Courses(courses) {
  370. return courses.map(course => {
  371. // 检查是否是教3楼且正好是第3-4节两节课
  372. if (course.isTeachingBuilding3 &&
  373. course.startSection === 3 &&
  374. course.endSection === 4) {
  375. // 设置为自定义时间模式
  376. course.isCustomTime = true;
  377. course.customStartTime = "10:10";
  378. course.customEndTime = "11:40";
  379. }
  380. return course;
  381. });
  382. }
  383. async function runImportFlow() {
  384. try {
  385. window.shiguangBridge.showToast("开始探测教务参数...");
  386. const params = await detectParameters();
  387. if (!params) throw new Error("未能识别教务参数,请确认已登录");
  388. const semester = await getSelectedSemester(params.tagId);
  389. if (!semester) return;
  390. window.shiguangBridge.showToast("正在同步课表...");
  391. let courses = await fetchAndParseCourses(semester.id, params.ids);
  392. if (!courses || courses.length === 0) throw new Error("未解析到课程数据");
  393. // 调整教3楼课程时间
  394. courses = adjustTeachingBuilding3Courses(courses);
  395. const config = await getCurrentSemesterConfig(semester);
  396. const exams = await getOptionalExamCourses(semester, config);
  397. courses = courses.concat(exams);
  398. await applyTimeSlots();
  399. if (config) {
  400. await window.shiguangBridgePromise.saveCourseConfig(JSON.stringify(config));
  401. window.shiguangBridge.showToast(`已推算第一教学周周一为 ${config.semesterStartDate}`);
  402. }
  403. const saveResult = await window.shiguangBridgePromise.saveImportedCourses(JSON.stringify(courses));
  404. if (saveResult) {
  405. window.shiguangBridge.showToast(`成功导入 ${courses.length} 个课程条目`);
  406. window.shiguangBridge.notifyTaskCompletion();
  407. }
  408. } catch (e) {
  409. console.error(`[异常] ${e.message}`);
  410. window.shiguangBridge.showToast(e.message);
  411. }
  412. }
  413. runImportFlow();