gdouyj2.js 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871
  1. /**
  2. * 广东海洋大学阳江校区教务适配(校外免 VPN 通道)
  3. * @date 2026-9-12
  4. * @author Yihe-ng
  5. * @version 1.0
  6. *
  7. * 数据取自教学质量综合评价系统(jxpj.gdou.edu.cn),校外可直连,无需 VPN 或校园网。
  8. * 该系统课表与教务同源同步,字段含周次、星期、节次、教室,可直接生成课表。
  9. *
  10. * 接口链路(均为同源请求,复用页面登录态):
  11. * POST /apiservice/University/GetAllSemester 学期列表
  12. * POST /mita/prepare/timetable/setting 学期设置(总周数、当前周、当前周周一)
  13. * POST /mita/online/message/student/course/list 学生课程列表(含教师工号)
  14. * POST /mita/prepare/timetable/timetables 按教师查询全学期排课
  15. *
  16. * 两处报文字段沿用服务端约定(非笔误):学期参数名为 semeter;请求体需加密并追加固定后缀。
  17. */
  18. (function () {
  19. // ==================== 常量 ====================
  20. const AES_KEY = "nfZYwnW2ppQc3CXr";
  21. const AES_SUFFIX = "d^PrEK&c";
  22. const API_SEMESTER_LIST = "/apiservice/University/GetAllSemester";
  23. const API_TIMETABLE_SETTING = "/prepare/timetable/setting";
  24. const API_COURSE_LIST = "/online/message/student/course/list";
  25. const API_TIMETABLE = "/prepare/timetable/timetables";
  26. const DEFAULT_TOTAL_WEEKS = 20;
  27. // 单次请求超时。若服务端不响应,fetch 会一直挂起,流程既无法失败也无法返回。
  28. const REQUEST_TIMEOUT_MS = 20000;
  29. // 阳江校区慎思楼上课时间
  30. const TimeSlots = [
  31. { number: 1, startTime: "08:10", endTime: "08:55" },
  32. { number: 2, startTime: "09:05", endTime: "09:50" },
  33. { number: 3, startTime: "10:20", endTime: "11:05" },
  34. { number: 4, startTime: "11:15", endTime: "12:00" },
  35. { number: 5, startTime: "14:30", endTime: "15:15" },
  36. { number: 6, startTime: "15:20", endTime: "16:05" },
  37. { number: 7, startTime: "16:20", endTime: "17:05" },
  38. { number: 8, startTime: "17:10", endTime: "17:55" },
  39. { number: 9, startTime: "19:30", endTime: "20:15" },
  40. { number: 10, startTime: "20:25", endTime: "21:10" }
  41. ];
  42. /**
  43. * 阳江校区其他场地(非慎思楼)的作息。
  44. * 只有第 3、4 节在校区作息表中是不同的连续时间块,使用自定义时间表示。
  45. */
  46. const OTHER_VENUE_SECTION_3_4_TIME = { startTime: "10:10", endTime: "11:40" };
  47. // ==================== AES-128-ECB 加密 ====================
  48. function utf8Bytes(text) {
  49. const bytes = [];
  50. for (let i = 0; i < text.length; i++) {
  51. let code = text.charCodeAt(i);
  52. if (code < 0x80) {
  53. bytes.push(code);
  54. } else if (code < 0x800) {
  55. bytes.push(0xc0 | (code >> 6), 0x80 | (code & 0x3f));
  56. } else {
  57. bytes.push(0xe0 | (code >> 12), 0x80 | ((code >> 6) & 0x3f), 0x80 | (code & 0x3f));
  58. }
  59. }
  60. return bytes;
  61. }
  62. function gfMultiply(a, b) {
  63. let product = 0;
  64. for (let i = 0; i < 8; i++) {
  65. if (b & 1) product ^= a;
  66. const highBit = a & 0x80;
  67. a = (a << 1) & 0xff;
  68. if (highBit) a ^= 0x1b;
  69. b >>= 1;
  70. }
  71. return product & 0xff;
  72. }
  73. function gfPower(base, exponent) {
  74. let result = 1;
  75. while (exponent > 0) {
  76. if (exponent & 1) result = gfMultiply(result, base);
  77. base = gfMultiply(base, base);
  78. exponent >>= 1;
  79. }
  80. return result;
  81. }
  82. const S_BOX = (function () {
  83. const box = new Array(256);
  84. for (let i = 0; i < 256; i++) {
  85. const inverse = i === 0 ? 0 : gfPower(i, 254);
  86. let value = 0;
  87. for (let bit = 0; bit < 8; bit++) {
  88. const b = ((inverse >> bit) & 1)
  89. ^ ((inverse >> ((bit + 4) % 8)) & 1)
  90. ^ ((inverse >> ((bit + 5) % 8)) & 1)
  91. ^ ((inverse >> ((bit + 6) % 8)) & 1)
  92. ^ ((inverse >> ((bit + 7) % 8)) & 1)
  93. ^ ((0x63 >> bit) & 1);
  94. value |= b << bit;
  95. }
  96. box[i] = value & 0xff;
  97. }
  98. return box;
  99. })();
  100. function expandKey(keyBytes) {
  101. const words = [];
  102. for (let i = 0; i < 4; i++) {
  103. words[i] = ((keyBytes[4 * i] << 24) | (keyBytes[4 * i + 1] << 16)
  104. | (keyBytes[4 * i + 2] << 8) | keyBytes[4 * i + 3]) >>> 0;
  105. }
  106. let roundConstant = 1;
  107. for (let i = 4; i < 44; i++) {
  108. let temp = words[i - 1];
  109. if (i % 4 === 0) {
  110. temp = ((temp << 8) | (temp >>> 24)) >>> 0;
  111. temp = ((S_BOX[(temp >>> 24) & 0xff] << 24)
  112. | (S_BOX[(temp >>> 16) & 0xff] << 16)
  113. | (S_BOX[(temp >>> 8) & 0xff] << 8)
  114. | S_BOX[temp & 0xff]) >>> 0;
  115. temp = (temp ^ (roundConstant << 24)) >>> 0;
  116. roundConstant = gfMultiply(roundConstant, 2);
  117. }
  118. words[i] = (words[i - 4] ^ temp) >>> 0;
  119. }
  120. return words;
  121. }
  122. function addRoundKey(state, words, round) {
  123. for (let column = 0; column < 4; column++) {
  124. const word = words[4 * round + column];
  125. state[4 * column] ^= (word >>> 24) & 0xff;
  126. state[4 * column + 1] ^= (word >>> 16) & 0xff;
  127. state[4 * column + 2] ^= (word >>> 8) & 0xff;
  128. state[4 * column + 3] ^= word & 0xff;
  129. }
  130. }
  131. function subBytes(state) {
  132. for (let i = 0; i < 16; i++) state[i] = S_BOX[state[i]];
  133. }
  134. function shiftRows(state) {
  135. let temp = state[1];
  136. state[1] = state[5]; state[5] = state[9]; state[9] = state[13]; state[13] = temp;
  137. temp = state[2]; state[2] = state[10]; state[10] = temp;
  138. temp = state[6]; state[6] = state[14]; state[14] = temp;
  139. temp = state[15]; state[15] = state[11]; state[11] = state[7]; state[7] = state[3]; state[3] = temp;
  140. }
  141. function mixColumns(state) {
  142. for (let column = 0; column < 4; column++) {
  143. const i = 4 * column;
  144. const a0 = state[i], a1 = state[i + 1], a2 = state[i + 2], a3 = state[i + 3];
  145. const all = a0 ^ a1 ^ a2 ^ a3;
  146. state[i] = a0 ^ all ^ gfMultiply(a0 ^ a1, 2);
  147. state[i + 1] = a1 ^ all ^ gfMultiply(a1 ^ a2, 2);
  148. state[i + 2] = a2 ^ all ^ gfMultiply(a2 ^ a3, 2);
  149. state[i + 3] = a3 ^ all ^ gfMultiply(a3 ^ a0, 2);
  150. }
  151. }
  152. function encryptBlock(words, input) {
  153. const state = input.slice();
  154. addRoundKey(state, words, 0);
  155. for (let round = 1; round <= 9; round++) {
  156. subBytes(state);
  157. shiftRows(state);
  158. mixColumns(state);
  159. addRoundKey(state, words, round);
  160. }
  161. subBytes(state);
  162. shiftRows(state);
  163. addRoundKey(state, words, 10);
  164. return state;
  165. }
  166. const BASE64_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  167. function bytesToBase64(bytes) {
  168. let output = "";
  169. for (let i = 0; i < bytes.length; i += 3) {
  170. const b0 = bytes[i];
  171. const b1 = i + 1 < bytes.length ? bytes[i + 1] : 0;
  172. const b2 = i + 2 < bytes.length ? bytes[i + 2] : 0;
  173. output += BASE64_CHARS[b0 >> 2];
  174. output += BASE64_CHARS[((b0 & 0x03) << 4) | (b1 >> 4)];
  175. output += i + 1 < bytes.length ? BASE64_CHARS[((b1 & 0x0f) << 2) | (b2 >> 6)] : "=";
  176. output += i + 2 < bytes.length ? BASE64_CHARS[b2 & 0x3f] : "=";
  177. }
  178. return output;
  179. }
  180. function encryptPayload(plainText) {
  181. const key = utf8Bytes(AES_KEY);
  182. const data = utf8Bytes(plainText + AES_SUFFIX);
  183. const padLength = 16 - (data.length % 16);
  184. for (let i = 0; i < padLength; i++) data.push(padLength);
  185. const words = expandKey(key);
  186. const output = [];
  187. for (let offset = 0; offset < data.length; offset += 16) {
  188. const block = encryptBlock(words, data.slice(offset, offset + 16));
  189. for (let i = 0; i < 16; i++) output.push(block[i]);
  190. }
  191. return bytesToBase64(output);
  192. }
  193. // ==================== 会话与请求 ====================
  194. function readStorageJson(storage, key) {
  195. try {
  196. return JSON.parse(storage.getItem(key) || "null");
  197. } catch (error) {
  198. return null;
  199. }
  200. }
  201. /**
  202. * 读取登录用户信息。
  203. * 该系统的桌面端将 current-user 存于 localStorage,微信/移动端存于 sessionStorage,
  204. * 应用中打开的是移动端,故两处都必须尝试。
  205. */
  206. function readCurrentUser() {
  207. return readStorageJson(sessionStorage, "current-user")
  208. || readStorageJson(localStorage, "current-user");
  209. }
  210. function readClientId() {
  211. const visitor = readStorageJson(localStorage, "visitorObj");
  212. return visitor && visitor.ClientId ? visitor.ClientId : "";
  213. }
  214. function readCachedSemester() {
  215. const cached = readStorageJson(sessionStorage, "semester")
  216. || readStorageJson(localStorage, "semester");
  217. return cached && cached.key ? String(cached.key) : "";
  218. }
  219. /**
  220. * 解析用户标识。移动端以 realCode 作为实际账号,桌面端仅提供 Code,故需回退。
  221. */
  222. function resolveUserCode(user) {
  223. return String((user && (user.realCode || user.Code)) || "");
  224. }
  225. function formatNow() {
  226. const date = new Date();
  227. const pad = (value) => String(value).padStart(2, "0");
  228. return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} `
  229. + `${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`;
  230. }
  231. function buildSystemParams(user, clientId, apiName, semester) {
  232. return {
  233. DegreeLevel: 0,
  234. Token: user.Token,
  235. UserCode: resolveUserCode(user),
  236. UniversityCode: user.UniversityCode,
  237. ApiName: apiName,
  238. ClientTime: formatNow(),
  239. ClientId: clientId,
  240. ClientType: 0,
  241. Semester: semester,
  242. RequestOriginPageAddress: window.location.href
  243. };
  244. }
  245. /**
  246. * 带超时的 fetch。旧版 WebView 可能没有 AbortController,此时退化为普通请求。
  247. */
  248. async function fetchWithTimeout(url, options) {
  249. if (typeof AbortController === "undefined") {
  250. return await fetch(url, options);
  251. }
  252. const controller = new AbortController();
  253. const timer = setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS);
  254. try {
  255. return await fetch(url, Object.assign({}, options, { signal: controller.signal }));
  256. } finally {
  257. clearTimeout(timer);
  258. }
  259. }
  260. async function postApi(user, clientId, path, apiName, semester, requestParams) {
  261. const payload = {
  262. SystemParams: buildSystemParams(user, clientId, apiName, semester),
  263. RequestParams: requestParams || {}
  264. };
  265. const response = await fetchWithTimeout(path, {
  266. method: "POST",
  267. headers: {
  268. "Content-Type": "application/json; charset=utf-8",
  269. "Accept": "application/json",
  270. "token": user.Token
  271. },
  272. body: encryptPayload(JSON.stringify(payload)),
  273. credentials: "include"
  274. });
  275. if (!response.ok) {
  276. throw new Error(`HTTP ${response.status}`);
  277. }
  278. return await response.json();
  279. }
  280. async function postMita(user, clientId, path, semester, params) {
  281. const userCode = resolveUserCode(user);
  282. const merged = Object.assign(
  283. {
  284. teacherCode: userCode,
  285. teacherName: user.Name,
  286. semeter: semester,
  287. schoolCode: user.UniversityCode,
  288. currentUser: userCode,
  289. Token: user.Token,
  290. ClientId: clientId
  291. },
  292. params || {},
  293. { RequestOriginPageAddress: window.location.href }
  294. );
  295. const response = await fetchWithTimeout("/mita" + path, {
  296. method: "POST",
  297. headers: {
  298. "Content-Type": "application/json",
  299. "token": user.Token
  300. },
  301. body: encryptPayload(JSON.stringify(merged)),
  302. credentials: "include"
  303. });
  304. if (!response.ok) {
  305. throw new Error(`HTTP ${response.status}`);
  306. }
  307. return await response.json();
  308. }
  309. // ==================== 数据转换 ====================
  310. function padTwo(value) {
  311. return String(value).padStart(2, "0");
  312. }
  313. /**
  314. * 由「当前周」与「当前周周一日期」反推学期第一周的周一日期。
  315. * 服务端返回的 firstOfWeek 是当前周的周一,需按已过周数向前回退。
  316. */
  317. function deriveSemesterStartDate(firstOfWeek, currentWeek) {
  318. const text = String(firstOfWeek || "").trim();
  319. const matched = text.match(/^(\d{4})-(\d{1,2})-(\d{1,2})/);
  320. if (!matched) return null;
  321. const week = Number(currentWeek);
  322. const offsetDays = Number.isInteger(week) && week > 0 ? (week - 1) * 7 : 0;
  323. const date = new Date(Date.UTC(Number(matched[1]), Number(matched[2]) - 1, Number(matched[3])));
  324. if (isNaN(date.getTime())) return null;
  325. date.setUTCDate(date.getUTCDate() - offsetDays);
  326. return `${date.getUTCFullYear()}-${padTwo(date.getUTCMonth() + 1)}-${padTwo(date.getUTCDate())}`;
  327. }
  328. function getOtherVenueCustomTime(position, startSection, endSection) {
  329. const positionText = position == null ? "" : String(position);
  330. if (!positionText || positionText.includes("慎思楼")) return null;
  331. if (startSection !== 3 || endSection !== 4) return null;
  332. return OTHER_VENUE_SECTION_3_4_TIME;
  333. }
  334. function normalizeWeek(value) {
  335. const week = Number(value);
  336. return Number.isInteger(week) && week > 0 ? week : null;
  337. }
  338. function normalizeSection(value) {
  339. const section = Number(value);
  340. return Number.isInteger(section) && section >= 1 ? section : null;
  341. }
  342. function splitClassNames(value) {
  343. return String(value == null ? "" : value)
  344. .split(/[,,]/)
  345. .map((item) => item.trim())
  346. .filter(Boolean);
  347. }
  348. /**
  349. * 从教师排课记录中筛选属于该学生的课程。
  350. * 评价系统的 classCode 与排课系统可能不同源,故先按 classCode 精确匹配,
  351. * 未命中时退回按班级名称匹配。
  352. */
  353. function pickStudentEntries(entries, course) {
  354. const sameCourse = entries.filter((entry) => entry.courseCode === course.courseCode);
  355. if (sameCourse.length === 0) return [];
  356. const byClassCode = sameCourse.filter((entry) => entry.classCode === course.classCode);
  357. if (byClassCode.length > 0) return byClassCode;
  358. const classNames = splitClassNames(course.className);
  359. if (classNames.length === 0) return [];
  360. return sameCourse.filter((entry) => (entry.reTimetableClasses || []).some((item) =>
  361. splitClassNames(item.className).some((name) => classNames.indexOf(name) !== -1)
  362. ));
  363. }
  364. function toCourseKey(course) {
  365. return [course.name, course.teacher, course.position, course.day,
  366. course.startSection, course.endSection].join("\u0001");
  367. }
  368. /**
  369. * 节次与周次合并去重。
  370. * 取自官方 wiki《课程合并与去重函数》的参考实现,未作改动;
  371. * 用于把服务端可能返回的「逐节」或「分段周次」记录归一为连续区间。
  372. */
  373. function mergeAndDistinctCourses(courses) {
  374. if (!Array.isArray(courses) || courses.length <= 1) return courses;
  375. const list = courses.map(c => ({
  376. ...c,
  377. name: c.name || '',
  378. teacher: c.teacher || '',
  379. position: c.position || '',
  380. weeks: Array.isArray(c.weeks) ? [...c.weeks].sort((a, b) => a - b) : []
  381. }));
  382. list.sort((a, b) =>
  383. a.name.localeCompare(b.name) ||
  384. a.teacher.localeCompare(b.teacher) ||
  385. a.position.localeCompare(b.position) ||
  386. (a.day || 0) - (b.day || 0) ||
  387. a.weeks.join(',').localeCompare(b.weeks.join(',')) ||
  388. (a.startSection || 0) - (b.startSection || 0)
  389. );
  390. const step1Merged = [];
  391. let current = list[0];
  392. for (let i = 1; i < list.length; i++) {
  393. const next = list[i];
  394. const isSameCourseAndWeeks =
  395. current.name === next.name &&
  396. current.teacher === next.teacher &&
  397. current.position === next.position &&
  398. current.day === next.day &&
  399. current.weeks.join(',') === next.weeks.join(',');
  400. const isContinuous = current.endSection + 1 === next.startSection;
  401. const isDuplicate = current.startSection === next.startSection && current.endSection === next.endSection;
  402. if (isSameCourseAndWeeks && isContinuous) {
  403. current.endSection = next.endSection;
  404. } else if (isSameCourseAndWeeks && isDuplicate) {
  405. continue;
  406. } else {
  407. step1Merged.push(current);
  408. current = next;
  409. }
  410. }
  411. step1Merged.push(current);
  412. step1Merged.sort((a, b) =>
  413. a.name.localeCompare(b.name) ||
  414. a.teacher.localeCompare(b.teacher) ||
  415. a.position.localeCompare(b.position) ||
  416. (a.day || 0) - (b.day || 0) ||
  417. (a.startSection || 0) - (b.startSection || 0) ||
  418. (a.endSection || 0) - (b.endSection || 0)
  419. );
  420. const step2Merged = [];
  421. let cur = step1Merged[0];
  422. for (let i = 1; i < step1Merged.length; i++) {
  423. const nxt = step1Merged[i];
  424. const isSameCourseAndSection =
  425. cur.name === nxt.name &&
  426. cur.teacher === nxt.teacher &&
  427. cur.position === nxt.position &&
  428. cur.day === nxt.day &&
  429. cur.startSection === nxt.startSection &&
  430. cur.endSection === nxt.endSection;
  431. if (isSameCourseAndSection) {
  432. cur.weeks = Array.from(new Set([...cur.weeks, ...nxt.weeks])).sort((a, b) => a - b);
  433. } else {
  434. step2Merged.push(cur);
  435. cur = nxt;
  436. }
  437. }
  438. step2Merged.push(cur);
  439. return step2Merged;
  440. }
  441. /**
  442. * 为其他场地第 3-4 节补充自定义时间。
  443. * 必须在合并之后调用:只有先合并成完整的 3-4 节,才满足自定义时间的匹配条件。
  444. */
  445. function applyOtherVenueCustomTime(course) {
  446. const customTime = getOtherVenueCustomTime(
  447. course.position,
  448. course.startSection,
  449. course.endSection
  450. );
  451. if (!customTime) return course;
  452. return Object.assign({}, course, {
  453. isCustomTime: true,
  454. customStartTime: customTime.startTime,
  455. customEndTime: customTime.endTime
  456. });
  457. }
  458. function aggregateCourses(entries, course) {
  459. const merged = new Map();
  460. entries.forEach((entry) => {
  461. const week = normalizeWeek(entry.onweek);
  462. const startSection = normalizeSection(entry.seqStart);
  463. const endSection = normalizeSection(entry.seqEnd);
  464. const day = normalizeSection(entry.dayOfWeek);
  465. if (week === null || startSection === null || endSection === null || day === null) return;
  466. if (day < 1 || day > 7 || endSection < startSection) return;
  467. const position = entry.address == null ? "" : String(entry.address).trim();
  468. const item = {
  469. name: String(entry.courseName || course.courseName || "").trim(),
  470. teacher: String(entry.teacherName || course.teacherName || "").trim(),
  471. position: position,
  472. day: day,
  473. startSection: startSection,
  474. endSection: endSection
  475. };
  476. const key = toCourseKey(item);
  477. if (!merged.has(key)) {
  478. merged.set(key, Object.assign({}, item, { weeks: [] }));
  479. }
  480. const target = merged.get(key);
  481. if (target.weeks.indexOf(week) === -1) target.weeks.push(week);
  482. });
  483. return mergeAndDistinctCourses(Array.from(merged.values()))
  484. .map(applyOtherVenueCustomTime);
  485. }
  486. function sortCourses(courses) {
  487. return courses.sort((a, b) =>
  488. a.day - b.day
  489. || a.startSection - b.startSection
  490. || a.name.localeCompare(b.name, "zh-Hans-CN")
  491. );
  492. }
  493. // ==================== 数据获取 ====================
  494. function describeError(error) {
  495. return error && error.message ? error.message : String(error);
  496. }
  497. async function fetchSemesters(user, clientId) {
  498. const data = await postApi(user, clientId, API_SEMESTER_LIST,
  499. "University/GetAllSemester", user.CurrentSemester, {});
  500. if (!data || data.Success !== true || !Array.isArray(data.Value)) return [];
  501. return data.Value
  502. .map((item) => ({
  503. key: String(item.key || "").trim(),
  504. name: String(item.name || item.key || "").trim(),
  505. selected: item.selected === true
  506. }))
  507. .filter((item) => item.key);
  508. }
  509. async function fetchSemesterSetting(user, clientId, semester) {
  510. try {
  511. const data = await postMita(user, clientId, API_TIMETABLE_SETTING, semester, {});
  512. if (!data || data.success !== true || !data.result) return null;
  513. return {
  514. currentWeek: Number(data.result.currentWeek) || null,
  515. firstOfWeek: data.result.firstOfWeek || null
  516. };
  517. } catch (error) {
  518. console.warn("JS: 读取学期设置失败:", error);
  519. return null;
  520. }
  521. }
  522. async function fetchCourseList(user, clientId, semester) {
  523. const data = await postMita(user, clientId, API_COURSE_LIST, semester, {
  524. pageNum: "1",
  525. pageSize: "999",
  526. studentCode: resolveUserCode(user),
  527. isAdmin: "0"
  528. });
  529. if (!data || data.success !== true || !data.result) return [];
  530. return Array.isArray(data.result.result) ? data.result.result : [];
  531. }
  532. async function fetchTeacherTimetable(user, clientId, semester, teacherCode) {
  533. const data = await postMita(user, clientId, API_TIMETABLE, semester, {
  534. onweek: null,
  535. teacherCode: teacherCode
  536. });
  537. if (!data || data.success !== true) return [];
  538. return Array.isArray(data.result) ? data.result : [];
  539. }
  540. async function collectCourses(user, clientId, semester) {
  541. const courseList = await fetchCourseList(user, clientId, semester);
  542. if (courseList.length === 0) return null;
  543. const byTeacher = new Map();
  544. courseList.forEach((course) => {
  545. const teacherCode = String(course.teacherCode || "").trim();
  546. if (!teacherCode) return;
  547. if (!byTeacher.has(teacherCode)) byTeacher.set(teacherCode, []);
  548. byTeacher.get(teacherCode).push(course);
  549. });
  550. const teacherCodes = Array.from(byTeacher.keys());
  551. const timetables = await Promise.all(teacherCodes.map((teacherCode) =>
  552. fetchTeacherTimetable(user, clientId, semester, teacherCode)
  553. .catch((error) => {
  554. console.warn(`JS: 读取教师 ${teacherCode} 排课失败:`, error);
  555. return [];
  556. })
  557. ));
  558. const courses = [];
  559. teacherCodes.forEach((teacherCode, index) => {
  560. const entries = timetables[index];
  561. if (!entries.length) return;
  562. byTeacher.get(teacherCode).forEach((course) => {
  563. const picked = pickStudentEntries(entries, course);
  564. if (picked.length === 0) return;
  565. courses.push.apply(courses, aggregateCourses(picked, course));
  566. });
  567. });
  568. return sortCourses(courses);
  569. }
  570. // ==================== 用户交互 ====================
  571. function showToast(message) {
  572. window.shiguangBridge.showToast(message);
  573. }
  574. async function promptUserToStart() {
  575. return await window.shiguangBridgePromise.showAlert(
  576. "广东海洋大学阳江校区课表导入(校外免 VPN)",
  577. "本适配器通过接口直接获取课表,无需停留在课表页面。\n\n"
  578. + "导入步骤:\n"
  579. + "1. 确认已登录教学质量综合评价系统(未登录请先完成统一认证)\n"
  580. + "2. 停留在任意页面即可,无需切换\n"
  581. + "3. 点击「执行导入」\n\n"
  582. + "说明:数据取自教学评价系统,部分课程可能缺失,可手动补录。",
  583. "我已登录,开始导入"
  584. );
  585. }
  586. async function promptUserToLogin() {
  587. return await window.shiguangBridgePromise.showAlert(
  588. "需要先登录",
  589. "未检测到登录状态,请先在本页面完成登录:\n\n"
  590. + "1. 页面若显示登录框,输入账号密码登录\n"
  591. + "2. 若已登录但提示本消息,请稍候几秒后重新点击「执行导入」\n\n"
  592. + "登录成功后无需切换页面,直接点击「执行导入」即可。",
  593. "我知道了"
  594. );
  595. }
  596. async function selectSemester(user, clientId) {
  597. let semesters = [];
  598. try {
  599. semesters = await fetchSemesters(user, clientId);
  600. } catch (error) {
  601. console.warn("JS: 读取学期列表失败:", error);
  602. }
  603. const fallback = String(user.CurrentSemester || "").trim() || readCachedSemester();
  604. if (semesters.length === 0) {
  605. if (!fallback) return null;
  606. return { key: fallback, name: fallback };
  607. }
  608. const labels = semesters.map((item) => item.name);
  609. let defaultIndex = semesters.findIndex((item) => item.selected);
  610. if (defaultIndex === -1) defaultIndex = semesters.findIndex((item) => item.key === fallback);
  611. if (defaultIndex === -1) defaultIndex = 0;
  612. const selectedIndex = await window.shiguangBridgePromise.showSingleSelection(
  613. "选择学期",
  614. JSON.stringify(labels),
  615. defaultIndex
  616. );
  617. if (selectedIndex === null || selectedIndex === -1 || !semesters[selectedIndex]) return null;
  618. return semesters[selectedIndex];
  619. }
  620. async function saveCourseConfig(config) {
  621. try {
  622. await window.shiguangBridgePromise.saveCourseConfig(JSON.stringify(config));
  623. return true;
  624. } catch (error) {
  625. showToast(`课表配置保存失败: ${describeError(error)}`);
  626. return false;
  627. }
  628. }
  629. async function saveCourses(courses) {
  630. try {
  631. await window.shiguangBridgePromise.saveImportedCourses(JSON.stringify(courses));
  632. return true;
  633. } catch (error) {
  634. showToast(`课程保存失败: ${describeError(error)}`);
  635. return false;
  636. }
  637. }
  638. async function importPresetTimeSlots() {
  639. if (TimeSlots.length === 0) return;
  640. try {
  641. await window.shiguangBridgePromise.savePresetTimeSlots(JSON.stringify(TimeSlots));
  642. } catch (error) {
  643. console.warn("JS: 预设时间段导入失败:", error);
  644. showToast("预设时间段导入失败,可稍后手动设置。");
  645. }
  646. }
  647. // ==================== 流程编排 ====================
  648. /**
  649. * 识别是否停留在统一认证相关页面。
  650. * 学校统一认证存在缺陷:认证完成后偶发不回跳到本应用,而落到统一认证自身的页面,
  651. * 此时登录其实已成功,但本应用读不到登录态,需引导用户退回后再导入。
  652. *
  653. * 认证平台对桌面端与移动端提供不同页面,两者都要覆盖:
  654. * 个人信息中心 桌面 /personalInfo/personCenter/,移动 /personalInfo/personalMobile/
  655. * 密码找回页面 桌面 /retrieve-password/retrievePassword/,移动 /retrieve-password/passwordMobile/
  656. * 故按目录前缀匹配而非具体页面名。
  657. *
  658. * 各路径验证程度:
  659. * 个人信息中心 移动版路径由实机反馈确认;桌面版复现路径为
  660. * 已认证 + 无 service 访问认证入口 → /authserver/index.do → /personalInfo/personCenter/。
  661. * 密码找回页面 移动版 /retrieve-password/passwordMobile/ 实测渲染「找回密码」,
  662. * 且移动版认证页的「忘记密码」链接正指向该地址并追加 service 参数。
  663. *
  664. * 判定依据为 URL 路径:登录态存于评价系统域,认证域与之跨域、读不到,只能靠当前地址判断。
  665. */
  666. function detectAuthPage() {
  667. const href = String(window.location.href);
  668. if (href.indexOf("/personalInfo/") !== -1) return "个人信息中心";
  669. if (href.indexOf("/retrieve-password/") !== -1) return "密码找回页面";
  670. if (href.indexOf("authserver.") !== -1) return "统一身份认证页面";
  671. return "";
  672. }
  673. async function promptWrongPage(pageName) {
  674. return await window.shiguangBridgePromise.showAlert(
  675. "请先返回评价系统",
  676. `当前停留在「${pageName}」,无法获取课表数据。\n\n`
  677. + "现象说明:学校统一认证平台在认证完成后,偶尔会跳转到自身的个人信息中心或密码找回页面,"
  678. + "此时登录其实已经成功,只是没有回到应用。\n\n"
  679. + "处理方式:点击左上角「返回」,回到教学质量综合评价系统页面后,再点击「执行导入」即可。",
  680. "我知道了"
  681. );
  682. }
  683. async function runImportFlow() {
  684. const authPage = detectAuthPage();
  685. if (authPage) {
  686. await promptWrongPage(authPage);
  687. return;
  688. }
  689. const user = readCurrentUser();
  690. if (!user || !user.Token) {
  691. await promptUserToLogin();
  692. return;
  693. }
  694. const alertConfirmed = await promptUserToStart();
  695. if (!alertConfirmed) {
  696. showToast("用户取消了导入。");
  697. return;
  698. }
  699. const clientId = readClientId();
  700. const semester = await selectSemester(user, clientId);
  701. if (!semester) {
  702. showToast("导入已取消。");
  703. return;
  704. }
  705. showToast("正在获取课程数据...");
  706. let courses = null;
  707. try {
  708. courses = await collectCourses(user, clientId, semester.key);
  709. } catch (error) {
  710. showToast(`获取课表失败: ${describeError(error)}`);
  711. return;
  712. }
  713. if (courses === null) {
  714. showToast("未查询到课程列表,请确认该学期有选课记录。");
  715. return;
  716. }
  717. if (courses.length === 0) {
  718. showToast("未匹配到任何排课记录,可尝试切换其他学期。");
  719. return;
  720. }
  721. const setting = await fetchSemesterSetting(user, clientId, semester.key);
  722. const config = {
  723. semesterTotalWeeks: DEFAULT_TOTAL_WEEKS,
  724. defaultClassDuration: 45,
  725. defaultBreakDuration: 10,
  726. firstDayOfWeek: 1
  727. };
  728. if (setting) {
  729. const startDate = deriveSemesterStartDate(setting.firstOfWeek, setting.currentWeek);
  730. if (startDate) config.semesterStartDate = startDate;
  731. }
  732. const configSaved = await saveCourseConfig(config);
  733. if (!configSaved) return;
  734. const coursesSaved = await saveCourses(courses);
  735. if (!coursesSaved) return;
  736. await importPresetTimeSlots();
  737. const tip = courses.length === 1 ? "1 门课程" : `${courses.length} 个课程时段`;
  738. showToast(`导入完成,共 ${tip}。部分课程可能缺失,可手动补录。`);
  739. window.shiguangBridge.notifyTaskCompletion();
  740. }
  741. runImportFlow();
  742. })();