hbguhx_01.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440
  1. // 河北地质大学华信学院强智教务 (61.182.88.214:8090) 拾光课程表适配脚本
  2. // 非该大学开发者适配,开发者无法及时发现问题
  3. // 出现问题请联系开发者或者提交 pr 更改,这更加快速
  4. /**
  5. * 解析周次字符串为数组
  6. */
  7. function parseWeeks(weekStr) {
  8. const weeks = [];
  9. if (!weekStr) return weeks;
  10. // 移除"周"字、括号和节次信息
  11. const pureWeekData = weekStr.replace(/周|\(.*?\)|\[\d+-\d+ 节\]/g, '').trim();
  12. if (!pureWeekData) return weeks;
  13. // 分割并处理每个段
  14. const segments = pureWeekData.split(',');
  15. segments.forEach(seg => {
  16. seg = seg.trim();
  17. if (!seg) return;
  18. if (seg.includes('-')) {
  19. const [start, end] = seg.split('-').map(Number);
  20. if (!isNaN(start) && !isNaN(end)) {
  21. for (let i = start; i <= end; i++) {
  22. weeks.push(i);
  23. }
  24. }
  25. } else {
  26. const w = parseInt(seg);
  27. if (!isNaN(w)) {
  28. weeks.push(w);
  29. }
  30. }
  31. });
  32. return [...new Set(weeks)].sort((a, b) => a - b);
  33. }
  34. /**
  35. * 合并连续节次的相同课程
  36. */
  37. function mergeAndDistinctCourses(courses) {
  38. if (courses.length <= 1) return courses;
  39. // 排序以便合并
  40. courses.sort((a, b) => {
  41. if (a.name !== b.name) return a.name.localeCompare(b.name);
  42. if (a.day !== b.day) return a.day - b.day;
  43. if (a.startSection !== b.startSection) return a.startSection - b.startSection;
  44. if (a.teacher !== b.teacher) return a.teacher.localeCompare(b.teacher);
  45. if (a.position !== b.position) return a.position.localeCompare(b.position);
  46. return a.weeks.join(',').localeCompare(b.weeks.join(','));
  47. });
  48. const merged = [];
  49. let current = courses[0];
  50. for (let i = 1; i < courses.length; i++) {
  51. const next = courses[i];
  52. // 判断是否为同一门课程
  53. const isSameCourse =
  54. current.name === next.name &&
  55. current.teacher === next.teacher &&
  56. current.position === next.position &&
  57. current.day === next.day &&
  58. current.weeks.join(',') === next.weeks.join(',');
  59. // 判断节次是否连续
  60. const isContinuous = (current.endSection + 1 === next.startSection);
  61. if (isSameCourse && isContinuous) {
  62. // 合并连续节次
  63. current.endSection = next.endSection;
  64. } else if (!(isSameCourse && current.startSection === next.startSection && current.endSection === next.endSection)) {
  65. merged.push(current);
  66. current = next;
  67. }
  68. }
  69. merged.push(current);
  70. return merged;
  71. }
  72. /**
  73. * 将 HTML 源码解析为课程模型
  74. */
  75. function parseTimetableToModel(htmlString) {
  76. const doc = new DOMParser().parseFromString(htmlString, "text/html");
  77. const timetable = doc.getElementById('kbtable');
  78. if (!timetable) {
  79. console.log('未找到课表表格元素');
  80. return [];
  81. }
  82. let rawCourses = [];
  83. const rows = Array.from(timetable.querySelectorAll('tr')).filter(r => r.querySelector('td'));
  84. console.log('找到课表行:', rows.length);
  85. rows.forEach((row, rowIndex) => {
  86. const cells = row.querySelectorAll('td');
  87. console.log(`第 ${rowIndex} 行,找到 ${cells.length} 个单元格`);
  88. cells.forEach((cell, dayIndex) => {
  89. const day = dayIndex + 1; // 星期几(1-7)
  90. // 获取所有课程详情 div,包括所有状态的
  91. const detailDivs = Array.from(cell.querySelectorAll('div.kbcontent'));
  92. console.log(`第 ${dayIndex} 天,找到 ${detailDivs.length} 个课程 div`);
  93. detailDivs.forEach((detailDiv, divIndex) => {
  94. const rawHtml = detailDiv.innerHTML.trim();
  95. const innerText = detailDiv.innerText.trim();
  96. console.log(`第 ${divIndex} 个 div,内容:`, innerText.substring(0, 100));
  97. if (!rawHtml || rawHtml === "&nbsp;" || innerText.length < 2) return;
  98. // 分割同一个格子内的多门课程
  99. const blocks = rawHtml.split(/---------------------|----------------------/);
  100. console.log(`分割出 ${blocks.length} 个课程块`);
  101. blocks.forEach((block, blockIndex) => {
  102. if (!block.trim()) return;
  103. const tempDiv = document.createElement('div');
  104. tempDiv.innerHTML = block;
  105. // 1. 提取课程名(包含所有文本,包括实验标记)
  106. let name = "";
  107. const firstLine = tempDiv.innerHTML.split('<br>')[0].trim();
  108. // 移除HTML标签,保留文本内容
  109. name = firstLine.replace(/<[^>]*>/g, '').trim();
  110. console.log(`课程名:${name}`);
  111. if (!name) return;
  112. // 2. 提取周次和节次信息
  113. const weekFont = tempDiv.querySelector('font[title="周次(节次)"]');
  114. const weekFull = weekFont?.innerText || "";
  115. console.log(`周次和节次信息:${weekFull}`);
  116. let startSection = 0;
  117. let endSection = 0;
  118. let weekStr = "";
  119. // 匹配 "1-17(周)[01-02节]" 格式
  120. const weekSectionMatch = weekFull.match(/(.+?)\(周\)\[(\d+)-(\d+)节\]/);
  121. if (weekSectionMatch) {
  122. weekStr = weekSectionMatch[1]; // "1-17"
  123. startSection = parseInt(weekSectionMatch[2], 10);
  124. endSection = parseInt(weekSectionMatch[3], 10);
  125. console.log(`匹配到格式1:周次=${weekStr}, 开始节次=${startSection}, 结束节次=${endSection}`);
  126. } else {
  127. // 尝试匹配 "1-17(周)[01-02 节]" 格式(带空格)
  128. const weekSectionMatchWithSpace = weekFull.match(/(.+?)\(周\)\[(\d+)-(\d+) 节\]/);
  129. if (weekSectionMatchWithSpace) {
  130. weekStr = weekSectionMatchWithSpace[1];
  131. startSection = parseInt(weekSectionMatchWithSpace[2], 10);
  132. endSection = parseInt(weekSectionMatchWithSpace[3], 10);
  133. console.log(`匹配到格式2:周次=${weekStr}, 开始节次=${startSection}, 结束节次=${endSection}`);
  134. } else {
  135. // 尝试匹配其他格式
  136. const altMatch = weekFull.match(/(\d+)-(\d+)/);
  137. if (altMatch) {
  138. weekStr = altMatch[0];
  139. // 假设是第1-2节
  140. startSection = 1;
  141. endSection = 2;
  142. console.log(`匹配到格式3:周次=${weekStr}, 开始节次=${startSection}, 结束节次=${endSection}`);
  143. } else {
  144. console.log('未匹配到周次和节次信息');
  145. }
  146. }
  147. }
  148. // 3. 提取教师信息
  149. const teacher = tempDiv.querySelector('font[title="老师"]')?.innerText.trim() || "未知教师";
  150. console.log(`教师:${teacher}`);
  151. // 4. 提取教室地点
  152. const position = tempDiv.querySelector('font[title="教室"]')?.innerText.trim() || "未知地点";
  153. console.log(`地点:${position}`);
  154. if (name && startSection > 0) {
  155. const course = {
  156. "name": name,
  157. "teacher": teacher,
  158. "weeks": parseWeeks(weekStr),
  159. "position": position,
  160. "day": day,
  161. "startSection": startSection,
  162. "endSection": endSection
  163. };
  164. rawCourses.push(course);
  165. console.log('添加课程:', course);
  166. }
  167. });
  168. });
  169. });
  170. });
  171. console.log(`原始课程数量:${rawCourses.length}`);
  172. const mergedCourses = mergeAndDistinctCourses(rawCourses);
  173. console.log(`合并后课程数量:${mergedCourses.length}`);
  174. return mergedCourses;
  175. }
  176. /**
  177. * 从网页中提取学期选项列表
  178. */
  179. function extractSemesterOptions(htmlString) {
  180. const doc = new DOMParser().parseFromString(htmlString, "text/html");
  181. const semesterSelect = doc.getElementById('xnxq01id');
  182. if (!semesterSelect) {
  183. console.log('未找到学期选择元素');
  184. return [];
  185. }
  186. const options = Array.from(semesterSelect.querySelectorAll('option')).map(opt => ({
  187. value: opt.value,
  188. text: opt.text
  189. }));
  190. console.log(`提取到 ${options.length} 个学期选项`);
  191. return options;
  192. }
  193. /**
  194. * 从网页中提取作息时间
  195. */
  196. function extractTimeSlots(htmlString) {
  197. const doc = new DOMParser().parseFromString(htmlString, "text/html");
  198. const timetable = doc.getElementById('kbtable');
  199. if (!timetable) return null;
  200. const timeSlots = [];
  201. const rows = Array.from(timetable.querySelectorAll('tr'));
  202. rows.forEach((row) => {
  203. const th = row.querySelector('th');
  204. if (!th) return;
  205. // 提取时间范围,如 "08:30-10:05"
  206. const timeText = th.innerText.trim();
  207. const timeMatch = timeText.match(/(\d{2}:\d{2})-(\d{2}:\d{2})/);
  208. if (timeMatch) {
  209. const startTime = timeMatch[1];
  210. const endTime = timeMatch[2];
  211. // 判断是否是有效的时间段(排除"中午"等)
  212. const sectionName = timeText.split('\n')[0].trim();
  213. if (startTime && endTime && sectionName !== '中午') {
  214. // 为每个大节创建两个时间段
  215. const sections = [
  216. {
  217. number: timeSlots.length + 1,
  218. startTime: startTime,
  219. endTime: `${startTime.split(':')[0]}:45`
  220. },
  221. {
  222. number: timeSlots.length + 2,
  223. startTime: `${startTime.split(':')[0]}:55`,
  224. endTime: endTime
  225. }
  226. ];
  227. timeSlots.push(...sections);
  228. }
  229. }
  230. });
  231. return timeSlots.length > 0 ? timeSlots : null;
  232. }
  233. /**
  234. * 显示欢迎提示
  235. */
  236. async function showWelcomeAlert() {
  237. return await window.AndroidBridgePromise.showAlert(
  238. "导入提示",
  239. "请确保已在内置浏览器中成功登录河北地质大学华信学院教务系统。",
  240. "开始导入"
  241. );
  242. }
  243. /**
  244. * 获取用户选择的学期参数
  245. */
  246. async function getSemesterParamsFromUser(semesterOptions) {
  247. if (!semesterOptions || semesterOptions.length === 0) {
  248. AndroidBridge.showToast("未获取到学期列表");
  249. return null;
  250. }
  251. // 直接显示所有学期选项,让用户一次性选择
  252. const semesterLabels = semesterOptions.map(opt => opt.text);
  253. const semesterIndex = await window.AndroidBridgePromise.showSingleSelection(
  254. "选择学期",
  255. JSON.stringify(semesterLabels),
  256. 0 // 默认选择第一个(最新学期)
  257. );
  258. if (semesterIndex === null) return null;
  259. return semesterOptions[semesterIndex].value;
  260. }
  261. /**
  262. * 请求课表 HTML 数据
  263. */
  264. async function fetchCourseHtml() {
  265. try {
  266. AndroidBridge.showToast("正在获取课表页面...");
  267. const response = await fetch("http://61.182.88.214:8090/jsxsd/xskb/xskb_list.do", {
  268. method: "GET",
  269. credentials: "include",
  270. headers: {
  271. "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36"
  272. }
  273. });
  274. if (!response.ok) {
  275. throw new Error(`HTTP error! status: ${response.status}`);
  276. }
  277. const text = await response.text();
  278. console.log('获取到课表页面,状态码:', response.status);
  279. return text;
  280. } catch (error) {
  281. console.error('获取课表页面失败:', error);
  282. AndroidBridge.showToast("获取课表页面失败:" + error.message);
  283. throw error;
  284. }
  285. }
  286. /**
  287. * 保存课程数据到 App
  288. */
  289. async function saveCourseDataToApp(courses, timeSlots) {
  290. // 保存学期配置
  291. await window.AndroidBridgePromise.saveCourseConfig(JSON.stringify({
  292. "semesterTotalWeeks": 20,
  293. "firstDayOfWeek": 1
  294. }));
  295. // 保存作息时间(从网页提取)
  296. if (timeSlots && timeSlots.length > 0) {
  297. await window.AndroidBridgePromise.savePresetTimeSlots(JSON.stringify(timeSlots));
  298. }
  299. // 保存课程数据
  300. return await window.AndroidBridgePromise.saveImportedCourses(JSON.stringify(courses));
  301. }
  302. /**
  303. * 主流程控制
  304. */
  305. async function runImportFlow() {
  306. try {
  307. // 1. 显示欢迎提示
  308. const start = await showWelcomeAlert();
  309. if (!start) return;
  310. // 2. 获取课表 HTML(包含学期选项和作息时间)
  311. AndroidBridge.showToast("正在获取课表页面...");
  312. const html = await fetchCourseHtml();
  313. console.log('获取到课表页面 HTML,长度:', html.length);
  314. // 3. 从网页中提取学期选项
  315. const semesterOptions = extractSemesterOptions(html);
  316. console.log('学期选项:', semesterOptions);
  317. // 4. 从网页中提取作息时间
  318. let timeSlots = extractTimeSlots(html);
  319. if (!timeSlots || timeSlots.length === 0) {
  320. console.warn("未能从网页提取作息时间,使用默认值");
  321. // 设置默认作息时间
  322. timeSlots = [
  323. { number: 1, startTime: "08:30", endTime: "09:15" },
  324. { number: 2, startTime: "09:25", endTime: "10:10" },
  325. { number: 3, startTime: "10:15", endTime: "11:00" },
  326. { number: 4, startTime: "11:10", endTime: "11:55" },
  327. { number: 5, startTime: "14:30", endTime: "15:15" },
  328. { number: 6, startTime: "15:25", endTime: "16:10" },
  329. { number: 7, startTime: "16:15", endTime: "17:00" },
  330. { number: 8, startTime: "17:10", endTime: "17:55" },
  331. { number: 9, startTime: "19:00", endTime: "19:45" },
  332. { number: 10, startTime: "19:55", endTime: "20:40" }
  333. ];
  334. }
  335. console.log('作息时间:', timeSlots);
  336. // 5. 让用户选择学期
  337. const semesterId = await getSemesterParamsFromUser(semesterOptions);
  338. if (!semesterId) return;
  339. console.log('选择的学期 ID:', semesterId);
  340. // 6. 根据选择的学期重新请求课表数据
  341. AndroidBridge.showToast("正在请求选定学期的课表数据...");
  342. const response = await fetch("http://61.182.88.214:8090/jsxsd/xskb/xskb_list.do", {
  343. method: "POST",
  344. headers: { "Content-Type": "application/x-www-form-urlencoded" },
  345. body: `cj0701id=&zc=&demo=&xnxq01id=${semesterId}`,
  346. credentials: "include"
  347. });
  348. const courseHtml = await response.text();
  349. console.log('获取到选定学期的课表 HTML,长度:', courseHtml.length);
  350. // 7. 解析课程数据
  351. const finalCourses = parseTimetableToModel(courseHtml);
  352. console.log('解析出的课程:', finalCourses);
  353. if (finalCourses.length === 0) {
  354. AndroidBridge.showToast("未发现课程,请检查学期选择或登录状态。");
  355. // 尝试直接从初始 HTML 中解析课程
  356. const initialCourses = parseTimetableToModel(html);
  357. console.log('从初始 HTML 解析的课程:', initialCourses);
  358. if (initialCourses.length > 0) {
  359. AndroidBridge.showToast("使用初始页面的课程数据");
  360. await saveCourseDataToApp(initialCourses, timeSlots);
  361. AndroidBridge.showToast(`成功导入 ${initialCourses.length} 门课程`);
  362. AndroidBridge.notifyTaskCompletion();
  363. }
  364. return;
  365. }
  366. // 8. 保存课程数据
  367. await saveCourseDataToApp(finalCourses, timeSlots);
  368. AndroidBridge.showToast(`成功导入 ${finalCourses.length} 门课程`);
  369. AndroidBridge.notifyTaskCompletion();
  370. } catch (error) {
  371. console.error('导入异常:', error);
  372. AndroidBridge.showToast("导入异常:" + error.message);
  373. }
  374. }
  375. // 启动执行
  376. runImportFlow();