mysy.js 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353
  1. // 绵阳师范学院正方教务系统课表适配脚本
  2. // 页面为 frameset 结构,课表主体在 iframe[name="Frame1"] 的 #kbtable 中。
  3. function showToast(message) {
  4. try {
  5. const bridge = window.shiguangBridge;
  6. if (bridge && typeof bridge.showToast === 'function') {
  7. bridge.showToast(message);
  8. }
  9. } catch (error) {
  10. console.error('[MYSY] showToast failed:', error);
  11. }
  12. }
  13. function getScheduleDocument() {
  14. if (document.querySelector && document.querySelector('#kbtable')) {
  15. return document;
  16. }
  17. const frames = [
  18. document.querySelector('iframe[name="Frame1"]'),
  19. document.querySelector('frame[name="Frame1"]')
  20. ];
  21. for (const frame of frames) {
  22. if (!frame) continue;
  23. try {
  24. const doc = frame.contentDocument || frame.contentWindow.document;
  25. if (doc && doc.querySelector('#kbtable')) return doc;
  26. } catch (error) {
  27. console.warn('[MYSY] Unable to access Frame1 document:', error);
  28. }
  29. }
  30. try {
  31. const namedFrame = window.frames && window.frames['Frame1'];
  32. if (namedFrame && namedFrame.document && namedFrame.document.querySelector('#kbtable')) {
  33. return namedFrame.document;
  34. }
  35. } catch (error) {
  36. console.warn('[MYSY] Unable to access named Frame1:', error);
  37. }
  38. return null;
  39. }
  40. function waitForScheduleTable(timeoutMs) {
  41. const timeout = timeoutMs || 15000;
  42. const start = Date.now();
  43. return new Promise((resolve) => {
  44. const check = () => {
  45. const doc = getScheduleDocument();
  46. if (doc && doc.querySelector('#kbtable')) {
  47. resolve(doc);
  48. return;
  49. }
  50. if (Date.now() - start >= timeout) {
  51. resolve(getScheduleDocument());
  52. return;
  53. }
  54. setTimeout(check, 250);
  55. };
  56. check();
  57. });
  58. }
  59. function parseWeeks(weekStr) {
  60. if (!weekStr) return [];
  61. const cleaned = String(weekStr)
  62. .replace(/\[[^\]]*节[^\]]*\]/g, '')
  63. .replace(/\s+/g, '');
  64. const weeks = [];
  65. const parts = cleaned.split(/[,,]/).filter(Boolean);
  66. for (const part of parts) {
  67. const parityMatch = part.match(/[((](单|双)[))]/);
  68. const parity = parityMatch ? parityMatch[1] : null;
  69. const numeric = part
  70. .replace(/[((](单|双)[))]/g, '')
  71. .replace(/[((]周[))]/g, '')
  72. .replace(/周/g, '');
  73. const match = numeric.match(/^(\d+)(?:[-~到](\d+))?$/);
  74. if (!match) continue;
  75. const start = Number(match[1]);
  76. const end = match[2] ? Number(match[2]) : start;
  77. for (let week = start; week <= end; week++) {
  78. if (parity === '单' && week % 2 === 0) continue;
  79. if (parity === '双' && week % 2 === 1) continue;
  80. weeks.push(week);
  81. }
  82. }
  83. return Array.from(new Set(weeks)).sort((a, b) => a - b);
  84. }
  85. function parseSectionRange(text) {
  86. const match = String(text || '').match(/\[(\d{1,2})(?:\s*[-~]\s*(\d{1,2}))?节\]/);
  87. if (!match) return null;
  88. return {
  89. start: Number(match[1]),
  90. end: Number(match[2] || match[1])
  91. };
  92. }
  93. function getDirectText(element) {
  94. const parts = [];
  95. for (const node of element.childNodes) {
  96. if (node.nodeType !== 3) continue;
  97. const text = (node.textContent || '').replace(/\s+/g, ' ').trim();
  98. if (text) parts.push(text);
  99. }
  100. return parts.join(' ').trim();
  101. }
  102. function getTitledText(element, title) {
  103. const target = element.querySelector(`font[title="${title}"]`);
  104. if (!target) return '';
  105. return (target.textContent || '').replace(/\s+/g, ' ').trim();
  106. }
  107. function parseCourseDiv(div) {
  108. const text = (div.textContent || '').replace(/\s+/g, ' ').trim();
  109. if (!text) return null;
  110. const idParts = (div.getAttribute('id') || '').split('_');
  111. const day = Number(idParts[1]) || 0;
  112. const name = getDirectText(div);
  113. const teacher = getTitledText(div, '老师') || '待定';
  114. const position = getTitledText(div, '教室') || '待定';
  115. const timeText = getTitledText(div, '周次(节次)');
  116. const weeks = parseWeeks(timeText);
  117. if (!name || weeks.length === 0 || day < 1 || day > 7) return null;
  118. const section = parseSectionRange(timeText);
  119. const course = {
  120. name: name,
  121. teacher: teacher,
  122. position: position,
  123. day: day,
  124. startSection: section ? section.start : 0,
  125. endSection: section ? section.end : 0,
  126. weeks: weeks
  127. };
  128. return course;
  129. }
  130. function extractCourses(doc) {
  131. const table = doc.querySelector('#kbtable');
  132. if (!table) return [];
  133. const courses = [];
  134. const seen = new Set();
  135. table.querySelectorAll('div.kbcontent').forEach((div) => {
  136. const course = parseCourseDiv(div);
  137. if (!course) return;
  138. const key = JSON.stringify(course);
  139. if (seen.has(key)) return;
  140. seen.add(key);
  141. courses.push(course);
  142. });
  143. courses.sort((a, b) => {
  144. if (a.day !== b.day) return a.day - b.day;
  145. if (a.startSection !== b.startSection) return a.startSection - b.startSection;
  146. return a.name.localeCompare(b.name);
  147. });
  148. return courses;
  149. }
  150. function toMinutes(hhmm) {
  151. const parts = String(hhmm).split(':').map(Number);
  152. return parts[0] * 60 + parts[1];
  153. }
  154. function toHHMM(totalMinutes) {
  155. const hours = Math.floor(totalMinutes / 60);
  156. const minutes = totalMinutes % 60;
  157. return `${String(hours).padStart(2, '0')}:${String(minutes).padStart(2, '0')}`;
  158. }
  159. function generateTimeSlots(doc) {
  160. const fallback = [
  161. { number: 1, startTime: '08:00', endTime: '08:45' },
  162. { number: 2, startTime: '08:50', endTime: '09:35' },
  163. { number: 3, startTime: '09:55', endTime: '10:40' },
  164. { number: 4, startTime: '10:45', endTime: '11:30' },
  165. { number: 5, startTime: '11:35', endTime: '12:20' },
  166. { number: 6, startTime: '14:00', endTime: '14:45' },
  167. { number: 7, startTime: '14:50', endTime: '15:35' },
  168. { number: 8, startTime: '15:55', endTime: '16:40' },
  169. { number: 9, startTime: '16:45', endTime: '17:30' },
  170. { number: 10, startTime: '17:35', endTime: '18:20' },
  171. { number: 11, startTime: '19:00', endTime: '19:45' },
  172. { number: 12, startTime: '19:50', endTime: '20:35' },
  173. { number: 13, startTime: '20:40', endTime: '21:25' }
  174. ];
  175. const table = doc.querySelector('#kbtable');
  176. if (!table) return fallback;
  177. const blocks = [];
  178. table.querySelectorAll('tr th[rowspan]').forEach((th) => {
  179. const text = (th.textContent || '').replace(/\s+/g, ' ').trim();
  180. const match = text.match(/(\d{1,2}):(\d{2})\s*[-~]\s*(\d{1,2}):(\d{2})/);
  181. if (!match) return;
  182. const rowspan = Number(th.getAttribute('rowspan')) || 1;
  183. blocks.push({
  184. rowspan: rowspan,
  185. start: `${match[1]}:${match[2]}`,
  186. end: `${match[3]}:${match[4]}`
  187. });
  188. });
  189. if (blocks.length === 0) return fallback;
  190. const slots = [];
  191. let number = 1;
  192. const classDuration = 45;
  193. const breakDuration = 5;
  194. for (const block of blocks) {
  195. const count = Math.max(1, block.rowspan);
  196. let cursor = toMinutes(block.start);
  197. for (let i = 0; i < count; i++) {
  198. const start = cursor;
  199. const end = start + classDuration;
  200. slots.push({
  201. number: number,
  202. startTime: toHHMM(start),
  203. endTime: toHHMM(end)
  204. });
  205. number++;
  206. cursor = end + (i < count - 1 ? breakDuration : 0);
  207. }
  208. }
  209. return slots.length > 0 ? slots : fallback;
  210. }
  211. async function saveCourses(courses) {
  212. try {
  213. if (!window.shiguangBridgePromise || typeof window.shiguangBridgePromise.saveImportedCourses !== 'function') {
  214. throw new Error('saveImportedCourses bridge not found');
  215. }
  216. await window.shiguangBridgePromise.saveImportedCourses(JSON.stringify(courses));
  217. return true;
  218. } catch (error) {
  219. console.error('[MYSY] save courses failed:', error);
  220. showToast(`课表保存失败: ${error.message}`);
  221. return false;
  222. }
  223. }
  224. async function saveTimeSlots(slots) {
  225. try {
  226. if (!window.shiguangBridgePromise || typeof window.shiguangBridgePromise.savePresetTimeSlots !== 'function') {
  227. throw new Error('savePresetTimeSlots bridge not found');
  228. }
  229. await window.shiguangBridgePromise.savePresetTimeSlots(JSON.stringify(slots));
  230. return true;
  231. } catch (error) {
  232. console.error('[MYSY] save time slots failed:', error);
  233. showToast(`时间模板保存失败: ${error.message}`);
  234. return false;
  235. }
  236. }
  237. async function saveCourseConfig() {
  238. try {
  239. if (!window.shiguangBridgePromise || typeof window.shiguangBridgePromise.saveCourseConfig !== 'function') {
  240. return;
  241. }
  242. await window.shiguangBridgePromise.saveCourseConfig(JSON.stringify({
  243. semesterTotalWeeks: 20,
  244. defaultClassDuration: 45,
  245. defaultBreakDuration: 5,
  246. firstDayOfWeek: 1
  247. }));
  248. } catch (error) {
  249. console.warn('[MYSY] save course config failed:', error);
  250. }
  251. }
  252. async function runImportFlow() {
  253. console.log('[MYSY] 开始导入绵阳师范学院课表...');
  254. showToast('正在检查课表页面...');
  255. const doc = await waitForScheduleTable(15000);
  256. if (!doc || !doc.querySelector('#kbtable')) {
  257. showToast('未找到课表,请先打开“学期理论课表”并确认已加载');
  258. return;
  259. }
  260. const courses = extractCourses(doc);
  261. if (courses.length === 0) {
  262. showToast('未找到已安排上课时间的课程');
  263. return;
  264. }
  265. try {
  266. const confirmed = await window.shiguangBridgePromise.showAlert(
  267. '教务系统课表导入',
  268. `检测到 ${courses.length} 门课程,是否导入?`,
  269. '确认导入'
  270. );
  271. if (!confirmed) {
  272. showToast('已取消导入');
  273. return;
  274. }
  275. } catch (error) {
  276. console.warn('[MYSY] confirmation dialog unavailable:', error);
  277. }
  278. if (!(await saveCourses(courses))) return;
  279. const timeSlots = generateTimeSlots(doc);
  280. if (!(await saveTimeSlots(timeSlots))) return;
  281. await saveCourseConfig();
  282. showToast(`课表导入成功,共导入 ${courses.length} 门课程`);
  283. console.log(`[MYSY] 成功导入 ${courses.length} 门课程`);
  284. try {
  285. if (window.shiguangBridge && typeof window.shiguangBridge.notifyTaskCompletion === 'function') {
  286. window.shiguangBridge.notifyTaskCompletion();
  287. }
  288. } catch (error) {
  289. console.warn('[MYSY] notifyTaskCompletion failed:', error);
  290. }
  291. }
  292. if (/mtc\.edu\.cn$/i.test(window.location.hostname)) {
  293. setTimeout(runImportFlow, 800);
  294. } else {
  295. showToast('请先在绵阳师范学院教务系统打开课表页面');
  296. }