hebeu.js 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488
  1. // 河北工程大学 (hebeu.edu.cn) 拾光课程表适配脚本
  2. // 教务系统:正方教务 v9(新版 UI zftal-ui-v5),根路径部署
  3. // 与常见 /jwglxt 部署相比仅前缀不同:/xtgl,接口路径与页面结构一致
  4. // 登录地址:https://jwglxxfwpt.hebeu.edu.cn/xtgl/login_slogin.html
  5. // 课表、校历与作息均通过接口获取,不解析当前页面 DOM,登录后停留在任意教务页面即可导入
  6. // 参考 resources/JSEI/jsei_01.js(正方 v9 案例)、resources/CJLU/cjlu.js
  7. var HEBEU_OPTIONS_URL = 'kbcx/xskbcx_cxXskbcxIndex.html?gnmkdm=N2151&layout=default';
  8. // 正方 v9 根路径部署:仅将 /jwglxt 换成 /xtgl,其余接口与页面结构一致
  9. function getBaseUrl() {
  10. return window.location.origin + '/';
  11. }
  12. // ==================== 文本 / 时间 ====================
  13. function normalizeText(value) {
  14. return String(value == null ? '' : value)
  15. .replace(/[!-~]/g, function (c) { return String.fromCharCode(c.charCodeAt(0) - 65248); })
  16. .replace(/\u3000/g, ' ')
  17. .replace(/[~~—–]/g, '-');
  18. }
  19. function normalizeTime(value) {
  20. const match = normalizeText(value).trim().match(/^(\d{1,2}):(\d{2})(?::(\d{2}))?$/);
  21. if (!match) throw new Error('无法识别时间:' + value);
  22. return String(match[1]).padStart(2, '0') + ':' + match[2];
  23. }
  24. // ==================== 桥接封装 ====================
  25. function toast(message) {
  26. if (window.shiguangBridge && typeof window.shiguangBridge.showToast === 'function') {
  27. window.shiguangBridge.showToast(message);
  28. }
  29. }
  30. async function alertUser(title, message, confirmText) {
  31. if (window.shiguangBridgePromise && typeof window.shiguangBridgePromise.showAlert === 'function') {
  32. const confirmed = await window.shiguangBridgePromise.showAlert(title, message, confirmText || '知道了');
  33. return !!confirmed;
  34. }
  35. alert(title + '\n' + message);
  36. return true;
  37. }
  38. // ==================== 请求 ====================
  39. async function requestJw(path, params, moduleId) {
  40. const response = await fetch(getBaseUrl() + path + '?gnmkdm=' + encodeURIComponent(moduleId), {
  41. method: 'POST',
  42. credentials: 'same-origin',
  43. headers: {
  44. 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
  45. 'Accept': 'application/json',
  46. 'X-Requested-With': 'XMLHttpRequest'
  47. },
  48. body: new URLSearchParams(params).toString()
  49. });
  50. if (!response.ok) throw new Error('教务请求失败(HTTP ' + response.status + ')');
  51. const text = await response.text();
  52. try {
  53. return JSON.parse(text);
  54. } catch (e) {
  55. if (/login_slogin|用户登录|统一身份认证/i.test(text)) {
  56. throw new Error('登录已过期,请重新登录教务系统后再导入');
  57. }
  58. throw new Error('教务未返回 JSON 数据,请重新登录后重试');
  59. }
  60. }
  61. // ==================== 校历:开学日期 + 总周数 ====================
  62. function parseSemesterConfig(rows) {
  63. const config = {};
  64. if (!Array.isArray(rows) || rows.length === 0) return config;
  65. let first = null, max = 0;
  66. const weeks = new Set();
  67. rows.forEach(function (row) {
  68. const match = normalizeText(row.zs == null ? row.zsmc : row.zs).trim().match(/^(?:第)?(\d+)(?:周)?$/);
  69. if (!match || +match[1] < 1) return;
  70. const week = +match[1];
  71. weeks.add(week);
  72. max = Math.max(max, week);
  73. if (week === 1) first = row;
  74. });
  75. const sorted = Array.from(weeks).sort(function (a, b) { return a - b; });
  76. let continuous = sorted.length > 0;
  77. for (let i = 1; i < sorted.length; i++) {
  78. if (sorted[i] - sorted[i - 1] !== 1) { continuous = false; break; }
  79. }
  80. // 仅接受连续且最大周次在 10~60 的校历,避免把整年周历当成学期
  81. if (continuous && max >= 10 && max <= 60) config.semesterTotalWeeks = max;
  82. if (first) {
  83. // 注意:正方部分页面重写了 Array.prototype.filter/some/every,这里一律用普通循环
  84. const keys = ['rq', 'zcrq', 'ksrq'];
  85. for (let i = 0; i < keys.length; i++) {
  86. const match = normalizeText(first[keys[i]]).match(/(\d{4})-(\d{1,2})-(\d{1,2})/);
  87. if (match) {
  88. config.semesterStartDate = match[1] + '-' + String(match[2]).padStart(2, '0') + '-' + String(match[3]).padStart(2, '0');
  89. break;
  90. }
  91. }
  92. }
  93. return config;
  94. }
  95. async function fetchSemesterConfig(year, term, warnings) {
  96. try {
  97. return parseSemesterConfig(await requestJw('kbcx/xskbcxZccx_cxZcByXnxq.html', { xnm: year, xqm: term }, 'N2154'));
  98. } catch (error) {
  99. warnings.push('校历获取失败:' + error.message);
  100. return {};
  101. }
  102. }
  103. // ==================== 作息 ====================
  104. // 兜底作息(2026-2027 学年第 1 学期自教务作息接口实测,xqh_id=108)
  105. var HEBEU_FALLBACK_TIME_SLOTS = [
  106. { number: 1, startTime: '08:30', endTime: '09:15' },
  107. { number: 2, startTime: '09:20', endTime: '10:05' },
  108. { number: 3, startTime: '10:25', endTime: '11:10' },
  109. { number: 4, startTime: '11:15', endTime: '12:00' },
  110. { number: 5, startTime: '14:00', endTime: '14:45' },
  111. { number: 6, startTime: '14:50', endTime: '15:35' },
  112. { number: 7, startTime: '15:55', endTime: '16:40' },
  113. { number: 8, startTime: '16:45', endTime: '17:30' },
  114. { number: 9, startTime: '19:00', endTime: '19:45' },
  115. { number: 10, startTime: '19:50', endTime: '20:35' }
  116. ];
  117. function parseTimeSlots(data) {
  118. if (!Array.isArray(data) || data.length === 0) throw new Error('未收到有效的作息列表');
  119. const byNumber = new Map();
  120. data.forEach(function (row) {
  121. const section = normalizeText(row.jcmc).trim();
  122. const number = +section;
  123. if (!/^\d+$/.test(section) || number < 1 || number > 30) return;
  124. const startTime = normalizeTime(row.qssj);
  125. const endTime = normalizeTime(row.jssj);
  126. const existing = byNumber.get(number);
  127. if (existing) {
  128. if (existing.startTime === startTime && existing.endTime === endTime) return;
  129. throw new Error('第 ' + number + ' 节返回不同时间:' + existing.startTime + '-' + existing.endTime + ' 与 ' + startTime + '-' + endTime);
  130. }
  131. byNumber.set(number, { number: number, startTime: startTime, endTime: endTime });
  132. });
  133. const slots = Array.from(byNumber.values()).sort(function (a, b) { return a.number - b.number; });
  134. if (slots.length === 0) throw new Error('作息列表无法解析');
  135. return slots;
  136. }
  137. async function fetchTimeSlots(year, term, campusId, warnings) {
  138. try {
  139. const params = { xnm: year, xqm: term };
  140. if (campusId) params.xqh_id = campusId;
  141. return parseTimeSlots(await requestJw('jzgl/skxxMobile_cxRsdjc.html', params, 'N2154'));
  142. } catch (error) {
  143. warnings.push('作息获取失败:' + error.message);
  144. return null;
  145. }
  146. }
  147. // ==================== 周次 / 课程解析 ====================
  148. function parseWeeks(value) {
  149. const weeks = new Set();
  150. // 清理 "第" 与 "共 N 周" 等修饰,统一全角标点和分隔符
  151. const text = normalizeText(value)
  152. .replace(/周数[::]/g, '')
  153. .replace(/第/g, '')
  154. .replace(/周/g, '')
  155. .replace(/共\s*\d+\s*.*$/g, '')
  156. .replace(/(/g, '(').replace(/)/g, ')')
  157. .replace(/[,、;;]/g, ',');
  158. text.split(',').forEach(function (part) {
  159. // 段内可能混合多种写法(如 "5-7(单)8-15"),逐段扫描而非整段匹配
  160. const segment = part.trim();
  161. if (!segment) return;
  162. const segmentRegex = /(\d+)(?:\s*[-~]\s*(\d+))?\s*(?:\(?\s*([单双])\s*周?\s*\)?)?/g;
  163. let match;
  164. while ((match = segmentRegex.exec(segment)) !== null) {
  165. if (match[0] === '') { segmentRegex.lastIndex++; continue; }
  166. const start = +match[1], end = +(match[2] || match[1]);
  167. if (start < 1 || end < start || end > 60) continue;
  168. for (let week = start; week <= end; week++) {
  169. if (match[3] === '单' && week % 2 === 0) continue;
  170. if (match[3] === '双' && week % 2 === 1) continue;
  171. weeks.add(week);
  172. }
  173. }
  174. });
  175. return Array.from(weeks).sort(function (a, b) { return a - b; });
  176. }
  177. // 节次与周次合并去重函数(官方 wiki 实现,逐字未改)
  178. function mergeAndDistinctCourses(courses) {
  179. if (!Array.isArray(courses) || courses.length <= 1) return courses;
  180. const list = courses.map(c => ({
  181. ...c,
  182. name: c.name || '',
  183. teacher: c.teacher || '',
  184. position: c.position || '',
  185. weeks: Array.isArray(c.weeks) ? [...c.weeks].sort((a, b) => a - b) : []
  186. }));
  187. list.sort((a, b) => {
  188. return a.name.localeCompare(b.name) ||
  189. a.teacher.localeCompare(b.teacher) ||
  190. a.position.localeCompare(b.position) ||
  191. (a.day || 0) - (b.day || 0) ||
  192. a.weeks.join(',').localeCompare(b.weeks.join(',')) ||
  193. (a.startSection || 0) - (b.startSection || 0);
  194. });
  195. const step1Merged = [];
  196. let current = list[0];
  197. for (let i = 1; i < list.length; i++) {
  198. const next = list[i];
  199. const isSameCourseAndWeeks =
  200. current.name === next.name &&
  201. current.teacher === next.teacher &&
  202. current.position === next.position &&
  203. current.day === next.day &&
  204. current.weeks.join(',') === next.weeks.join(',');
  205. const isContinuous = current.endSection + 1 === next.startSection;
  206. const isDuplicate = current.startSection === next.startSection && current.endSection === next.endSection;
  207. if (isSameCourseAndWeeks && isContinuous) {
  208. current.endSection = next.endSection;
  209. } else if (isSameCourseAndWeeks && isDuplicate) {
  210. continue;
  211. } else {
  212. step1Merged.push(current);
  213. current = next;
  214. }
  215. }
  216. step1Merged.push(current);
  217. step1Merged.sort((a, b) => {
  218. return a.name.localeCompare(b.name) ||
  219. a.teacher.localeCompare(b.teacher) ||
  220. a.position.localeCompare(b.position) ||
  221. (a.day || 0) - (b.day || 0) ||
  222. (a.startSection || 0) - (b.startSection || 0) ||
  223. (a.endSection || 0) - (b.endSection || 0);
  224. });
  225. const step2Merged = [];
  226. let merged = step1Merged[0];
  227. for (let i = 1; i < step1Merged.length; i++) {
  228. const next = step1Merged[i];
  229. const isSameCourseAndSection =
  230. merged.name === next.name &&
  231. merged.teacher === next.teacher &&
  232. merged.position === next.position &&
  233. merged.day === next.day &&
  234. merged.startSection === next.startSection &&
  235. merged.endSection === next.endSection;
  236. if (isSameCourseAndSection) {
  237. merged.weeks = Array.from(new Set([...merged.weeks, ...next.weeks])).sort((a, b) => a - b);
  238. } else {
  239. step2Merged.push(merged);
  240. merged = next;
  241. }
  242. }
  243. step2Merged.push(merged);
  244. return step2Merged;
  245. }
  246. function parseCourses(data, warnings) {
  247. if (!data || !Array.isArray(data.kbList)) throw new Error('未收到课表数据,请确认登录状态');
  248. const courses = [];
  249. data.kbList.forEach(function (row) {
  250. try {
  251. const name = String(row.kcmc || '').trim();
  252. const section = normalizeText(row.jcs || row.jc).match(/^(\d+)\s*(?:-\s*(\d+))?\s*节?$/);
  253. const day = +normalizeText(row.xqj);
  254. if (!name || !section || !/^[1-7]$/.test(String(day))) throw new Error('排课信息异常');
  255. const weeks = parseWeeks(row.zcd);
  256. if (weeks.length === 0) throw new Error('周次为空');
  257. const startSection = +section[1], endSection = +(section[2] || section[1]);
  258. if (startSection < 1 || endSection < startSection) throw new Error('节次异常');
  259. const credit = parseFloat(row.xf);
  260. const course = {
  261. name: name,
  262. teacher: String(row.xm || '').trim(),
  263. position: String(row.cdmc || '').trim(),
  264. day: day,
  265. startSection: startSection,
  266. endSection: endSection,
  267. weeks: weeks
  268. };
  269. if (!isNaN(credit) && credit > 0) course.credit = credit;
  270. courses.push(course);
  271. } catch (error) {
  272. warnings.push('跳过课程 ' + String(row && row.kcmc || '未命名') + ':' + error.message);
  273. }
  274. });
  275. return mergeAndDistinctCourses(courses);
  276. }
  277. // ==================== 学年 / 学期选择 ====================
  278. function getDefaultOptionIndex(options, key) {
  279. const match = function (value) {
  280. const text = String(value == null ? '' : value).trim();
  281. if (!text) return -1;
  282. for (let i = 0; i < options.length; i++) if (options[i].value === text) return i;
  283. return -1;
  284. };
  285. let index = match(window[key]);
  286. if (index >= 0) return index;
  287. try {
  288. index = match(new URL(window.location.href).searchParams.get(key));
  289. if (index >= 0) return index;
  290. } catch (e) { /* ignore */ }
  291. const selected = options.findIndex(function (option) { return option.selected; });
  292. return selected >= 0 ? selected : 0;
  293. }
  294. function parseAcademicOptions(doc) {
  295. const read = function (selector) {
  296. const list = [];
  297. const nodes = doc.querySelectorAll(selector);
  298. for (let i = 0; i < nodes.length; i++) {
  299. const value = String(nodes[i].value).trim();
  300. if (nodes[i].disabled || value === '') continue;
  301. list.push({ value: value, text: nodes[i].textContent.trim(), selected: nodes[i].selected });
  302. }
  303. return list;
  304. };
  305. const years = read('#xnm option');
  306. const terms = read('#xqm option');
  307. if (years.length === 0 || terms.length === 0) throw new Error('未获取到学年学期选项,请确认已登录教务系统后重试');
  308. const selectedYear = getDefaultOptionIndex(years, 'xnm');
  309. const start = Math.max(0, selectedYear - 2);
  310. const yearOptions = years.slice(start, selectedYear + 3);
  311. return {
  312. yearOptions: yearOptions,
  313. termOptions: terms,
  314. defaultYearIndex: selectedYear - start,
  315. defaultTermIndex: getDefaultOptionIndex(terms, 'xqm')
  316. };
  317. }
  318. async function fetchAcademicOptions() {
  319. const response = await fetch(getBaseUrl() + HEBEU_OPTIONS_URL, { method: 'GET', credentials: 'same-origin' });
  320. if (!response.ok) throw new Error('获取学年学期失败(HTTP ' + response.status + ')');
  321. const html = await response.text();
  322. return parseAcademicOptions(new DOMParser().parseFromString(html, 'text/html'));
  323. }
  324. async function selectAcademicYearAndSemester(bridge) {
  325. const options = await fetchAcademicOptions();
  326. const select = async function (title, entries, defaultIndex) {
  327. const result = await bridge.showSingleSelection(title, JSON.stringify(entries.map(function (item) { return item.text; })), defaultIndex);
  328. if (result === null || result === undefined || String(result).trim() === 'null') return null;
  329. const index = parseInt(result, 10);
  330. return entries[index] || null;
  331. };
  332. const make = function (year, term) { return { year: year.value, term: term.value, label: year.text + ' / ' + term.text }; };
  333. const defaultSelection = make(options.yearOptions[options.defaultYearIndex], options.termOptions[options.defaultTermIndex]);
  334. const action = await select('选择导入学期', [
  335. { value: 'default', text: '导入默认学期:' + defaultSelection.label },
  336. { value: 'change', text: '更换学年、学期' }
  337. ], 0);
  338. if (!action) return null;
  339. if (action.value === 'default') return defaultSelection;
  340. const year = await select('选择学年', options.yearOptions, options.defaultYearIndex);
  341. if (!year) return null;
  342. const term = await select('选择学期', options.termOptions, options.defaultTermIndex);
  343. if (!term) return null;
  344. return make(year, term);
  345. }
  346. // ==================== 保存 ====================
  347. async function saveWithConfirmation(method, data, label) {
  348. const result = await window.shiguangBridgePromise[method](JSON.stringify(data));
  349. if (!result) throw new Error(label + '保存未成功,请重试');
  350. }
  351. // ==================== 流程编排 ====================
  352. async function runImportFlow() {
  353. const bridge = window.shiguangBridgePromise;
  354. let coursesSaved = false;
  355. let saveStage = '课程';
  356. try {
  357. if (!/hebeu\.edu\.cn$/i.test(window.location.hostname)) {
  358. await alertUser('请先进入教务系统', '请登录河北工程大学教务系统后,停留在任意教务页面再执行导入。');
  359. return;
  360. }
  361. const startAlert = await alertUser('河北工程大学课表导入', '导入前请确保已登录教务系统。', '开始导入');
  362. if (!startAlert) { toast('导入已取消'); return; }
  363. const selection = await selectAcademicYearAndSemester(bridge);
  364. if (!selection) { toast('导入已取消'); return; }
  365. const warnings = [];
  366. toast('正在获取课程、校历和作息…');
  367. const kbData = await requestJw('kbcx/xskbcx_cxXsgrkb.html', {
  368. xnm: selection.year, xqm: selection.term, kzlx: 'ck', xsdm: '', kclbdm: '', kclxdm: ''
  369. }, 'N2151');
  370. // 先判空:未排课的学期(含尚未开放的未来学期)直接提示,不再拉作息
  371. const kbList = Array.isArray(kbData.kbList) ? kbData.kbList : [];
  372. if (kbList.length === 0) {
  373. await alertUser('该学期暂无课程', selection.label + ' 未查询到课程数据。\n\n如该学期尚未选课或课表未发布,请稍后再试或更换学期。', '确定');
  374. return;
  375. }
  376. let campusId = '';
  377. for (let i = 0; i < kbList.length; i++) {
  378. if (kbList[i].xqh_id) { campusId = kbList[i].xqh_id; break; }
  379. }
  380. const configResult = await Promise.all([
  381. fetchSemesterConfig(selection.year, selection.term, warnings),
  382. fetchTimeSlots(selection.year, selection.term, campusId, warnings)
  383. ]);
  384. const config = configResult[0];
  385. let slots = configResult[1];
  386. if (!slots || !slots.length) {
  387. slots = HEBEU_FALLBACK_TIME_SLOTS;
  388. warnings.push('已使用内置作息,如与本校实际作息不符请反馈');
  389. }
  390. let courses = parseCourses(kbData, warnings);
  391. // 校验节次覆盖,缺作息的节次在 App 里排不下,先剔除并提示(用普通循环,避开被改写的 filter)
  392. const numbers = new Set();
  393. for (let i = 0; i < slots.length; i++) numbers.add(slots[i].number);
  394. const kept = [];
  395. for (let i = 0; i < courses.length; i++) {
  396. const course = courses[i];
  397. let ok = true;
  398. for (let n = course.startSection; n <= course.endSection; n++) {
  399. if (!numbers.has(n)) { warnings.push('跳过课程 ' + course.name + ':第 ' + n + ' 节缺少作息'); ok = false; break; }
  400. }
  401. if (ok) kept.push(course);
  402. }
  403. courses = kept;
  404. if (courses.length === 0) throw new Error('课程解析后为空,请核对学期或联系适配维护者。' + (warnings.length ? '\n' + warnings.join('\n') : ''));
  405. // 总周数不能小于课程最大周次
  406. if (config.semesterTotalWeeks) {
  407. const maxWeek = Math.max.apply(null, courses.reduce(function (all, c) { return all.concat(c.weeks); }, [0]));
  408. if (maxWeek > config.semesterTotalWeeks) {
  409. warnings.push('校历总周数小于课程周次,未保存总周数');
  410. delete config.semesterTotalWeeks;
  411. }
  412. }
  413. const practices = Array.isArray(kbData.sjkList) ? kbData.sjkList : [];
  414. const practiceNote = practices.length
  415. ? '\n\n以下实践课无固定星期/节次,本次不导入:\n' + practices.map(function (row) { return String(row.kcmc || '未命名') + '(' + String(row.qsjsz || '周次未定') + ')'; }).join('\n')
  416. : '';
  417. const message = selection.label + '\n共 ' + courses.length + ' 条课程时段。\n\n作息:\n' +
  418. slots.map(function (s) { return '第' + s.number + '节 ' + s.startTime + '-' + s.endTime; }).join('\n') +
  419. '\n\n开学日期:' + (config.semesterStartDate || '需手动设置') +
  420. '\n学期总周数:' + (config.semesterTotalWeeks || '需手动设置') +
  421. practiceNote + (warnings.length ? '\n\n注意:\n' + warnings.join('\n') : '');
  422. const confirmed = await bridge.showAlert('核对课程与作息', message, '确认并保存');
  423. if (!confirmed) { toast('导入已取消'); return; }
  424. await saveWithConfirmation('saveImportedCourses', courses, '课程');
  425. coursesSaved = true;
  426. saveStage = '作息';
  427. await saveWithConfirmation('savePresetTimeSlots', slots, '作息');
  428. if (config.semesterStartDate || config.semesterTotalWeeks) {
  429. saveStage = '学期配置';
  430. await saveWithConfirmation('saveCourseConfig', Object.assign({ firstDayOfWeek: 1 }, config), '学期配置');
  431. }
  432. toast('已导入 ' + courses.length + ' 条课程时段及 ' + slots.length + ' 节作息');
  433. if (window.shiguangBridge && typeof window.shiguangBridge.notifyTaskCompletion === 'function') {
  434. window.shiguangBridge.notifyTaskCompletion();
  435. }
  436. } catch (error) {
  437. await alertUser('导入未完成', (coursesSaved ? '课程已保存,但' + saveStage + '未保存成功,请重试。\n' : '') + (error && error.message ? error.message : String(error)), '确定');
  438. }
  439. }
  440. runImportFlow();