cjlu.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312
  1. // 基于 HTML 页面抓取的拾光课表正方适配脚本
  2. // 中国计量大学(cjlu.edu.cn)
  3. /**
  4. * 解析表格
  5. */
  6. function parserTbale() {
  7. const regexName = /[●★○]/g;
  8. const courseInfoList = [];
  9. const $ = window.jQuery;
  10. if (!$) return courseInfoList;
  11. $('#kbgrid_table_0 td').each((i, td) => {
  12. if ($(td).hasClass('td_wrap') && $(td).text().trim() !== '') {
  13. const day = parseInt($(td).attr('id').split('-')[0]);
  14. $(td).find('.timetable_con.text-left').each((i, course) => {
  15. const name = $(course).find('.title font').text().replace(regexName, '').trim();
  16. const infoStr = $(course).find('p').eq(0).find('font').eq(1).text().trim();
  17. const position = $(course).find('p').eq(1).find('font').text().trim();
  18. const teacher = $(course).find('p').eq(2).find('font').text().trim();
  19. if (infoStr && infoStr.match(/\((\d+-\d+节)\)/) && infoStr.split('节)')[1]) {
  20. const [sections, weeks] = parserInfo(infoStr);
  21. if (name && position && teacher && sections.length && weeks.length) {
  22. const startSection = sections[0];
  23. const endSection = sections[sections.length - 1];
  24. const finalPosition = position.split(/\s+/).pop();
  25. const data = { name, day, weeks, teacher, position: finalPosition, startSection, endSection };
  26. courseInfoList.push(data);
  27. }
  28. }
  29. });
  30. }
  31. });
  32. return courseInfoList;
  33. }
  34. /**
  35. * 解析列表
  36. */
  37. function parserList() {
  38. const regexName = /[●★○]/g;
  39. const regexWeekNum = /周数:|周/g;
  40. const regexPosition = /上课地点:/g;
  41. const regexTeacher = /教师 :/g;
  42. const $ = window.jQuery;
  43. if (!$) return [];
  44. let courseInfoList = [];
  45. $('#kblist_table tbody').each((day, tbody) => {
  46. if (day > 0 && day < 8) {
  47. let sections;
  48. $(tbody).find('tr:not(:first-child)').each((trIndex, tr) => {
  49. let name, font;
  50. if ($(tr).find('td').length > 1) {
  51. sections = parserSections($(tr).find('td:first-child').text());
  52. name = $(tr).find('td:nth-child(2)').find('.title').text().replace(regexName, '').trim();
  53. font = $(tr).find('td:nth-child(2)').find('p font');
  54. } else {
  55. name = $(tr).find('td').find('.title').text().replace(regexName, '').trim();
  56. font = $(tr).find('td').find('p font');
  57. }
  58. const weekStr = $(font[0]).text().replace(regexWeekNum, '').trim();
  59. const weeks = parserWeeks(weekStr);
  60. const positionRaw = $(font[1]).text().replace(regexPosition, '').trim();
  61. const finalPosition = positionRaw.split(/\s+/).pop();
  62. const teacher = $(font[2]).text().replace(regexTeacher, '').trim();
  63. if (name && sections && weeks.length && teacher && finalPosition) {
  64. const startSection = sections[0];
  65. const endSection = sections[sections.length - 1];
  66. const data = {
  67. name,
  68. day,
  69. weeks,
  70. teacher,
  71. position: finalPosition,
  72. startSection,
  73. endSection
  74. };
  75. courseInfoList.push(data);
  76. }
  77. });
  78. }
  79. });
  80. return courseInfoList;
  81. }
  82. /**
  83. * 解析课程信息
  84. */
  85. function parserInfo(str) {
  86. const sections = parserSections(str.match(/\((\d+-\d+节)\)/)[1].replace(/节/g, ''));
  87. const weekStrWithMarker = str.split('节)')[1];
  88. const weeks = parserWeeks(weekStrWithMarker.replace(/周/g, '').trim());
  89. return [sections, weeks];
  90. }
  91. /**
  92. * 解析节次
  93. */
  94. function parserSections(str) {
  95. const [start, end] = str.split('-').map(Number);
  96. if (isNaN(start) || isNaN(end) || start > end) return [];
  97. return Array.from({ length: end - start + 1 }, (_, i) => start + i);
  98. }
  99. /**
  100. * 解析周次
  101. */
  102. function parserWeeks(str) {
  103. const segments = str.split(',');
  104. let weeks = [];
  105. const segmentRegex = /(\d+)(?:-(\d+))?\s*(\([单双]\))?/g;
  106. for (const segment of segments) {
  107. const cleanSegment = segment.replace(/周/g, '').trim();
  108. segmentRegex.lastIndex = 0;
  109. let match;
  110. while ((match = segmentRegex.exec(cleanSegment)) !== null) {
  111. const start = parseInt(match[1]);
  112. const end = match[2] ? parseInt(match[2]) : start;
  113. const flagStr = match[3] || '';
  114. let flag = 0;
  115. if (flagStr.includes('单')) {
  116. flag = 1;
  117. } else if (flagStr.includes('双')) {
  118. flag = 2;
  119. }
  120. for (let i = start; i <= end; i++) {
  121. if (flag === 1 && i % 2 !== 1) continue;
  122. if (flag === 2 && i % 2 !== 0) continue;
  123. if (!weeks.includes(i)) {
  124. weeks.push(i);
  125. }
  126. }
  127. }
  128. }
  129. return weeks.sort((a, b) => a - b);
  130. }
  131. /**
  132. * 构建课表配置,从课程数据中推断最大周次
  133. */
  134. function buildCourseConfig(courses) {
  135. let maxWeek = 0;
  136. for (const course of courses) {
  137. for (const week of course.weeks) {
  138. if (week > maxWeek) {
  139. maxWeek = week;
  140. }
  141. }
  142. }
  143. return {
  144. semesterTotalWeeks: maxWeek || 20,
  145. firstDayOfWeek: 1
  146. };
  147. }
  148. /**
  149. * 抓取和解析课程数据
  150. */
  151. async function scrapeAndParseCourses() {
  152. AndroidBridge.showToast("正在检查页面并抓取课程数据...");
  153. const ts = `1.登陆教务系统\n2.导航到学生课表查询页面\n3.等待课表信息加载,选择对应学年、学期,确认无误后点击【查询】\n4.确保页面上显示了课程表\n5.点击下方【一键导入】`;
  154. try {
  155. const response = await fetch(window.location.href);
  156. const text = await response.text();
  157. if (!text.includes("课表查询")) {
  158. await window.AndroidBridgePromise.showAlert("导入失败", "当前页面似乎不是学生课表查询页面。请检查:\n" + ts, "确定");
  159. return null;
  160. }
  161. const typeElement = document.querySelector('#shcPDF');
  162. if (!typeElement) {
  163. await window.AndroidBridgePromise.showAlert("导入失败", "未能识别课表视图类型,请确认您已点击查询且课表已加载完毕。", "确定");
  164. return null;
  165. }
  166. const type = typeElement.dataset['type'];
  167. const tableElement = document.querySelector(type === 'list' ? '#kblist_table' : '#kbgrid_table_0');
  168. if (!tableElement) {
  169. await window.AndroidBridgePromise.showAlert("导入失败", `未能找到课表主体 (${type} 视图),请确认您已点击查询且课表已加载完毕。`, "确定");
  170. return null;
  171. }
  172. let result = [];
  173. if (type === 'list') {
  174. result = parserList();
  175. } else {
  176. result = parserTbale();
  177. }
  178. if (result.length === 0) {
  179. AndroidBridge.showToast("未找到任何课程数据,请检查所选学年学期是否正确或本学期无课。");
  180. return null;
  181. }
  182. console.log(`JS: 课程数据解析成功,共找到 ${result.length} 门课程。`);
  183. const config = buildCourseConfig(result);
  184. return { courses: result, config: config };
  185. } catch (error) {
  186. AndroidBridge.showToast(`抓取或解析失败: ${error.message}`);
  187. console.error('JS: Scrape/Parse Error:', error);
  188. await window.AndroidBridgePromise.showAlert("抓取或解析失败", `发生错误:${error.message}。请重试或联系开发者。`, "确定");
  189. return null;
  190. }
  191. }
  192. async function saveCourses(parsedCourses) {
  193. AndroidBridge.showToast(`正在保存 ${parsedCourses.length} 门课程...`);
  194. console.log(`JS: 尝试保存 ${parsedCourses.length} 门课程...`);
  195. try {
  196. await window.AndroidBridgePromise.saveImportedCourses(JSON.stringify(parsedCourses, null, 2));
  197. console.log("JS: 课程保存成功!");
  198. return true;
  199. } catch (error) {
  200. AndroidBridge.showToast(`课程保存失败: ${error.message}`);
  201. console.error('JS: Save Courses Error:', error);
  202. return false;
  203. }
  204. }
  205. // 中国计量大学作息时间表
  206. const TimeSlots = [
  207. { number: 1, startTime: "08:00", endTime: "08:45" },
  208. { number: 2, startTime: "08:50", endTime: "09:35" },
  209. { number: 3, startTime: "09:55", endTime: "10:40" },
  210. { number: 4, startTime: "10:45", endTime: "11:30" },
  211. { number: 5, startTime: "11:35", endTime: "12:20" },
  212. { number: 6, startTime: "13:30", endTime: "14:15" },
  213. { number: 7, startTime: "14:20", endTime: "15:05" },
  214. { number: 8, startTime: "15:15", endTime: "16:00" },
  215. { number: 9, startTime: "16:05", endTime: "16:50" },
  216. { number: 10, startTime: "18:00", endTime: "18:45" },
  217. { number: 11, startTime: "18:50", endTime: "19:35" },
  218. { number: 12, startTime: "19:40", endTime: "20:25" }
  219. ];
  220. async function importPresetTimeSlots(timeSlots) {
  221. if (timeSlots.length > 0) {
  222. AndroidBridge.showToast(`正在导入 ${timeSlots.length} 个预设时间段...`);
  223. try {
  224. await window.AndroidBridgePromise.savePresetTimeSlots(JSON.stringify(timeSlots));
  225. AndroidBridge.showToast("预设时间段导入成功!");
  226. } catch (error) {
  227. AndroidBridge.showToast("导入时间段失败: " + error.message);
  228. console.error('JS: Save Time Slots Error:', error);
  229. }
  230. }
  231. }
  232. async function runImportFlow() {
  233. const alertConfirmed = await window.AndroidBridgePromise.showAlert(
  234. "教务系统课表导入",
  235. "导入前请确保您已在浏览器中成功登录中国计量大学教务系统,\n并处于课表查询页面且已点击查询。",
  236. "好的,开始导入"
  237. );
  238. if (!alertConfirmed) {
  239. AndroidBridge.showToast("用户取消了导入。");
  240. return;
  241. }
  242. if (typeof window.jQuery === 'undefined' && typeof $ === 'undefined') {
  243. const errorMsg = "当前教务系统页面似乎没有加载 jQuery 库。本脚本依赖 jQuery 进行 DOM 解析。";
  244. AndroidBridge.showToast(errorMsg);
  245. await window.AndroidBridgePromise.showAlert("导入失败", errorMsg + "\n请尝试刷新页面或使用其他导入方式。", "确定");
  246. console.error("JS: 缺少 jQuery 依赖,流程终止。");
  247. return;
  248. }
  249. const result = await scrapeAndParseCourses();
  250. if (result === null) {
  251. return;
  252. }
  253. const { courses, config } = result;
  254. const saveResult = await saveCourses(courses);
  255. if (!saveResult) {
  256. return;
  257. }
  258. try {
  259. await window.AndroidBridgePromise.saveCourseConfig(JSON.stringify(config));
  260. AndroidBridge.showToast(`课表配置更新成功!总周数:${config.semesterTotalWeeks}周。`);
  261. } catch (error) {
  262. AndroidBridge.showToast(`课表配置保存失败: ${error.message}`);
  263. console.error('JS: Save Config Error:', error);
  264. }
  265. await importPresetTimeSlots(TimeSlots);
  266. AndroidBridge.showToast(`课程导入成功,共导入 ${courses.length} 门课程!`);
  267. console.log("JS: 整个导入流程执行完毕并成功。");
  268. AndroidBridge.notifyTaskCompletion();
  269. }
  270. runImportFlow();