@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,342 +0,0 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.registerVideosCommand = registerVideosCommand;
7
- const utils_js_1 = require("../lib/utils.js");
8
- const moodle_js_1 = require("../lib/moodle.js");
9
- const logger_js_1 = require("../lib/logger.js");
10
- const auth_js_1 = require("../lib/auth.js");
11
- const session_js_1 = require("../lib/session.js");
12
- const auth_js_2 = require("../lib/auth.js");
13
- const index_js_1 = require("../index.js");
14
- const token_js_1 = require("../lib/token.js");
15
- const node_path_1 = __importDefault(require("node:path"));
16
- const node_fs_1 = __importDefault(require("node:fs"));
17
- function registerVideosCommand(program) {
18
- const videosCmd = program.command("videos");
19
- videosCmd.description("Video progress operations");
20
- // Pure API context - no browser required (fast!)
21
- async function createApiContext(options, command) {
22
- const opts = command?.optsWithGlobals ? command.optsWithGlobals() : options;
23
- // Don't silence logs for commands that don't have explicit output format control
24
- const outputFormat = command && command.optsWithGlobals ? (0, utils_js_1.getOutputFormat)(command) : "table";
25
- const silent = outputFormat === "json" && !opts.verbose;
26
- const log = (0, logger_js_1.createLogger)(opts.verbose, silent, outputFormat);
27
- const baseDir = (0, utils_js_1.getBaseDir)();
28
- const sessionPath = node_path_1.default.resolve(baseDir, ".auth", "storage-state.json");
29
- // Check if session exists
30
- if (!node_fs_1.default.existsSync(sessionPath)) {
31
- console.error("未找到登入 session。請先執行 'openape login' 進行登入。");
32
- log.info(`Session 預期位置: ${sessionPath}`);
33
- return null;
34
- }
35
- // Try to load WS token
36
- const wsToken = (0, token_js_1.loadWsToken)(sessionPath);
37
- if (!wsToken) {
38
- console.error("未找到 WS token。請先執行 'openape login' 進行登入。");
39
- return null;
40
- }
41
- return {
42
- log,
43
- session: {
44
- wsToken,
45
- moodleBaseUrl: "https://ilearning.cycu.edu.tw",
46
- },
47
- };
48
- }
49
- // Helper function to create session context (for browser-only commands)
50
- async function createSessionContext(options, command) {
51
- const opts = command?.optsWithGlobals ? command.optsWithGlobals() : options;
52
- const outputFormat = (0, utils_js_1.getOutputFormat)(command || { optsWithGlobals: () => ({ output: "json" }) });
53
- const silent = outputFormat === "json" && !opts.verbose;
54
- const log = (0, logger_js_1.createLogger)(opts.verbose, silent, outputFormat);
55
- const baseDir = (0, utils_js_1.getBaseDir)();
56
- const sessionPath = node_path_1.default.resolve(baseDir, ".auth", "storage-state.json");
57
- if (!node_fs_1.default.existsSync(sessionPath)) {
58
- console.error("未找到登入 session。請先執行 'openape login' 進行登入。");
59
- return null;
60
- }
61
- const config = {
62
- username: "",
63
- password: "",
64
- courseUrl: "",
65
- moodleBaseUrl: "https://ilearning.cycu.edu.tw",
66
- headless: !options.headed,
67
- slowMo: 0,
68
- authStatePath: sessionPath,
69
- ollamaBaseUrl: "",
70
- };
71
- log.info("啟動瀏覽器...");
72
- const { browser, context, page } = await (0, auth_js_1.launchAuthenticated)(config, log);
73
- try {
74
- const session = await (0, session_js_1.extractSessionInfo)(page, config, log);
75
- return { log, page, session, browser, context };
76
- }
77
- catch (err) {
78
- await context.close();
79
- await browser.close();
80
- throw err;
81
- }
82
- }
83
- videosCmd
84
- .command("list")
85
- .description("List videos in a course")
86
- .argument("<course-id>", "Course ID")
87
- .option("--incomplete-only", "Show only incomplete videos")
88
- .option("--output <format>", "Output format: json|csv|table|silent")
89
- .action(async (courseId, options, command) => {
90
- const output = (0, utils_js_1.getOutputFormat)(command);
91
- const apiContext = await createApiContext(options, command);
92
- if (!apiContext) {
93
- process.exitCode = 1;
94
- return;
95
- }
96
- let videos = await (0, moodle_js_1.getSupervideosInCourseApi)(apiContext.session, parseInt(courseId, 10));
97
- // Filter for incomplete videos if requested
98
- if (options.incompleteOnly) {
99
- videos = videos.filter(v => !v.isComplete);
100
- }
101
- (0, index_js_1.formatAndOutput)(videos, output, apiContext.log);
102
- });
103
- videosCmd
104
- .command("complete")
105
- .description("Complete videos in a course (uses API for list & completion, browser for metadata)")
106
- .argument("<course-id>", "Course ID")
107
- .option("--dry-run", "Discover videos but don't complete them")
108
- .option("--output <format>", "Output format: json|csv|table|silent")
109
- .action(async (courseId, options, command) => {
110
- const output = (0, utils_js_1.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 incomplete videos via API (fast, no browser needed)
118
- const incompleteVideos = await (0, moodle_js_1.getIncompleteVideosApi)(apiContext.session, parseInt(courseId, 10));
119
- if (incompleteVideos.length === 0) {
120
- apiContext.log.info("所有影片已完成(或無影片)。");
121
- return;
122
- }
123
- apiContext.log.info(`找到 ${incompleteVideos.length} 部未完成影片`);
124
- // Dry-run: show videos without needing browser
125
- if (options.dryRun) {
126
- const results = incompleteVideos.map(v => ({ name: v.name, success: true }));
127
- for (const video of incompleteVideos) {
128
- apiContext.log.info(` [試執行] ${video.name}`);
129
- }
130
- apiContext.log.info(`\n執行結果: ${results.length} 影片將被完成`);
131
- if (output !== "silent") {
132
- (0, index_js_1.formatAndOutput)(results, output, apiContext.log);
133
- }
134
- return;
135
- }
136
- // Need browser only for getting viewId and duration (not needed for dry-run)
137
- const context = await createSessionContext(options, command);
138
- if (!context) {
139
- process.exitCode = 1;
140
- return;
141
- }
142
- const { log, page, browser, context: browserContext } = context;
143
- try {
144
- const results = [];
145
- for (const sv of incompleteVideos) {
146
- log.info(`處理中: ${sv.name}`);
147
- try {
148
- const video = await (0, moodle_js_1.getVideoMetadata)(page, sv.url, log);
149
- // Use WS API for completion
150
- const success = await (0, moodle_js_1.completeVideoApi)(apiContext.session, { ...video, cmid: sv.cmid.toString() });
151
- if (success) {
152
- log.success(` 已完成!`);
153
- results.push({ name: sv.name, success: true });
154
- }
155
- else {
156
- log.error(` 失敗。`);
157
- results.push({ name: sv.name, success: false, error: "Failed to complete" });
158
- }
159
- }
160
- catch (err) {
161
- const msg = err instanceof Error ? err.message : String(err);
162
- log.error(` 錯誤: ${msg}`);
163
- results.push({ name: sv.name, success: false, error: msg });
164
- }
165
- }
166
- const completed = results.filter(r => r.success).length;
167
- const failed = results.filter(r => !r.success).length;
168
- log.info(`\n執行結果: ${completed} 成功, ${failed} 失敗`);
169
- if (output !== "silent") {
170
- (0, index_js_1.formatAndOutput)(results, output, log);
171
- }
172
- }
173
- finally {
174
- await (0, auth_js_2.closeBrowserSafely)(browser, browserContext);
175
- }
176
- });
177
- videosCmd
178
- .command("complete-all")
179
- .description("Complete all incomplete videos across all courses (uses API for list & completion, browser for metadata)")
180
- .option("--dry-run", "Discover videos but don't complete them")
181
- .option("--output <format>", "Output format: json|csv|table|silent")
182
- .action(async (options, command) => {
183
- const output = (0, utils_js_1.getOutputFormat)(command);
184
- // Get API context for getting incomplete videos and completion
185
- const apiContext = await createApiContext(options, command);
186
- if (!apiContext) {
187
- process.exitCode = 1;
188
- return;
189
- }
190
- // Get all courses via API
191
- const classification = undefined; // all courses
192
- const courses = await (0, moodle_js_1.getEnrolledCoursesApi)(apiContext.session, { classification });
193
- apiContext.log.info(`掃描 ${courses.length} 個課程...`);
194
- // Collect all incomplete videos across all courses using flatMap for cleaner code
195
- const allIncompleteVideos = (await Promise.allSettled(courses.map(async (course) => {
196
- try {
197
- const videos = await (0, moodle_js_1.getIncompleteVideosApi)(apiContext.session, course.id);
198
- return videos.map((video) => ({
199
- courseId: course.id,
200
- courseName: course.fullname,
201
- cmid: video.cmid,
202
- name: video.name,
203
- url: video.url,
204
- }));
205
- }
206
- catch (e) {
207
- apiContext.log.warn(`無法取得課程 ${course.fullname} 的影片: ${e}`);
208
- return [];
209
- }
210
- })))
211
- .filter((result) => result.status === "fulfilled")
212
- .flatMap((result) => result.status === "fulfilled" ? result.value : []);
213
- if (allIncompleteVideos.length === 0) {
214
- apiContext.log.info("所有影片已完成(或無影片)。");
215
- return;
216
- }
217
- apiContext.log.info(`找到 ${allIncompleteVideos.length} 部未完成影片`);
218
- // Dry-run: show videos without needing browser
219
- if (options.dryRun) {
220
- for (const video of allIncompleteVideos) {
221
- apiContext.log.info(` [試執行] [${video.courseName}] ${video.name}`);
222
- }
223
- apiContext.log.info("\n===== 執行結果 =====");
224
- apiContext.log.info(`掃描課程數: ${courses.length}`);
225
- apiContext.log.info(`找到未完成影片: ${allIncompleteVideos.length}`);
226
- apiContext.log.info(`執行影片數: ${allIncompleteVideos.length} (試執行)`);
227
- return;
228
- }
229
- // Need browser only for getting viewId and duration (not needed for dry-run)
230
- const context = await createSessionContext(options, command);
231
- if (!context) {
232
- process.exitCode = 1;
233
- return;
234
- }
235
- const { log, page, browser, context: browserContext } = context;
236
- try {
237
- const allResults = [];
238
- let totalCompleted = 0;
239
- let totalFailed = 0;
240
- for (const video of allIncompleteVideos) {
241
- log.info(`處理中: [${video.courseName}] ${video.name}`);
242
- try {
243
- const metadata = await (0, moodle_js_1.getVideoMetadata)(page, video.url, log);
244
- // Use WS API for completion
245
- const success = await (0, moodle_js_1.completeVideoApi)(apiContext.session, { ...metadata, cmid: video.cmid.toString() });
246
- if (success) {
247
- log.success(` 已完成!`);
248
- allResults.push({ courseName: video.courseName, name: video.name, success: true });
249
- totalCompleted++;
250
- }
251
- else {
252
- log.error(` 失敗。`);
253
- allResults.push({ courseName: video.courseName, name: video.name, success: false, error: "Failed to complete" });
254
- totalFailed++;
255
- }
256
- }
257
- catch (err) {
258
- const msg = err instanceof Error ? err.message : String(err);
259
- log.error(` 錯誤: ${msg}`);
260
- allResults.push({ courseName: video.courseName, name: video.name, success: false, error: msg });
261
- totalFailed++;
262
- }
263
- }
264
- log.info("\n===== 執行結果 =====");
265
- log.info(`掃描課程數: ${courses.length}`);
266
- log.info(`找到未完成影片: ${allIncompleteVideos.length}`);
267
- log.info(`執行影片數: ${totalCompleted}`);
268
- if (totalFailed > 0)
269
- log.warn(`失敗影片數: ${totalFailed}`);
270
- if (output !== "silent") {
271
- (0, index_js_1.formatAndOutput)(allResults, output, log);
272
- }
273
- }
274
- finally {
275
- await (0, auth_js_2.closeBrowserSafely)(browser, browserContext);
276
- }
277
- });
278
- videosCmd
279
- .command("download")
280
- .description("Download videos from a course (requires browser)")
281
- .argument("<course-id>", "Course ID")
282
- .option("--output-dir <path>", "Output directory", "./downloads/videos")
283
- .option("--incomplete-only", "Download only incomplete videos")
284
- .action(async (courseId, options, command) => {
285
- const context = await createSessionContext(options, command);
286
- if (!context) {
287
- process.exitCode = 1;
288
- return;
289
- }
290
- const { log, page, session, browser, context: browserContext } = context;
291
- try {
292
- const videos = await (0, moodle_js_1.getSupervideosInCourse)(page, session, parseInt(courseId, 10), log, {
293
- incompleteOnly: options.incompleteOnly,
294
- });
295
- log.info(`找到 ${videos.length} 個影片`);
296
- const baseDir = (0, utils_js_1.getBaseDir)();
297
- const outputDir = node_path_1.default.resolve(baseDir, options.outputDir);
298
- node_fs_1.default.mkdirSync(outputDir, { recursive: true });
299
- const downloaded = [];
300
- for (const video of videos) {
301
- const filename = (0, utils_js_1.sanitizeFilename)(video.name) + ".mp4";
302
- const outputPath = node_path_1.default.join(outputDir, filename);
303
- log.info(`處理中: ${video.name}`);
304
- try {
305
- const metadata = await (0, moodle_js_1.getVideoMetadata)(page, video.url, log);
306
- const result = await (0, moodle_js_1.downloadVideo)(page, metadata, outputPath, log);
307
- if (result.success) {
308
- log.success(` 已下載: ${result.path}`);
309
- downloaded.push({ name: video.name, path: result.path, success: true, type: result.type });
310
- }
311
- else {
312
- log.warn(` 失敗: ${result.error}`);
313
- downloaded.push({ name: video.name, path: "", success: false, error: result.error, type: result.type });
314
- }
315
- }
316
- catch (err) {
317
- const msg = err instanceof Error ? err.message : String(err);
318
- log.error(` 錯誤: ${msg}`);
319
- downloaded.push({ name: video.name, path: "", success: false, error: msg });
320
- }
321
- }
322
- const completed = downloaded.filter(d => d.success).length;
323
- const failed = downloaded.filter(d => !d.success).length;
324
- log.info(`\n執行結果: ${completed} 成功, ${failed} 失敗`);
325
- console.log(JSON.stringify({
326
- status: "success",
327
- timestamp: new Date().toISOString(),
328
- course_id: courseId,
329
- output_dir: outputDir,
330
- total_videos: videos.length,
331
- downloaded: completed,
332
- failed,
333
- }));
334
- for (const v of downloaded) {
335
- console.log(JSON.stringify(v));
336
- }
337
- }
338
- finally {
339
- await (0, auth_js_2.closeBrowserSafely)(browser, browserContext);
340
- }
341
- });
342
- }
@@ -1,27 +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
- */
25
- export declare function formatAndOutput<T extends Record<string, unknown>>(data: T | T[], format: OutputFormat, log: Logger): void;
26
- export { createLogger, type AppConfig, type Logger, type SessionInfo, type OutputFormat };
27
- //# 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;;;GAGG;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,GACV,IAAI,CAyBN;AA2CD,OAAO,EAAE,YAAY,EAAE,KAAK,SAAS,EAAE,KAAK,MAAM,EAAE,KAAK,WAAW,EAAE,KAAK,YAAY,EAAE,CAAC"}
@@ -1,167 +0,0 @@
1
- #!/usr/bin/env node
2
- "use strict";
3
- var __importDefault = (this && this.__importDefault) || function (mod) {
4
- return (mod && mod.__esModule) ? mod : { "default": mod };
5
- };
6
- Object.defineProperty(exports, "__esModule", { value: true });
7
- exports.createLogger = void 0;
8
- exports.createSessionContext = createSessionContext;
9
- exports.formatAndOutput = formatAndOutput;
10
- require("../_dnt.polyfills.js");
11
- const utils_js_1 = require("./lib/utils.js");
12
- const commander_1 = require("commander");
13
- const config_js_1 = require("./lib/config.js");
14
- const auth_js_1 = require("./lib/auth.js");
15
- const session_js_1 = require("./lib/session.js");
16
- const logger_js_1 = require("./lib/logger.js");
17
- Object.defineProperty(exports, "createLogger", { enumerable: true, get: function () { return logger_js_1.createLogger; } });
18
- const deno_js_1 = __importDefault(require("../deno.js"));
19
- // Import command handlers
20
- const courses_js_1 = require("./commands/courses.js");
21
- const videos_js_1 = require("./commands/videos.js");
22
- const quizzes_js_1 = require("./commands/quizzes.js");
23
- const auth_js_2 = require("./commands/auth.js");
24
- const materials_js_1 = require("./commands/materials.js");
25
- const grades_js_1 = require("./commands/grades.js");
26
- const forums_js_1 = require("./commands/forums.js");
27
- const announcements_js_1 = require("./commands/announcements.js");
28
- const calendar_js_1 = require("./commands/calendar.js");
29
- const skills_js_1 = require("./commands/skills.js");
30
- const assignments_js_1 = require("./commands/assignments.js");
31
- const upload_js_1 = require("./commands/upload.js");
32
- const program = new commander_1.Command();
33
- program
34
- .name("openape")
35
- .description(deno_js_1.default.description)
36
- .version(deno_js_1.default.version);
37
- // Global options
38
- program
39
- .option("--config <path>", "Custom config file path")
40
- .option("--session <path>", "Session file path", ".auth/storage-state.json")
41
- .option("--output <format>", "Output format: json|csv|table|silent", "json")
42
- .option("--verbose", "Enable debug logging")
43
- .option("--silent", "Suppress all log output (JSON only)")
44
- .option("--headed", "Run browser in visible mode");
45
- // Register subcommands
46
- (0, auth_js_2.registerCommand)(program);
47
- (0, courses_js_1.registerCoursesCommand)(program);
48
- (0, videos_js_1.registerVideosCommand)(program);
49
- (0, quizzes_js_1.registerQuizzesCommand)(program);
50
- (0, materials_js_1.registerMaterialsCommand)(program);
51
- (0, grades_js_1.registerGradesCommand)(program);
52
- (0, forums_js_1.registerForumsCommand)(program);
53
- (0, announcements_js_1.registerAnnouncementsCommand)(program);
54
- (0, calendar_js_1.registerCalendarCommand)(program);
55
- (0, skills_js_1.registerSkillsCommand)(program);
56
- (0, assignments_js_1.registerAssignmentsCommand)(program);
57
- (0, upload_js_1.registerUploadCommand)(program);
58
- /**
59
- * Load configuration and authenticate, returning the context for commands.
60
- */
61
- async function createCommandContext(options) {
62
- const log = (0, logger_js_1.createLogger)(options.verbose, options.silent);
63
- const baseDir = (0, utils_js_1.getBaseDir)();
64
- const config = (0, config_js_1.loadConfig)(baseDir);
65
- // Apply CLI overrides
66
- if (options.headed)
67
- config.headless = false;
68
- if (options.session)
69
- config.authStatePath = options.session;
70
- return { config, log };
71
- }
72
- /**
73
- * Create a session context for commands that need authentication.
74
- */
75
- async function createSessionContext(options) {
76
- const context = await createCommandContext(options);
77
- if (!context)
78
- return null;
79
- const { config, log } = context;
80
- log.info("啟動瀏覽器...");
81
- const { browser, context: browserContext, page, wsToken } = await (0, auth_js_1.launchAuthenticated)(config, log);
82
- try {
83
- const session = await (0, session_js_1.extractSessionInfo)(page, config, log, wsToken);
84
- // Keep the browser context alive for the duration of the command
85
- // Note: Caller is responsible for closing the browser
86
- return { config, log, page, session };
87
- }
88
- catch (err) {
89
- await browserContext.close();
90
- await browser.close();
91
- throw err;
92
- }
93
- }
94
- /**
95
- * Helper to output formatted data.
96
- * For JSON output (agent mode), exits immediately after output.
97
- */
98
- function formatAndOutput(data, format, log) {
99
- if (format === "json") {
100
- if (Array.isArray(data)) {
101
- for (const item of data) {
102
- console.log(JSON.stringify(item));
103
- }
104
- }
105
- else {
106
- console.log(JSON.stringify(data));
107
- }
108
- // Exit immediately for AI agent - no need to wait for browser cleanup
109
- process.exit(0);
110
- }
111
- else if (format === "csv") {
112
- const arr = Array.isArray(data) ? data : [data];
113
- if (arr.length === 0)
114
- return;
115
- const fields = Object.keys(arr[0]);
116
- console.log(formatAsCsv(arr, fields));
117
- }
118
- else if (format === "table") {
119
- const arr = Array.isArray(data) ? data : [data];
120
- if (arr.length === 0) {
121
- console.log("No data");
122
- return;
123
- }
124
- console.log(formatAsTable(arr));
125
- }
126
- // "silent" produces no output
127
- }
128
- function formatAsCsv(data, fields) {
129
- const headers = fields.join(",");
130
- const rows = data.map((item) => {
131
- return fields.map((field) => {
132
- const value = item[field];
133
- if (value === null || value === undefined)
134
- return "";
135
- if (typeof value === "string") {
136
- if (value.includes(",") || value.includes('"') || value.includes("\n")) {
137
- return `"${value.replace(/"/g, '""')}"`;
138
- }
139
- return value;
140
- }
141
- return String(value);
142
- }).join(",");
143
- });
144
- return [headers, ...rows].join("\n");
145
- }
146
- function formatAsTable(data) {
147
- const allFields = Array.from(new Set(data.flatMap((item) => Object.keys(item))));
148
- const widths = {};
149
- allFields.forEach((field) => {
150
- widths[field] = Math.max(field.length, ...data.map((item) => String(item[field] ?? "").length)) + 2;
151
- });
152
- const header = allFields.map((f) => f.padEnd(widths[f])).join(" | ");
153
- const separator = allFields.map((f) => "-".repeat(widths[f] - 1)).join("-+-");
154
- const rows = data.map((item) => {
155
- return allFields.map((f) => String(item[f] ?? "").padEnd(widths[f])).join(" | ");
156
- });
157
- return [header, separator, ...rows].join("\n");
158
- }
159
- // Run the program
160
- if (globalThis[Symbol.for("import-meta-ponyfill-commonjs")](require, module).main) {
161
- // If no subcommand provided, show help
162
- const args = process.argv.slice(2);
163
- if (args.length === 0) {
164
- program.help();
165
- }
166
- program.parse();
167
- }
@@ -1,47 +0,0 @@
1
- import { type Browser, type BrowserContext, type Page } from "playwright-core";
2
- import type { AppConfig, Logger, OutputFormat } from "./types.js";
3
- /**
4
- * Find a Chromium-based browser executable on Windows.
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
- //# 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,MAAM,YAAY,CAAC;AAGlE;;;GAGG;AACH,wBAAgB,YAAY,IAAI,MAAM,CAuBrC;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,CA0BR"}