@mo7yw4ng/openape 1.0.5 → 2.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (152) hide show
  1. package/bin/openape +29 -0
  2. package/bin/openape.js +29 -0
  3. package/package.json +22 -28
  4. package/LICENSE +0 -21
  5. package/README.md +0 -135
  6. package/esm/_dnt.polyfills.d.ts +0 -101
  7. package/esm/_dnt.polyfills.d.ts.map +0 -1
  8. package/esm/_dnt.polyfills.js +0 -127
  9. package/esm/_dnt.shims.d.ts +0 -6
  10. package/esm/_dnt.shims.d.ts.map +0 -1
  11. package/esm/_dnt.shims.js +0 -61
  12. package/esm/deno.d.ts +0 -25
  13. package/esm/deno.d.ts.map +0 -1
  14. package/esm/deno.js +0 -23
  15. package/esm/package.json +0 -3
  16. package/esm/src/commands/announcements.d.ts +0 -3
  17. package/esm/src/commands/announcements.d.ts.map +0 -1
  18. package/esm/src/commands/announcements.js +0 -134
  19. package/esm/src/commands/assignments.d.ts +0 -3
  20. package/esm/src/commands/assignments.d.ts.map +0 -1
  21. package/esm/src/commands/assignments.js +0 -230
  22. package/esm/src/commands/auth.d.ts +0 -3
  23. package/esm/src/commands/auth.d.ts.map +0 -1
  24. package/esm/src/commands/auth.js +0 -290
  25. package/esm/src/commands/calendar.d.ts +0 -3
  26. package/esm/src/commands/calendar.d.ts.map +0 -1
  27. package/esm/src/commands/calendar.js +0 -179
  28. package/esm/src/commands/courses.d.ts +0 -3
  29. package/esm/src/commands/courses.d.ts.map +0 -1
  30. package/esm/src/commands/courses.js +0 -348
  31. package/esm/src/commands/forums.d.ts +0 -3
  32. package/esm/src/commands/forums.d.ts.map +0 -1
  33. package/esm/src/commands/forums.js +0 -318
  34. package/esm/src/commands/grades.d.ts +0 -3
  35. package/esm/src/commands/grades.d.ts.map +0 -1
  36. package/esm/src/commands/grades.js +0 -121
  37. package/esm/src/commands/materials.d.ts +0 -3
  38. package/esm/src/commands/materials.d.ts.map +0 -1
  39. package/esm/src/commands/materials.js +0 -413
  40. package/esm/src/commands/quizzes.d.ts +0 -3
  41. package/esm/src/commands/quizzes.d.ts.map +0 -1
  42. package/esm/src/commands/quizzes.js +0 -271
  43. package/esm/src/commands/skills.d.ts +0 -3
  44. package/esm/src/commands/skills.d.ts.map +0 -1
  45. package/esm/src/commands/skills.js +0 -106
  46. package/esm/src/commands/upload.d.ts +0 -3
  47. package/esm/src/commands/upload.d.ts.map +0 -1
  48. package/esm/src/commands/upload.js +0 -58
  49. package/esm/src/commands/videos.d.ts +0 -3
  50. package/esm/src/commands/videos.d.ts.map +0 -1
  51. package/esm/src/commands/videos.js +0 -336
  52. package/esm/src/index.d.ts +0 -27
  53. package/esm/src/index.d.ts.map +0 -1
  54. package/esm/src/index.js +0 -160
  55. package/esm/src/lib/auth.d.ts +0 -47
  56. package/esm/src/lib/auth.d.ts.map +0 -1
  57. package/esm/src/lib/auth.js +0 -227
  58. package/esm/src/lib/config.d.ts +0 -6
  59. package/esm/src/lib/config.d.ts.map +0 -1
  60. package/esm/src/lib/config.js +0 -36
  61. package/esm/src/lib/logger.d.ts +0 -3
  62. package/esm/src/lib/logger.d.ts.map +0 -1
  63. package/esm/src/lib/logger.js +0 -27
  64. package/esm/src/lib/moodle.d.ts +0 -433
  65. package/esm/src/lib/moodle.d.ts.map +0 -1
  66. package/esm/src/lib/moodle.js +0 -1318
  67. package/esm/src/lib/session.d.ts +0 -8
  68. package/esm/src/lib/session.d.ts.map +0 -1
  69. package/esm/src/lib/session.js +0 -42
  70. package/esm/src/lib/token.d.ts +0 -38
  71. package/esm/src/lib/token.d.ts.map +0 -1
  72. package/esm/src/lib/token.js +0 -178
  73. package/esm/src/lib/types.d.ts +0 -189
  74. package/esm/src/lib/types.d.ts.map +0 -1
  75. package/esm/src/lib/types.js +0 -2
  76. package/esm/src/lib/utils.d.ts +0 -57
  77. package/esm/src/lib/utils.d.ts.map +0 -1
  78. package/esm/src/lib/utils.js +0 -129
  79. package/script/_dnt.polyfills.d.ts +0 -101
  80. package/script/_dnt.polyfills.d.ts.map +0 -1
  81. package/script/_dnt.polyfills.js +0 -130
  82. package/script/_dnt.shims.d.ts +0 -6
  83. package/script/_dnt.shims.d.ts.map +0 -1
  84. package/script/_dnt.shims.js +0 -65
  85. package/script/deno.d.ts +0 -25
  86. package/script/deno.d.ts.map +0 -1
  87. package/script/deno.js +0 -25
  88. package/script/package.json +0 -3
  89. package/script/src/commands/announcements.d.ts +0 -3
  90. package/script/src/commands/announcements.d.ts.map +0 -1
  91. package/script/src/commands/announcements.js +0 -140
  92. package/script/src/commands/assignments.d.ts +0 -3
  93. package/script/src/commands/assignments.d.ts.map +0 -1
  94. package/script/src/commands/assignments.js +0 -269
  95. package/script/src/commands/auth.d.ts +0 -3
  96. package/script/src/commands/auth.d.ts.map +0 -1
  97. package/script/src/commands/auth.js +0 -296
  98. package/script/src/commands/calendar.d.ts +0 -3
  99. package/script/src/commands/calendar.d.ts.map +0 -1
  100. package/script/src/commands/calendar.js +0 -185
  101. package/script/src/commands/courses.d.ts +0 -3
  102. package/script/src/commands/courses.d.ts.map +0 -1
  103. package/script/src/commands/courses.js +0 -354
  104. package/script/src/commands/forums.d.ts +0 -3
  105. package/script/src/commands/forums.d.ts.map +0 -1
  106. package/script/src/commands/forums.js +0 -324
  107. package/script/src/commands/grades.d.ts +0 -3
  108. package/script/src/commands/grades.d.ts.map +0 -1
  109. package/script/src/commands/grades.js +0 -127
  110. package/script/src/commands/materials.d.ts +0 -3
  111. package/script/src/commands/materials.d.ts.map +0 -1
  112. package/script/src/commands/materials.js +0 -419
  113. package/script/src/commands/quizzes.d.ts +0 -3
  114. package/script/src/commands/quizzes.d.ts.map +0 -1
  115. package/script/src/commands/quizzes.js +0 -277
  116. package/script/src/commands/skills.d.ts +0 -3
  117. package/script/src/commands/skills.d.ts.map +0 -1
  118. package/script/src/commands/skills.js +0 -112
  119. package/script/src/commands/upload.d.ts +0 -3
  120. package/script/src/commands/upload.d.ts.map +0 -1
  121. package/script/src/commands/upload.js +0 -64
  122. package/script/src/commands/videos.d.ts +0 -3
  123. package/script/src/commands/videos.d.ts.map +0 -1
  124. package/script/src/commands/videos.js +0 -342
  125. package/script/src/index.d.ts +0 -27
  126. package/script/src/index.d.ts.map +0 -1
  127. package/script/src/index.js +0 -167
  128. package/script/src/lib/auth.d.ts +0 -47
  129. package/script/src/lib/auth.d.ts.map +0 -1
  130. package/script/src/lib/auth.js +0 -269
  131. package/script/src/lib/config.d.ts +0 -6
  132. package/script/src/lib/config.d.ts.map +0 -1
  133. package/script/src/lib/config.js +0 -42
  134. package/script/src/lib/logger.d.ts +0 -3
  135. package/script/src/lib/logger.d.ts.map +0 -1
  136. package/script/src/lib/logger.js +0 -30
  137. package/script/src/lib/moodle.d.ts +0 -433
  138. package/script/src/lib/moodle.d.ts.map +0 -1
  139. package/script/src/lib/moodle.js +0 -1389
  140. package/script/src/lib/session.d.ts +0 -8
  141. package/script/src/lib/session.d.ts.map +0 -1
  142. package/script/src/lib/session.js +0 -45
  143. package/script/src/lib/token.d.ts +0 -38
  144. package/script/src/lib/token.d.ts.map +0 -1
  145. package/script/src/lib/token.js +0 -189
  146. package/script/src/lib/types.d.ts +0 -189
  147. package/script/src/lib/types.d.ts.map +0 -1
  148. package/script/src/lib/types.js +0 -3
  149. package/script/src/lib/utils.d.ts +0 -57
  150. package/script/src/lib/utils.d.ts.map +0 -1
  151. package/script/src/lib/utils.js +0 -175
  152. package/skills/openape/SKILL.md +0 -115
@@ -1,179 +0,0 @@
1
- import { getBaseDir, formatTimestamp } from "../lib/utils.js";
2
- import { getEnrolledCoursesApi, getCalendarEventsApi } from "../lib/moodle.js";
3
- import { createLogger } from "../lib/logger.js";
4
- import { loadWsToken } from "../lib/token.js";
5
- import path from "node:path";
6
- import fs from "node:fs";
7
- export function registerCalendarCommand(program) {
8
- const calendarCmd = program.command("calendar");
9
- calendarCmd.description("Calendar operations");
10
- // Helper to get output format from global or local options
11
- function getOutputFormat(command) {
12
- const opts = command.optsWithGlobals();
13
- return opts.output || "json";
14
- }
15
- // Pure API context - no browser required (fast!)
16
- async function createApiContext(options, command) {
17
- const opts = command?.optsWithGlobals ? command.optsWithGlobals() : options;
18
- const outputFormat = getOutputFormat(command || { optsWithGlobals: () => ({ output: "json" }) });
19
- const silent = outputFormat === "json" && !opts.verbose;
20
- const log = createLogger(opts.verbose, silent, outputFormat);
21
- const baseDir = getBaseDir();
22
- const sessionPath = path.resolve(baseDir, ".auth", "storage-state.json");
23
- // Check if session exists
24
- if (!fs.existsSync(sessionPath)) {
25
- console.error("未找到登入 session。請先執行 'openape login' 進行登入。");
26
- log.info(`Session 預期位置: ${sessionPath}`);
27
- return null;
28
- }
29
- // Try to load WS token
30
- const wsToken = loadWsToken(sessionPath);
31
- if (!wsToken) {
32
- console.error("未找到 WS token。請先執行 'openape login' 進行登入。");
33
- return null;
34
- }
35
- return {
36
- log,
37
- session: {
38
- wsToken,
39
- moodleBaseUrl: "https://ilearning.cycu.edu.tw",
40
- },
41
- };
42
- }
43
- calendarCmd
44
- .command("events")
45
- .description("List calendar events")
46
- .option("--upcoming", "Show only upcoming events")
47
- .option("--days <n>", "Number of days ahead to look", "30")
48
- .option("--course <id>", "Filter by course ID")
49
- .option("--output <format>", "Output format: json|csv|table|silent")
50
- .action(async (options, command) => {
51
- const days = parseInt(options.days, 10);
52
- const apiContext = await createApiContext(options, command);
53
- if (!apiContext) {
54
- process.exitCode = 1;
55
- return;
56
- }
57
- const courses = await getEnrolledCoursesApi(apiContext.session);
58
- // Calculate time range
59
- const now = Math.floor(Date.now() / 1000);
60
- const endTime = now + (days * 24 * 60 * 60);
61
- let allEvents = [];
62
- if (options.course) {
63
- // Get events for specific course
64
- const courseId = parseInt(options.course, 10);
65
- const events = await getCalendarEventsApi(apiContext.session, {
66
- startTime: now,
67
- endTime: endTime,
68
- });
69
- allEvents = events.filter(e => e.courseid === courseId);
70
- }
71
- else {
72
- // Get events for all courses
73
- for (const course of courses) {
74
- try {
75
- const events = await getCalendarEventsApi(apiContext.session, {
76
- courseId: course.id,
77
- startTime: now,
78
- endTime: endTime,
79
- });
80
- allEvents.push(...events);
81
- }
82
- catch (err) {
83
- apiContext.log.debug(`Failed to fetch calendar events for ${course.fullname}: ${err}`);
84
- }
85
- }
86
- }
87
- // Sort by start time
88
- allEvents.sort((a, b) => a.timestart - b.timestart);
89
- // Filter upcoming only if requested
90
- let filteredEvents = allEvents;
91
- if (options.upcoming) {
92
- filteredEvents = allEvents.filter(e => e.timestart > now);
93
- }
94
- console.log(JSON.stringify({
95
- status: "success",
96
- timestamp: new Date().toISOString(),
97
- total_events: allEvents.length,
98
- upcoming: allEvents.filter(e => e.timestart > now).length,
99
- by_type: allEvents.reduce((acc, e) => {
100
- acc[e.eventtype] = (acc[e.eventtype] || 0) + 1;
101
- return acc;
102
- }, {}),
103
- }));
104
- for (const e of filteredEvents) {
105
- console.log(JSON.stringify({
106
- id: e.id,
107
- name: e.name,
108
- description: e.description,
109
- course_id: e.courseid,
110
- event_type: e.eventtype,
111
- start_time: formatTimestamp(e.timestart),
112
- end_time: e.timeduration ? formatTimestamp(e.timestart + Math.floor(e.timeduration / 1000)) : null,
113
- location: e.location,
114
- }));
115
- }
116
- });
117
- calendarCmd
118
- .command("export")
119
- .description("Export calendar events to file")
120
- .option("--output <path>", "Output file path", "./calendar.json")
121
- .option("--days <n>", "Number of days ahead to include", "30")
122
- .action(async (options, command) => {
123
- const apiContext = await createApiContext(options, command);
124
- if (!apiContext) {
125
- process.exitCode = 1;
126
- return;
127
- }
128
- const courses = await getEnrolledCoursesApi(apiContext.session);
129
- // Calculate time range
130
- const now = Math.floor(Date.now() / 1000);
131
- const days = parseInt(options.days, 10);
132
- const endTime = now + (days * 24 * 60 * 60);
133
- const allEvents = [];
134
- for (const course of courses) {
135
- try {
136
- const events = await getCalendarEventsApi(apiContext.session, {
137
- courseId: course.id,
138
- startTime: now,
139
- endTime: endTime,
140
- });
141
- allEvents.push(...events);
142
- }
143
- catch (err) {
144
- apiContext.log.debug(`Failed to fetch calendar events for ${course.fullname}: ${err}`);
145
- }
146
- }
147
- // Sort by start time
148
- allEvents.sort((a, b) => a.timestart - b.timestart);
149
- // Export data
150
- const exportData = {
151
- exported_at: new Date().toISOString(),
152
- time_range: {
153
- start: new Date(now * 1000).toISOString(),
154
- end: new Date(endTime * 1000).toISOString(),
155
- days: days,
156
- },
157
- events: allEvents.map(e => ({
158
- id: e.id,
159
- name: e.name,
160
- description: e.description,
161
- course_id: e.courseid,
162
- event_type: e.eventtype,
163
- start_time: formatTimestamp(e.timestart),
164
- end_time: e.timeduration ? formatTimestamp(e.timestart + Math.floor(e.timeduration / 1000)) : null,
165
- location: e.location,
166
- })),
167
- summary: {
168
- total_events: allEvents.length,
169
- by_type: allEvents.reduce((acc, e) => {
170
- acc[e.eventtype] = (acc[e.eventtype] || 0) + 1;
171
- return acc;
172
- }, {}),
173
- },
174
- };
175
- // Write to file
176
- fs.writeFileSync(options.output, JSON.stringify(exportData));
177
- apiContext.log.success(`Exported ${allEvents.length} events to ${options.output}`);
178
- });
179
- }
@@ -1,3 +0,0 @@
1
- import { Command } from "commander";
2
- export declare function registerCoursesCommand(program: Command): void;
3
- //# sourceMappingURL=courses.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"courses.d.ts","sourceRoot":"","sources":["../../../src/src/commands/courses.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AASpC,wBAAgB,sBAAsB,CAAC,OAAO,EAAE,OAAO,GAAG,IAAI,CA4Y7D"}
@@ -1,348 +0,0 @@
1
- import { getBaseDir, formatTimestamp } from "../lib/utils.js";
2
- import { getEnrolledCoursesApi } from "../lib/moodle.js";
3
- import { createLogger } from "../lib/logger.js";
4
- import { loadWsToken } from "../lib/token.js";
5
- import { formatAndOutput } from "../index.js";
6
- import path from "node:path";
7
- import fs from "node:fs";
8
- export function registerCoursesCommand(program) {
9
- const coursesCmd = program.command("courses");
10
- coursesCmd.description("Course operations");
11
- // Helper to get output format from global or local options
12
- function getOutputFormat(command) {
13
- const opts = command.optsWithGlobals();
14
- return opts.output || "json";
15
- }
16
- // Pure API context - no browser required (fast!)
17
- async function createApiContext(options, command) {
18
- const opts = command?.optsWithGlobals ? command.optsWithGlobals() : options;
19
- const outputFormat = getOutputFormat(command || { optsWithGlobals: () => ({ output: "json" }) });
20
- const silent = outputFormat === "json" && !opts.verbose;
21
- const log = createLogger(opts.verbose, silent, outputFormat);
22
- const baseDir = getBaseDir();
23
- const sessionPath = path.resolve(baseDir, ".auth", "storage-state.json");
24
- // Check if session exists
25
- if (!fs.existsSync(sessionPath)) {
26
- console.error("未找到登入 session。請先執行 'openape login' 進行登入。");
27
- log.info(`Session 預期位置: ${sessionPath}`);
28
- return null;
29
- }
30
- // Try to load WS token
31
- const wsToken = loadWsToken(sessionPath);
32
- if (!wsToken) {
33
- console.error("未找到 WS token。請先執行 'openape login' 進行登入。");
34
- return null;
35
- }
36
- return {
37
- log,
38
- session: {
39
- wsToken,
40
- moodleBaseUrl: "https://ilearning.cycu.edu.tw",
41
- },
42
- };
43
- }
44
- coursesCmd
45
- .command("list")
46
- .description("List enrolled courses")
47
- .option("--incomplete-only", "Show only incomplete courses")
48
- .option("--output <format>", "Output format: json|csv|table|silent")
49
- .option("--level <type>", "Course level: in_progress (default) | past | future | all", "in_progress")
50
- .action(async (options, command) => {
51
- const output = getOutputFormat(command);
52
- const apiContext = await createApiContext(options, command);
53
- if (!apiContext) {
54
- process.exitCode = 1;
55
- return;
56
- }
57
- // Map level to classification
58
- const classification = options.level === "all" ? undefined :
59
- options.level === "past" ? "past" :
60
- options.level === "future" ? "future" : "inprogress";
61
- const courses = await getEnrolledCoursesApi(apiContext.session, {
62
- classification,
63
- });
64
- let filteredCourses = courses;
65
- if (options.incompleteOnly) {
66
- filteredCourses = courses.filter(c => (c.progress ?? 0) < 100);
67
- }
68
- formatAndOutput(filteredCourses, output, apiContext.log);
69
- });
70
- coursesCmd
71
- .command("info")
72
- .description("Show detailed course information")
73
- .argument("<course-id>", "Course ID")
74
- .option("--output <format>", "Output format: json|csv|table|silent")
75
- .action(async (courseId, options, command) => {
76
- const output = getOutputFormat(command);
77
- const apiContext = await createApiContext(options, command);
78
- if (!apiContext) {
79
- process.exitCode = 1;
80
- return;
81
- }
82
- const courses = await getEnrolledCoursesApi(apiContext.session);
83
- const course = courses.find(c => c.id === parseInt(courseId, 10));
84
- if (!course) {
85
- apiContext.log.error(`Course not found: ${courseId}`);
86
- process.exitCode = 1;
87
- return;
88
- }
89
- formatAndOutput(course, output, apiContext.log);
90
- });
91
- coursesCmd
92
- .command("progress")
93
- .description("Show course progress")
94
- .argument("<course-id>", "Course ID")
95
- .option("--output <format>", "Output format: json|csv|table|silent")
96
- .action(async (courseId, options, command) => {
97
- const output = getOutputFormat(command);
98
- const apiContext = await createApiContext(options, command);
99
- if (!apiContext) {
100
- process.exitCode = 1;
101
- return;
102
- }
103
- const courses = await getEnrolledCoursesApi(apiContext.session);
104
- const course = courses.find(c => c.id === parseInt(courseId, 10));
105
- if (!course) {
106
- apiContext.log.error(`Course not found: ${courseId}`);
107
- process.exitCode = 1;
108
- return;
109
- }
110
- const progressData = {
111
- courseId: course.id,
112
- courseName: course.fullname,
113
- progress: course.progress ?? 0,
114
- startDate: course.startdate ? formatTimestamp(course.startdate) : null,
115
- endDate: course.enddate ? formatTimestamp(course.enddate) : null,
116
- };
117
- formatAndOutput(progressData, output, apiContext.log);
118
- });
119
- // Helper function to fetch syllabus from CMAP using GWT-RPC API
120
- async function fetchSyllabus(shortname) {
121
- try {
122
- const parts = shortname.split("_");
123
- if (parts.length < 2) {
124
- return { error: "Invalid course shortname format" };
125
- }
126
- const [yearTerm, opCode] = parts;
127
- // Build GWT-RPC request body
128
- // Format: 7|0|8|<base_url>|<permutation>|<service>|<method>|<param_types>|<params>...|1|2|3|4|3|5|5|5|6|7|8|
129
- const gwtBody = `7|0|8|https://cmap.cycu.edu.tw:8443/Syllabus/syllabus/|339796D6E7B561A6465F5E9B5F4943FA|com.sanfong.syllabus.shared.SyllabusClientService|findClassTargetByYearAndOpCode|java.lang.String/2004016611|${yearTerm}|${opCode}|zh_TW|1|2|3|4|3|5|5|5|6|7|8|`;
130
- const response = await fetch("https://cmap.cycu.edu.tw:8443/Syllabus/syllabus/syllabusClientService", {
131
- method: "POST",
132
- headers: {
133
- "X-GWT-Permutation": "339796D6E7B561A6465F5E9B5F4943FA",
134
- "Accept": "text/x-gwt-rpc, */*; q=0.01",
135
- "Content-Type": "text/x-gwt-rpc; charset=UTF-8",
136
- },
137
- body: gwtBody,
138
- });
139
- if (!response.ok) {
140
- return { error: `HTTP ${response.status}`, url: "https://cmap.cycu.edu.tw:8443/Syllabus/syllabus/syllabusClientService" };
141
- }
142
- const rawText = await response.text();
143
- // GWT-RPC response format: //OK[...data...]
144
- if (!rawText.startsWith("//OK")) {
145
- return { error: "Invalid GWT-RPC response", rawResponse: rawText.slice(0, 200) };
146
- }
147
- // Extract the JSON array part from the GWT response
148
- // Response format: //OK[data1,data2,...]
149
- const content = rawText.slice(4); // Remove "//OK"
150
- // Parse the GWT string table - GWT uses a special format where strings are escaped
151
- // Format: ["string1","string2",...] or [123,"string2",...]
152
- const stringTable = [];
153
- // Simple parser for GWT string table
154
- let current = "";
155
- let inString = false;
156
- let escaped = false;
157
- for (let i = 0; i < content.length; i++) {
158
- const char = content[i];
159
- if (escaped) {
160
- // Handle escape sequences
161
- switch (char) {
162
- case 'n':
163
- current += '\n';
164
- break;
165
- case 'r':
166
- current += '\r';
167
- break;
168
- case 't':
169
- current += '\t';
170
- break;
171
- case '"':
172
- current += '"';
173
- break;
174
- case '\\':
175
- current += '\\';
176
- break;
177
- case '0':
178
- current += '\0';
179
- break;
180
- default:
181
- // Unknown escape, just append the char
182
- current += char;
183
- }
184
- escaped = false;
185
- continue;
186
- }
187
- if (char === "\\") {
188
- escaped = true;
189
- continue;
190
- }
191
- if (char === '"') {
192
- inString = !inString;
193
- if (!inString && current.length > 0) {
194
- stringTable.push(current);
195
- current = "";
196
- }
197
- continue;
198
- }
199
- if (inString) {
200
- current += char;
201
- }
202
- }
203
- // Parse schedule from string table
204
- // Strategy: Find week numbers (1-18), extract title (previous field) and date
205
- const schedule = [];
206
- const datePattern = /^\d{4}-\d{2}-\d{2}$/;
207
- // Track processed indices to avoid duplicates
208
- const processedIndices = new Set();
209
- for (let i = 0; i < stringTable.length; i++) {
210
- const s = stringTable[i];
211
- // Look for week numbers (1-18)
212
- if (/^[1-9]$|^1[0-8]$/.test(s) && !processedIndices.has(i)) {
213
- const week = s;
214
- let date = "";
215
- let title = "";
216
- // Previous field is the title
217
- if (i - 1 >= 0 && !processedIndices.has(i - 1)) {
218
- title = stringTable[i - 1];
219
- }
220
- // For week 1 & 2, find date before the week number
221
- // For week 18, also look before (last week has no "next week")
222
- // For other weeks (3-17), next field is next week's date
223
- if (week === "1" || week === "2" || week === "18") {
224
- // Look backwards for date pattern (search further back for week 18)
225
- const maxLookback = week === "18" ? 15 : 6;
226
- for (let j = i - 1; j >= Math.max(0, i - maxLookback); j--) {
227
- if (datePattern.test(stringTable[j]) && !processedIndices.has(j)) {
228
- date = stringTable[j];
229
- processedIndices.add(j);
230
- break;
231
- }
232
- }
233
- }
234
- else {
235
- // Week 3-17: look for next week number, then get date before it
236
- for (let j = i + 1; j < Math.min(i + 10, stringTable.length); j++) {
237
- if (/^[1-9]$|^1[0-8]$/.test(stringTable[j]) && !processedIndices.has(j)) {
238
- // Found next week, look before it for date
239
- for (let k = j - 1; k >= Math.max(0, j - 6); k--) {
240
- if (datePattern.test(stringTable[k]) && !processedIndices.has(k)) {
241
- date = stringTable[k];
242
- processedIndices.add(k);
243
- break;
244
- }
245
- }
246
- break;
247
- }
248
- }
249
- }
250
- // Clean up title
251
- title = title.trim()
252
- .replace(/[\r\n]+/g, ' ')
253
- .replace(/,+$/, '')
254
- .trim()
255
- .slice(0, 200);
256
- // Only add if we have title (date is optional, will be inferred if missing)
257
- if (title.length > 1) {
258
- // If no date found, try to infer from the last added date
259
- if (date.length === 0 && schedule.length > 0) {
260
- const lastEntry = schedule[schedule.length - 1];
261
- const lastDate = new Date(lastEntry.date);
262
- const nextDate = new Date(lastDate.getTime() + 7 * 24 * 60 * 60 * 1000);
263
- const year = nextDate.getFullYear();
264
- const month = String(nextDate.getMonth() + 1).padStart(2, "0");
265
- const day = String(nextDate.getDate()).padStart(2, "0");
266
- date = `${year}-${month}-${day}`;
267
- }
268
- schedule.push({
269
- week,
270
- date,
271
- title,
272
- });
273
- }
274
- processedIndices.add(i);
275
- }
276
- }
277
- // Sort by date to maintain order
278
- schedule.sort((a, b) => a.date.localeCompare(b.date));
279
- // Extract course info from string table
280
- const result = {
281
- yearTerm,
282
- opCode,
283
- url: `https://cmap.cycu.edu.tw:8443/Syllabus/CoursePreview.html?yearTerm=${yearTerm}&opCode=${opCode}&locale=zh_TW`,
284
- schedule,
285
- };
286
- // Try to find instructor (look for common patterns)
287
- for (let i = 0; i < stringTable.length; i++) {
288
- const s = stringTable[i];
289
- if (s.includes("教授") || s.includes("老師") || s.includes("教師") || s.includes("Instructor")) {
290
- result.instructor = s;
291
- break;
292
- }
293
- }
294
- return result;
295
- }
296
- catch (e) {
297
- return { error: e instanceof Error ? e.message : String(e) };
298
- }
299
- }
300
- coursesCmd
301
- .command("syllabus")
302
- .description("Show course syllabus (from CMAP)")
303
- .argument("<course-id>", "Course ID")
304
- .option("--output <format>", "Output format: json|csv|table|silent")
305
- .action(async (courseId, options, command) => {
306
- const output = getOutputFormat(command);
307
- const apiContext = await createApiContext(options, command);
308
- if (!apiContext) {
309
- process.exitCode = 1;
310
- return;
311
- }
312
- try {
313
- const courses = await getEnrolledCoursesApi(apiContext.session);
314
- const course = courses.find(c => c.id === parseInt(courseId, 10));
315
- if (!course) {
316
- apiContext.log.error(`Course not found: ${courseId}`);
317
- process.exitCode = 1;
318
- return;
319
- }
320
- // Fetch syllabus from CMAP
321
- const syllabus = await fetchSyllabus(course.shortname);
322
- if (!syllabus) {
323
- apiContext.log.warn(`Syllabus not found for course: ${course.shortname}`);
324
- // Return course info at least
325
- formatAndOutput({
326
- courseId: course.id,
327
- shortname: course.shortname,
328
- fullname: course.fullname,
329
- note: "Syllabus not available from CMAP",
330
- }, output, apiContext.log);
331
- return;
332
- }
333
- // Combine course info with syllabus
334
- const result = {
335
- courseId: course.id,
336
- shortname: course.shortname,
337
- fullname: course.fullname,
338
- ...syllabus,
339
- };
340
- formatAndOutput(result, output, apiContext.log);
341
- }
342
- catch (e) {
343
- const msg = e instanceof Error ? e.message : String(e);
344
- apiContext.log.error(`Error fetching syllabus: ${msg}`);
345
- process.exitCode = 1;
346
- }
347
- });
348
- }
@@ -1,3 +0,0 @@
1
- import { Command } from "commander";
2
- export declare function registerForumsCommand(program: Command): void;
3
- //# sourceMappingURL=forums.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"forums.d.ts","sourceRoot":"","sources":["../../../src/src/commands/forums.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAmBpC,wBAAgB,qBAAqB,CAAC,OAAO,EAAE,OAAO,GAAG,IAAI,CAkX5D"}