gdcp_01.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358
  1. // 广东交通职业技术学院强智教务拾光适配脚本
  2. // 适配作者:小漫君
  3. // 接口与字段参考拾光 HNIU/hniu_01.js、HHTC/hhtc.js;悬浮详情处理参考 NJFU/njfu_01.js。
  4. // 周次与教学周历解析、合并去重沿用 QFNU/qfnu_01.js(Yumu-banxia)及官方 Wiki。
  5. // 校区选择、按教学楼设置课程独立时间参考 GDOU/gdou.js(Mccurtain)。
  6. // 上游:https://github.com/ShiGuangSchedule/shiguang_warehouse/tree/pending/resources
  7. // 以上参考实现按上游 MIT 许可复用;本校使用已确认的 xskb_list.do 接口与详表结构。
  8. const GDCP_TIMETABLE_URL = 'https://jw.gdcp.edu.cn/jsxsd/xskb/xskb_list.do';
  9. const GDCP_CALENDAR_URL = 'https://jw.gdcp.edu.cn/jsxsd/jxzl/jxzl_query';
  10. // 来源:学校《各校区上课作息时间表(新)》(用户提供)。
  11. // 第 7~8、9~10、11~12 节各为 80 分钟连堂,网格按每小节 40 分钟连续排列;课程保留整段实际时间。
  12. const GDCP_TIME_SLOTS = [
  13. { number: 1, startTime: '08:30', endTime: '09:10' },
  14. { number: 2, startTime: '09:15', endTime: '09:55' },
  15. { number: 3, startTime: '10:10', endTime: '10:50' },
  16. { number: 4, startTime: '10:55', endTime: '11:35' },
  17. { number: 5, startTime: '14:15', endTime: '14:55' },
  18. { number: 6, startTime: '15:00', endTime: '15:40' },
  19. { number: 7, startTime: '15:55', endTime: '16:35' },
  20. { number: 8, startTime: '16:35', endTime: '17:15' },
  21. { number: 9, startTime: '18:05', endTime: '18:45' },
  22. { number: 10, startTime: '18:45', endTime: '19:25' },
  23. { number: 11, startTime: '19:40', endTime: '20:20' },
  24. { number: 12, startTime: '20:20', endTime: '21:00' }
  25. ];
  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. const GDCP_CAMPUSES = [
  31. // 轨道楼(16#)未列入原表;用户明确确认第 3、4 节使用 10:10 起的作息。
  32. { name: '天河校区', early: ['9号楼', '10号楼', '12号楼', '图书馆', '公路楼', '汽车实训楼', '轨道楼'], late: ['2号楼', '运动场'] },
  33. { name: '花都校区', early: ['1号楼', '图书馆'], late: ['10号楼', '15号楼', '16号楼', '运动场'] },
  34. { name: '国际校区', early: ['教学楼', '运动场'], late: [] },
  35. { name: '清远校区', early: ['厚德楼', '明德楼', '立业楼', '创新楼', '求是楼', '笃实楼'], late: ['融新楼', '融创楼', '运动场', '体育馆'] }
  36. ];
  37. function applyCampusTimes(courses, campus) {
  38. return courses.map(function ({ building, ...course }) {
  39. if (course.startSection < 1 || course.endSection > GDCP_TIME_SLOTS.length) {
  40. throw new Error('学校作息表只提供第 1~12 节,课程“' + course.name + '”的节次超出范围。');
  41. }
  42. const slots = GDCP_TIME_SLOTS.slice();
  43. if (course.startSection <= 4 && course.endSection >= 3) {
  44. // 教务实测楼名含【】、编号前导零与校区后缀;操场对应学校作息表的运动场。
  45. const venue = building.replace(/[【】]/g, '').replace(/((?:天河|花都|国际|清远))$/, '')
  46. .replace(/^0+(\d+号楼)$/, '$1').replace(/^操场$/, '运动场');
  47. const matches = function (name) { return venue === name || venue.startsWith(name + '('); };
  48. if (!campus.early.some(matches)) {
  49. // 国际校区的“其他区域”是学校表格明确规定的第二套作息。
  50. if (!campus.late.some(matches) && campus.name !== '国际校区') {
  51. throw new Error(campus.name + '的“' + building + '”未列入学校作息表,无法确定第 3、4 节时间。');
  52. }
  53. slots[2] = GDCP_LATE_MORNING[0];
  54. slots[3] = GDCP_LATE_MORNING[1];
  55. }
  56. }
  57. // 学校将这三组小节分别视为一个完整时间块,不能按普通课间拆开。
  58. const startTime = course.startSection === 8 ? '15:55'
  59. : course.startSection === 10 ? '18:05'
  60. : course.startSection === 12 ? '19:40' : slots[course.startSection - 1].startTime;
  61. const endTime = course.endSection === 7 ? '17:15'
  62. : course.endSection === 9 ? '19:25'
  63. : course.endSection === 11 ? '21:00' : slots[course.endSection - 1].endTime;
  64. return {
  65. ...course,
  66. isCustomTime: true,
  67. customStartTime: startTime,
  68. customEndTime: endTime
  69. };
  70. });
  71. }
  72. async function fetchTimetableDoc(parameters) {
  73. const options = { credentials: 'include' };
  74. if (parameters !== undefined) {
  75. options.method = 'POST';
  76. options.headers = { 'Content-Type': 'application/x-www-form-urlencoded' };
  77. options.body = parameters.toString();
  78. }
  79. const response = await fetch(GDCP_TIMETABLE_URL, options);
  80. if (!response.ok) throw new Error('课表请求失败(HTTP ' + response.status + ')。');
  81. return new DOMParser().parseFromString(await response.text(), 'text/html');
  82. }
  83. // 来源:QFNU/qfnu_01.js,保留原实现。
  84. function parseWeeksAndSections(text) {
  85. const result = { weeks: [], sections: [] };
  86. const content = String(text || '').trim();
  87. if (!content) return result;
  88. const parity = /双/.test(content) ? 2 : (/单/.test(content) ? 1 : 0);
  89. const bracketIndex = content.indexOf('[');
  90. const cleaned = (bracketIndex >= 0 ? content.slice(0, bracketIndex) : content)
  91. .replace(/第/g, '')
  92. .replace(/至|到|~/g, '-')
  93. .replace(/[((][^()()]*[))]/g, '')
  94. .replace(/周/g, '');
  95. cleaned.split(/[,,、;;\s]+/).forEach(function (segment) {
  96. const item = segment.trim();
  97. const range = item.match(/^(\d+)\s*[-–—]\s*(\d+)$/);
  98. if (range) {
  99. for (let week = parseInt(range[1], 10); week <= parseInt(range[2], 10); week++) result.weeks.push(week);
  100. } else if (/^\d+$/.test(item)) {
  101. result.weeks.push(parseInt(item, 10));
  102. }
  103. });
  104. if (parity) {
  105. result.weeks = result.weeks.filter(function (week) { return week % 2 === (parity === 1 ? 1 : 0); });
  106. }
  107. result.weeks = Array.from(new Set(result.weeks)).sort(function (a, b) { return a - b; });
  108. const sectionMatch = content.match(/\[([^\]]*)\]/);
  109. if (sectionMatch) {
  110. (sectionMatch[1].match(/\d+/g) || []).forEach(function (number) {
  111. const section = parseInt(number, 10);
  112. if (result.sections.indexOf(section) < 0) result.sections.push(section);
  113. });
  114. result.sections.sort(function (a, b) { return a - b; });
  115. }
  116. return result;
  117. }
  118. function parseTimetable(doc) {
  119. const table = doc.getElementById('timetable');
  120. if (!table) throw new Error('未获取到课表,请确认已登录新教务系统。');
  121. const courses = [];
  122. Array.from(table.querySelectorAll('tr')).forEach(function (row) {
  123. const cells = row.querySelectorAll('td');
  124. if (cells.length !== 7) return;
  125. cells.forEach(function (cell, index) {
  126. const detail = cell.querySelector('div.kbcontent');
  127. if (!detail) throw new Error('课表详表结构不匹配。');
  128. const content = detail.cloneNode(true);
  129. // NJFU 同样移除重复的悬浮信息,只解析详表中的课程字段。
  130. content.querySelectorAll('.item-box').forEach(function (node) { node.remove(); });
  131. if (!content.textContent.trim()) return;
  132. content.innerHTML.split(/-{10,}\s*<br\s*\/?>/i).forEach(function (html) {
  133. const block = doc.createElement('div');
  134. block.innerHTML = html;
  135. const name = block.querySelector('font:not([title])');
  136. const teacher = block.querySelector('font[title="教师"]');
  137. const time = block.querySelector('font[title="周次(节次)"]');
  138. const position = block.querySelector('font[title="教室"]');
  139. const building = block.querySelector('font[title="教学楼"]');
  140. if (!name || !teacher || !time || !position || !building) throw new Error('课程字段结构不匹配。');
  141. const parsed = parseWeeksAndSections(time.textContent);
  142. if (!name.textContent.trim() || parsed.weeks.length === 0 || parsed.sections.length === 0) {
  143. throw new Error('课程名称、周次或节次为空。');
  144. }
  145. courses.push({
  146. name: name.textContent.trim(),
  147. teacher: teacher.textContent.trim(),
  148. position: position.textContent.trim(),
  149. building: building.textContent.trim(),
  150. day: index + 1,
  151. weeks: parsed.weeks,
  152. startSection: parsed.sections[0],
  153. endSection: parsed.sections[parsed.sections.length - 1]
  154. });
  155. });
  156. });
  157. });
  158. return courses;
  159. }
  160. // 来源:QFNU/qfnu_01.js / 官方 Wiki《课程合并与去重函数》,保留原实现。
  161. // https://github.com/ShiGuangSchedule/shiguangschedule/wiki/课程合并与去重函数
  162. function mergeAndDistinctCourses(courses) {
  163. if (!Array.isArray(courses) || courses.length <= 1) return courses;
  164. const list = courses.map(c => ({
  165. ...c,
  166. name: c.name || '',
  167. teacher: c.teacher || '',
  168. position: c.position || '',
  169. weeks: Array.isArray(c.weeks) ? [...c.weeks].sort((a, b) => a - b) : []
  170. }));
  171. list.sort((a, b) => {
  172. return a.name.localeCompare(b.name) ||
  173. a.teacher.localeCompare(b.teacher) ||
  174. a.position.localeCompare(b.position) ||
  175. (a.day || 0) - (b.day || 0) ||
  176. a.weeks.join(',').localeCompare(b.weeks.join(',')) ||
  177. (a.startSection || 0) - (b.startSection || 0);
  178. });
  179. const step1Merged = [];
  180. let current = list[0];
  181. for (let i = 1; i < list.length; i++) {
  182. const next = list[i];
  183. const isSameCourseAndWeeks =
  184. current.name === next.name &&
  185. current.teacher === next.teacher &&
  186. current.position === next.position &&
  187. current.day === next.day &&
  188. current.weeks.join(',') === next.weeks.join(',');
  189. const isContinuous = current.endSection + 1 === next.startSection;
  190. const isDuplicate = current.startSection === next.startSection && current.endSection === next.endSection;
  191. if (isSameCourseAndWeeks && isContinuous) {
  192. current.endSection = next.endSection;
  193. } else if (isSameCourseAndWeeks && isDuplicate) {
  194. continue;
  195. } else {
  196. step1Merged.push(current);
  197. current = next;
  198. }
  199. }
  200. step1Merged.push(current);
  201. step1Merged.sort((a, b) => {
  202. return a.name.localeCompare(b.name) ||
  203. a.teacher.localeCompare(b.teacher) ||
  204. a.position.localeCompare(b.position) ||
  205. (a.day || 0) - (b.day || 0) ||
  206. (a.startSection || 0) - (b.startSection || 0) ||
  207. (a.endSection || 0) - (b.endSection || 0);
  208. });
  209. const step2Merged = [];
  210. let merged = step1Merged[0];
  211. for (let i = 1; i < step1Merged.length; i++) {
  212. const next = step1Merged[i];
  213. const isSameCourseAndSection =
  214. merged.name === next.name &&
  215. merged.teacher === next.teacher &&
  216. merged.position === next.position &&
  217. merged.day === next.day &&
  218. merged.startSection === next.startSection &&
  219. merged.endSection === next.endSection;
  220. if (isSameCourseAndSection) {
  221. merged.weeks = Array.from(new Set([...merged.weeks, ...next.weeks])).sort((a, b) => a - b);
  222. } else {
  223. step2Merged.push(merged);
  224. merged = next;
  225. }
  226. }
  227. step2Merged.push(merged);
  228. return step2Merged;
  229. }
  230. // 教学周历解析来源:QFNU/qfnu_01.js(Yumu-banxia),保留原实现。
  231. function parseCalendar(doc) {
  232. const result = { semesterStartDate: null, totalWeeks: null };
  233. const table = doc.querySelector('table');
  234. if (!table) return result;
  235. const toDate = function (text) {
  236. const match = String(text || '').match(/(\d{4})\s*[-年]\s*(\d{1,2})\s*[-月]\s*(\d{1,2})/);
  237. return match ? match[1] + '-' + match[2].padStart(2, '0') + '-' + match[3].padStart(2, '0') : null;
  238. };
  239. Array.from(table.querySelectorAll('tr')).forEach(function (row) {
  240. const cells = Array.from(row.children);
  241. const first = cells.length > 0 ? String(cells[0].textContent).trim() : '';
  242. if (!/^\d+$/.test(first)) return;
  243. const week = parseInt(first, 10);
  244. result.totalWeeks = result.totalWeeks === null ? week : Math.max(result.totalWeeks, week);
  245. if (week === 1 && !result.semesterStartDate && cells.length > 1) {
  246. result.semesterStartDate = toDate(cells[1].getAttribute('title')) || toDate(cells[1].textContent);
  247. }
  248. });
  249. return result;
  250. }
  251. async function fetchCourseConfig(semesterValue) {
  252. const response = await fetch(GDCP_CALENDAR_URL, {
  253. method: 'POST',
  254. headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
  255. body: new URLSearchParams({ xnxq01id: semesterValue }).toString(),
  256. credentials: 'include'
  257. });
  258. if (!response.ok) throw new Error('教学周历请求失败(HTTP ' + response.status + ')。');
  259. const doc = new DOMParser().parseFromString(await response.text(), 'text/html');
  260. if (doc.getElementById('xnxq01id')?.value !== semesterValue) throw new Error('返回周历与所选学期不一致。');
  261. const calendar = parseCalendar(doc);
  262. if (!calendar.semesterStartDate || !Number.isInteger(calendar.totalWeeks) || calendar.totalWeeks < 1) {
  263. throw new Error('教学周历未提供完整的首周日期或总周数。');
  264. }
  265. const monday = new Date(calendar.semesterStartDate + 'T00:00:00Z');
  266. if (Number.isNaN(monday.getTime()) || monday.toISOString().slice(0, 10) !== calendar.semesterStartDate || monday.getUTCDay() !== 1) {
  267. throw new Error('教学周历第 1 周的星期一日期无效。');
  268. }
  269. return {
  270. semesterStartDate: calendar.semesterStartDate,
  271. semesterTotalWeeks: calendar.totalWeeks,
  272. firstDayOfWeek: 1,
  273. defaultClassDuration: 40,
  274. defaultBreakDuration: 5
  275. };
  276. }
  277. async function runImportFlow() {
  278. try {
  279. if (window.location.origin !== 'https://jw.gdcp.edu.cn') {
  280. await window.shiguangBridgePromise.showAlert('请进入新教务系统', '请先登录融合门户,打开“新教务系统”后再导入。', '知道了');
  281. return;
  282. }
  283. window.shiguangBridge.showToast('正在获取学期信息…');
  284. const initialDoc = await fetchTimetableDoc();
  285. const semesterSelect = initialDoc.getElementById('xnxq01id');
  286. const modeSelect = initialDoc.getElementById('kbjcmsid');
  287. if (!semesterSelect || semesterSelect.options.length === 0 || !modeSelect || !modeSelect.value) {
  288. throw new Error('未获取到学期或节次模式,请确认教务登录状态。');
  289. }
  290. const semesters = Array.from(semesterSelect.options);
  291. const picked = await window.shiguangBridgePromise.showSingleSelection(
  292. '选择学期', JSON.stringify(semesters.map(function (option) { return option.textContent.trim(); })), semesterSelect.selectedIndex
  293. );
  294. if (picked === null) return;
  295. if (!Number.isInteger(picked) || picked < 0 || picked >= semesters.length) throw new Error('学期选择无效。');
  296. const parameters = new URLSearchParams({
  297. cj0701id: '', zc: '', demo: '', xnxq01id: semesters[picked].value, sfFD: '1', kbjcmsid: modeSelect.value
  298. });
  299. window.shiguangBridge.showToast('正在获取整学期课表…');
  300. const doc = await fetchTimetableDoc(parameters);
  301. if (doc.getElementById('xnxq01id')?.value !== semesters[picked].value) throw new Error('返回课表与所选学期不一致。');
  302. const parsedCourses = mergeAndDistinctCourses(parseTimetable(doc));
  303. if (parsedCourses.length === 0) {
  304. await window.shiguangBridgePromise.showAlert('该学期暂无课程', '所选学期没有已排定上课时间的课程。', '知道了');
  305. return;
  306. }
  307. const campusIndex = await window.shiguangBridgePromise.showSingleSelection(
  308. '选择上课校区', JSON.stringify(GDCP_CAMPUSES.map(function (campus) { return campus.name; })), 0
  309. );
  310. if (campusIndex === null) return;
  311. if (!Number.isInteger(campusIndex) || campusIndex < 0 || campusIndex >= GDCP_CAMPUSES.length) throw new Error('校区选择无效。');
  312. const courses = applyCampusTimes(parsedCourses, GDCP_CAMPUSES[campusIndex]);
  313. window.shiguangBridge.showToast('正在获取所选学期的教学周历…');
  314. const config = await fetchCourseConfig(semesters[picked].value);
  315. if (!await window.shiguangBridgePromise.saveCourseConfig(JSON.stringify(config))) throw new Error('课表配置保存失败。');
  316. if (!await window.shiguangBridgePromise.savePresetTimeSlots(JSON.stringify(GDCP_TIME_SLOTS))) throw new Error('作息时间保存失败。');
  317. if (!await window.shiguangBridgePromise.saveImportedCourses(JSON.stringify(courses))) throw new Error('课程保存失败。');
  318. window.shiguangBridge.showToast('已获取 ' + courses.length + ' 条课程时段,请校对上课时间。');
  319. window.shiguangBridge.notifyTaskCompletion();
  320. } catch (error) {
  321. await window.shiguangBridgePromise.showAlert('导入失败', error.message, '知道了');
  322. }
  323. }
  324. runImportFlow();