xjtu.js 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281
  1. /**
  2. * 西安交通大学教务系统课表适配脚本 (API版)
  3. * 适配系统: e-hall 教务系统 (wdkb)
  4. * API端点: xskcb.do (课程数据), dqxnxq.do (当前学期)
  5. */
  6. const BASE_URL = 'https://ehall.xjtu.edu.cn/jwapp/sys/wdkb/modules';
  7. // ==================== 周次解析 ====================
  8. /**
  9. * 将 SKZC 二进制位串解析为周次数组
  10. * 输入: "000001" → [6], "00000000000000001111" → [1,2,3,4]
  11. * SKZC 是二进制字符串,从左到右依次表示第1-20周,'1'表示上课
  12. */
  13. function parseWeeksFromBinary(skzc) {
  14. if (!skzc) return [];
  15. const weeks = [];
  16. for (let i = 0; i < skzc.length; i++) {
  17. if (skzc[i] === '1') {
  18. weeks.push(i + 1);
  19. }
  20. }
  21. return weeks;
  22. }
  23. // ==================== 学期选择 ====================
  24. /**
  25. * 生成学期选项列表
  26. * 格式: ["2025-2026 秋季(1)", "2025-2026 春季(2)", "2025-2026 暑假(4)"]
  27. */
  28. function generateSemesterOptions(currentYear) {
  29. const options = [];
  30. const semesterNames = { '1': '秋季', '2': '春季', '4': '暑假' };
  31. const semesterCodes = ['1', '2', '4'];
  32. // 从当前学年前2年到后1年
  33. const startYear = parseInt(currentYear.split('-')[0], 10) - 1;
  34. const endYear = parseInt(currentYear.split('-')[0], 10) + 1;
  35. for (let y = endYear; y >= startYear; y--) {
  36. const yearCode = `${y}-${y + 1}`;
  37. for (const semCode of semesterCodes) {
  38. const xnxqdm = `${yearCode}-${semCode}`;
  39. const displayName = `${yearCode}学年 ${semesterNames[semCode]}`;
  40. options.push({ xnxqdm, displayName });
  41. }
  42. }
  43. return options;
  44. }
  45. /**
  46. * 获取当前学期信息
  47. */
  48. async function fetchCurrentSemester() {
  49. try {
  50. const response = await fetch(`${BASE_URL}/jshkcb/dqxnxq.do`, {
  51. method: 'POST',
  52. headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' },
  53. credentials: 'include'
  54. });
  55. if (!response.ok) return null;
  56. const data = await response.json();
  57. const row = data?.datas?.dqxnxq?.rows?.[0];
  58. return row ? row.DM : null;
  59. } catch (e) {
  60. console.warn('获取当前学期失败:', e);
  61. return null;
  62. }
  63. }
  64. /**
  65. * 让用户选择学年学期
  66. */
  67. async function selectSemester() {
  68. // 获取当前学期
  69. const currentSemester = await fetchCurrentSemester();
  70. if (!currentSemester) {
  71. shiguangBridge.showToast('获取学期信息失败,请确保已登录');
  72. return null;
  73. }
  74. // 从当前学期提取学年
  75. const parts = currentSemester.split('-');
  76. const currentYear = `${parts[0]}-${parts[1]}`;
  77. // 生成选项
  78. const options = generateSemesterOptions(currentYear);
  79. const displayNames = options.map(o => o.displayName);
  80. // 找到当前学期的默认索引
  81. const defaultIndex = options.findIndex(o => o.xnxqdm === currentSemester);
  82. const selectedIndex = await window.shiguangBridgePromise.showSingleSelection(
  83. '选择学期',
  84. JSON.stringify(displayNames),
  85. defaultIndex >= 0 ? defaultIndex : 0
  86. );
  87. if (selectedIndex === null || selectedIndex < 0) return null;
  88. return options[selectedIndex].xnxqdm;
  89. }
  90. // ==================== 课程数据获取与解析 ====================
  91. /**
  92. * 从API获取课程数据
  93. */
  94. async function fetchCourses(xnxqdm) {
  95. const response = await fetch(`${BASE_URL}/xskcb/xskcb.do`, {
  96. method: 'POST',
  97. headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' },
  98. body: `XNXQDM=${xnxqdm}`,
  99. credentials: 'include'
  100. });
  101. if (!response.ok) throw new Error('请求课程数据失败');
  102. const data = await response.json();
  103. if (data.code !== '0') throw new Error('课程数据返回异常');
  104. return data?.datas?.xskcb?.rows || [];
  105. }
  106. /**
  107. * 按课程代码分组,合并同课程不同天的记录
  108. * API返回的每条记录是一门课在某一天的信息
  109. * 需要将同一KCH的记录合并,将多天信息聚合到一起
  110. */
  111. function groupCoursesByCode(rows) {
  112. const grouped = {};
  113. for (const row of rows) {
  114. const key = `${row.KCH}_${row.KSJC}_${row.JASMC}`;
  115. if (!grouped[key]) {
  116. grouped[key] = {
  117. name: row.KCM || '',
  118. teacher: row.SKJS || '',
  119. position: row.JASMC || '',
  120. startSection: parseInt(row.KSJC, 10),
  121. endSection: parseInt(row.JSJC, 10),
  122. days: [],
  123. weeks: []
  124. };
  125. }
  126. const day = parseInt(row.SKXQ, 10);
  127. if (day >= 1 && day <= 7 && !grouped[key].days.includes(day)) {
  128. grouped[key].days.push(day);
  129. }
  130. const weeks = parseWeeksFromBinary(row.SKZC);
  131. grouped[key].weeks = [...new Set([...grouped[key].weeks, ...weeks])].sort((a, b) => a - b);
  132. }
  133. return Object.values(grouped);
  134. }
  135. /**
  136. * 将分组后的课程数据展开为拾光课程表格式
  137. * 每个课程 × 每天 生成一条独立记录
  138. */
  139. function buildCourseList(groupedCourses) {
  140. const courses = [];
  141. for (const g of groupedCourses) {
  142. if (!g.name || g.days.length === 0 || g.weeks.length === 0) continue;
  143. for (const day of g.days) {
  144. courses.push({
  145. name: g.name,
  146. teacher: g.teacher,
  147. position: g.position,
  148. day: day,
  149. startSection: g.startSection,
  150. endSection: g.endSection,
  151. weeks: g.weeks
  152. });
  153. }
  154. }
  155. return courses;
  156. }
  157. // ==================== 时间段配置 ====================
  158. // 每节课50分钟,相邻节间休息10分钟,每两节之间休息20分钟
  159. // 早上8:00,下午夏令时14:30/冬令时14:00,晚上夏令时19:40/冬令时19:10
  160. const TIME_SLOTS_SUMMER = [
  161. { "number": 1, "startTime": "08:00", "endTime": "08:50" },
  162. { "number": 2, "startTime": "09:00", "endTime": "09:50" },
  163. { "number": 3, "startTime": "10:10", "endTime": "11:00" },
  164. { "number": 4, "startTime": "11:10", "endTime": "12:00" },
  165. { "number": 5, "startTime": "14:30", "endTime": "15:20" },
  166. { "number": 6, "startTime": "15:30", "endTime": "16:20" },
  167. { "number": 7, "startTime": "16:40", "endTime": "17:30" },
  168. { "number": 8, "startTime": "17:40", "endTime": "18:30" },
  169. { "number": 9, "startTime": "19:40", "endTime": "20:30" },
  170. { "number": 10, "startTime": "20:40", "endTime": "21:30" },
  171. { "number": 11, "startTime": "21:40", "endTime": "22:30" }
  172. ];
  173. const TIME_SLOTS_WINTER = [
  174. { "number": 1, "startTime": "08:00", "endTime": "08:50" },
  175. { "number": 2, "startTime": "09:00", "endTime": "09:50" },
  176. { "number": 3, "startTime": "10:10", "endTime": "11:00" },
  177. { "number": 4, "startTime": "11:10", "endTime": "12:00" },
  178. { "number": 5, "startTime": "14:00", "endTime": "14:50" },
  179. { "number": 6, "startTime": "15:00", "endTime": "15:50" },
  180. { "number": 7, "startTime": "16:10", "endTime": "17:00" },
  181. { "number": 8, "startTime": "17:10", "endTime": "18:00" },
  182. { "number": 9, "startTime": "19:10", "endTime": "20:00" },
  183. { "number": 10, "startTime": "20:10", "endTime": "21:00" },
  184. { "number": 11, "startTime": "21:10", "endTime": "22:00" }
  185. ];
  186. async function importTimeSlots() {
  187. try {
  188. const selectedIndex = await window.shiguangBridgePromise.showSingleSelection(
  189. '选择作息时间',
  190. JSON.stringify(['夏令时 (下午14:30 晚上19:40)', '冬令时 (下午14:00 晚上19:10)']),
  191. 0
  192. );
  193. if (selectedIndex === null) return;
  194. const timeSlots = selectedIndex === 0 ? TIME_SLOTS_SUMMER : TIME_SLOTS_WINTER;
  195. await window.shiguangBridgePromise.savePresetTimeSlots(JSON.stringify(timeSlots));
  196. } catch (e) {
  197. console.warn('时间段导入失败:', e);
  198. }
  199. }
  200. // ==================== 主流程 ====================
  201. async function importXJTUCourses() {
  202. try {
  203. // 1. 提示用户确认已登录
  204. const confirmed = await window.shiguangBridgePromise.showAlert(
  205. '课表导入',
  206. '导入前请确保已在浏览器中成功登录西安交通大学教务系统',
  207. '好的,开始导入'
  208. );
  209. if (!confirmed) {
  210. shiguangBridge.showToast('用户取消了导入');
  211. return;
  212. }
  213. // 2. 选择学年学期
  214. const xnxqdm = await selectSemester();
  215. if (!xnxqdm) {
  216. shiguangBridge.showToast('未选择学期,导入终止');
  217. return;
  218. }
  219. // 3. 获取课程数据
  220. shiguangBridge.showToast('正在获取课程数据...');
  221. const rows = await fetchCourses(xnxqdm);
  222. if (rows.length === 0) {
  223. shiguangBridge.showToast('该学期暂无课程数据');
  224. return;
  225. }
  226. // 4. 解析并构建课程列表
  227. const grouped = groupCoursesByCode(rows);
  228. const courses = buildCourseList(grouped);
  229. if (courses.length === 0) {
  230. shiguangBridge.showToast('课程数据解析失败');
  231. return;
  232. }
  233. // 5. 导入课程
  234. const result = await window.shiguangBridgePromise.saveImportedCourses(JSON.stringify(courses));
  235. if (result !== true) {
  236. shiguangBridge.showToast('课程导入失败,请重试');
  237. return;
  238. }
  239. // 6. 导入时间段配置
  240. await importTimeSlots();
  241. // 7. 完成
  242. shiguangBridge.showToast(`成功导入 ${courses.length} 门课程`);
  243. shiguangBridge.notifyTaskCompletion();
  244. } catch (error) {
  245. console.error('XJTU导入错误:', error);
  246. shiguangBridge.showToast('导入出错: ' + error.message);
  247. }
  248. }
  249. // 启动导入
  250. importXJTUCourses();