gdcp_01.js 17 KB

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