zust_01.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278
  1. // 浙江科技大学(zust.edu.cn)正方 V9 教务适配
  2. // 适配作者 / 维护者:小漫君
  3. // 接口及桥接选择参考 resources/JSEI/jsei_01.js(星河欲转);保留原 CJLU(ying-ck、salt-fishes)方案来源。
  4. // 本文件沿用仓库 MIT 许可证。
  5. function zustToast(message) {
  6. window.shiguangBridge.showToast(message);
  7. }
  8. function zustConfirmed(value) {
  9. return value === true || value === 'true';
  10. }
  11. function zustText(value) {
  12. return String(value == null ? '' : value).trim();
  13. }
  14. function zustBaseUrl() {
  15. const host = window.location.hostname;
  16. if (host !== 'https-newjwxt-zust-edu-cn-443.webvpn.zust.edu.cn' && host !== 'newjwxt.zust.edu.cn') {
  17. throw new Error('请登录 WebVPN,点击“教务系统”,进入教学管理信息服务平台后再导入。');
  18. }
  19. return window.location.origin + '/jwglxt/';
  20. }
  21. async function zustRequest(path, params, json = true) {
  22. const url = new URL(zustBaseUrl() + path);
  23. for (const key in params) url.searchParams.set(key, params[key]);
  24. const response = await fetch(url.toString(), {
  25. method: 'GET',
  26. credentials: 'same-origin',
  27. headers: { Accept: json ? 'application/json' : 'text/html' }
  28. });
  29. if (!response.ok) throw new Error('教务请求失败(HTTP ' + response.status + '),请稍后重试。');
  30. const text = await response.text();
  31. if (/authserver\/|login_slogin|site-nav\//i.test(response.url || '') || /<title[^>]*>\s*统一身份认证/.test(text)) {
  32. throw new Error('登录已过期,请通过 WebVPN 重新进入教务系统。');
  33. }
  34. if (!json) return text;
  35. try {
  36. return JSON.parse(text);
  37. } catch (error) {
  38. throw new Error('教务未返回有效数据,请确认已经进入教务系统并重新登录。');
  39. }
  40. }
  41. async function zustSelect(title, entries, defaultIndex) {
  42. const labels = [];
  43. for (const entry of entries) labels.push(entry.label);
  44. const value = await window.shiguangBridgePromise.showSingleSelection(title, JSON.stringify(labels), defaultIndex);
  45. if (value === null || value === undefined || value === 'null' || value === -1 || value === '-1') return null;
  46. if (!/^\d+$/.test(String(value)) || !entries[Number(value)]) throw new Error('学期或校区选择无效,请重新导入。');
  47. return entries[Number(value)];
  48. }
  49. async function zustFetchAcademicOptions() {
  50. const html = await zustRequest('kbcx/xskbcx_cxXskbcxIndex.html', { gnmkdm: 'N2151', layout: 'default' }, false);
  51. const responseDoc = new DOMParser().parseFromString(html, 'text/html');
  52. const read = function (selector) {
  53. const entries = [];
  54. for (const option of responseDoc.querySelectorAll(selector + ' option')) {
  55. if (!option.disabled && option.value.trim()) entries.push({ value: option.value.trim(), label: option.textContent.trim(), selected: option.selected });
  56. }
  57. if (entries.length === 0) throw new Error('未取得教务返回的学年学期列表,请确认登录状态。');
  58. return entries;
  59. };
  60. return { years: read('#xnm'), terms: read('#xqm') };
  61. }
  62. async function zustFetchCourses(semester) {
  63. const params = { gnmkdm: 'N2151', xnm: semester.year, xqm: semester.term, kzlx: 'ck', xsdm: '', kclbdm: '', kclxdm: '' };
  64. return zustRequest('kbcx/xskbcx_cxXsgrkb.html', params);
  65. }
  66. async function zustChooseSemester() {
  67. const options = await zustFetchAcademicOptions();
  68. let yearIndex = 0, termIndex = 0;
  69. for (let i = 0; i < options.years.length; i++) if (options.years[i].selected) yearIndex = i;
  70. for (let i = 0; i < options.terms.length; i++) if (options.terms[i].selected) termIndex = i;
  71. const make = function (year, term) { return { year: year.value, term: term.value, label: year.label + ' 第 ' + term.label + ' 学期' }; };
  72. const defaultSelection = make(options.years[yearIndex], options.terms[termIndex]);
  73. const action = await zustSelect('选择导入学期', [
  74. { label: defaultSelection.label, value: 'current' },
  75. { label: '更换学年、学期', value: 'change' }
  76. ], 0);
  77. if (!action) return null;
  78. if (action.value === 'current') return defaultSelection;
  79. const year = await zustSelect('选择学年', options.years, yearIndex);
  80. if (!year) return null;
  81. const term = await zustSelect('选择学期', options.terms, termIndex);
  82. return term ? make(year, term) : null;
  83. }
  84. function zustParseWeeks(value) {
  85. const text = zustText(value).replace(/[第周\s]/g, '').replace(/(/g, '(').replace(/)/g, ')').replace(/[,、]/g, ',');
  86. const weeks = new Set();
  87. for (const part of text.split(',')) {
  88. const match = part.match(/^(\d+)(?:-(\d+))?(?:\(([单双])\))?$/);
  89. if (!match) throw new Error('无法识别课程周次,请核对教务课表。');
  90. const start = Number(match[1]), end = Number(match[2] || match[1]);
  91. if (start < 1 || end < start || end > 60) throw new Error('课程周次超出有效范围。');
  92. for (let week = start; week <= end; week++) {
  93. if (match[3] === '单' && week % 2 === 0) continue;
  94. if (match[3] === '双' && week % 2 === 1) continue;
  95. weeks.add(week);
  96. }
  97. }
  98. if (weeks.size === 0) throw new Error('课程周次为空。');
  99. return Array.from(weeks).sort((a, b) => a - b);
  100. }
  101. function zustParseCourses(data, semester) {
  102. if (!data || !Array.isArray(data.kbList) || !data.xsxx ||
  103. zustText(data.xsxx.XNM) !== semester.year || zustText(data.xsxx.XQM) !== semester.term) {
  104. throw new Error('课表响应与所选学期不一致,请重新进入教务系统。');
  105. }
  106. const courses = [], campuses = new Map();
  107. // 接口已返回连续节次,保留每条记录的周次与地点,不合并换教室后的课程。
  108. for (const row of data.kbList) {
  109. const name = zustText(row.kcmc), day = Number(row.xqj);
  110. const section = zustText(row.jcs).match(/^(\d+)(?:-(\d+))?$/);
  111. const campusId = zustText(row.xqh_id), campusName = zustText(row.xqmc);
  112. if (!name || !Number.isInteger(day) || day < 1 || day > 7 || !section || !campusId || !campusName) {
  113. throw new Error('课程名称、星期、节次或校区缺失,请核对教务课表。');
  114. }
  115. const startSection = Number(section[1]), endSection = Number(section[2] || section[1]);
  116. if (startSection < 1 || endSection < startSection || endSection > 30) throw new Error('课程节次无效。');
  117. const course = {
  118. name: name,
  119. teacher: zustText(row.xm),
  120. position: campusName + (zustText(row.cdmc) ? ' ' + zustText(row.cdmc) : ''),
  121. day: day,
  122. startSection: startSection,
  123. endSection: endSection,
  124. weeks: zustParseWeeks(row.zcd)
  125. };
  126. if (zustText(row.xf) !== '') {
  127. const credit = Number(row.xf);
  128. if (!Number.isFinite(credit) || credit < 0) throw new Error('课程学分无效。');
  129. course.credit = credit;
  130. }
  131. courses.push({ course: course, campusId: campusId });
  132. campuses.set(campusId, campusName);
  133. }
  134. if (courses.length === 0) throw new Error('该学期没有固定时间的课程,请更换学期或等待排课。');
  135. if (!Array.isArray(data.sjkList)) throw new Error('教务未返回完整的未排课信息,请重试。');
  136. return { courses: courses, campuses: campuses, unscheduled: data.sjkList };
  137. }
  138. function zustParseCalendar(rows) {
  139. if (!Array.isArray(rows) || rows.length === 0) throw new Error('未取得所选学期的校历。');
  140. const weeks = [];
  141. for (const row of rows) {
  142. if (!/^\d+$/.test(zustText(row.zs))) throw new Error('校历周次格式异常。');
  143. const match = zustText(row.rq).match(/^(\d{4}-\d{2}-\d{2})\/(\d{4}-\d{2}-\d{2})$/);
  144. if (!match) throw new Error('校历日期格式异常。');
  145. weeks.push({ number: Number(row.zs), start: match[1], end: match[2] });
  146. }
  147. weeks.sort((a, b) => a.number - b.number);
  148. if (weeks.length > 60) throw new Error('校历周数超出有效范围。');
  149. let firstDate = null;
  150. for (let i = 0; i < weeks.length; i++) {
  151. const week = weeks[i], start = new Date(week.start + 'T00:00:00Z'), end = new Date(week.end + 'T00:00:00Z');
  152. if (week.number !== i + 1 || isNaN(start.getTime()) || isNaN(end.getTime()) ||
  153. start.toISOString().slice(0, 10) !== week.start || end.toISOString().slice(0, 10) !== week.end ||
  154. start.getUTCDay() !== 1 || end < start || end - start > 6 * 86400000 ||
  155. (i < weeks.length - 1 && end - start !== 6 * 86400000)) throw new Error('校历周次或日期不连续。');
  156. if (i === 0) firstDate = start;
  157. if (start - firstDate !== i * 7 * 86400000) throw new Error('校历日期与教学周不对应。');
  158. }
  159. // 校历接口的范围包含假期;如实保存,不从课程最大周次猜测总周数。
  160. return { semesterStartDate: weeks[0].start, semesterTotalWeeks: weeks.length, firstDayOfWeek: 1 };
  161. }
  162. function zustClock(value) {
  163. const match = zustText(value).match(/^(\d{2}):(\d{2})(?::00)?$/);
  164. if (!match || Number(match[1]) > 23 || Number(match[2]) > 59) throw new Error('作息时间格式异常。');
  165. return match[1] + ':' + match[2];
  166. }
  167. function zustParseTimeSlots(rows, campusId) {
  168. if (!Array.isArray(rows) || rows.length === 0) throw new Error('未取得课程所属校区的作息。');
  169. const slots = [], numbers = new Map();
  170. for (const row of rows) {
  171. if (zustText(row.xqh_id) !== campusId || !/^\d+$/.test(zustText(row.jcmc))) throw new Error('作息校区或节次与请求不一致。');
  172. const slot = { number: Number(row.jcmc), startTime: zustClock(row.qssj), endTime: zustClock(row.jssj) };
  173. const previous = numbers.get(slot.number);
  174. if (previous) {
  175. if (previous.startTime !== slot.startTime || previous.endTime !== slot.endTime) throw new Error('同一节次返回了不同作息。');
  176. continue;
  177. }
  178. numbers.set(slot.number, slot);
  179. slots.push(slot);
  180. }
  181. slots.sort((a, b) => a.number - b.number);
  182. for (let i = 0; i < slots.length; i++) {
  183. const slot = slots[i];
  184. if (slot.number !== i + 1 || slot.number > 30 || slot.startTime >= slot.endTime ||
  185. (i > 0 && slot.startTime < slots[i - 1].endTime)) throw new Error('作息编号不连续或时间重叠。');
  186. }
  187. // 安吉第 5 节在接口中保留为 12:10-13:10,校方说明其为午休,不删除或压缩编号。
  188. return slots;
  189. }
  190. async function zustSave(method, value, label) {
  191. const result = await window.shiguangBridgePromise[method](JSON.stringify(value));
  192. if (!zustConfirmed(result)) throw new Error(label + '保存未成功,请重新导入。');
  193. }
  194. async function zustRunImport() {
  195. let savedStage = '';
  196. try {
  197. zustBaseUrl();
  198. zustToast('正在读取学年学期列表…');
  199. const semester = await zustChooseSemester();
  200. if (!semester) { zustToast('导入已取消'); return; }
  201. zustToast('正在读取整学期课表、校历和校区作息…');
  202. const data = await zustFetchCourses(semester);
  203. const parsed = zustParseCourses(data, semester);
  204. const config = zustParseCalendar(await zustRequest('kbcx/xskbcxZccx_cxZcByXnxq.html', {
  205. gnmkdm: 'N2154', xnm: semester.year, xqm: semester.term
  206. }));
  207. const schedules = new Map(), campusOptions = [];
  208. for (const [id, name] of parsed.campuses) {
  209. schedules.set(id, zustParseTimeSlots(await zustRequest('jzgl/skxxMobile_cxRsdjc.html', {
  210. gnmkdm: 'N2154', xnm: semester.year, xqm: semester.term, xqh_id: id
  211. }), id));
  212. campusOptions.push({ value: id, label: name });
  213. }
  214. let campus = campusOptions[0];
  215. if (campusOptions.length > 1) {
  216. campus = await zustSelect('选择课表基础作息校区', campusOptions, 0);
  217. if (!campus) { zustToast('导入已取消'); return; }
  218. }
  219. const slots = schedules.get(campus.value), courses = [];
  220. let customCount = 0;
  221. for (const item of parsed.courses) {
  222. const course = item.course, ownSlots = schedules.get(item.campusId);
  223. let different = false;
  224. for (let n = course.startSection; n <= course.endSection; n++) {
  225. if (!ownSlots[n - 1]) throw new Error('课程节次超出所属校区作息,请核对教务课表。');
  226. if (!slots[n - 1] || ownSlots[n - 1].startTime !== slots[n - 1].startTime || ownSlots[n - 1].endTime !== slots[n - 1].endTime) different = true;
  227. }
  228. for (const week of course.weeks) if (week > config.semesterTotalWeeks) throw new Error('课程周次超出所选学期校历。');
  229. if (different) {
  230. course.isCustomTime = true;
  231. course.customStartTime = ownSlots[course.startSection - 1].startTime;
  232. course.customEndTime = ownSlots[course.endSection - 1].endTime;
  233. customCount++;
  234. }
  235. courses.push(course);
  236. }
  237. let note = semester.label + '\n' + courses.length + ' 条课程时段\n基础作息:' + campus.label + ',共 ' + slots.length + ' 节\n第一周周一:' + config.semesterStartDate +
  238. '\n教务校历:' + config.semesterTotalWeeks + ' 周(范围可能包含假期)';
  239. note += '\n\n作息时间:';
  240. for (const slot of slots) note += '\n第 ' + slot.number + ' 节 ' + slot.startTime + '-' + slot.endTime +
  241. (campus.value === '3' && slot.number === 5 ? '(午休预留,保留原编号)' : '');
  242. if (customCount) note += '\n另有 ' + customCount + ' 条跨校区课程按所属校区真实时间导入,并保留原节次。';
  243. if (parsed.unscheduled.length) {
  244. note += '\n\n以下课程尚无固定上课时间,本次不导入:';
  245. for (const row of parsed.unscheduled) note += '\n' + zustText(row.kcmc) + '(' + zustText(row.qsjsz) + ')';
  246. }
  247. const confirmed = await window.shiguangBridgePromise.showAlert('核对导入信息', note, '确认导入');
  248. if (!zustConfirmed(confirmed)) { zustToast('导入已取消'); return; }
  249. await zustSave('saveCourseConfig', config, '学期配置');
  250. savedStage = '学期配置';
  251. await zustSave('savePresetTimeSlots', slots, '作息');
  252. savedStage = '学期配置和作息';
  253. await zustSave('saveImportedCourses', courses, '课程');
  254. zustToast('已导入 ' + courses.length + ' 条课程时段及 ' + slots.length + ' 节作息');
  255. window.shiguangBridge.notifyTaskCompletion();
  256. } catch (error) {
  257. await window.shiguangBridgePromise.showAlert('导入未完成',
  258. (savedStage ? savedStage + '已保存,后续步骤未完成,请重新导入。\n' : '') + (error && error.message ? error.message : String(error)), '知道了');
  259. }
  260. }
  261. zustRunImport();