gdcp_02.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436
  1. // 广东交通职业技术学院(gdcp.edu.cn)拾光课程表适配脚本(自动判定校区作息版)
  2. // 接口与作息数据参考同目录 gdcp_01.js(作者:小漫君),本适配不再让用户选择校区。
  3. // 适配作者:Haooz
  4. // 课表:GET /jsxsd/xskb/xskb_list.do 读学期下拉与节次模式;POST 同路径取整学期详表(div.kbcontent)。
  5. // 周历:POST /jsxsd/jxzl/jxzl_query 读首周日期与总周数。
  6. // 作息:按教学楼自动判断校区;校区有两套作息时,课程较多的一套写入预设作息,较少的一套按自定义时间写入。
  7. const GDCP_ORIGIN = 'https://jw.gdcp.edu.cn';
  8. const GDCP_TIMETABLE_URL = GDCP_ORIGIN + '/jsxsd/xskb/xskb_list.do';
  9. const GDCP_CALENDAR_URL = GDCP_ORIGIN + '/jsxsd/jxzl/jxzl_query';
  10. // 第 7~8、9~10、11~12 节各为 80 分钟连堂,网格按每小节 40 分钟连续排列;课程保留整段实际时间。
  11. const GDCP_TIME_SLOTS = [
  12. { number: 1, startTime: '08:30', endTime: '09:10' },
  13. { number: 2, startTime: '09:15', endTime: '09:55' },
  14. { number: 3, startTime: '10:10', endTime: '10:50' },
  15. { number: 4, startTime: '10:55', endTime: '11:35' },
  16. { number: 5, startTime: '14:15', endTime: '14:55' },
  17. { number: 6, startTime: '15:00', endTime: '15:40' },
  18. { number: 7, startTime: '15:55', endTime: '16:35' },
  19. { number: 8, startTime: '16:35', endTime: '17:15' },
  20. { number: 9, startTime: '18:05', endTime: '18:45' },
  21. { number: 10, startTime: '18:45', endTime: '19:25' },
  22. { number: 11, startTime: '19:40', endTime: '20:20' },
  23. { number: 12, startTime: '20:20', endTime: '21:00' }
  24. ];
  25. // 部分楼栋第 3、4 节使用的晚班作息(早班取 GDCP_TIME_SLOTS 的值)
  26. const GDCP_LATE_MORNING = [
  27. { number: 3, startTime: '10:30', endTime: '11:10' },
  28. { number: 4, startTime: '11:15', endTime: '11:55' }
  29. ];
  30. // 晚班完整作息(仅第 3、4 节与早班不同)
  31. const GDCP_LATE_TIME_SLOTS = GDCP_TIME_SLOTS.map(function (slot) {
  32. if (slot.number === 3) return GDCP_LATE_MORNING[0];
  33. if (slot.number === 4) return GDCP_LATE_MORNING[1];
  34. return slot;
  35. });
  36. const GDCP_CAMPUSES = [
  37. // 轨道楼(16#)未列入原表;用户已确认第 3、4 节使用 10:10 起的早班作息。
  38. { name: '天河校区', early: ['9号楼', '10号楼', '12号楼', '图书馆', '公路楼', '汽车实训楼', '轨道楼'], late: ['2号楼', '运动场'] },
  39. { name: '花都校区', early: ['1号楼', '图书馆'], late: ['10号楼', '15号楼', '16号楼', '运动场'] },
  40. { name: '国际校区', early: ['教学楼', '运动场'], late: [] },
  41. { name: '清远校区', early: ['厚德楼', '明德楼', '立业楼', '创新楼', '求是楼', '笃实楼'], late: ['融新楼', '融创楼', '运动场', '体育馆'] }
  42. ];
  43. // 教学楼名归一:去掉【】与校区后缀,楼号去前导零;“操场”对应作息表的“运动场”
  44. function normalizeVenue(building) {
  45. return String(building)
  46. .replace(/[【】]/g, '')
  47. .replace(/((?:天河|花都|国际|清远))$/, '')
  48. .replace(/^0+(\d+号楼)$/, '$1')
  49. .replace(/^操场$/, '运动场');
  50. }
  51. function isBuildingMatch(venue, name) {
  52. return venue === name || venue.startsWith(name + '(');
  53. }
  54. // 7-8、9-10、11-12 由学校视为一个完整时间块,不能取普通小节的边界
  55. function sectionTime(slots, section, isStart) {
  56. if (isStart) {
  57. if (section === 8) return '15:55';
  58. if (section === 10) return '18:05';
  59. if (section === 12) return '19:40';
  60. return slots[section - 1].startTime;
  61. }
  62. if (section === 7) return '17:15';
  63. if (section === 9) return '19:25';
  64. if (section === 11) return '21:00';
  65. return slots[section - 1].endTime;
  66. }
  67. // 某一教学楼出现在哪些校区(早班、晚班名单都算;如“运动场”会同时出现在多个校区)
  68. function campusesOf(building) {
  69. const venue = normalizeVenue(building);
  70. return GDCP_CAMPUSES.filter(function (campus) {
  71. return campus.early.some(function (name) { return isBuildingMatch(venue, name); }) ||
  72. campus.late.some(function (name) { return isBuildingMatch(venue, name); });
  73. });
  74. }
  75. // 课程在所属校区走早班还是晚班;国际校区未列入名单的“其他区域”按晚班处理
  76. function scheduleOf(campus, building) {
  77. const venue = normalizeVenue(building);
  78. if (campus.early.some(function (name) { return isBuildingMatch(venue, name); })) return 'early';
  79. if (campus.late.some(function (name) { return isBuildingMatch(venue, name); })) return 'late';
  80. if (campus.name === '国际校区') return 'late';
  81. throw new Error(campus.name + '的“' + building + '”未列入学校作息表,无法确定第 3、4 节时间。');
  82. }
  83. // 课程数最多的校区即当前上课校区
  84. function dominantCampus(courses) {
  85. const count = new Map();
  86. courses.forEach(function (course) {
  87. campusesOf(course.building).forEach(function (campus) {
  88. count.set(campus, (count.get(campus) || 0) + 1);
  89. });
  90. });
  91. let picked = null;
  92. count.forEach(function (times, campus) {
  93. if (!picked || times > count.get(picked)) picked = campus;
  94. });
  95. if (!picked) throw new Error('未能根据教学楼名称判断上课校区。');
  96. return picked;
  97. }
  98. // 按指定作息写入课程的自定义起止时间
  99. function applyGroupTime(course, slots) {
  100. if (course.startSection < 1 || course.endSection > GDCP_TIME_SLOTS.length) {
  101. throw new Error('学校作息表只提供第 1~12 节,课程“' + course.name + '”的节次超出范围。');
  102. }
  103. return {
  104. ...course,
  105. isCustomTime: true,
  106. customStartTime: sectionTime(slots, course.startSection, true),
  107. customEndTime: sectionTime(slots, course.endSection, false)
  108. };
  109. }
  110. async function fetchTimetableDoc(parameters) {
  111. const options = { credentials: 'include' };
  112. if (parameters !== undefined) {
  113. options.method = 'POST';
  114. options.headers = { 'Content-Type': 'application/x-www-form-urlencoded' };
  115. options.body = parameters.toString();
  116. }
  117. const response = await fetch(GDCP_TIMETABLE_URL, options);
  118. if (!response.ok) throw new Error('课表请求失败(HTTP ' + response.status + ')。');
  119. return new DOMParser().parseFromString(await response.text(), 'text/html');
  120. }
  121. // 解析详表“周次(节次)”文本,如“1-16周(全部)[01-02节]”“1-8周(单)”
  122. function parseWeeksAndSections(text) {
  123. const result = { weeks: [], sections: [] };
  124. const content = String(text || '').trim();
  125. if (!content) return result;
  126. const parity = /双/.test(content) ? 2 : (/单/.test(content) ? 1 : 0);
  127. const bracketIndex = content.indexOf('[');
  128. const cleaned = (bracketIndex >= 0 ? content.slice(0, bracketIndex) : content)
  129. .replace(/第/g, '')
  130. .replace(/至|到|~/g, '-')
  131. .replace(/[((][^()()]*[))]/g, '')
  132. .replace(/周/g, '');
  133. cleaned.split(/[,,、;;\s]+/).forEach(function (segment) {
  134. const item = segment.trim();
  135. const range = item.match(/^(\d+)\s*[-–—]\s*(\d+)$/);
  136. if (range) {
  137. for (let week = parseInt(range[1], 10); week <= parseInt(range[2], 10); week++) result.weeks.push(week);
  138. } else if (/^\d+$/.test(item)) {
  139. result.weeks.push(parseInt(item, 10));
  140. }
  141. });
  142. if (parity) {
  143. result.weeks = result.weeks.filter(function (week) { return week % 2 === (parity === 1 ? 1 : 0); });
  144. }
  145. result.weeks = Array.from(new Set(result.weeks)).sort(function (a, b) { return a - b; });
  146. const sectionMatch = content.match(/\[([^\]]*)\]/);
  147. if (sectionMatch) {
  148. (sectionMatch[1].match(/\d+/g) || []).forEach(function (number) {
  149. const section = parseInt(number, 10);
  150. if (result.sections.indexOf(section) < 0) result.sections.push(section);
  151. });
  152. result.sections.sort(function (a, b) { return a - b; });
  153. }
  154. return result;
  155. }
  156. function parseTimetable(doc) {
  157. const table = doc.getElementById('timetable');
  158. if (!table) throw new Error('未获取到课表,请确认已登录新教务系统。');
  159. const courses = [];
  160. Array.from(table.querySelectorAll('tr')).forEach(function (row) {
  161. const cells = row.querySelectorAll('td');
  162. if (cells.length !== 7) return;
  163. cells.forEach(function (cell, index) {
  164. const detail = cell.querySelector('div.kbcontent');
  165. if (!detail) throw new Error('课表详表结构不匹配。');
  166. const content = detail.cloneNode(true);
  167. // 悬浮信息在详表里是重复的,只解析详表字段
  168. content.querySelectorAll('.item-box').forEach(function (node) { node.remove(); });
  169. if (!content.textContent.trim()) return;
  170. content.innerHTML.split(/-{10,}\s*<br\s*\/?>/i).forEach(function (html) {
  171. const block = doc.createElement('div');
  172. block.innerHTML = html;
  173. const name = block.querySelector('font:not([title])');
  174. const teacher = block.querySelector('font[title="教师"]');
  175. const time = block.querySelector('font[title="周次(节次)"]');
  176. const position = block.querySelector('font[title="教室"]');
  177. const building = block.querySelector('font[title="教学楼"]');
  178. if (!name || !teacher || !time || !position || !building) throw new Error('课程字段结构不匹配。');
  179. const parsed = parseWeeksAndSections(time.textContent);
  180. if (!name.textContent.trim() || parsed.weeks.length === 0 || parsed.sections.length === 0) {
  181. throw new Error('课程名称、周次或节次为空。');
  182. }
  183. courses.push({
  184. name: name.textContent.trim(),
  185. teacher: teacher.textContent.trim(),
  186. position: position.textContent.trim(),
  187. building: building.textContent.trim(),
  188. day: index + 1,
  189. weeks: parsed.weeks,
  190. startSection: parsed.sections[0],
  191. endSection: parsed.sections[parsed.sections.length - 1]
  192. });
  193. });
  194. });
  195. });
  196. return courses;
  197. }
  198. // 课程合并与去重(连续节次合并、同节次周次合并、完全重复剔除)
  199. function mergeAndDistinctCourses(courses) {
  200. if (!Array.isArray(courses) || courses.length <= 1) return courses;
  201. const list = courses.map(c => ({
  202. ...c,
  203. name: c.name || '',
  204. teacher: c.teacher || '',
  205. position: c.position || '',
  206. weeks: Array.isArray(c.weeks) ? [...c.weeks].sort((a, b) => a - b) : []
  207. }));
  208. list.sort((a, b) => {
  209. return a.name.localeCompare(b.name) ||
  210. a.teacher.localeCompare(b.teacher) ||
  211. a.position.localeCompare(b.position) ||
  212. (a.day || 0) - (b.day || 0) ||
  213. a.weeks.join(',').localeCompare(b.weeks.join(',')) ||
  214. (a.startSection || 0) - (b.startSection || 0);
  215. });
  216. const step1Merged = [];
  217. let current = list[0];
  218. for (let i = 1; i < list.length; i++) {
  219. const next = list[i];
  220. const isSameCourseAndWeeks =
  221. current.name === next.name &&
  222. current.teacher === next.teacher &&
  223. current.position === next.position &&
  224. current.day === next.day &&
  225. current.weeks.join(',') === next.weeks.join(',');
  226. const isContinuous = current.endSection + 1 === next.startSection;
  227. const isDuplicate = current.startSection === next.startSection && current.endSection === next.endSection;
  228. if (isSameCourseAndWeeks && isContinuous) {
  229. current.endSection = next.endSection;
  230. } else if (isSameCourseAndWeeks && isDuplicate) {
  231. continue;
  232. } else {
  233. step1Merged.push(current);
  234. current = next;
  235. }
  236. }
  237. step1Merged.push(current);
  238. step1Merged.sort((a, b) => {
  239. return a.name.localeCompare(b.name) ||
  240. a.teacher.localeCompare(b.teacher) ||
  241. a.position.localeCompare(b.position) ||
  242. (a.day || 0) - (b.day || 0) ||
  243. (a.startSection || 0) - (b.startSection || 0) ||
  244. (a.endSection || 0) - (b.endSection || 0);
  245. });
  246. const step2Merged = [];
  247. let merged = step1Merged[0];
  248. for (let i = 1; i < step1Merged.length; i++) {
  249. const next = step1Merged[i];
  250. const isSameCourseAndSection =
  251. merged.name === next.name &&
  252. merged.teacher === next.teacher &&
  253. merged.position === next.position &&
  254. merged.day === next.day &&
  255. merged.startSection === next.startSection &&
  256. merged.endSection === next.endSection;
  257. if (isSameCourseAndSection) {
  258. merged.weeks = Array.from(new Set([...merged.weeks, ...next.weeks])).sort((a, b) => a - b);
  259. } else {
  260. step2Merged.push(merged);
  261. merged = next;
  262. }
  263. }
  264. step2Merged.push(merged);
  265. return step2Merged;
  266. }
  267. // 教学周历:行首为周次,第 1 周第 2 格的日期即开学日
  268. function parseCalendar(doc) {
  269. const result = { semesterStartDate: null, totalWeeks: null };
  270. const table = doc.querySelector('table');
  271. if (!table) return result;
  272. const toDate = function (text) {
  273. const match = String(text || '').match(/(\d{4})\s*[-年]\s*(\d{1,2})\s*[-月]\s*(\d{1,2})/);
  274. return match ? match[1] + '-' + match[2].padStart(2, '0') + '-' + match[3].padStart(2, '0') : null;
  275. };
  276. Array.from(table.querySelectorAll('tr')).forEach(function (row) {
  277. const cells = Array.from(row.children);
  278. const first = cells.length > 0 ? String(cells[0].textContent).trim() : '';
  279. if (!/^\d+$/.test(first)) return;
  280. const week = parseInt(first, 10);
  281. result.totalWeeks = result.totalWeeks === null ? week : Math.max(result.totalWeeks, week);
  282. if (week === 1 && !result.semesterStartDate && cells.length > 1) {
  283. result.semesterStartDate = toDate(cells[1].getAttribute('title')) || toDate(cells[1].textContent);
  284. }
  285. });
  286. return result;
  287. }
  288. async function fetchCourseConfig(semesterValue) {
  289. const response = await fetch(GDCP_CALENDAR_URL, {
  290. method: 'POST',
  291. headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
  292. body: new URLSearchParams({ xnxq01id: semesterValue }).toString(),
  293. credentials: 'include'
  294. });
  295. if (!response.ok) throw new Error('教学周历请求失败(HTTP ' + response.status + ')。');
  296. const doc = new DOMParser().parseFromString(await response.text(), 'text/html');
  297. const returned = doc.getElementById('xnxq01id');
  298. if (!returned || returned.value !== semesterValue) throw new Error('返回周历与所选学期不一致。');
  299. const calendar = parseCalendar(doc);
  300. const totalWeeks = calendar.totalWeeks;
  301. if (!calendar.semesterStartDate || !Number.isInteger(totalWeeks) || totalWeeks < 1) {
  302. throw new Error('教学周历未提供完整的首周日期或总周数。');
  303. }
  304. const monday = new Date(calendar.semesterStartDate + 'T00:00:00Z');
  305. const isMonday = !Number.isNaN(monday.getTime()) && monday.getUTCDay() === 1 &&
  306. monday.toISOString().slice(0, 10) === calendar.semesterStartDate;
  307. if (!isMonday) throw new Error('教学周历第 1 周的星期一日期无效。');
  308. return {
  309. semesterStartDate: calendar.semesterStartDate,
  310. semesterTotalWeeks: totalWeeks,
  311. firstDayOfWeek: 1,
  312. defaultClassDuration: 40,
  313. defaultBreakDuration: 5
  314. };
  315. }
  316. async function runImportFlow() {
  317. try {
  318. if (window.location.origin !== GDCP_ORIGIN) {
  319. await window.shiguangBridgePromise.showAlert(
  320. '请先登录教务系统',
  321. '请先登录教务系统后再执行导入。',
  322. '知道了'
  323. );
  324. return;
  325. }
  326. window.shiguangBridge.showToast('正在获取学期信息...');
  327. const initialDoc = await fetchTimetableDoc();
  328. const semesterSelect = initialDoc.getElementById('xnxq01id');
  329. const modeSelect = initialDoc.getElementById('kbjcmsid');
  330. if (!semesterSelect || semesterSelect.options.length === 0 || !modeSelect || !modeSelect.value) {
  331. throw new Error('未获取到学期或节次模式,请确认教务登录状态。');
  332. }
  333. const semesters = Array.from(semesterSelect.options);
  334. const picked = await window.shiguangBridgePromise.showSingleSelection(
  335. '选择学期',
  336. JSON.stringify(semesters.map(function (option) { return option.textContent.trim(); })),
  337. semesterSelect.selectedIndex
  338. );
  339. if (picked === null) return;
  340. if (!Number.isInteger(picked) || picked < 0 || picked >= semesters.length) throw new Error('学期选择无效。');
  341. const semesterValue = semesters[picked].value;
  342. const parameters = new URLSearchParams({
  343. cj0701id: '', zc: '', demo: '', xnxq01id: semesterValue, sfFD: '1', kbjcmsid: modeSelect.value
  344. });
  345. window.shiguangBridge.showToast('正在获取整学期课表...');
  346. const doc = await fetchTimetableDoc(parameters);
  347. const returned = doc.getElementById('xnxq01id');
  348. if (!returned || returned.value !== semesterValue) throw new Error('返回课表与所选学期不一致。');
  349. const parsedCourses = mergeAndDistinctCourses(parseTimetable(doc));
  350. if (!parsedCourses.length) { window.shiguangBridge.showToast('该学期暂无课程。'); return; }
  351. // 不弹校区选择:按教学楼判断校区,两组作息中课程较多的一套作为默认作息
  352. const campus = dominantCampus(parsedCourses);
  353. const groupCount = { early: 0, late: 0 };
  354. parsedCourses.forEach(function (course) { groupCount[scheduleOf(campus, course.building)]++; });
  355. const majority = groupCount.early >= groupCount.late ? 'early' : 'late';
  356. const minority = majority === 'early' ? 'late' : 'early';
  357. const minoritySlots = minority === 'late' ? GDCP_LATE_TIME_SLOTS : GDCP_TIME_SLOTS;
  358. let customCount = 0;
  359. const courses = parsedCourses.map(function ({ building, ...course }) {
  360. if (scheduleOf(campus, building) !== minority) return course;
  361. customCount++;
  362. return applyGroupTime(course, minoritySlots);
  363. });
  364. window.shiguangBridge.showToast('正在获取所选学期的教学周历...');
  365. const config = await fetchCourseConfig(semesterValue);
  366. await window.shiguangBridgePromise.saveCourseConfig(JSON.stringify(config));
  367. await window.shiguangBridgePromise.savePresetTimeSlots(JSON.stringify(majority === 'late' ? GDCP_LATE_TIME_SLOTS : GDCP_TIME_SLOTS));
  368. await window.shiguangBridgePromise.saveImportedCourses(JSON.stringify(courses));
  369. window.shiguangBridge.showToast('导入成功:' + courses.length + ' 条 · ' + campus.name + ' · 默认' +
  370. (majority === 'late' ? '10:30' : '10:10') + (customCount ? ' · 自定义 ' + customCount + ' 条' : ''));
  371. window.shiguangBridge.notifyTaskCompletion();
  372. } catch (error) {
  373. window.shiguangBridge.showToast('导入失败:' + error.message);
  374. console.error('JS: Import Error', error);
  375. }
  376. }
  377. runImportFlow();