ouc_01.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417
  1. // 中国海洋大学(ouc.edu.cn) 拾光课程表适配脚本 v3
  2. // 基于强智教务系统网络请求方式导入 流程:确认登录 -> 拉取学期列表 -> 用户选择学期 -> 拉取教学周历 -> 请求课表 -> 选择校区作息 -> 保存课程/作息/配置
  3. const BASE_URL = "https://jwgl2024.ouc.edu.cn";
  4. const URL_COURSE = `${BASE_URL}/jsxsd/xskb/xskb_list.do`;
  5. const URL_CALENDAR = `${BASE_URL}/jsxsd/jxzl/jxzl_query`;
  6. const KBJCMSID = "16FD8C2BE55E15F9E0630100007FF6B5";
  7. function pad2(n) { return String(n).padStart(2, "0"); }
  8. function parseWeeks(weekStr) {
  9. const weeks = [];
  10. if (!weekStr) return weeks;
  11. const isSingle = weekStr.includes("(单)");
  12. const isDouble = weekStr.includes("(双)");
  13. const clean = weekStr.replace(/\([单双]\)/g, "").replace(/[周课]/g, "");
  14. clean.split(/[,,、]/).forEach(seg => {
  15. seg = seg.trim();
  16. if (!seg) return;
  17. const m = seg.match(/^(\d+)\s*-\s*(\d+)$/);
  18. let start, end;
  19. if (m) { start = Number(m[1]); end = Number(m[2]); }
  20. else if (/^\d+$/.test(seg)) { start = end = Number(seg); }
  21. else { return; }
  22. for (let w = start; w <= end; w++) {
  23. if (isSingle && w % 2 === 0) continue;
  24. if (isDouble && w % 2 !== 0) continue;
  25. weeks.push(w);
  26. }
  27. });
  28. return [...new Set(weeks)].sort((a, b) => a - b);
  29. }
  30. function mergeAndDistinctCourses(courses) {
  31. if (!Array.isArray(courses) || courses.length <= 1) return courses;
  32. const list = courses.map(c => ({ ...c, name: c.name || '', teacher: c.teacher || '', position: c.position || '', weeks: Array.isArray(c.weeks) ? [...c.weeks].sort((a, b) => a - b) : [] }));
  33. list.sort((a, b) => {
  34. return (a.name || '').localeCompare(b.name || '') ||
  35. (a.teacher || '').localeCompare(b.teacher || '') ||
  36. (a.position || '').localeCompare(b.position || '') ||
  37. (a.day || 0) - (b.day || 0) ||
  38. (a.weeks || []).join(',').localeCompare((b.weeks || []).join(',')) ||
  39. (a.startSection || 0) - (b.startSection || 0);
  40. });
  41. const step1Merged = [];
  42. let current = list[0] && { ...list[0] };
  43. for (let i = 1; i < list.length; i++) {
  44. const next = list[i];
  45. if (!current) { current = { ...next }; continue; }
  46. const same = current.name === next.name &&
  47. current.teacher === next.teacher &&
  48. current.position === next.position &&
  49. current.day === next.day &&
  50. (current.weeks || []).join(',') === (next.weeks || []).join(',');
  51. const isContinuous = current.endSection + 1 === next.startSection;
  52. const isDuplicate = current.startSection === next.startSection && current.endSection === next.endSection;
  53. if (same && isContinuous) {
  54. current.endSection = next.endSection;
  55. } else if (same && isDuplicate) {
  56. continue;
  57. } else {
  58. step1Merged.push(current);
  59. current = { ...next };
  60. }
  61. }
  62. if (current) step1Merged.push(current);
  63. const step2Merged = [];
  64. let cur = step1Merged[0] && { ...step1Merged[0] };
  65. for (let i = 1; i < step1Merged.length; i++) {
  66. const nxt = step1Merged[i];
  67. if (!cur) { cur = { ...nxt }; continue; }
  68. const same = cur.name === nxt.name &&
  69. cur.teacher === nxt.teacher &&
  70. cur.position === nxt.position &&
  71. cur.day === nxt.day &&
  72. cur.startSection === nxt.startSection &&
  73. cur.endSection === nxt.endSection;
  74. if (same) {
  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. if (cur) step2Merged.push(cur);
  82. return step2Merged;
  83. }
  84. // 课表解析
  85. function parseCourseItem(li, day) {
  86. const titleEl = li.querySelector && li.querySelector(".qz-hasCourse-title");
  87. const name = titleEl ? titleEl.textContent.trim() : "";
  88. const text = (li.textContent || "").replace(/\s+/g, "");
  89. const timeMatch = text.match(/时间[::]([^;;]*)(?:;|$)/);
  90. let weeks = [];
  91. let startSection = 1;
  92. let endSection = 1;
  93. if (timeMatch) {
  94. const timePart = timeMatch[1];
  95. const weekMatch = timePart.match(/([\d][\d,,、-]*(?:\([单双]\))?)\s*周/);
  96. if (weekMatch) weeks = parseWeeks(weekMatch[1]);
  97. const secMatch = timePart.match(/\[(\d+)(?:\s*-\s*(\d+))?\s*节\]/);
  98. if (secMatch) {
  99. startSection = Number(secMatch[1]);
  100. endSection = secMatch[2] ? Number(secMatch[2]) : startSection;
  101. }
  102. }
  103. const teacherMatch = text.match(/老师[::]([^;;]+)/);
  104. const teacher = teacherMatch ? teacherMatch[1].trim() : "";
  105. const posMatch = text.match(/地点[::]([^;;]*)/);
  106. const position = posMatch ? posMatch[1].trim() : "";
  107. if (!name || weeks.length === 0) return null;
  108. return { name, teacher, position, day, startSection, endSection, weeks };
  109. }
  110. function parseTimetableToModel(doc) {
  111. const table = doc.querySelector("table.qz-weeklyTable");
  112. if (!table) return [];
  113. const courses = [];
  114. const body = table.querySelector("tbody") || table;
  115. body.querySelectorAll("tr.qz-weeklyTable-tr").forEach(row => {
  116. let day = 0;
  117. row.querySelectorAll("td[name=kbDataTd], td[name='kbDataTd']").forEach(cell => {
  118. day++;
  119. cell.querySelectorAll("li.courselists-item").forEach(li => {
  120. const c = parseCourseItem(li, day);
  121. if (c) courses.push(c);
  122. });
  123. });
  124. });
  125. return mergeAndDistinctCourses(courses);
  126. }
  127. function parseSemesterOptions(doc) {
  128. const select = doc.querySelector("select#xnxq01id");
  129. if (!select) return { list: [], defaultIndex: -1 };
  130. const options = Array.from(select.querySelectorAll("option"));
  131. const allOptions = options.map(opt => ({
  132. value: opt.value.trim(),
  133. label: opt.textContent.trim()
  134. }));
  135. if (allOptions.length === 0) return { list: [], defaultIndex: -1 };
  136. let defaultIndex = options.findIndex(o => o.hasAttribute("selected"));
  137. if (defaultIndex === -1) defaultIndex = 0;
  138. const start = Math.max(0, defaultIndex - 3);
  139. const end = Math.min(allOptions.length, defaultIndex + 4);
  140. const list = allOptions.slice(start, end);
  141. const localDefault = defaultIndex - start;
  142. return { list, defaultIndex: localDefault };
  143. }
  144. function parseCalendarRows(doc) {
  145. const rows = [];
  146. const table = doc.querySelector("table.qz-weeklyTable") || doc.querySelector("table");
  147. if (!table) return rows;
  148. const body = table.querySelector("tbody") || table;
  149. body.querySelectorAll("tr").forEach(tr => {
  150. const cells = Array.from(tr.querySelectorAll("td"));
  151. if (!cells.length) return;
  152. const label = cells[0].textContent.replace(/\s+/g, "");
  153. const wkMatch = label.match(/第\s*(\d+)\s*周/);
  154. if (!wkMatch) return;
  155. const dayText = cells.slice(1).map(c => c.textContent.replace(/\s+/g, ""));
  156. rows.push({ week: Number(wkMatch[1]), cells: dayText });
  157. });
  158. return rows;
  159. }
  160. function deriveMondayFromRow(row, week, semesterYear) {
  161. const yearGuess = [semesterYear, semesterYear + 1];
  162. const fullDateIdx = [];
  163. row.cells.forEach((t, i) => {
  164. const m = t.match(/^(\d{1,2})月(\d{1,2})日$/);
  165. if (m) fullDateIdx.push({ idx: i, month: Number(m[1]), day: Number(m[2]) });
  166. });
  167. for (const fd of fullDateIdx) {
  168. const weekdayFrom = (fd.idx + 1) % 7;
  169. for (const y of yearGuess) {
  170. const d = new Date(y, fd.month - 1, fd.day);
  171. if (d.getDay() === weekdayFrom) {
  172. const monday = new Date(d.getTime() - fd.idx * 86400000);
  173. return `${monday.getFullYear()}-${pad2(monday.getMonth() + 1)}-${pad2(monday.getDate())}`;
  174. }
  175. }
  176. }
  177. const mondayCell = row.cells[0];
  178. const mm = mondayCell.match(/^(\d{1,2})月(\d{1,2})日$/);
  179. if (mm) {
  180. for (const y of yearGuess) {
  181. const d = new Date(y, Number(mm[1]) - 1, Number(mm[2]));
  182. if (d.getDay() === 1) return `${y}-${pad2(Number(mm[1]))}-${pad2(Number(mm[2]))}`;
  183. }
  184. }
  185. return null;
  186. }
  187. async function fetchSemesterList() {
  188. const html = await requestText(`${URL_COURSE}?viweType=0`);
  189. const doc = new DOMParser().parseFromString(html, "text/html");
  190. return parseSemesterOptions(doc);
  191. }
  192. async function fetchCalendarInfo(semesterId, semesterYear) {
  193. const url = `${URL_CALENDAR}?xnxq01id=${encodeURIComponent(semesterId)}`;
  194. const html = await requestText(url);
  195. const doc = new DOMParser().parseFromString(html, "text/html");
  196. const calendarRows = parseCalendarRows(doc);
  197. if (calendarRows.length === 0) return { startDate: null, totalWeeks: null };
  198. let startDate = null;
  199. let totalWeeks = 0;
  200. calendarRows.forEach(r => {
  201. if (r.week > totalWeeks) totalWeeks = r.week;
  202. if (r.week === 1) {
  203. startDate = deriveMondayFromRow(r, r.week, semesterYear);
  204. }
  205. });
  206. return { startDate, totalWeeks };
  207. }
  208. async function fetchCourses(semesterId) {
  209. const url = `${URL_COURSE}?viweType=0&showallprint=0&showkchprint=0&showkink=0&showfzmprint=0`
  210. + `&baseUrl=%2Fjsxsd&xsflMapListJsonStr=${encodeURIComponent("讲课学时,实践学时,")}`
  211. + `&xnxq01id=${encodeURIComponent(semesterId)}&zc=&kbjcmsid=${KBJCMSID}`;
  212. const html = await requestText(url);
  213. const doc = new DOMParser().parseFromString(html, "text/html");
  214. return parseTimetableToModel(doc);
  215. }
  216. async function requestText(url) {
  217. const resp = await fetch(url, { method: "GET", credentials: "include" });
  218. if (!resp.ok) {
  219. throw new Error(`请求失败:HTTP ${resp.status}`);
  220. }
  221. return await resp.text();
  222. }
  223. function buildCourseConfig(semesterStartDate, totalWeeks) {
  224. const config = {
  225. semesterTotalWeeks: totalWeeks || 20,
  226. firstDayOfWeek: 1,
  227. defaultClassDuration: 50,
  228. defaultBreakDuration: 10
  229. };
  230. if (semesterStartDate) config.semesterStartDate = semesterStartDate;
  231. return config;
  232. }
  233. async function saveCourseConfig(config) {
  234. try {
  235. await window.shiguangBridgePromise.saveCourseConfig(JSON.stringify(config));
  236. return true;
  237. } catch (error) {
  238. window.shiguangBridge.showToast(`课表配置保存失败: ${error.message}`);
  239. return false;
  240. }
  241. }
  242. async function saveCourses(courses) {
  243. try {
  244. await window.shiguangBridgePromise.saveImportedCourses(JSON.stringify(courses, null, 2));
  245. return true;
  246. } catch (error) {
  247. window.shiguangBridge.showToast(`课程保存失败: ${error.message}`);
  248. return false;
  249. }
  250. }
  251. async function importPresetTimeSlots(timeSlots) {
  252. if (timeSlots.length === 0) {
  253. window.shiguangBridge.showToast("警告:时间段为空,未导入时间段信息。");
  254. return;
  255. }
  256. window.shiguangBridge.showToast(`正在导入 ${timeSlots.length} 个预设时间段...`);
  257. try {
  258. await window.shiguangBridgePromise.savePresetTimeSlots(JSON.stringify(timeSlots));
  259. window.shiguangBridge.showToast("预设时间段导入成功!");
  260. } catch (error) {
  261. window.shiguangBridge.showToast("导入时间段失败: " + error.message);
  262. }
  263. }
  264. const LAOSHAN_TIME_SLOTS = [
  265. { number: 1, startTime: "08:00", endTime: "08:50" },
  266. { number: 2, startTime: "09:00", endTime: "09:50" },
  267. { number: 3, startTime: "10:10", endTime: "11:00" },
  268. { number: 4, startTime: "11:10", endTime: "12:00" },
  269. { number: 5, startTime: "13:30", endTime: "14:20" },
  270. { number: 6, startTime: "14:30", endTime: "15:20" },
  271. { number: 7, startTime: "15:30", endTime: "16:20" },
  272. { number: 8, startTime: "16:30", endTime: "17:20" },
  273. { number: 9, startTime: "17:30", endTime: "18:20" },
  274. { number: 10, startTime: "18:30", endTime: "19:20" },
  275. { number: 11, startTime: "19:30", endTime: "20:20" },
  276. { number: 12, startTime: "20:30", endTime: "21:20" }
  277. ];
  278. const WEST_COAST_TIME_SLOTS = [
  279. { number: 1, startTime: "08:30", endTime: "09:20" },
  280. { number: 2, startTime: "09:25", endTime: "10:15" },
  281. { number: 3, startTime: "10:30", endTime: "11:20" },
  282. { number: 4, startTime: "11:25", endTime: "12:15" },
  283. ...LAOSHAN_TIME_SLOTS.slice(4)
  284. ];
  285. const SCHEDULE_OPTIONS = [
  286. { name: "崂山/鱼山校区", slots: LAOSHAN_TIME_SLOTS },
  287. { name: "西海岸校区", slots: WEST_COAST_TIME_SLOTS }
  288. ];
  289. async function runImportFlow() {
  290. try {
  291. window.shiguangBridge.showToast("课程导入流程即将开始...");
  292. const confirmed = await window.shiguangBridgePromise.showAlert(
  293. "中国海洋大学课表导入",
  294. "导入前请确保已成功登录教务系统,且当前网络可访问",
  295. "好的,开始导入"
  296. );
  297. if (!confirmed) {
  298. window.shiguangBridge.showToast("用户取消了导入。");
  299. return;
  300. }
  301. window.shiguangBridge.showToast("正在获取学期列表...");
  302. const { list: semesters, defaultIndex } = await fetchSemesterList();
  303. if (!semesters || semesters.length === 0) {
  304. window.shiguangBridge.showToast("未获取到学期列表,请检查登录状态。");
  305. return;
  306. }
  307. const labels = semesters.map(s => s.label);
  308. const selectedIndex = await window.shiguangBridgePromise.showSingleSelection(
  309. "选择学期",
  310. JSON.stringify(labels),
  311. defaultIndex
  312. );
  313. if (selectedIndex === null || selectedIndex === undefined || selectedIndex < 0) {
  314. window.shiguangBridge.showToast("用户取消了导入。");
  315. return;
  316. }
  317. const semester = semesters[Math.min(selectedIndex, semesters.length - 1)];
  318. const semesterId = semester.value;
  319. const parts = semesterId.split("-");
  320. const suffix = Number(parts[2]);
  321. const semesterYear = suffix === 3 ? Number(parts[0]) + 1 : Number(parts[0]);
  322. window.shiguangBridge.showToast("正在获取学期信息...");
  323. let startDate = null, totalWeeks = null;
  324. try {
  325. const cal = await fetchCalendarInfo(semesterId, semesterYear);
  326. startDate = cal.startDate;
  327. totalWeeks = cal.totalWeeks;
  328. } catch (e) {
  329. console.warn("获取教学周历失败:", e.message);
  330. }
  331. window.shiguangBridge.showToast("正在请求课程数据...");
  332. const courses = await fetchCourses(semesterId);
  333. if (courses.length === 0) {
  334. window.shiguangBridge.showToast("未发现课程,请检查学期选择或登录状态。");
  335. return;
  336. }
  337. const scheduleIdxRaw = await window.shiguangBridgePromise.showSingleSelection(
  338. "请选择校区作息表:",
  339. JSON.stringify(SCHEDULE_OPTIONS.map(option => option.name)),
  340. 0
  341. );
  342. const scheduleIndex = Number(scheduleIdxRaw);
  343. const schedule = SCHEDULE_OPTIONS[
  344. Number.isInteger(scheduleIndex) && scheduleIndex >= 0 && scheduleIndex < SCHEDULE_OPTIONS.length
  345. ? scheduleIndex
  346. : 0
  347. ];
  348. const config = buildCourseConfig(startDate, totalWeeks);
  349. await saveCourseConfig(config);
  350. await importPresetTimeSlots(schedule.slots);
  351. const courseSaved = await saveCourses(courses);
  352. if (!courseSaved) {
  353. window.shiguangBridge.showToast("课程保存失败,请重试。");
  354. return;
  355. }
  356. window.shiguangBridge.showToast(
  357. `导入成功:${courses.length} 门课程,作息 ${schedule.name},共 ${config.semesterTotalWeeks} 周。`
  358. );
  359. window.shiguangBridge.notifyTaskCompletion();
  360. } catch (error) {
  361. console.error("课程导入失败:", error);
  362. window.shiguangBridge.showToast("异常: " + error.message);
  363. }
  364. }
  365. runImportFlow();