cqust_01.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403
  1. /**
  2. * 重庆科技大学 (CQUST) 树维EAMS教务系统课表导入脚本
  3. * 适用系统:树维 EAMS 教学管理系统 (本科)
  4. * 适配支持:拾光课程表 (shiguangschedule)
  5. * Maintainer: yuexps
  6. */
  7. (async () => {
  8. 'use strict';
  9. // 允许的教务系统域名(IPv6 专线与 IPv4 备用)
  10. const ALLOWED_HOSTS = [
  11. 'jwnew.cqust.edu.ex2.http.80.ipv6.cqust.edu.cn',
  12. 'jwnew.cqust.edu.cn'
  13. ];
  14. // 重庆科技大学标准作息时间表(共 11 节)
  15. const CQUST_TIME_SLOTS = [
  16. { number: 1, startTime: '08:30', endTime: '09:15' },
  17. { number: 2, startTime: '09:25', endTime: '10:10' },
  18. { number: 3, startTime: '10:30', endTime: '11:15' },
  19. { number: 4, startTime: '11:25', endTime: '12:10' },
  20. { number: 5, startTime: '14:00', endTime: '14:45' },
  21. { number: 6, startTime: '14:55', endTime: '15:40' },
  22. { number: 7, startTime: '16:00', endTime: '16:45' },
  23. { number: 8, startTime: '16:55', endTime: '17:40' },
  24. { number: 9, startTime: '19:00', endTime: '19:45' },
  25. { number: 10, startTime: '19:55', endTime: '20:40' },
  26. { number: 11, startTime: '20:50', endTime: '21:35' }
  27. ];
  28. // 显示 Toast 提示
  29. const toast = (msg) => {
  30. if (window.shiguangBridge && typeof window.shiguangBridge.showToast === 'function') {
  31. window.shiguangBridge.showToast(msg);
  32. } else {
  33. console.log('[Toast]', msg);
  34. }
  35. };
  36. // 检查是否在教务系统域名下
  37. const checkHost = () => {
  38. const curHost = window.location.hostname;
  39. return ALLOWED_HOSTS.some(h => curHost.includes(h) || curHost === h);
  40. };
  41. // 通用 HTTP 请求封装(自动带凭据与当前域名)
  42. const request = async (path, options = {}) => {
  43. const url = path.startsWith('http') ? path : `${window.location.origin}${path}`;
  44. const resp = await fetch(url, {
  45. credentials: 'include',
  46. ...options
  47. });
  48. if (!resp.ok) {
  49. throw new Error(`请求接口异常: ${resp.status} ${resp.statusText}`);
  50. }
  51. return await resp.text();
  52. };
  53. // 获取周一日期(格式化为 YYYY-MM-DD)
  54. const getWeekMondayStr = (date) => {
  55. const d = new Date(date);
  56. d.setHours(0, 0, 0, 0);
  57. const day = d.getDay() === 0 ? 7 : d.getDay();
  58. d.setDate(d.getDate() - (day - 1));
  59. const y = d.getFullYear();
  60. const m = String(d.getMonth() + 1).padStart(2, '0');
  61. const dayStr = String(d.getDate()).padStart(2, '0');
  62. return `${y}-${m}-${dayStr}`;
  63. };
  64. // 根据学年学期推算开学首周周一日期
  65. const calcSemesterStartDate = (schoolYear, termName) => {
  66. const years = (schoolYear || '').match(/\d{4}/g) || [];
  67. const isSecond = String(termName) === '2' || (termName && termName.includes('2'));
  68. if (years.length >= 2) {
  69. return isSecond ? getWeekMondayStr(`${years[1]}-02-22`) : getWeekMondayStr(`${years[0]}-09-07`);
  70. }
  71. const nowYear = new Date().getFullYear();
  72. return isSecond ? getWeekMondayStr(`${nowYear}-02-22`) : getWeekMondayStr(`${nowYear}-09-07`);
  73. };
  74. // 探测教务会话状态并提取排课标识 ids
  75. const detectParams = async () => {
  76. const html = await request('/eams/courseTableForStd.action');
  77. if (html.includes('actionError') || html.includes('login.action') || html.includes('密码错误') || html.includes('用户登录')) {
  78. throw new Error('未检测到教务系统登录状态,请先登录教务后重新导入');
  79. }
  80. const idsMatch = html.match(/bg\.form\.addInput\(form,\s*["']ids["'],\s*["'](\d+)["']\)/);
  81. const tagMatch = html.match(/id=["'](semesterBar\d+Semester)["']/);
  82. let ids = idsMatch ? idsMatch[1] : null;
  83. if (!ids) {
  84. const inputEl = document.querySelector('form input[name="ids"]');
  85. if (inputEl && inputEl.value) ids = inputEl.value;
  86. }
  87. if (!ids) {
  88. throw new Error('未能获取学生排课标识,请确认当前账号有选课排课权限');
  89. }
  90. const tagId = tagMatch ? tagMatch[1] : 'semesterBar8875271691Semester';
  91. return { ids, tagId };
  92. };
  93. // 获取学期列表并弹出单选框供用户选择
  94. const selectSemester = async (tagId) => {
  95. let semesterList = [];
  96. let curSemId = '561';
  97. try {
  98. const queryRes = await request('/eams/dataQuery.action', {
  99. method: 'POST',
  100. headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' },
  101. body: `tagId=${encodeURIComponent(tagId)}&dataType=semesterCalendar&value=561&empty=false`
  102. });
  103. const semIdMatch = queryRes.match(/semesterId:\s*["']?(\d+)["']?/);
  104. if (semIdMatch) curSemId = semIdMatch[1];
  105. const itemRegex = /\{id:(\d+),schoolYear:"([^"]+)",name:"([^"]+)"\}/g;
  106. let m;
  107. while ((m = itemRegex.exec(queryRes)) !== null) {
  108. semesterList.unshift({
  109. id: m[1],
  110. schoolYear: m[2],
  111. name: m[3],
  112. label: `${m[2]}学年 第${m[3]}学期${m[1] === curSemId ? ' (当前)' : ''}`
  113. });
  114. }
  115. } catch (e) {
  116. console.warn('[学期日历查询失败,使用默认配置]', e);
  117. }
  118. if (!semesterList.length) {
  119. return {
  120. id: curSemId,
  121. schoolYear: '2026-2027',
  122. name: '1',
  123. label: '当前学期'
  124. };
  125. }
  126. let defaultIdx = semesterList.findIndex(s => s.id === curSemId);
  127. if (defaultIdx < 0) defaultIdx = 0;
  128. if (window.shiguangBridgePromise && typeof window.shiguangBridgePromise.showSingleSelection === 'function') {
  129. const labels = semesterList.map(s => s.label);
  130. const chosenIdx = await window.shiguangBridgePromise.showSingleSelection(
  131. '请选择需要导入的学期',
  132. JSON.stringify(labels),
  133. defaultIdx
  134. );
  135. if (chosenIdx === null || chosenIdx < 0) {
  136. return null;
  137. }
  138. return semesterList[chosenIdx];
  139. }
  140. return semesterList[defaultIdx];
  141. };
  142. // 解析 TaskActivity 课表与未排实践课程
  143. const parseCourseTableHtml = (html) => {
  144. const rawSlots = [];
  145. const creditMap = new Map();
  146. // 提取课程代码与学分映射
  147. const cReg = />([A-Za-z0-9._-]+)<\/a>\s*<\/td>\s*<td>([^<]+)<\/td>\s*<td>([0-9.]+)<\/td>/g;
  148. let cm;
  149. while ((cm = cReg.exec(html)) !== null) {
  150. if (cm[1]) creditMap.set(cm[1].trim(), cm[3].trim());
  151. if (cm[2]) creditMap.set(cm[2].trim(), cm[3].trim());
  152. }
  153. // 解析已排网格课程 TaskActivity
  154. const scriptMatch = html.match(/var\s+table0\s*=\s*new\s+CourseTable[\s\S]*?<\/script>/);
  155. if (scriptMatch) {
  156. const lines = scriptMatch[0].split('\n');
  157. let curAct = null;
  158. const actReg = /activity\s*=\s*new\s+TaskActivity\((.*)\);/;
  159. const idxReg = /index\s*=\s*(\d+)\s*\*\s*unitCount\s*\+\s*(\d+);/;
  160. const strReg = /"([^"]*)"/g;
  161. for (const lineRaw of lines) {
  162. const line = lineRaw.trim();
  163. const aM = line.match(actReg);
  164. if (aM) {
  165. const args = [];
  166. let sm;
  167. while ((sm = strReg.exec(aM[1])) !== null) args.push(sm[1]);
  168. if (args.length >= 7) {
  169. const rawName = args[3] || '未知课程';
  170. const cleanName = rawName.replace(/\([A-Za-z0-9._-]+\)$/, '').trim() || rawName;
  171. curAct = {
  172. teacher: args[1] || '未知教师',
  173. name: cleanName,
  174. room: args[5] || '待定',
  175. weeksStr: args[6] || ''
  176. };
  177. }
  178. }
  179. const iM = line.match(idxReg);
  180. if (iM && curAct) {
  181. const day = parseInt(iM[1], 10) + 1;
  182. const sec = parseInt(iM[2], 10) + 1;
  183. const weeks = [];
  184. for (let w = 1; w < curAct.weeksStr.length; w++) {
  185. if (curAct.weeksStr[w] === '1') weeks.push(w);
  186. }
  187. rawSlots.push({
  188. name: curAct.name,
  189. teacher: curAct.teacher,
  190. position: curAct.room,
  191. day,
  192. section: sec,
  193. weeks
  194. });
  195. }
  196. }
  197. }
  198. // 合并同一门课连续的节次
  199. const groups = new Map();
  200. for (const slot of rawSlots) {
  201. const key = `${slot.name}|${slot.teacher}|${slot.position}|${slot.day}|${slot.weeks.join(',')}`;
  202. if (!groups.has(key)) groups.set(key, []);
  203. groups.get(key).push(slot);
  204. }
  205. const mergedCourses = [];
  206. for (const slots of groups.values()) {
  207. if (!slots.length) continue;
  208. slots.sort((a, b) => a.section - b.section);
  209. let startSec = slots[0].section;
  210. let endSec = slots[0].section;
  211. for (let i = 1; i < slots.length; i++) {
  212. if (slots[i].section === endSec + 1) {
  213. endSec = slots[i].section;
  214. } else {
  215. mergedCourses.push({
  216. name: slots[0].name,
  217. teacher: slots[0].teacher,
  218. position: slots[0].position,
  219. day: slots[0].day,
  220. startSection: startSec,
  221. endSection: endSec,
  222. weeks: slots[0].weeks
  223. });
  224. startSec = slots[i].section;
  225. endSec = slots[i].section;
  226. }
  227. }
  228. mergedCourses.push({
  229. name: slots[0].name,
  230. teacher: slots[0].teacher,
  231. position: slots[0].position,
  232. day: slots[0].day,
  233. startSection: startSec,
  234. endSection: endSec,
  235. weeks: slots[0].weeks
  236. });
  237. }
  238. // 解析未安排时间任务列表(实践课程/金工实习等)
  239. const unarrangedMatch = html.match(/未安排时间任务列表[\s\S]*?<table[^>]*>([\s\S]*?)<\/table>/i);
  240. if (unarrangedMatch) {
  241. const tableHtml = unarrangedMatch[1];
  242. const trReg = /<tr[^>]*>([\s\S]*?)<\/tr>/gi;
  243. const strip = /<[^>]+>/g;
  244. let tr;
  245. while ((tr = trReg.exec(tableHtml)) !== null) {
  246. const tds = (tr[1].match(/<td[^>]*>[\s\S]*?<\/td>/gi) || []).map(td => td.replace(strip, '').trim());
  247. if (tds.length >= 8 && /^\d+$/.test(tds[0])) {
  248. const name = tds[2];
  249. const teacher = tds[5] || '指导教师';
  250. const weeksStr = tds[6] || '';
  251. const weeks = [];
  252. if (weeksStr) {
  253. const parts = weeksStr.split(/[,,]/);
  254. for (const p of parts) {
  255. const range = p.trim().match(/^(\d+)\s*[-~至]\s*(\d+)$/);
  256. if (range) {
  257. const s = parseInt(range[1], 10);
  258. const e = parseInt(range[2], 10);
  259. for (let w = s; w <= e; w++) weeks.push(w);
  260. } else {
  261. const single = parseInt(p.trim(), 10);
  262. if (!isNaN(single)) weeks.push(single);
  263. }
  264. }
  265. }
  266. if (name) {
  267. mergedCourses.push({
  268. name,
  269. teacher,
  270. position: '集中实践/待定',
  271. day: 0,
  272. startSection: 0,
  273. endSection: 0,
  274. weeks: weeks.length ? weeks : [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]
  275. });
  276. }
  277. }
  278. }
  279. }
  280. return mergedCourses;
  281. };
  282. // 主执行流程
  283. const runImport = async () => {
  284. if (!checkHost()) {
  285. throw new Error(`请先进入重庆科技大学教务系统 (jwnew.cqust.edu.cn)`);
  286. }
  287. toast('正在检查教务系统登录状态...');
  288. const { ids, tagId } = await detectParams();
  289. toast('正在获取可用学期日历...');
  290. const semester = await selectSemester(tagId);
  291. if (!semester) {
  292. toast('已取消学期选择');
  293. return;
  294. }
  295. toast(`正在同步 ${semester.label || ''} 课表...`);
  296. const courseHtml = await request('/eams/courseTableForStd!courseTable.action', {
  297. method: 'POST',
  298. headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
  299. body: `ignoreHead=1&setting.kind=std&startWeek=1&project.id=1&semester.id=${semester.id}&ids=${ids}`
  300. });
  301. if (!courseHtml.includes('TaskActivity')) {
  302. throw new Error('未在教务系统中查询到该学期的有效排课数据');
  303. }
  304. const courses = parseCourseTableHtml(courseHtml);
  305. if (!courses || !courses.length) {
  306. throw new Error('未能从课表页面中解析出课程记录');
  307. }
  308. // 计算最大周次与开学日期
  309. let maxWeek = 20;
  310. courses.forEach(c => {
  311. if (Array.isArray(c.weeks) && c.weeks.length) {
  312. const m = Math.max(...c.weeks);
  313. if (m > maxWeek) maxWeek = m;
  314. }
  315. });
  316. const semesterStartDate = calcSemesterStartDate(semester.schoolYear, semester.name);
  317. const config = {
  318. semesterStartDate,
  319. semesterTotalWeeks: maxWeek,
  320. defaultClassDuration: 45,
  321. defaultBreakDuration: 10
  322. };
  323. toast('正在保存课程与作息配置...');
  324. // 保存学期配置
  325. if (window.shiguangBridgePromise && typeof window.shiguangBridgePromise.saveCourseConfig === 'function') {
  326. await window.shiguangBridgePromise.saveCourseConfig(JSON.stringify(config));
  327. }
  328. // 保存重科 11 节作息时间
  329. if (window.shiguangBridgePromise && typeof window.shiguangBridgePromise.savePresetTimeSlots === 'function') {
  330. await window.shiguangBridgePromise.savePresetTimeSlots(JSON.stringify(CQUST_TIME_SLOTS));
  331. }
  332. // 保存解析后的课程列表
  333. if (window.shiguangBridgePromise && typeof window.shiguangBridgePromise.saveImportedCourses === 'function') {
  334. const ok = await window.shiguangBridgePromise.saveImportedCourses(JSON.stringify(courses));
  335. if (ok) {
  336. toast(`导入成功!共导入 ${courses.length} 条课程安排`);
  337. } else {
  338. toast('课程数据保存完成');
  339. }
  340. } else {
  341. console.log('[导出课程结果]', courses);
  342. toast(`解析成功:共 ${courses.length} 门课程`);
  343. }
  344. };
  345. try {
  346. await runImport();
  347. } catch (err) {
  348. console.error('[CQUST 课表导入失败]', err);
  349. toast(`导入失败: ${err.message || '未知错误'}`);
  350. } finally {
  351. if (window.shiguangBridge && typeof window.shiguangBridge.notifyTaskCompletion === 'function') {
  352. window.shiguangBridge.notifyTaskCompletion();
  353. }
  354. }
  355. })();