jngcxy.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379
  1. // 济南工程职业技术学院 — 正方新一代教务(jwglxt)
  2. // 维护者:西郊有密林(@xianzhaowang0-code)
  3. const GNMKDM = "N2151";
  4. const JW_ORIGIN = "http://vpnxt.jngcxy.edu.cn";
  5. const MIN_TOTAL_WEEKS = 20;
  6. const DEFAULT_TIME_SLOTS = [
  7. { number: 1, startTime: "08:30", endTime: "09:15" },
  8. { number: 2, startTime: "09:20", endTime: "10:05" },
  9. { number: 3, startTime: "10:20", endTime: "11:05" },
  10. { number: 4, startTime: "11:10", endTime: "11:55" },
  11. { number: 5, startTime: "13:30", endTime: "14:15" },
  12. { number: 6, startTime: "14:20", endTime: "15:05" },
  13. { number: 7, startTime: "15:15", endTime: "16:00" },
  14. { number: 8, startTime: "16:05", endTime: "16:50" },
  15. { number: 9, startTime: "19:00", endTime: "19:50" },
  16. { number: 10, startTime: "20:00", endTime: "20:50" }
  17. ];
  18. function sortBy(list, key) {
  19. const out = [];
  20. for (let i = 0; i < list.length; i++) out.push(list[i]);
  21. for (let i = 1; i < out.length; i++) {
  22. const current = out[i];
  23. const currentKey = key(current);
  24. let j = i - 1;
  25. while (j >= 0 && key(out[j]) > currentKey) {
  26. out[j + 1] = out[j];
  27. j--;
  28. }
  29. out[j + 1] = current;
  30. }
  31. return out;
  32. }
  33. function toList(data) {
  34. if (Array.isArray(data)) return data;
  35. return (data && (data.data || data.rows)) || [];
  36. }
  37. function buildApiUrl(modulePath) {
  38. const path = String(window.location.pathname || "");
  39. const prefix = (path.match(/^\/(?:https?|webvpn)\/[0-9a-z]+/i) || [""])[0];
  40. const origin = /\/jwglxt\//i.test(path) ? window.location.origin : JW_ORIGIN;
  41. return origin + prefix + "/jwglxt" + modulePath + "?gnmkdm=" + GNMKDM;
  42. }
  43. async function postForm(modulePath, body) {
  44. const response = await fetch(buildApiUrl(modulePath), {
  45. method: "POST",
  46. credentials: "include",
  47. headers: {
  48. "content-type": "application/x-www-form-urlencoded;charset=UTF-8",
  49. "X-Requested-With": "XMLHttpRequest"
  50. },
  51. body: body
  52. });
  53. if (!response.ok) throw new Error("HTTP " + response.status);
  54. const text = await response.text();
  55. if (text.trim().charAt(0) === "<") throw new Error("SESSION_LOST");
  56. return JSON.parse(text);
  57. }
  58. function isOnSsoPage() {
  59. const host = String(window.location.hostname || "");
  60. const path = String(window.location.pathname || "");
  61. return /^uap\./i.test(host) || /\/authserver\//i.test(path) || /\/lyuapServer\//i.test(path);
  62. }
  63. function parseWeeks(text) {
  64. const weeks = new Set();
  65. const parts = String(text || "")
  66. .replace(/[(]/g, "(")
  67. .replace(/[)]/g, ")")
  68. .replace(/[,、;;]/g, ",")
  69. .split(",");
  70. for (let i = 0; i < parts.length; i++) {
  71. const seg = parts[i].trim();
  72. if (!seg) continue;
  73. const range = seg.match(/(\d+)\s*[-~至]\s*(\d+)/);
  74. const single = seg.match(/\d+/);
  75. const start = range ? Number(range[1]) : Number(single && single[0]);
  76. const end = range ? Number(range[2]) : start;
  77. if (!(start > 0) || !(end >= start)) continue;
  78. const odd = seg.indexOf("单") >= 0;
  79. const even = seg.indexOf("双") >= 0;
  80. for (let week = start; week <= end; week++) {
  81. if (odd && week % 2 === 0) continue;
  82. if (even && week % 2 !== 0) continue;
  83. weeks.add(week);
  84. }
  85. }
  86. return sortBy(Array.from(weeks), (week) => week);
  87. }
  88. function parseSections(text) {
  89. const nums = String(text || "").match(/\d+/g);
  90. if (!nums) return null;
  91. let start = 0;
  92. let end = 0;
  93. for (let i = 0; i < nums.length; i++) {
  94. const value = Number(nums[i]);
  95. if (!(value > 0)) continue;
  96. if (!start || value < start) start = value;
  97. if (value > end) end = value;
  98. }
  99. return start ? [start, end] : null;
  100. }
  101. function parseKbList(json) {
  102. const rows = (json && json.kbList) || [];
  103. const courses = [];
  104. const seen = new Set();
  105. let skipped = 0;
  106. for (let i = 0; i < rows.length; i++) {
  107. const row = rows[i] || {};
  108. const name = String(row.kcmc || "").trim();
  109. const day = Number(row.xqj);
  110. const weeks = parseWeeks(row.zcd);
  111. const sections = parseSections(row.jcs);
  112. if (!name || !(day >= 1 && day <= 7) || !weeks.length || !sections) {
  113. skipped++;
  114. continue;
  115. }
  116. const key = [name, row.xm, row.cdmc, day, sections[0], sections[1], weeks.join("-")].join("|");
  117. if (seen.has(key)) continue;
  118. seen.add(key);
  119. const course = {
  120. name: name,
  121. teacher: String(row.xm || "").trim(),
  122. position: String(row.cdmc || "").trim(),
  123. day: day,
  124. startSection: sections[0],
  125. endSection: sections[1],
  126. weeks: weeks
  127. };
  128. const credit = Number(row.xf);
  129. if (credit > 0) course.credit = credit;
  130. courses.push(course);
  131. }
  132. const sorted = sortBy(courses, (course) => course.day * 100 + course.startSection);
  133. console.log(`JS: 课表解析完成,共 ${sorted.length} 条课程记录,跳过 ${skipped} 条无固定时间的记录`);
  134. return sorted;
  135. }
  136. function readOptions(doc, selector) {
  137. const nodes = doc.querySelectorAll(selector + " option");
  138. const options = [];
  139. for (let i = 0; i < nodes.length; i++) {
  140. const node = nodes[i];
  141. const value = String(node.getAttribute("value") || "").trim();
  142. if (!value) continue;
  143. options.push({
  144. value: value,
  145. text: (node.textContent || "").trim(),
  146. selected: node.hasAttribute("selected")
  147. });
  148. }
  149. return options;
  150. }
  151. async function fetchAcademicOptions() {
  152. const response = await fetch(buildApiUrl("/kbcx/xskbcx_cxXskbcxIndex.html"), {
  153. method: "GET",
  154. credentials: "include"
  155. });
  156. if (!response.ok) throw new Error("HTTP " + response.status);
  157. const html = await response.text();
  158. if (/\/authserver\/|name="password"/i.test(html)) throw new Error("SESSION_LOST");
  159. const doc = new DOMParser().parseFromString(html, "text/html");
  160. const yearOptions = readOptions(doc, "#xnm");
  161. const termOptions = readOptions(doc, "#xqm");
  162. if (!yearOptions.length || !termOptions.length) throw new Error("未取到学年/学期选项");
  163. return { yearOptions: yearOptions, termOptions: termOptions };
  164. }
  165. async function chooseYearAndSemester() {
  166. const options = await fetchAcademicOptions();
  167. const { yearOptions, termOptions } = options;
  168. let defaultYear = 0;
  169. for (let i = 0; i < yearOptions.length; i++) {
  170. if (yearOptions[i].selected) defaultYear = i;
  171. }
  172. const yearTexts = [];
  173. for (let i = 0; i < yearOptions.length; i++) yearTexts.push(yearOptions[i].text);
  174. const yearIndex = await window.shiguangBridgePromise.showSingleSelection(
  175. "选择学年", JSON.stringify(yearTexts), defaultYear
  176. );
  177. if (!(yearIndex >= 0)) return null;
  178. let defaultTerm = 0;
  179. for (let i = 0; i < termOptions.length; i++) {
  180. if (termOptions[i].selected) defaultTerm = i;
  181. }
  182. const termTexts = [];
  183. for (let i = 0; i < termOptions.length; i++) termTexts.push(termOptions[i].text);
  184. const termIndex = await window.shiguangBridgePromise.showSingleSelection(
  185. "选择学期", JSON.stringify(termTexts), defaultTerm
  186. );
  187. if (!(termIndex >= 0)) return null;
  188. return {
  189. xnm: yearOptions[yearIndex].value,
  190. xqm: termOptions[termIndex].value
  191. };
  192. }
  193. async function fetchCourseTable(xnm, xqm) {
  194. const body = `xnm=${encodeURIComponent(xnm)}&xqm=${encodeURIComponent(xqm)}&kzlx=ck&xsdm=&kclbdm=`;
  195. return postForm("/kbcx/xskbcx_cxXsgrkb.html", body);
  196. }
  197. async function fetchStartDate(xnm, xqm) {
  198. const body = `xnm=${encodeURIComponent(xnm)}&xqm=${encodeURIComponent(xqm)}`;
  199. const rows = toList(await postForm("/kbcx/xskbcxZccx_cxZcByXnxq.html", body));
  200. let first = rows[0];
  201. for (let i = 0; i < rows.length; i++) {
  202. const item = rows[i] || {};
  203. if (String(item.zs || item.zcmc || "") === "1") first = item;
  204. }
  205. const match = String((first && (first.rq || first.zcrq)) || "").match(/(\d{4})-(\d{1,2})-(\d{1,2})/);
  206. if (!match) throw new Error("未取到本学期开学日期");
  207. return `${match[1]}-${match[2].padStart(2, "0")}-${match[3].padStart(2, "0")}`;
  208. }
  209. async function fetchTimeSlots(xnm, xqm) {
  210. const body = `xnm=${encodeURIComponent(xnm)}&xqm=${encodeURIComponent(xqm)}&kzlx=ck&xsdm=&kclbdm=&kclxdm=`;
  211. let rows;
  212. try {
  213. rows = toList(await postForm("/kbcx/xskbcx_cxRjc.html", body));
  214. } catch (e) {
  215. console.warn("JS: 读取节次作息失败:" + (e && e.message));
  216. return [];
  217. }
  218. const slots = [];
  219. for (let i = 0; i < rows.length; i++) {
  220. const item = rows[i] || {};
  221. const number = Number(item.jcdm);
  222. const sksj = String(item.sksj || "").split(/[~\-—至到]/);
  223. const startTime = String(item.qssj || sksj[0] || "").trim().slice(0, 5);
  224. const endTime = String(item.jssj || sksj[1] || "").trim().slice(0, 5);
  225. if (!(number > 0) || !startTime || !endTime) continue;
  226. slots.push({ number: number, startTime: startTime, endTime: endTime });
  227. }
  228. return sortBy(slots, (slot) => slot.number);
  229. }
  230. function toMinutes(time) {
  231. const match = String(time || "").match(/(\d{1,2}):(\d{2})/);
  232. return match ? Number(match[1]) * 60 + Number(match[2]) : 0;
  233. }
  234. function buildCourseConfig(courses, startDate, firstDayOfWeek, slots) {
  235. let maxWeek = 0;
  236. for (let i = 0; i < courses.length; i++) {
  237. const weeks = courses[i].weeks;
  238. for (let j = 0; j < weeks.length; j++) {
  239. if (weeks[j] > maxWeek) maxWeek = weeks[j];
  240. }
  241. }
  242. return {
  243. semesterStartDate: startDate,
  244. semesterTotalWeeks: Math.max(maxWeek, MIN_TOTAL_WEEKS),
  245. firstDayOfWeek: firstDayOfWeek,
  246. defaultClassDuration: toMinutes(slots[0].endTime) - toMinutes(slots[0].startTime),
  247. defaultBreakDuration: toMinutes(slots[1].startTime) - toMinutes(slots[0].endTime)
  248. };
  249. }
  250. async function runImportFlow() {
  251. const bridge = window.shiguangBridgePromise;
  252. if (isOnSsoPage()) {
  253. await bridge.showAlert(
  254. "还停在统一认证页",
  255. "当前页面是统一认证或门户,请先完成登录,并进入「教务系统」," +
  256. "等地址栏变成教务系统的 /jwglxt/ 页面之后再执行导入。",
  257. "知道了"
  258. );
  259. return;
  260. }
  261. const confirmed = await bridge.showAlert(
  262. "济南工程职业技术学院课表导入",
  263. "开始前请确认:\n" +
  264. "1. 已登录教务系统,且当前页面在教务系统内(地址带 /jwglxt/);\n" +
  265. "2. 校外访问需先连接学校的 aTrust 客户端,否则教务页面无法打开;\n" +
  266. "3. 导入会覆盖应用内现有课表,请先备份需要保留的课程。\n\n" +
  267. "点击「开始导入」后请依次选择学年和学期。",
  268. "开始导入"
  269. );
  270. if (!confirmed) {
  271. window.shiguangBridge.showToast("已取消导入。");
  272. return;
  273. }
  274. window.shiguangBridge.showToast("正在拉取课表...");
  275. let courses;
  276. let startDate;
  277. let slots;
  278. let firstDayOfWeek;
  279. try {
  280. const selection = await chooseYearAndSemester();
  281. if (selection === null) {
  282. window.shiguangBridge.showToast("已取消导入。");
  283. return;
  284. }
  285. const json = await fetchCourseTable(selection.xnm, selection.xqm);
  286. courses = parseKbList(json);
  287. if (!courses.length) {
  288. await bridge.showAlert(
  289. "没有取到课程",
  290. "接口返回了空课表。请确认所选学年/学期是否正确;若确认无误,可能是本学期尚未排课。",
  291. "知道了"
  292. );
  293. return;
  294. }
  295. startDate = await fetchStartDate(selection.xnm, selection.xqm);
  296. slots = await fetchTimeSlots(selection.xnm, selection.xqm);
  297. if (slots.length < 2) {
  298. slots = DEFAULT_TIME_SLOTS;
  299. console.warn("JS: 未取到节次作息,使用内置的本校作息");
  300. window.shiguangBridge.showToast("未取到真实作息,改用内置的本校作息。");
  301. }
  302. const qsxqj = Number(json.qsxqj);
  303. firstDayOfWeek = (qsxqj >= 1 && qsxqj <= 7) ? qsxqj : 1;
  304. window.shiguangBridge.showToast(`解析到 ${courses.length} 条课程记录,正在保存...`);
  305. await bridge.saveImportedCourses(JSON.stringify(courses));
  306. await bridge.savePresetTimeSlots(JSON.stringify(slots));
  307. await bridge.saveCourseConfig(JSON.stringify(
  308. buildCourseConfig(courses, startDate, firstDayOfWeek, slots)
  309. ));
  310. } catch (e) {
  311. const message = e && e.message;
  312. if (message === "SESSION_LOST") {
  313. await bridge.showAlert(
  314. "未登录或会话已失效",
  315. "教务系统返回的是登录页。请先在页面中重新登录教务,再执行导入。",
  316. "知道了"
  317. );
  318. } else {
  319. await bridge.showAlert(
  320. "导入失败",
  321. "错误信息:" + message + "\n\n请确认:\n" +
  322. "1. 已连接校园网,或已先打开学校的 aTrust 客户端;\n" +
  323. "2. 已登录教务系统且页面在 /jwglxt/ 内;\n" +
  324. "3. 所选学年/学期正确。",
  325. "知道了"
  326. );
  327. }
  328. return;
  329. }
  330. window.shiguangBridge.showToast(`导入完成,共 ${courses.length} 条课程`);
  331. console.log(`JS: 导入完成,共 ${courses.length} 条课程,作息 ${slots.length} 节,开学日期 ${startDate}`);
  332. window.shiguangBridge.notifyTaskCompletion();
  333. }
  334. runImportFlow();