nuaa_01.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318
  1. // 南京航空航天大学(aao-eas.nuaa.edu.cn) 拾光课程表适配脚本
  2. // 基于旧树维(TJAU)方案,调整 TaskActivity 参数位次与 13 节作息
  3. const BASE = "https://aao-eas.nuaa.edu.cn/eams";
  4. function powerSplit(paramsRaw) {
  5. const args = [];
  6. let current = "";
  7. let depth = 0;
  8. let inQuote = false;
  9. let quoteChar = "";
  10. for (let i = 0; i < paramsRaw.length; i++) {
  11. let char = paramsRaw[i];
  12. if ((char === '"' || char === "'") && (i === 0 || paramsRaw[i - 1] !== '\\')) {
  13. if (!inQuote) { inQuote = true; quoteChar = char; }
  14. else if (char === quoteChar) { inQuote = false; }
  15. }
  16. if (!inQuote) {
  17. if (char === '(' || char === '[' || char === '{') depth++;
  18. if (char === ')' || char === ']' || char === '}') depth--;
  19. }
  20. if (char === ',' && depth === 0 && !inQuote) {
  21. args.push(cleanArg(current));
  22. current = "";
  23. } else {
  24. current += char;
  25. }
  26. }
  27. args.push(cleanArg(current));
  28. return args;
  29. }
  30. function cleanArg(s) {
  31. s = s.trim();
  32. if (s === "null") return null;
  33. return s.replace(/^["']|["']$/g, "");
  34. }
  35. function mergeContinuousLessons(lessons) {
  36. if (!lessons || lessons.length === 0) return [];
  37. const groups = {};
  38. lessons.forEach(l => {
  39. const key = `${l.name}|${l.teacher}|${l.position}|${l.day}`;
  40. if (!groups[key]) {
  41. groups[key] = {
  42. name: l.name,
  43. teacher: l.teacher,
  44. position: l.position,
  45. campus: l.campus || "",
  46. day: l.day,
  47. weeksMatrix: Array.from({ length: 50 }, () => new Set())
  48. };
  49. } else if (!groups[key].campus && l.campus) {
  50. groups[key].campus = l.campus;
  51. }
  52. if (l.weeks && Array.isArray(l.weeks)) {
  53. l.weeks.forEach(w => {
  54. if (w >= 0 && w < 50) {
  55. for (let s = l.startSection; s <= l.endSection; s++) {
  56. groups[key].weeksMatrix[w].add(s);
  57. }
  58. }
  59. });
  60. }
  61. });
  62. const merged = [];
  63. for (const key in groups) {
  64. const group = groups[key];
  65. const matrix = group.weeksMatrix;
  66. const blockMap = {};
  67. for (let w = 0; w < matrix.length; w++) {
  68. const sections = Array.from(matrix[w]).sort((a, b) => a - b);
  69. if (sections.length === 0) continue;
  70. let start = sections[0];
  71. let prev = sections[0];
  72. for (let i = 1; i < sections.length; i++) {
  73. const curr = sections[i];
  74. if (curr === prev + 1) {
  75. prev = curr;
  76. } else {
  77. const blockKey = `${start}-${prev}`;
  78. if (!blockMap[blockKey]) blockMap[blockKey] = [];
  79. blockMap[blockKey].push(w);
  80. start = curr;
  81. prev = curr;
  82. }
  83. }
  84. const blockKey = `${start}-${prev}`;
  85. if (!blockMap[blockKey]) blockMap[blockKey] = [];
  86. blockMap[blockKey].push(w);
  87. }
  88. for (const blockKey in blockMap) {
  89. const [startSec, endSec] = blockKey.split('-').map(Number);
  90. merged.push({
  91. name: group.name,
  92. teacher: group.teacher,
  93. position: group.position,
  94. campus: group.campus || "",
  95. day: group.day,
  96. startSection: startSec,
  97. endSection: endSec,
  98. weeks: blockMap[blockKey]
  99. });
  100. }
  101. }
  102. merged.sort((a, b) => {
  103. if (a.day !== b.day) return a.day - b.day;
  104. if (a.startSection !== b.startSection) return a.startSection - b.startSection;
  105. return a.name.localeCompare(b.name);
  106. });
  107. return merged;
  108. }
  109. // 系统节次 5/6 为午一/午二,不导入课表
  110. // 1-4 保持;7-13 映射为官方第五节至第十一节(应用内 5-11)
  111. function mapSection(nuaaSection) {
  112. if (nuaaSection >= 1 && nuaaSection <= 4) return nuaaSection;
  113. if (nuaaSection >= 7 && nuaaSection <= 13) return nuaaSection - 2;
  114. return null;
  115. }
  116. // 南航 TaskActivity 相对天津农学院整体右移 1 位:
  117. // args[3]=课程名, args[6]=地点, args[7]=周次位图
  118. function parseTaskActivities(html) {
  119. const rawResults = [];
  120. const blocks = html.split(/var\s+teachers\s*=/);
  121. for (let i = 1; i < blocks.length; i++) {
  122. const block = blocks[i];
  123. let teacherName = "未知教师";
  124. const tMatch = block.match(/actTeachers\s*=\s*\[\s*\{[\s\S]*?name:\s*"(.*?)"/);
  125. if (tMatch) teacherName = tMatch[1];
  126. const activityMatch = block.match(/new\s+TaskActivity\(([\s\S]*?)\);/);
  127. if (!activityMatch) continue;
  128. const args = powerSplit(activityMatch[1]);
  129. const courseName = (args[3] || "未知课程").trim();
  130. const positionRaw = (args[6] || "").trim();
  131. const position = positionRaw.replace(/\(.*?\)/g, "").trim() || "未知地点";
  132. const campus = /天目湖/.test(positionRaw) ? "天目湖" : "";
  133. const weeksBitmap = args[7] || "";
  134. const weeks = [];
  135. for (let j = 0; j < weeksBitmap.length; j++) {
  136. if (weeksBitmap[j] === '1') weeks.push(j);
  137. }
  138. const unitCountMatch = html.match(/unitCount\s*=\s*(\d+)/);
  139. const unitCount = unitCountMatch ? parseInt(unitCountMatch[1]) : 13;
  140. const idxRegex = /index\s*=\s*(\d+)\s*\*\s*unitCount\s*\+\s*(\d+);/g;
  141. let m;
  142. while ((m = idxRegex.exec(block)) !== null) {
  143. const day = parseInt(m[1]) + 1;
  144. const section = mapSection(parseInt(m[2]) + 1);
  145. if (section === null) continue;
  146. rawResults.push({
  147. name: courseName,
  148. teacher: teacherName,
  149. position: position,
  150. campus: campus,
  151. day: day,
  152. startSection: section,
  153. endSection: section,
  154. weeks: weeks
  155. });
  156. }
  157. }
  158. return mergeContinuousLessons(rawResults);
  159. }
  160. async function request(url, options = {}) {
  161. const res = await fetch(url, { credentials: "include", ...options });
  162. if (!res.ok) throw new Error(`网络请求失败: ${res.status}`);
  163. return await res.text();
  164. }
  165. function extractDefaultSemesterId(html) {
  166. // 教务页当前加载的学期:hidden input 或 semesterCalendar 初始化 value
  167. const target = html.match(/id="semesterCalendar_target"[\s\S]*?value="(\d+)"/);
  168. if (target) return target[1];
  169. const cal = html.match(/semesterCalendar\(\{[^}]*value:"(\d+)"/);
  170. if (cal) return cal[1];
  171. return "";
  172. }
  173. async function detectParameters() {
  174. const html = await request(`${BASE}/courseTableForStd.action?sf_request_type=ajax`);
  175. const idsMatch = html.match(/bg\.form\.addInput\(form,\s*"ids",\s*"(\d+)"\)/);
  176. const tagIdMatch = html.match(/id="(semesterBar\d+Semester)"/);
  177. if (!idsMatch || !tagIdMatch) return null;
  178. return {
  179. ids: idsMatch[1],
  180. tagId: tagIdMatch[1],
  181. defaultSemesterId: extractDefaultSemesterId(html)
  182. };
  183. }
  184. async function getSelectedSemester(tagId, defaultSemesterId) {
  185. const raw = await request(`${BASE}/dataQuery.action?sf_request_type=ajax`, {
  186. method: "POST",
  187. headers: { "Content-Type": "application/x-www-form-urlencoded" },
  188. body: `tagId=${encodeURIComponent(tagId)}&dataType=semesterCalendar`
  189. });
  190. const data = Function(`return (${raw});`)();
  191. const list = [];
  192. for (let key in data.semesters) {
  193. data.semesters[key].forEach(s => list.push({
  194. id: String(s.id),
  195. name: `${s.schoolYear} ${s.name}学期`
  196. }));
  197. }
  198. if (list.length === 0) throw new Error("未解析到学期列表,请确认已登录教务系统");
  199. // 默认选中教务页当前加载的学期,而不是列表里的第一条
  200. let defaultIndex = 0;
  201. if (defaultSemesterId) {
  202. const found = list.findIndex(s => s.id === String(defaultSemesterId));
  203. if (found >= 0) defaultIndex = found;
  204. }
  205. const idx = await window.shiguangBridgePromise.showSingleSelection(
  206. "选择学期",
  207. JSON.stringify(list.map(s => s.name)),
  208. defaultIndex
  209. );
  210. return idx !== null ? list[idx] : null;
  211. }
  212. async function fetchAndParseCourses(semesterId, ids) {
  213. const html = await request(`${BASE}/courseTableForStd!courseTable.action?sf_request_type=ajax`, {
  214. method: "POST",
  215. headers: { "Content-Type": "application/x-www-form-urlencoded" },
  216. body: `ignoreHead=1&setting.kind=std&semester.id=${semesterId}&ids=${ids}`
  217. });
  218. return parseTaskActivities(html);
  219. }
  220. // 官方校历 11 节作息,不含午一/午二
  221. function getTimeSlots(campus) {
  222. const tianmuhu = [
  223. ["08:30", "09:20"], ["09:25", "10:15"], ["10:30", "11:20"], ["11:25", "12:15"],
  224. ["14:00", "14:50"], ["14:55", "15:45"], ["16:00", "16:50"], ["16:55", "17:45"],
  225. ["18:45", "19:35"], ["19:40", "20:30"], ["20:35", "21:25"]
  226. ];
  227. const other = [
  228. ["08:00", "08:50"], ["08:55", "09:45"], ["10:15", "11:05"], ["11:10", "12:00"],
  229. ["14:00", "14:50"], ["14:55", "15:45"], ["16:15", "17:05"], ["17:10", "18:00"],
  230. ["18:45", "19:35"], ["19:40", "20:30"], ["20:35", "21:25"]
  231. ];
  232. const pairs = campus === "天目湖" ? tianmuhu : other;
  233. return pairs.map((p, i) => ({
  234. number: i + 1,
  235. startTime: p[0],
  236. endTime: p[1]
  237. }));
  238. }
  239. function detectCampusFromCourses(courses) {
  240. if (!courses || courses.length === 0) return "";
  241. const first = courses.find(c => c.campus);
  242. return first ? first.campus : "";
  243. }
  244. async function applyTimeSlots(courses) {
  245. const campus = detectCampusFromCourses(courses) || "其他校区";
  246. const slots = getTimeSlots(campus === "天目湖" ? "天目湖" : "other");
  247. window.shiguangBridge.showToast(`按${campus || "默认"}作息导入时间段`);
  248. return await window.shiguangBridgePromise.savePresetTimeSlots(JSON.stringify(slots));
  249. }
  250. async function runImportFlow() {
  251. try {
  252. window.shiguangBridge.showToast("开始探测教务参数...");
  253. const params = await detectParameters();
  254. if (!params) {
  255. window.shiguangBridge.showToast("无法识别当前页面,请先登录教务系统并进入课表页面");
  256. return;
  257. }
  258. const semester = await getSelectedSemester(params.tagId, params.defaultSemesterId);
  259. if (!semester) {
  260. window.shiguangBridge.showToast("导入已取消");
  261. return;
  262. }
  263. window.shiguangBridge.showToast("正在同步课表...");
  264. const courses = await fetchAndParseCourses(semester.id, params.ids);
  265. if (!courses || courses.length === 0) {
  266. window.shiguangBridge.showToast("未解析到课程数据,可能是学期选择错误或尚未登录");
  267. return;
  268. }
  269. await applyTimeSlots(courses);
  270. const payload = courses.map(({ campus, ...rest }) => rest);
  271. const saveResult = await window.shiguangBridgePromise.saveImportedCourses(JSON.stringify(payload));
  272. if (saveResult) {
  273. window.shiguangBridge.showToast(`成功导入 ${courses.length} 个课程条目`);
  274. window.shiguangBridge.notifyTaskCompletion();
  275. }
  276. } catch (e) {
  277. console.error(`[异常] ${e.message}`);
  278. window.shiguangBridge.showToast(e.message);
  279. }
  280. }
  281. runImportFlow();