@mo7yw4ng/openape 1.0.6 → 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 -138
  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 -71
  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 -229
  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 -127
  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 -312
  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 -190
  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 -84
  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 -402
  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 -236
  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 -55
  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 -266
  52. package/esm/src/index.d.ts +0 -28
  53. package/esm/src/index.d.ts.map +0 -1
  54. package/esm/src/index.js +0 -164
  55. package/esm/src/lib/auth.d.ts +0 -66
  56. package/esm/src/lib/auth.d.ts.map +0 -1
  57. package/esm/src/lib/auth.js +0 -286
  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 -26
  64. package/esm/src/lib/moodle.d.ts +0 -447
  65. package/esm/src/lib/moodle.d.ts.map +0 -1
  66. package/esm/src/lib/moodle.js +0 -1353
  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 -52
  77. package/esm/src/lib/utils.d.ts.map +0 -1
  78. package/esm/src/lib/utils.js +0 -122
  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 -74
  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 -268
  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 -133
  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 -315
  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 -193
  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 -87
  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 -408
  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 -239
  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 -61
  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 -272
  125. package/script/src/index.d.ts +0 -28
  126. package/script/src/index.d.ts.map +0 -1
  127. package/script/src/index.js +0 -171
  128. package/script/src/lib/auth.d.ts +0 -66
  129. package/script/src/lib/auth.d.ts.map +0 -1
  130. package/script/src/lib/auth.js +0 -296
  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 -29
  137. package/script/src/lib/moodle.d.ts +0 -447
  138. package/script/src/lib/moodle.d.ts.map +0 -1
  139. package/script/src/lib/moodle.js +0 -1425
  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 -52
  150. package/script/src/lib/utils.d.ts.map +0 -1
  151. package/script/src/lib/utils.js +0 -167
  152. package/skills/openape/SKILL.md +0 -115
@@ -1,266 +0,0 @@
1
- import { getBaseDir, getOutputFormat, sanitizeFilename } from "../lib/utils.js";
2
- import { getEnrolledCoursesApi, getSupervideosInCourse, getSupervideosInCourseApi, getVideoMetadata, completeVideoApi, downloadVideo, getIncompleteVideosApi } from "../lib/moodle.js";
3
- import { createApiContext, createBrowserContext, closeBrowserSafely } from "../lib/auth.js";
4
- import { formatAndOutput } from "../index.js";
5
- import path from "node:path";
6
- import fs from "node:fs";
7
- export function registerVideosCommand(program) {
8
- const videosCmd = program.command("videos");
9
- videosCmd.description("Video progress operations");
10
- videosCmd
11
- .command("list")
12
- .description("List videos in a course")
13
- .argument("<course-id>", "Course ID")
14
- .option("--incomplete-only", "Show only incomplete videos")
15
- .option("--output <format>", "Output format: json|csv|table|silent")
16
- .action(async (courseId, options, command) => {
17
- const output = getOutputFormat(command);
18
- const apiContext = await createApiContext(options, command);
19
- if (!apiContext) {
20
- process.exitCode = 1;
21
- return;
22
- }
23
- let videos = await getSupervideosInCourseApi(apiContext.session, parseInt(courseId, 10));
24
- // Filter for incomplete videos if requested
25
- if (options.incompleteOnly) {
26
- videos = videos.filter(v => !v.isComplete);
27
- }
28
- formatAndOutput(videos, output, apiContext.log);
29
- });
30
- videosCmd
31
- .command("complete")
32
- .description("Complete videos in a course (uses API for list & completion, browser for metadata)")
33
- .argument("<course-id>", "Course ID")
34
- .option("--dry-run", "Discover videos but don't complete them")
35
- .option("--output <format>", "Output format: json|csv|table|silent")
36
- .action(async (courseId, options, command) => {
37
- const output = getOutputFormat(command);
38
- // Get API context for getting incomplete videos and completion
39
- const apiContext = await createApiContext(options, command);
40
- if (!apiContext) {
41
- process.exitCode = 1;
42
- return;
43
- }
44
- // Get incomplete videos via API (fast, no browser needed)
45
- const incompleteVideos = await getIncompleteVideosApi(apiContext.session, parseInt(courseId, 10));
46
- if (incompleteVideos.length === 0) {
47
- apiContext.log.info("所有影片已完成(或無影片)。");
48
- return;
49
- }
50
- apiContext.log.info(`找到 ${incompleteVideos.length} 部未完成影片`);
51
- // Dry-run: show videos without needing browser
52
- if (options.dryRun) {
53
- const results = incompleteVideos.map(v => ({ name: v.name, success: true }));
54
- for (const video of incompleteVideos) {
55
- apiContext.log.info(` [試執行] ${video.name}`);
56
- }
57
- apiContext.log.info(`\n執行結果: ${results.length} 影片將被完成`);
58
- if (output !== "silent") {
59
- formatAndOutput(results, output, apiContext.log);
60
- }
61
- return;
62
- }
63
- // Need browser only for getting viewId and duration (not needed for dry-run)
64
- const context = await createBrowserContext(options, command);
65
- if (!context) {
66
- process.exitCode = 1;
67
- return;
68
- }
69
- const { log, page, browser, context: browserContext } = context;
70
- try {
71
- const results = [];
72
- for (const sv of incompleteVideos) {
73
- log.info(`處理中: ${sv.name}`);
74
- try {
75
- const video = await getVideoMetadata(page, sv.url, log);
76
- // Use WS API for completion
77
- const success = await completeVideoApi(apiContext.session, { ...video, cmid: sv.cmid.toString() });
78
- if (success) {
79
- log.success(` 已完成!`);
80
- results.push({ name: sv.name, success: true });
81
- }
82
- else {
83
- log.error(` 失敗。`);
84
- results.push({ name: sv.name, success: false, error: "Failed to complete" });
85
- }
86
- }
87
- catch (err) {
88
- const msg = err instanceof Error ? err.message : String(err);
89
- log.error(` 錯誤: ${msg}`);
90
- results.push({ name: sv.name, success: false, error: msg });
91
- }
92
- }
93
- const completed = results.filter(r => r.success).length;
94
- const failed = results.filter(r => !r.success).length;
95
- log.info(`\n執行結果: ${completed} 成功, ${failed} 失敗`);
96
- if (output !== "silent") {
97
- formatAndOutput(results, output, log);
98
- }
99
- }
100
- finally {
101
- await closeBrowserSafely(browser, browserContext);
102
- }
103
- });
104
- videosCmd
105
- .command("complete-all")
106
- .description("Complete all incomplete videos across all courses (uses API for list & completion, browser for metadata)")
107
- .option("--dry-run", "Discover videos but don't complete them")
108
- .option("--output <format>", "Output format: json|csv|table|silent")
109
- .action(async (options, command) => {
110
- const output = getOutputFormat(command);
111
- // Get API context for getting incomplete videos and completion
112
- const apiContext = await createApiContext(options, command);
113
- if (!apiContext) {
114
- process.exitCode = 1;
115
- return;
116
- }
117
- // Get all courses via API
118
- const classification = undefined; // all courses
119
- const courses = await getEnrolledCoursesApi(apiContext.session, { classification });
120
- apiContext.log.info(`掃描 ${courses.length} 個課程...`);
121
- // Collect all incomplete videos across all courses using flatMap for cleaner code
122
- const allIncompleteVideos = (await Promise.allSettled(courses.map(async (course) => {
123
- try {
124
- const videos = await getIncompleteVideosApi(apiContext.session, course.id);
125
- return videos.map((video) => ({
126
- courseId: course.id,
127
- courseName: course.fullname,
128
- cmid: video.cmid,
129
- name: video.name,
130
- url: video.url,
131
- }));
132
- }
133
- catch (e) {
134
- apiContext.log.warn(`無法取得課程 ${course.fullname} 的影片: ${e}`);
135
- return [];
136
- }
137
- })))
138
- .filter((result) => result.status === "fulfilled")
139
- .flatMap((result) => result.status === "fulfilled" ? result.value : []);
140
- if (allIncompleteVideos.length === 0) {
141
- apiContext.log.info("所有影片已完成(或無影片)。");
142
- return;
143
- }
144
- apiContext.log.info(`找到 ${allIncompleteVideos.length} 部未完成影片`);
145
- // Dry-run: show videos without needing browser
146
- if (options.dryRun) {
147
- for (const video of allIncompleteVideos) {
148
- apiContext.log.info(` [試執行] [${video.courseName}] ${video.name}`);
149
- }
150
- apiContext.log.info("\n===== 執行結果 =====");
151
- apiContext.log.info(`掃描課程數: ${courses.length}`);
152
- apiContext.log.info(`找到未完成影片: ${allIncompleteVideos.length}`);
153
- apiContext.log.info(`執行影片數: ${allIncompleteVideos.length} (試執行)`);
154
- return;
155
- }
156
- // Need browser only for getting viewId and duration (not needed for dry-run)
157
- const context = await createBrowserContext(options, command);
158
- if (!context) {
159
- process.exitCode = 1;
160
- return;
161
- }
162
- const { log, page, browser, context: browserContext } = context;
163
- try {
164
- const allResults = [];
165
- let totalCompleted = 0;
166
- let totalFailed = 0;
167
- for (const video of allIncompleteVideos) {
168
- log.info(`處理中: [${video.courseName}] ${video.name}`);
169
- try {
170
- const metadata = await getVideoMetadata(page, video.url, log);
171
- // Use WS API for completion
172
- const success = await completeVideoApi(apiContext.session, { ...metadata, cmid: video.cmid.toString() });
173
- if (success) {
174
- log.success(` 已完成!`);
175
- allResults.push({ courseName: video.courseName, name: video.name, success: true });
176
- totalCompleted++;
177
- }
178
- else {
179
- log.error(` 失敗。`);
180
- allResults.push({ courseName: video.courseName, name: video.name, success: false, error: "Failed to complete" });
181
- totalFailed++;
182
- }
183
- }
184
- catch (err) {
185
- const msg = err instanceof Error ? err.message : String(err);
186
- log.error(` 錯誤: ${msg}`);
187
- allResults.push({ courseName: video.courseName, name: video.name, success: false, error: msg });
188
- totalFailed++;
189
- }
190
- }
191
- log.info("\n===== 執行結果 =====");
192
- log.info(`掃描課程數: ${courses.length}`);
193
- log.info(`找到未完成影片: ${allIncompleteVideos.length}`);
194
- log.info(`執行影片數: ${totalCompleted}`);
195
- if (totalFailed > 0)
196
- log.warn(`失敗影片數: ${totalFailed}`);
197
- if (output !== "silent") {
198
- formatAndOutput(allResults, output, log);
199
- }
200
- }
201
- finally {
202
- await closeBrowserSafely(browser, browserContext);
203
- }
204
- });
205
- videosCmd
206
- .command("download")
207
- .description("Download videos from a course (requires browser)")
208
- .argument("<course-id>", "Course ID")
209
- .option("--output-dir <path>", "Output directory", "./downloads/videos")
210
- .option("--incomplete-only", "Download only incomplete videos")
211
- .action(async (courseId, options, command) => {
212
- const context = await createBrowserContext(options, command);
213
- if (!context) {
214
- process.exitCode = 1;
215
- return;
216
- }
217
- const { log, page, session, browser, context: browserContext } = context;
218
- try {
219
- const videos = await getSupervideosInCourse(page, session, parseInt(courseId, 10), log, {
220
- incompleteOnly: options.incompleteOnly,
221
- });
222
- log.info(`找到 ${videos.length} 個影片`);
223
- const baseDir = getBaseDir();
224
- const outputDir = path.resolve(baseDir, options.outputDir);
225
- fs.mkdirSync(outputDir, { recursive: true });
226
- const downloaded = [];
227
- for (const video of videos) {
228
- const filename = sanitizeFilename(video.name) + ".mp4";
229
- const outputPath = path.join(outputDir, filename);
230
- log.info(`處理中: ${video.name}`);
231
- try {
232
- const metadata = await getVideoMetadata(page, video.url, log);
233
- const result = await downloadVideo(page, metadata, outputPath, log);
234
- if (result.success) {
235
- log.success(` 已下載: ${result.path}`);
236
- downloaded.push({ name: video.name, path: result.path, success: true, type: result.type });
237
- }
238
- else {
239
- log.warn(` 失敗: ${result.error}`);
240
- downloaded.push({ name: video.name, path: "", success: false, error: result.error, type: result.type });
241
- }
242
- }
243
- catch (err) {
244
- const msg = err instanceof Error ? err.message : String(err);
245
- log.error(` 錯誤: ${msg}`);
246
- downloaded.push({ name: video.name, path: "", success: false, error: msg });
247
- }
248
- }
249
- const completed = downloaded.filter(d => d.success).length;
250
- const failed = downloaded.filter(d => !d.success).length;
251
- log.info(`\n執行結果: ${completed} 成功, ${failed} 失敗`);
252
- formatAndOutput(downloaded, "json", log, {
253
- status: "success",
254
- timestamp: new Date().toISOString(),
255
- course_id: courseId,
256
- output_dir: outputDir,
257
- total_videos: videos.length,
258
- downloaded: completed,
259
- failed,
260
- });
261
- }
262
- finally {
263
- await closeBrowserSafely(browser, browserContext);
264
- }
265
- });
266
- }
@@ -1,28 +0,0 @@
1
- #!/usr/bin/env node
2
- import "../_dnt.polyfills.js";
3
- import { createLogger } from "./lib/logger.js";
4
- import type { AppConfig, Logger, SessionInfo, OutputFormat } from "./lib/types.js";
5
- /**
6
- * Create a session context for commands that need authentication.
7
- */
8
- export declare function createSessionContext(options: {
9
- config?: string;
10
- session?: string;
11
- verbose?: boolean;
12
- silent?: boolean;
13
- headed?: boolean;
14
- interactive?: boolean;
15
- }): Promise<{
16
- config: AppConfig;
17
- log: Logger;
18
- page: import("playwright-core").Page;
19
- session: SessionInfo;
20
- } | null>;
21
- /**
22
- * Helper to output formatted data.
23
- * For JSON output (agent mode), exits immediately after output.
24
- * If meta is provided, it is printed as the first line before items.
25
- */
26
- export declare function formatAndOutput<T extends Record<string, unknown>>(data: T | T[], format: OutputFormat, log: Logger, meta?: Record<string, unknown>): void;
27
- export { createLogger, type AppConfig, type Logger, type SessionInfo, type OutputFormat };
28
- //# sourceMappingURL=index.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/src/index.ts"],"names":[],"mappings":";AACA,OAAO,sBAAsB,CAAC;AAO9B,OAAO,EAAE,YAAY,EAAE,MAAM,iBAAiB,CAAC;AAC/C,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,EAAE,WAAW,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAwEnF;;GAEG;AACH,wBAAsB,oBAAoB,CACxC,OAAO,EAAE;IACP,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,OAAO,CAAC,EAAE,OAAO,CAAC;IAClB,MAAM,CAAC,EAAE,OAAO,CAAC;IACjB,MAAM,CAAC,EAAE,OAAO,CAAC;IACjB,WAAW,CAAC,EAAE,OAAO,CAAC;CACvB,GACA,OAAO,CAAC;IAAE,MAAM,EAAE,SAAS,CAAC;IAAC,GAAG,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,OAAO,iBAAiB,EAAE,IAAI,CAAC;IAAC,OAAO,EAAE,WAAW,CAAA;CAAE,GAAG,IAAI,CAAC,CAoBhH;AAED;;;;GAIG;AACH,wBAAgB,eAAe,CAAC,CAAC,SAAS,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAC/D,IAAI,EAAE,CAAC,GAAG,CAAC,EAAE,EACb,MAAM,EAAE,YAAY,EACpB,GAAG,EAAE,MAAM,EACX,IAAI,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAC7B,IAAI,CA4BN;AA2CD,OAAO,EAAE,YAAY,EAAE,KAAK,SAAS,EAAE,KAAK,MAAM,EAAE,KAAK,WAAW,EAAE,KAAK,YAAY,EAAE,CAAC"}
package/esm/src/index.js DELETED
@@ -1,164 +0,0 @@
1
- #!/usr/bin/env node
2
- import "../_dnt.polyfills.js";
3
- import { getBaseDir } from "./lib/utils.js";
4
- import { Command } from "commander";
5
- import { loadConfig } from "./lib/config.js";
6
- import { launchAuthenticated } from "./lib/auth.js";
7
- import { extractSessionInfo } from "./lib/session.js";
8
- import { createLogger } from "./lib/logger.js";
9
- import denoJson from "../deno.js";
10
- // Import command handlers
11
- import { registerCoursesCommand } from "./commands/courses.js";
12
- import { registerVideosCommand } from "./commands/videos.js";
13
- import { registerQuizzesCommand } from "./commands/quizzes.js";
14
- import { registerCommand } from "./commands/auth.js";
15
- import { registerMaterialsCommand } from "./commands/materials.js";
16
- import { registerGradesCommand } from "./commands/grades.js";
17
- import { registerForumsCommand } from "./commands/forums.js";
18
- import { registerAnnouncementsCommand } from "./commands/announcements.js";
19
- import { registerCalendarCommand } from "./commands/calendar.js";
20
- import { registerSkillsCommand } from "./commands/skills.js";
21
- import { registerAssignmentsCommand } from "./commands/assignments.js";
22
- import { registerUploadCommand } from "./commands/upload.js";
23
- const program = new Command();
24
- program
25
- .name("openape")
26
- .description(denoJson.description)
27
- .version(denoJson.version);
28
- // Global options
29
- program
30
- .option("--config <path>", "Custom config file path")
31
- .option("--session <path>", "Session file path", ".auth/storage-state.json")
32
- .option("--output <format>", "Output format: json|csv|table|silent", "json")
33
- .option("--verbose", "Enable debug logging")
34
- .option("--silent", "Suppress all log output (JSON only)")
35
- .option("--headed", "Run browser in visible mode");
36
- // Register subcommands
37
- registerCommand(program);
38
- registerCoursesCommand(program);
39
- registerVideosCommand(program);
40
- registerQuizzesCommand(program);
41
- registerMaterialsCommand(program);
42
- registerGradesCommand(program);
43
- registerForumsCommand(program);
44
- registerAnnouncementsCommand(program);
45
- registerCalendarCommand(program);
46
- registerSkillsCommand(program);
47
- registerAssignmentsCommand(program);
48
- registerUploadCommand(program);
49
- /**
50
- * Load configuration and authenticate, returning the context for commands.
51
- */
52
- async function createCommandContext(options) {
53
- const log = createLogger(options.verbose, options.silent);
54
- const baseDir = getBaseDir();
55
- const config = loadConfig(baseDir);
56
- // Apply CLI overrides
57
- if (options.headed)
58
- config.headless = false;
59
- if (options.session)
60
- config.authStatePath = options.session;
61
- return { config, log };
62
- }
63
- /**
64
- * Create a session context for commands that need authentication.
65
- */
66
- export async function createSessionContext(options) {
67
- const context = await createCommandContext(options);
68
- if (!context)
69
- return null;
70
- const { config, log } = context;
71
- log.info("啟動瀏覽器...");
72
- const { browser, context: browserContext, page, wsToken } = await launchAuthenticated(config, log);
73
- try {
74
- const session = await extractSessionInfo(page, config, log, wsToken);
75
- // Keep the browser context alive for the duration of the command
76
- // Note: Caller is responsible for closing the browser
77
- return { config, log, page, session };
78
- }
79
- catch (err) {
80
- await browserContext.close();
81
- await browser.close();
82
- throw err;
83
- }
84
- }
85
- /**
86
- * Helper to output formatted data.
87
- * For JSON output (agent mode), exits immediately after output.
88
- * If meta is provided, it is printed as the first line before items.
89
- */
90
- export function formatAndOutput(data, format, log, meta) {
91
- if (format === "json") {
92
- if (meta) {
93
- console.log(JSON.stringify(meta));
94
- }
95
- if (Array.isArray(data)) {
96
- for (const item of data) {
97
- console.log(JSON.stringify(item));
98
- }
99
- }
100
- else {
101
- console.log(JSON.stringify(data));
102
- }
103
- // Exit immediately for AI agent - no need to wait for browser cleanup
104
- process.exit(0);
105
- }
106
- else if (format === "csv") {
107
- const arr = Array.isArray(data) ? data : [data];
108
- if (arr.length === 0)
109
- return;
110
- const fields = Object.keys(arr[0]);
111
- console.log(formatAsCsv(arr, fields));
112
- }
113
- else if (format === "table") {
114
- const arr = Array.isArray(data) ? data : [data];
115
- if (arr.length === 0) {
116
- console.log("No data");
117
- return;
118
- }
119
- console.log(formatAsTable(arr));
120
- }
121
- // "silent" produces no output
122
- }
123
- function formatAsCsv(data, fields) {
124
- const headers = fields.join(",");
125
- const rows = data.map((item) => {
126
- return fields.map((field) => {
127
- const value = item[field];
128
- if (value === null || value === undefined)
129
- return "";
130
- if (typeof value === "string") {
131
- if (value.includes(",") || value.includes('"') || value.includes("\n")) {
132
- return `"${value.replace(/"/g, '""')}"`;
133
- }
134
- return value;
135
- }
136
- return String(value);
137
- }).join(",");
138
- });
139
- return [headers, ...rows].join("\n");
140
- }
141
- function formatAsTable(data) {
142
- const allFields = Array.from(new Set(data.flatMap((item) => Object.keys(item))));
143
- const widths = {};
144
- allFields.forEach((field) => {
145
- widths[field] = Math.max(field.length, ...data.map((item) => String(item[field] ?? "").length)) + 2;
146
- });
147
- const header = allFields.map((f) => f.padEnd(widths[f])).join(" | ");
148
- const separator = allFields.map((f) => "-".repeat(widths[f] - 1)).join("-+-");
149
- const rows = data.map((item) => {
150
- return allFields.map((f) => String(item[f] ?? "").padEnd(widths[f])).join(" | ");
151
- });
152
- return [header, separator, ...rows].join("\n");
153
- }
154
- // Export utilities for commands
155
- export { createLogger };
156
- // Run the program
157
- if (globalThis[Symbol.for("import-meta-ponyfill-esmodule")](import.meta).main) {
158
- // If no subcommand provided, show help
159
- const args = process.argv.slice(2);
160
- if (args.length === 0) {
161
- program.help();
162
- }
163
- program.parse();
164
- }
@@ -1,66 +0,0 @@
1
- import { type Browser, type BrowserContext, type Page } from "playwright-core";
2
- import type { AppConfig, Logger, OutputFormat, SessionInfo } from "./types.js";
3
- /**
4
- * Find a Chromium-based browser executable on Windows, macOS, or Linux.
5
- * Priority: Edge → Chrome → Brave
6
- */
7
- export declare function findEdgePath(): string;
8
- /**
9
- * Launch a browser and return an authenticated context.
10
- * Tries to restore a saved session first; falls back to fresh OAuth login.
11
- * Also acquires Moodle Web Service Token for API calls.
12
- */
13
- export declare function launchAuthenticated(config: AppConfig, log: Logger): Promise<{
14
- browser: Browser;
15
- context: BrowserContext;
16
- page: Page;
17
- wsToken?: string;
18
- }>;
19
- /**
20
- * Safely close browser and context with timeout.
21
- * Designed for AI agent usage - no human interaction needed.
22
- * If noWait is true, initiates cleanup but doesn't wait for completion.
23
- *
24
- * Note: Closes sequentially (context first, then browser) to avoid libuv
25
- * assertion failures on Windows when handles are closed concurrently.
26
- */
27
- export declare function closeBrowserSafely(browser: Browser, context?: BrowserContext, timeoutMs?: number, noWait?: boolean): Promise<void>;
28
- /**
29
- * Create API context for WS token operations (no browser required).
30
- * Returns null if session is invalid or WS token is missing.
31
- */
32
- export declare function createApiContext(options: {
33
- verbose?: boolean;
34
- headed?: boolean;
35
- }, command?: {
36
- optsWithGlobals(): {
37
- output?: OutputFormat;
38
- verbose?: boolean;
39
- };
40
- }): Promise<{
41
- log: Logger;
42
- session: {
43
- wsToken: string;
44
- moodleBaseUrl: string;
45
- };
46
- } | null>;
47
- /**
48
- * Create an authenticated browser context for commands that need page access.
49
- * Launches a browser, restores or creates a session, and extracts session info.
50
- */
51
- export declare function createBrowserContext(options: {
52
- verbose?: boolean;
53
- headed?: boolean;
54
- }, command?: {
55
- optsWithGlobals(): {
56
- output?: OutputFormat;
57
- verbose?: boolean;
58
- };
59
- }): Promise<{
60
- log: Logger;
61
- page: Page;
62
- session: SessionInfo;
63
- browser: Browser;
64
- context: BrowserContext;
65
- } | null>;
66
- //# sourceMappingURL=auth.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"auth.d.ts","sourceRoot":"","sources":["../../../src/src/lib/auth.ts"],"names":[],"mappings":"AAEA,OAAO,EAAY,KAAK,OAAO,EAAE,KAAK,cAAc,EAAE,KAAK,IAAI,EAAE,MAAM,iBAAiB,CAAC;AACzF,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,EAAE,YAAY,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AAM/E;;;GAGG;AACH,wBAAgB,YAAY,IAAI,MAAM,CAiDrC;AAED;;;;GAIG;AACH,wBAAsB,mBAAmB,CACvC,MAAM,EAAE,SAAS,EACjB,GAAG,EAAE,MAAM,GACV,OAAO,CAAC;IAAE,OAAO,EAAE,OAAO,CAAC;IAAC,OAAO,EAAE,cAAc,CAAC;IAAC,IAAI,EAAE,IAAI,CAAC;IAAC,OAAO,CAAC,EAAE,MAAM,CAAA;CAAE,CAAC,CA4DtF;AAED;;;;;;;GAOG;AACH,wBAAsB,kBAAkB,CACtC,OAAO,EAAE,OAAO,EAChB,OAAO,CAAC,EAAE,cAAc,EACxB,SAAS,GAAE,MAAa,EACxB,MAAM,GAAE,OAAe,GACtB,OAAO,CAAC,IAAI,CAAC,CA+Bf;AAoHD;;;GAGG;AACH,wBAAsB,gBAAgB,CACpC,OAAO,EAAE;IAAE,OAAO,CAAC,EAAE,OAAO,CAAC;IAAC,MAAM,CAAC,EAAE,OAAO,CAAA;CAAE,EAChD,OAAO,CAAC,EAAE;IAAE,eAAe,IAAI;QAAE,MAAM,CAAC,EAAE,YAAY,CAAC;QAAC,OAAO,CAAC,EAAE,OAAO,CAAA;KAAE,CAAA;CAAE,GAC5E,OAAO,CAAC;IACT,GAAG,EAAE,MAAM,CAAC;IACZ,OAAO,EAAE;QAAE,OAAO,EAAE,MAAM,CAAC;QAAC,aAAa,EAAE,MAAM,CAAA;KAAE,CAAC;CACrD,GAAG,IAAI,CAAC,CAoBR;AAED;;;GAGG;AACH,wBAAsB,oBAAoB,CACxC,OAAO,EAAE;IAAE,OAAO,CAAC,EAAE,OAAO,CAAC;IAAC,MAAM,CAAC,EAAE,OAAO,CAAA;CAAE,EAChD,OAAO,CAAC,EAAE;IAAE,eAAe,IAAI;QAAE,MAAM,CAAC,EAAE,YAAY,CAAC;QAAC,OAAO,CAAC,EAAE,OAAO,CAAA;KAAE,CAAA;CAAE,GAC5E,OAAO,CAAC;IACT,GAAG,EAAE,MAAM,CAAC;IACZ,IAAI,EAAE,IAAI,CAAC;IACX,OAAO,EAAE,WAAW,CAAC;IACrB,OAAO,EAAE,OAAO,CAAC;IACjB,OAAO,EAAE,cAAc,CAAC;CACzB,GAAG,IAAI,CAAC,CA0BR"}