njupt_01.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362
  1. // 南京邮电大学正方教务(V9)拾光课程表适配脚本
  2. // 通过正方 API 获取课程与学期第一周日期
  3. const NJUPT_TIME_SLOTS = [
  4. { number: 1, startTime: "08:00", endTime: "08:45" },
  5. { number: 2, startTime: "08:50", endTime: "09:35" },
  6. { number: 3, startTime: "09:50", endTime: "10:35" },
  7. { number: 4, startTime: "10:40", endTime: "11:25" },
  8. { number: 5, startTime: "11:30", endTime: "12:15" },
  9. { number: 6, startTime: "13:45", endTime: "14:30" },
  10. { number: 7, startTime: "14:35", endTime: "15:20" },
  11. { number: 8, startTime: "15:35", endTime: "16:20" },
  12. { number: 9, startTime: "16:25", endTime: "17:10" },
  13. { number: 10, startTime: "18:30", endTime: "19:15" },
  14. { number: 11, startTime: "19:25", endTime: "20:10" },
  15. { number: 12, startTime: "20:20", endTime: "21:05" }
  16. ];
  17. function mergeAndDistinctCourses(courses) {
  18. if (!Array.isArray(courses) || courses.length <= 1) return courses;
  19. const list = courses.map(course => ({
  20. ...course,
  21. name: course.name || "",
  22. teacher: course.teacher || "",
  23. position: course.position || "",
  24. weeks: Array.isArray(course.weeks)
  25. ? [...course.weeks].sort((a, b) => a - b)
  26. : []
  27. }));
  28. list.sort((a, b) =>
  29. a.name.localeCompare(b.name) ||
  30. a.teacher.localeCompare(b.teacher) ||
  31. a.position.localeCompare(b.position) ||
  32. a.day - b.day ||
  33. a.weeks.join(",").localeCompare(b.weeks.join(",")) ||
  34. a.startSection - b.startSection
  35. );
  36. const sectionMerged = [];
  37. let current = list[0];
  38. for (let index = 1; index < list.length; index++) {
  39. const next = list[index];
  40. const sameCourseAndWeeks =
  41. current.name === next.name &&
  42. current.teacher === next.teacher &&
  43. current.position === next.position &&
  44. current.day === next.day &&
  45. current.weeks.join(",") === next.weeks.join(",");
  46. const continuous = current.endSection + 1 === next.startSection;
  47. const duplicate =
  48. current.startSection === next.startSection &&
  49. current.endSection === next.endSection;
  50. if (sameCourseAndWeeks && continuous) {
  51. current.endSection = next.endSection;
  52. } else if (!sameCourseAndWeeks || !duplicate) {
  53. sectionMerged.push(current);
  54. current = next;
  55. }
  56. }
  57. sectionMerged.push(current);
  58. sectionMerged.sort((a, b) =>
  59. a.name.localeCompare(b.name) ||
  60. a.teacher.localeCompare(b.teacher) ||
  61. a.position.localeCompare(b.position) ||
  62. a.day - b.day ||
  63. a.startSection - b.startSection ||
  64. a.endSection - b.endSection
  65. );
  66. const result = [];
  67. let merged = sectionMerged[0];
  68. for (let index = 1; index < sectionMerged.length; index++) {
  69. const next = sectionMerged[index];
  70. const sameCourseAndSections =
  71. merged.name === next.name &&
  72. merged.teacher === next.teacher &&
  73. merged.position === next.position &&
  74. merged.day === next.day &&
  75. merged.startSection === next.startSection &&
  76. merged.endSection === next.endSection;
  77. if (sameCourseAndSections) {
  78. merged.weeks = [...new Set([...merged.weeks, ...next.weeks])]
  79. .sort((a, b) => a - b);
  80. } else {
  81. result.push(merged);
  82. merged = next;
  83. }
  84. }
  85. result.push(merged);
  86. return result;
  87. }
  88. function parseWeeks(weekText) {
  89. if (!weekText) return [];
  90. const weeks = [];
  91. for (const segment of String(weekText).split(/[,,]/)) {
  92. const normalized = segment.trim().replace(/(/g, "(").replace(/)/g, ")");
  93. const match = normalized.match(/(\d+)(?:-(\d+))?\s*周?/);
  94. if (!match) continue;
  95. const start = Number(match[1]);
  96. const end = match[2] ? Number(match[2]) : start;
  97. const oddOnly = normalized.includes("(单)");
  98. const evenOnly = normalized.includes("(双)");
  99. for (let week = start; week <= end; week++) {
  100. if (oddOnly && week % 2 === 0) continue;
  101. if (evenOnly && week % 2 !== 0) continue;
  102. weeks.push(week);
  103. }
  104. }
  105. return [...new Set(weeks)].sort((a, b) => a - b);
  106. }
  107. function parseJsonData(jsonData) {
  108. if (!jsonData || !Array.isArray(jsonData.kbList)) {
  109. console.warn("JS: API 数据中缺少 kbList。");
  110. return [];
  111. }
  112. const courses = [];
  113. for (const rawCourse of jsonData.kbList) {
  114. if (!rawCourse.kcmc || !rawCourse.xqj || !rawCourse.jcs || !rawCourse.zcd) {
  115. continue;
  116. }
  117. const weeks = parseWeeks(rawCourse.zcd);
  118. const sectionNumbers = String(rawCourse.jcs).match(/\d+/g)?.map(Number) || [];
  119. const day = Number(rawCourse.xqj);
  120. const startSection = sectionNumbers[0];
  121. const endSection = sectionNumbers[sectionNumbers.length - 1];
  122. if (
  123. weeks.length === 0 ||
  124. !Number.isInteger(day) || day < 1 || day > 7 ||
  125. !Number.isInteger(startSection) || !Number.isInteger(endSection) ||
  126. startSection < 1 || startSection > endSection
  127. ) {
  128. continue;
  129. }
  130. courses.push({
  131. name: String(rawCourse.kcmc).trim(),
  132. teacher: String(rawCourse.xm || "").trim(),
  133. position: String(rawCourse.cdmc || "").trim(),
  134. day,
  135. startSection,
  136. endSection,
  137. weeks
  138. });
  139. }
  140. return mergeAndDistinctCourses(courses);
  141. }
  142. function getNjuptApiBasePath() {
  143. // 直接匹配路径,避免依赖教务页面可能改写的数组和字符串方法。
  144. const isTeachingSystemPage = /\/(?:kbcx|xtgl)\//.test(window.location.pathname);
  145. if (!isTeachingSystemPage) return null;
  146. // 南邮 WebVPN 会拦截并改写根相对请求。若传入已经带 WebVPN
  147. // 哈希前缀的完整 URL,会被二次改写成“当前页面.htm/kbcx/...”。
  148. return "";
  149. }
  150. async function postForm(url, requestBody) {
  151. const response = await fetch(url, {
  152. method: "POST",
  153. headers: {
  154. "Accept": "application/json, text/javascript, */*; q=0.01",
  155. "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8",
  156. "X-Requested-With": "XMLHttpRequest"
  157. },
  158. body: requestBody,
  159. credentials: "include"
  160. });
  161. if (!response.ok) throw new Error(`HTTP ${response.status}`);
  162. return response;
  163. }
  164. async function fetchAcademicOptions(appBasePath) {
  165. const url = `${appBasePath}/kbcx/xskbcx_cxXskbcxIndex.html?gnmkdm=N2151&layout=default`;
  166. try {
  167. const response = await fetch(url, {
  168. method: "GET",
  169. credentials: "include"
  170. });
  171. if (!response.ok) return null;
  172. const html = await response.text();
  173. const document = new DOMParser().parseFromString(html, "text/html");
  174. const readOptions = selector => {
  175. const nodes = document.querySelectorAll(selector);
  176. const options = [];
  177. for (let index = 0; index < nodes.length; index++) {
  178. const option = nodes[index];
  179. const value = String(option.value || "").trim();
  180. const text = String(option.textContent || "").trim();
  181. if (value === "" || text === "") continue;
  182. options.push({ value, text, selected: option.selected });
  183. }
  184. return options;
  185. };
  186. const allYearOptions = readOptions("#xnm option");
  187. const semesterOptions = readOptions("#xqm option");
  188. if (allYearOptions.length === 0 || semesterOptions.length === 0) return null;
  189. const selectedYearIndex = allYearOptions.findIndex(option => option.selected);
  190. const start = selectedYearIndex === -1 ? 0 : Math.max(0, selectedYearIndex - 2);
  191. const end = selectedYearIndex === -1
  192. ? Math.min(allYearOptions.length, 5)
  193. : Math.min(allYearOptions.length, selectedYearIndex + 3);
  194. const yearOptions = allYearOptions.slice(start, end);
  195. const selectedSemesterIndex = semesterOptions.findIndex(option => option.selected);
  196. return {
  197. yearOptions,
  198. semesterOptions,
  199. defaultYearIndex: selectedYearIndex === -1 ? 0 : selectedYearIndex - start,
  200. defaultSemesterIndex: selectedSemesterIndex === -1 ? 0 : selectedSemesterIndex
  201. };
  202. } catch (error) {
  203. console.error("JS: 获取学年学期列表失败:", error);
  204. return null;
  205. }
  206. }
  207. async function selectAcademicYearAndSemester(appBasePath) {
  208. const options = await fetchAcademicOptions(appBasePath);
  209. if (!options) {
  210. await window.shiguangBridgePromise.showAlert(
  211. "无法读取学年学期",
  212. "请确认已登录教务系统,并重新尝试导入。",
  213. "确定"
  214. );
  215. return null;
  216. }
  217. const yearIndex = await window.shiguangBridgePromise.showSingleSelection(
  218. "选择学年",
  219. JSON.stringify(options.yearOptions.map(option => option.text)),
  220. options.defaultYearIndex
  221. );
  222. if (yearIndex === null || yearIndex === -1 || !options.yearOptions[yearIndex]) return null;
  223. const semesterIndex = await window.shiguangBridgePromise.showSingleSelection(
  224. "选择学期",
  225. JSON.stringify(options.semesterOptions.map(option => option.text)),
  226. options.defaultSemesterIndex
  227. );
  228. if (
  229. semesterIndex === null ||
  230. semesterIndex === -1 ||
  231. !options.semesterOptions[semesterIndex]
  232. ) return null;
  233. return {
  234. academicYear: options.yearOptions[yearIndex].value,
  235. semesterCode: options.semesterOptions[semesterIndex].value
  236. };
  237. }
  238. async function fetchSemesterStartDate(appBasePath, academicYear, semesterCode) {
  239. const url = `${appBasePath}/kbcx/xskbcxZccx_cxZcByXnxq.html?gnmkdm=N2154`;
  240. try {
  241. const response = await postForm(url, `xnm=${academicYear}&xqm=${semesterCode}`);
  242. const data = await response.json();
  243. if (!Array.isArray(data) || data.length === 0) return null;
  244. const firstWeek = data.find(item => String(item.zs) === "1" || String(item.zsmc) === "1") || data[0];
  245. if (firstWeek.rq) {
  246. const date = String(firstWeek.rq).split("/")[0];
  247. if (/^\d{4}-\d{2}-\d{2}$/.test(date)) return date;
  248. }
  249. if (firstWeek.zcrq) {
  250. const match = String(firstWeek.zcrq).match(/\d{4}-\d{2}-\d{2}/);
  251. if (match) return match[0];
  252. }
  253. } catch (error) {
  254. console.error("JS: 获取开学日期失败:", error);
  255. }
  256. return null;
  257. }
  258. async function fetchCourses(appBasePath, academicYear, semesterCode) {
  259. const url = `${appBasePath}/kbcx/xskbcx_cxXsgrkb.html?gnmkdm=N2151`;
  260. const body = `xnm=${academicYear}&xqm=${semesterCode}&kzlx=ck&xsdm=&kclbdm=`;
  261. const response = await postForm(url, body);
  262. const data = await response.json();
  263. return parseJsonData(data);
  264. }
  265. async function saveImportResult(courses, semesterStartDate) {
  266. await window.shiguangBridgePromise.saveImportedCourses(JSON.stringify(courses, null, 2));
  267. const config = { semesterTotalWeeks: 20 };
  268. if (semesterStartDate) config.semesterStartDate = semesterStartDate;
  269. await window.shiguangBridgePromise.saveCourseConfig(JSON.stringify(config));
  270. await window.shiguangBridgePromise.savePresetTimeSlots(JSON.stringify(NJUPT_TIME_SLOTS));
  271. }
  272. async function runImportFlow() {
  273. const confirmed = await window.shiguangBridgePromise.showAlert(
  274. "南京邮电大学课表导入",
  275. "请先登录智慧校园并进入教务系统,建议打开课表页面后再导入。",
  276. "好的,开始导入"
  277. );
  278. if (!confirmed) return;
  279. const appBasePath = getNjuptApiBasePath();
  280. if (appBasePath === null) {
  281. await window.shiguangBridgePromise.showAlert(
  282. "无法识别当前页面",
  283. "请先从智慧校园进入教务系统,并打开课表页面后重试。",
  284. "确定"
  285. );
  286. return;
  287. }
  288. try {
  289. const selection = await selectAcademicYearAndSemester(appBasePath);
  290. if (!selection) return;
  291. const { academicYear, semesterCode } = selection;
  292. window.shiguangBridge.showToast("正在从教务系统获取课表...");
  293. const [courses, semesterStartDate] = await Promise.all([
  294. fetchCourses(appBasePath, academicYear, semesterCode),
  295. fetchSemesterStartDate(appBasePath, academicYear, semesterCode)
  296. ]);
  297. if (courses.length === 0) {
  298. await window.shiguangBridgePromise.showAlert(
  299. "未获取到课程",
  300. "请确认已登录教务系统,并检查所选学年、学期是否正确。",
  301. "确定"
  302. );
  303. return;
  304. }
  305. await saveImportResult(courses, semesterStartDate);
  306. const dateMessage = semesterStartDate ? `,开学日期 ${semesterStartDate}` : "";
  307. window.shiguangBridge.showToast(`导入成功:${courses.length} 门课程${dateMessage}`);
  308. window.shiguangBridge.notifyTaskCompletion();
  309. } catch (error) {
  310. console.error("JS: API 课表导入失败:", error);
  311. await window.shiguangBridgePromise.showAlert(
  312. "导入失败",
  313. `无法从教务系统 API 获取或保存数据:${error.message}`,
  314. "确定"
  315. );
  316. }
  317. }
  318. runImportFlow();