njfu_01.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346
  1. const STANDARD_TIME_SLOTS = [
  2. { number: 1, startTime: "08:00", endTime: "08:45" },
  3. { number: 2, startTime: "08:55", endTime: "09:40" },
  4. { number: 3, startTime: "10:00", endTime: "10:45" },
  5. { number: 4, startTime: "10:55", endTime: "11:40" },
  6. { number: 5, startTime: "14:00", endTime: "14:45" },
  7. { number: 6, startTime: "14:50", endTime: "15:35" },
  8. { number: 7, startTime: "15:55", endTime: "16:40" },
  9. { number: 8, startTime: "16:45", endTime: "17:30" },
  10. { number: 9, startTime: "18:30", endTime: "19:15" },
  11. { number: 10, startTime: "19:20", endTime: "20:05" },
  12. { number: 11, startTime: "20:10", endTime: "20:55" }
  13. ];
  14. const CAMPUS_TIME_SLOTS = {
  15. "新庄校区": STANDARD_TIME_SLOTS,
  16. "淮安校区": STANDARD_TIME_SLOTS,
  17. "白马校区": [
  18. { number: 1, startTime: "08:30", endTime: "09:15" },
  19. { number: 2, startTime: "09:20", endTime: "10:05" },
  20. { number: 3, startTime: "10:25", endTime: "11:10" },
  21. { number: 4, startTime: "11:15", endTime: "12:00" },
  22. { number: 5, startTime: "14:00", endTime: "14:45" },
  23. { number: 6, startTime: "14:50", endTime: "15:35" },
  24. { number: 7, startTime: "15:55", endTime: "16:40" },
  25. { number: 8, startTime: "16:45", endTime: "17:30" },
  26. { number: 9, startTime: "18:30", endTime: "19:15" },
  27. { number: 10, startTime: "19:20", endTime: "20:05" },
  28. { number: 11, startTime: "20:10", endTime: "20:55" }
  29. ]
  30. };
  31. const CAMPUS_KEYWORDS = [
  32. { campus: "淮安校区", keywords: ["淮安校区"] },
  33. { campus: "白马校区", keywords: ["白马校区"] },
  34. { campus: "新庄校区", keywords: ["新庄校区"] }
  35. ];
  36. function cleanPosition(position) {
  37. return String(position || "")
  38. .replace(/^(新庄校区|淮安校区|白马校区)/, "")
  39. .replace(/[((]\d+人[))]\s*$/g, "")
  40. .trim() || "待定";
  41. }
  42. function showToast(message) {
  43. if (typeof window.AndroidBridge !== "undefined") {
  44. AndroidBridge.showToast(message);
  45. } else {
  46. console.log(message);
  47. }
  48. }
  49. function parseWeeks(rawText) {
  50. if (!rawText) return [];
  51. const weekPart = String(rawText)
  52. .replace(/\s+/g, "")
  53. .replace(/\(周\).*/, "")
  54. .replace(/周次[::]?/g, "");
  55. const weeks = new Set();
  56. weekPart.split(/[,,]/).forEach((segment) => {
  57. if (!segment) return;
  58. const isOdd = segment.includes("单");
  59. const isEven = segment.includes("双");
  60. const cleaned = segment.replace(/[单双周]/g, "");
  61. const match = cleaned.match(/^(\d+)(?:-(\d+))?$/);
  62. if (!match) return;
  63. const start = Number(match[1]);
  64. const end = Number(match[2] || match[1]);
  65. for (let week = start; week <= end; week++) {
  66. if (isOdd && week % 2 === 0) continue;
  67. if (isEven && week % 2 !== 0) continue;
  68. weeks.add(week);
  69. }
  70. });
  71. return Array.from(weeks).sort((a, b) => a - b);
  72. }
  73. function detectCampusOrNull(...texts) {
  74. const text = texts
  75. .filter(Boolean)
  76. .map((item) => String(item))
  77. .join(" ");
  78. for (const item of CAMPUS_KEYWORDS) {
  79. if (item.keywords.some((keyword) => text.includes(keyword))) {
  80. return item.campus;
  81. }
  82. }
  83. return null;
  84. }
  85. function readLineTexts(div) {
  86. const cloned = div.cloneNode(true);
  87. cloned.querySelectorAll(".item-box").forEach((node) => node.remove());
  88. return cloned.innerHTML
  89. .split(/<br\s*\/?>/i)
  90. .map((line) => line.replace(/<[^>]+>/g, "").trim())
  91. .filter(Boolean);
  92. }
  93. function extractCourseName(lines) {
  94. const metadataPrefixes = ["通知单编号", "班级", "备注"];
  95. const metadataKeywords = ["周", "节", "教师", "教室", "校区"];
  96. const nameLines = [];
  97. for (const line of lines) {
  98. if (!line) continue;
  99. if (metadataPrefixes.some((prefix) => line.startsWith(prefix))) break;
  100. if (metadataKeywords.some((keyword) => line.includes(keyword))) break;
  101. nameLines.push(line);
  102. }
  103. return nameLines.join("").trim();
  104. }
  105. function parseCourseBlock(blockHtml, fallbackDay) {
  106. const tempDiv = document.createElement("div");
  107. tempDiv.innerHTML = blockHtml;
  108. const lines = readLineTexts(tempDiv);
  109. if (!lines.length) return null;
  110. const name = extractCourseName(lines);
  111. const teacher = tempDiv.querySelector('font[title="教师"]')?.innerText.trim() || "未知";
  112. const positionRaw = tempDiv.querySelector('font[title="教室"]')?.innerText.trim() || "待定";
  113. const building = tempDiv.querySelector('font[title="教学楼"]')?.innerText.trim()
  114. || tempDiv.querySelector('font[name="jxlmc"]')?.innerText.trim()
  115. || "";
  116. const position = cleanPosition(positionRaw);
  117. const timeText = tempDiv.querySelector('font[title="周次(节次)"]')?.innerText.trim() || "";
  118. if (!timeText) return null;
  119. const weekMatch = timeText.match(/^(.*?)\(周\)/);
  120. const sectionMatch = timeText.match(/\[(\d+)(?:-(\d+))?(?:-(\d+))?(?:-(\d+))?节\]/);
  121. const weeks = parseWeeks(weekMatch ? weekMatch[1] : timeText);
  122. let startSection = 0;
  123. let endSection = 0;
  124. if (sectionMatch) {
  125. const values = sectionMatch.slice(1).filter(Boolean).map(Number);
  126. startSection = values[0];
  127. endSection = values[values.length - 1];
  128. }
  129. if (!name || !weeks.length || !startSection || !endSection) return null;
  130. return {
  131. name,
  132. teacher,
  133. position,
  134. day: fallbackDay,
  135. startSection,
  136. endSection,
  137. weeks,
  138. campus: detectCampusOrNull(positionRaw, building, lines.join(" "))
  139. };
  140. }
  141. function extractCoursesFromDoc(doc) {
  142. const table = doc.getElementById("timetable");
  143. if (!table) {
  144. throw new Error("未获取到课表表格,请确认当前账号已登录教务系统。");
  145. }
  146. const rows = Array.from(table.querySelectorAll("tr")).slice(1, -1);
  147. const courses = [];
  148. rows.forEach((row) => {
  149. const cells = Array.from(row.querySelectorAll("td"));
  150. cells.forEach((cell, index) => {
  151. const day = index + 1;
  152. const detailDivs = cell.querySelectorAll("div.kbcontent");
  153. detailDivs.forEach((div) => {
  154. const html = div.innerHTML.trim();
  155. if (!html || html === "&nbsp;") return;
  156. const blocks = html.split(/-{10,}\s*<br\s*\/?>/i).filter((item) => item.trim());
  157. if (!blocks.length) blocks.push(html);
  158. blocks.forEach((block) => {
  159. const course = parseCourseBlock(block, day);
  160. if (course) {
  161. courses.push(course);
  162. }
  163. });
  164. });
  165. });
  166. });
  167. const uniqueMap = new Map();
  168. courses.forEach((course) => {
  169. const key = [
  170. course.name,
  171. course.teacher,
  172. course.position,
  173. course.day,
  174. course.startSection,
  175. course.endSection,
  176. course.weeks.join(",")
  177. ].join("|");
  178. if (!uniqueMap.has(key)) {
  179. uniqueMap.set(key, course);
  180. }
  181. });
  182. return Array.from(uniqueMap.values());
  183. }
  184. function choosePrimaryCampus(courses) {
  185. for (const course of courses) {
  186. if (course.campus) {
  187. return course.campus;
  188. }
  189. }
  190. return "新庄校区";
  191. }
  192. function normalizeCourses(courses, primaryCampus) {
  193. return courses.map((course) => {
  194. return {
  195. name: course.name,
  196. teacher: course.teacher,
  197. position: course.position,
  198. day: course.day,
  199. startSection: course.startSection,
  200. endSection: course.endSection,
  201. weeks: course.weeks,
  202. campus: course.campus || primaryCampus
  203. };
  204. });
  205. }
  206. function parseSemesterOptions(doc) {
  207. const select = doc.getElementById("xnxq01id");
  208. if (!select) return { labels: [], values: [], defaultIndex: 0 };
  209. const labels = [];
  210. const values = [];
  211. let defaultIndex = 0;
  212. Array.from(select.querySelectorAll("option")).forEach((option) => {
  213. labels.push(option.innerText.trim());
  214. values.push(option.value);
  215. if (option.selected || option.hasAttribute("selected")) {
  216. defaultIndex = labels.length - 1;
  217. }
  218. });
  219. return { labels, values, defaultIndex };
  220. }
  221. async function fetchTermDoc(termValue) {
  222. const body = new URLSearchParams();
  223. if (termValue) body.append("xnxq01id", termValue);
  224. const response = await fetch("/jsxsd/xskb/xskb_list.do", {
  225. method: termValue ? "POST" : "GET",
  226. headers: termValue ? { "Content-Type": "application/x-www-form-urlencoded" } : undefined,
  227. body: termValue ? body.toString() : undefined,
  228. credentials: "include"
  229. });
  230. const html = await response.text();
  231. return new DOMParser().parseFromString(html, "text/html");
  232. }
  233. async function pickTerm(doc) {
  234. const { labels, values, defaultIndex } = parseSemesterOptions(doc);
  235. if (!labels.length || typeof window.AndroidBridgePromise === "undefined") {
  236. return { doc, termLabel: labels[defaultIndex] || "" };
  237. }
  238. const selectedIndex = await window.AndroidBridgePromise.showSingleSelection(
  239. "请选择要导入的学期",
  240. JSON.stringify(labels),
  241. defaultIndex
  242. );
  243. if (selectedIndex === null || selectedIndex === -1) {
  244. throw new Error("已取消导入");
  245. }
  246. if (selectedIndex === defaultIndex) {
  247. return { doc, termLabel: labels[selectedIndex] };
  248. }
  249. const selectedDoc = await fetchTermDoc(values[selectedIndex]);
  250. return { doc: selectedDoc, termLabel: labels[selectedIndex] };
  251. }
  252. async function saveToApp(courses, primaryCampus) {
  253. const timeSlots = CAMPUS_TIME_SLOTS[primaryCampus];
  254. const allWeeks = courses.flatMap((course) => course.weeks || []);
  255. const semesterTotalWeeks = allWeeks.length ? Math.max(...allWeeks) : 20;
  256. if (typeof window.AndroidBridgePromise === "undefined") {
  257. console.log("Primary campus:", primaryCampus);
  258. console.log("Time slots:", timeSlots);
  259. console.log("Courses:", courses);
  260. alert(`解析完成:${primaryCampus},共 ${courses.length} 门课程。请查看控制台输出。`);
  261. return;
  262. }
  263. await window.AndroidBridgePromise.saveCourseConfig(JSON.stringify({
  264. semesterTotalWeeks,
  265. firstDayOfWeek: 1
  266. }));
  267. await window.AndroidBridgePromise.savePresetTimeSlots(JSON.stringify(timeSlots));
  268. const appCourses = courses.map(({ campus, ...course }) => course);
  269. await window.AndroidBridgePromise.saveImportedCourses(JSON.stringify(appCourses));
  270. }
  271. async function runImportFlow() {
  272. try {
  273. showToast("正在获取 NJFU 课表数据...");
  274. const initialDoc = await fetchTermDoc("");
  275. const { doc, termLabel } = await pickTerm(initialDoc);
  276. const parsedCourses = extractCoursesFromDoc(doc);
  277. if (!parsedCourses.length) {
  278. throw new Error("未解析到课程,请确认当前账号已登录教务系统。");
  279. }
  280. const primaryCampus = choosePrimaryCampus(parsedCourses);
  281. const courses = normalizeCourses(parsedCourses, primaryCampus);
  282. await saveToApp(courses, primaryCampus);
  283. const message = `导入完成:${primaryCampus}${termLabel ? ` ${termLabel}` : ""}`;
  284. showToast(message);
  285. if (typeof window.AndroidBridge !== "undefined") {
  286. AndroidBridge.notifyTaskCompletion();
  287. }
  288. } catch (error) {
  289. console.error(error);
  290. showToast(`导入失败: ${error.message}`);
  291. }
  292. }
  293. runImportFlow();