cqust_01.js 16 KB

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