@mo7yw4ng/openape 1.0.0 → 1.0.2

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 (133) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +15 -5
  3. package/esm/_dnt.polyfills.d.ts +83 -6
  4. package/esm/_dnt.polyfills.d.ts.map +1 -0
  5. package/esm/_dnt.polyfills.js +127 -1
  6. package/esm/_dnt.shims.d.ts +1 -0
  7. package/esm/_dnt.shims.d.ts.map +1 -0
  8. package/esm/deno.d.ts +2 -0
  9. package/esm/deno.d.ts.map +1 -0
  10. package/esm/deno.js +2 -1
  11. package/esm/src/commands/announcements.d.ts +3 -0
  12. package/esm/src/commands/announcements.d.ts.map +1 -0
  13. package/esm/src/commands/announcements.js +135 -0
  14. package/esm/src/commands/auth.d.ts +3 -0
  15. package/esm/src/commands/auth.d.ts.map +1 -0
  16. package/esm/src/commands/auth.js +264 -0
  17. package/esm/src/commands/calendar.d.ts +3 -0
  18. package/esm/src/commands/calendar.d.ts.map +1 -0
  19. package/esm/src/commands/calendar.js +180 -0
  20. package/esm/src/commands/courses.d.ts +3 -0
  21. package/esm/src/commands/courses.d.ts.map +1 -0
  22. package/esm/src/commands/courses.js +348 -0
  23. package/esm/src/commands/forums.d.ts +3 -0
  24. package/esm/src/commands/forums.d.ts.map +1 -0
  25. package/esm/src/commands/forums.js +231 -0
  26. package/esm/src/commands/grades.d.ts +3 -0
  27. package/esm/src/commands/grades.d.ts.map +1 -0
  28. package/esm/src/commands/grades.js +121 -0
  29. package/esm/src/commands/materials.d.ts +3 -0
  30. package/esm/src/commands/materials.d.ts.map +1 -0
  31. package/esm/src/commands/materials.js +362 -0
  32. package/esm/src/commands/quizzes.d.ts +3 -0
  33. package/esm/src/commands/quizzes.d.ts.map +1 -0
  34. package/esm/src/commands/quizzes.js +160 -0
  35. package/esm/src/commands/skills.d.ts +3 -0
  36. package/esm/src/commands/skills.d.ts.map +1 -0
  37. package/esm/src/commands/skills.js +110 -0
  38. package/esm/src/commands/videos.d.ts +3 -0
  39. package/esm/src/commands/videos.d.ts.map +1 -0
  40. package/esm/src/commands/videos.js +302 -0
  41. package/esm/src/index.d.ts +27 -0
  42. package/esm/src/index.d.ts.map +1 -0
  43. package/esm/src/index.js +149 -0
  44. package/esm/src/lib/auth.d.ts +25 -0
  45. package/esm/src/lib/auth.d.ts.map +1 -0
  46. package/esm/src/lib/auth.js +194 -0
  47. package/esm/src/lib/config.d.ts +6 -0
  48. package/esm/src/lib/config.d.ts.map +1 -0
  49. package/esm/src/lib/config.js +36 -0
  50. package/esm/src/lib/logger.d.ts +3 -0
  51. package/esm/src/lib/logger.d.ts.map +1 -0
  52. package/esm/src/lib/logger.js +24 -0
  53. package/esm/src/lib/moodle.d.ts +205 -0
  54. package/esm/src/lib/moodle.d.ts.map +1 -0
  55. package/esm/src/lib/moodle.js +690 -0
  56. package/esm/src/lib/session.d.ts +8 -0
  57. package/esm/src/lib/session.d.ts.map +1 -0
  58. package/esm/src/lib/session.js +42 -0
  59. package/esm/src/lib/token.d.ts +38 -0
  60. package/esm/src/lib/token.d.ts.map +1 -0
  61. package/esm/src/lib/token.js +178 -0
  62. package/esm/src/lib/types.d.ts +271 -0
  63. package/esm/src/lib/types.d.ts.map +1 -0
  64. package/esm/src/lib/types.js +1 -0
  65. package/esm/src/lib/utils.d.ts +17 -0
  66. package/esm/src/lib/utils.d.ts.map +1 -0
  67. package/esm/src/lib/utils.js +51 -0
  68. package/package.json +7 -3
  69. package/script/_dnt.polyfills.d.ts +83 -6
  70. package/script/_dnt.polyfills.d.ts.map +1 -0
  71. package/script/_dnt.polyfills.js +128 -0
  72. package/script/_dnt.shims.d.ts +1 -0
  73. package/script/_dnt.shims.d.ts.map +1 -0
  74. package/script/deno.d.ts +2 -0
  75. package/script/deno.d.ts.map +1 -0
  76. package/script/deno.js +2 -1
  77. package/script/src/commands/announcements.d.ts +1 -0
  78. package/script/src/commands/announcements.d.ts.map +1 -0
  79. package/script/src/commands/announcements.js +75 -222
  80. package/script/src/commands/auth.d.ts +1 -0
  81. package/script/src/commands/auth.d.ts.map +1 -0
  82. package/script/src/commands/auth.js +49 -17
  83. package/script/src/commands/calendar.d.ts +1 -0
  84. package/script/src/commands/calendar.d.ts.map +1 -0
  85. package/script/src/commands/calendar.js +112 -301
  86. package/script/src/commands/courses.d.ts +1 -0
  87. package/script/src/commands/courses.d.ts.map +1 -0
  88. package/script/src/commands/courses.js +43 -173
  89. package/script/src/commands/forums.d.ts +1 -0
  90. package/script/src/commands/forums.d.ts.map +1 -0
  91. package/script/src/commands/forums.js +145 -311
  92. package/script/src/commands/grades.d.ts +1 -0
  93. package/script/src/commands/grades.d.ts.map +1 -0
  94. package/script/src/commands/grades.js +62 -194
  95. package/script/src/commands/materials.d.ts +1 -0
  96. package/script/src/commands/materials.d.ts.map +1 -0
  97. package/script/src/commands/materials.js +111 -166
  98. package/script/src/commands/quizzes.d.ts +1 -0
  99. package/script/src/commands/quizzes.d.ts.map +1 -0
  100. package/script/src/commands/quizzes.js +40 -102
  101. package/script/src/commands/skills.d.ts +1 -0
  102. package/script/src/commands/skills.d.ts.map +1 -0
  103. package/script/src/commands/skills.js +17 -18
  104. package/script/src/commands/videos.d.ts +1 -0
  105. package/script/src/commands/videos.d.ts.map +1 -0
  106. package/script/src/commands/videos.js +26 -52
  107. package/script/src/index.d.ts +1 -0
  108. package/script/src/index.d.ts.map +1 -0
  109. package/script/src/index.js +4 -4
  110. package/script/src/lib/auth.d.ts +1 -0
  111. package/script/src/lib/auth.d.ts.map +1 -0
  112. package/script/src/lib/auth.js +9 -10
  113. package/script/src/lib/config.d.ts +1 -0
  114. package/script/src/lib/config.d.ts.map +1 -0
  115. package/script/src/lib/config.js +6 -7
  116. package/script/src/lib/logger.d.ts +1 -0
  117. package/script/src/lib/logger.d.ts.map +1 -0
  118. package/script/src/lib/logger.js +1 -2
  119. package/script/src/lib/moodle.d.ts +25 -54
  120. package/script/src/lib/moodle.d.ts.map +1 -0
  121. package/script/src/lib/moodle.js +103 -324
  122. package/script/src/lib/session.d.ts +1 -0
  123. package/script/src/lib/session.d.ts.map +1 -0
  124. package/script/src/lib/session.js +3 -29
  125. package/script/src/lib/token.d.ts +16 -5
  126. package/script/src/lib/token.d.ts.map +1 -0
  127. package/script/src/lib/token.js +71 -36
  128. package/script/src/lib/types.d.ts +10 -0
  129. package/script/src/lib/types.d.ts.map +1 -0
  130. package/script/src/lib/utils.d.ts +12 -0
  131. package/script/src/lib/utils.d.ts.map +1 -0
  132. package/script/src/lib/utils.js +57 -11
  133. package/skills/openape/SKILL.md +331 -328
@@ -0,0 +1,110 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import os from "node:os";
4
+ const SKILL_NAME = "openape";
5
+ const GITHUB_RAW_URL = `https://raw.githubusercontent.com/mo7yw4ng/openape/refs/heads/main/skills/${SKILL_NAME}/SKILL.md`;
6
+ /**
7
+ * Known agent platforms and their skills directories
8
+ */
9
+ const PLATFORMS = {
10
+ claude: { name: "Claude Code", path: path.join(os.homedir(), ".claude", "skills") },
11
+ codex: { name: "Codex CLI", path: path.join(os.homedir(), ".codex", "skills") },
12
+ opencode: { name: "OpenCode", path: path.join(os.homedir(), ".opencode", "skills") },
13
+ };
14
+ /**
15
+ * Try to read SKILL.md from local project first (dev mode / bundled build),
16
+ * fallback to fetching from GitHub (when installed globally via npm).
17
+ */
18
+ async function readSkillContent() {
19
+ // Try local path first (relative to this file's location)
20
+ try {
21
+ const base = path.dirname(new URL(globalThis[Symbol.for("import-meta-ponyfill-esmodule")](import.meta).url).pathname);
22
+ const normalized = process.platform === "win32" ? base.replace(/^\//, "") : base;
23
+ // When running from source: src/commands/ → ../../skills/openape/SKILL.md
24
+ // When bundled by dnt into build/: esm/commands/ or script/ → ../../skills/openape/SKILL.md
25
+ const localPath = path.resolve(normalized, "..", "..", "skills", SKILL_NAME, "SKILL.md");
26
+ if (fs.existsSync(localPath)) {
27
+ return fs.readFileSync(localPath, "utf-8");
28
+ }
29
+ }
30
+ catch {
31
+ // import.meta.url may be unavailable in some environments
32
+ }
33
+ // Fallback: fetch from GitHub
34
+ const res = await fetch(GITHUB_RAW_URL, { headers: { "User-Agent": "openape-cli" } });
35
+ if (!res.ok) {
36
+ throw new Error(`Failed to fetch skill from GitHub: ${res.status} ${res.statusText}`);
37
+ }
38
+ return res.text();
39
+ }
40
+ export function registerSkillsCommand(program) {
41
+ const skills = program
42
+ .command("skills")
43
+ .description("Manage OpenApe skills for AI agents");
44
+ skills
45
+ .command("install [platform]")
46
+ .description("Install the OpenApe skill to an agent platform (claude, codex, opencode)")
47
+ .option("--all", "Detect installed agents and install to all")
48
+ .action(async (platform, opts) => {
49
+ try {
50
+ let targets = [];
51
+ if (opts?.all) {
52
+ for (const [key, info] of Object.entries(PLATFORMS)) {
53
+ const parentDir = path.dirname(info.path);
54
+ if (fs.existsSync(parentDir)) {
55
+ targets.push({ key, ...info });
56
+ }
57
+ }
58
+ if (targets.length === 0) {
59
+ console.log("No supported agents detected. Supported platforms: " + Object.keys(PLATFORMS).join(", "));
60
+ return;
61
+ }
62
+ }
63
+ else if (platform) {
64
+ const info = PLATFORMS[platform.toLowerCase()];
65
+ if (!info) {
66
+ console.error(`Unknown platform: ${platform}`);
67
+ console.error(`Supported platforms: ${Object.keys(PLATFORMS).join(", ")}`);
68
+ process.exitCode = 1;
69
+ return;
70
+ }
71
+ targets = [{ key: platform.toLowerCase(), ...info }];
72
+ }
73
+ else {
74
+ console.error("Specify a platform or use --all.");
75
+ console.error(`Example: openape skills install claude`);
76
+ process.exitCode = 1;
77
+ return;
78
+ }
79
+ console.log(`Fetching ${SKILL_NAME} skill...`);
80
+ const content = await readSkillContent();
81
+ for (const target of targets) {
82
+ console.log(`Installing to ${target.name} (${target.path})...`);
83
+ const destDir = path.join(target.path, SKILL_NAME);
84
+ if (!fs.existsSync(destDir)) {
85
+ fs.mkdirSync(destDir, { recursive: true });
86
+ }
87
+ fs.writeFileSync(path.join(destDir, "SKILL.md"), content, "utf-8");
88
+ console.log(` \x1b[32m✔\x1b[0m ${SKILL_NAME} installed!`);
89
+ }
90
+ console.log("\nDone!");
91
+ }
92
+ catch (err) {
93
+ console.error(`\x1b[31mFailed to install skill: ${err.message}\x1b[0m`);
94
+ process.exitCode = 1;
95
+ }
96
+ });
97
+ skills
98
+ .command("show")
99
+ .description("Print the raw SKILL.md content")
100
+ .action(async () => {
101
+ try {
102
+ const content = await readSkillContent();
103
+ process.stdout.write(content);
104
+ }
105
+ catch (err) {
106
+ console.error(`\x1b[31mFailed: ${err.message}\x1b[0m`);
107
+ process.exitCode = 1;
108
+ }
109
+ });
110
+ }
@@ -0,0 +1,3 @@
1
+ import { Command } from "commander";
2
+ export declare function registerVideosCommand(program: Command): void;
3
+ //# sourceMappingURL=videos.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"videos.d.ts","sourceRoot":"","sources":["../../../src/src/commands/videos.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAYpC,wBAAgB,qBAAqB,CAAC,OAAO,EAAE,OAAO,GAAG,IAAI,CAuV5D"}
@@ -0,0 +1,302 @@
1
+ import { getBaseDir } from "../lib/utils.js";
2
+ import { getEnrolledCourses, getSupervideosInCourse, getSupervideosInCourseApi, getVideoMetadata, completeVideo, downloadVideo } from "../lib/moodle.js";
3
+ import { createLogger } from "../lib/logger.js";
4
+ import { launchAuthenticated } from "../lib/auth.js";
5
+ import { extractSessionInfo } from "../lib/session.js";
6
+ import { closeBrowserSafely } from "../lib/auth.js";
7
+ import { formatAndOutput } from "../index.js";
8
+ import { loadWsToken } from "../lib/token.js";
9
+ import path from "node:path";
10
+ import fs from "node:fs";
11
+ export function registerVideosCommand(program) {
12
+ const videosCmd = program.command("videos");
13
+ videosCmd.description("Video progress operations");
14
+ // Helper to get output format from global or local options
15
+ function getOutputFormat(command) {
16
+ const opts = command.optsWithGlobals();
17
+ return opts.output || "json";
18
+ }
19
+ // Pure API context - no browser required (fast!)
20
+ async function createApiContext(options, command) {
21
+ const opts = command?.optsWithGlobals ? command.optsWithGlobals() : options;
22
+ const outputFormat = getOutputFormat(command || { optsWithGlobals: () => ({ output: "json" }) });
23
+ const silent = outputFormat === "json" && !opts.verbose;
24
+ const log = createLogger(opts.verbose, silent);
25
+ const baseDir = getBaseDir();
26
+ const sessionPath = path.resolve(baseDir, ".auth", "storage-state.json");
27
+ // Check if session exists
28
+ if (!fs.existsSync(sessionPath)) {
29
+ log.error("未找到登入 session。請先執行 'openape auth login' 進行登入。");
30
+ log.info(`Session 預期位置: ${sessionPath}`);
31
+ return null;
32
+ }
33
+ // Try to load WS token
34
+ const wsToken = loadWsToken(sessionPath);
35
+ if (!wsToken) {
36
+ log.error("未找到 WS token。請先執行 'openape auth login' 進行登入。");
37
+ return null;
38
+ }
39
+ return {
40
+ log,
41
+ session: {
42
+ wsToken,
43
+ moodleBaseUrl: "https://ilearning.cycu.edu.tw",
44
+ },
45
+ };
46
+ }
47
+ // Helper function to create session context (for browser-only commands)
48
+ async function createSessionContext(options, command) {
49
+ const opts = command?.optsWithGlobals ? command.optsWithGlobals() : options;
50
+ const outputFormat = getOutputFormat(command || { optsWithGlobals: () => ({ output: "json" }) });
51
+ const silent = outputFormat === "json" && !opts.verbose;
52
+ const log = createLogger(opts.verbose, silent);
53
+ const baseDir = getBaseDir();
54
+ const sessionPath = path.resolve(baseDir, ".auth", "storage-state.json");
55
+ if (!fs.existsSync(sessionPath)) {
56
+ log.error("未找到登入 session。請先執行 'openape auth login' 進行登入。");
57
+ return null;
58
+ }
59
+ const config = {
60
+ username: "",
61
+ password: "",
62
+ courseUrl: "",
63
+ moodleBaseUrl: "https://ilearning.cycu.edu.tw",
64
+ headless: !options.headed,
65
+ slowMo: 0,
66
+ authStatePath: sessionPath,
67
+ ollamaBaseUrl: "",
68
+ };
69
+ log.info("啟動瀏覽器...");
70
+ const { browser, context, page } = await launchAuthenticated(config, log);
71
+ try {
72
+ const session = await extractSessionInfo(page, config, log);
73
+ return { log, page, session, browser, context };
74
+ }
75
+ catch (err) {
76
+ await context.close();
77
+ await browser.close();
78
+ throw err;
79
+ }
80
+ }
81
+ videosCmd
82
+ .command("list")
83
+ .description("List videos in a course")
84
+ .argument("<course-id>", "Course ID")
85
+ .option("--incomplete-only", "Show only incomplete videos")
86
+ .option("--output <format>", "Output format: json|csv|table|silent")
87
+ .action(async (courseId, options, command) => {
88
+ const output = getOutputFormat(command);
89
+ const apiContext = await createApiContext(options, command);
90
+ if (!apiContext) {
91
+ process.exitCode = 1;
92
+ return;
93
+ }
94
+ const videos = await getSupervideosInCourseApi(apiContext.session, parseInt(courseId, 10));
95
+ // Note: API doesn't provide completion status, so --incomplete-only shows all
96
+ if (options.incompleteOnly) {
97
+ apiContext.log.warn("--incomplete-only is not supported in API mode, showing all videos");
98
+ }
99
+ formatAndOutput(videos, output, apiContext.log);
100
+ });
101
+ videosCmd
102
+ .command("complete")
103
+ .description("Complete videos in a course (requires browser)")
104
+ .argument("<course-id>", "Course ID")
105
+ .option("--dry-run", "Discover videos but don't complete them")
106
+ .option("--output <format>", "Output format: json|csv|table|silent")
107
+ .action(async (courseId, options, command) => {
108
+ const context = await createSessionContext(options, command);
109
+ if (!context) {
110
+ process.exitCode = 1;
111
+ return;
112
+ }
113
+ const { log, page, session, browser, context: browserContext } = context;
114
+ const output = getOutputFormat(command);
115
+ try {
116
+ const videos = await getSupervideosInCourse(page, session, parseInt(courseId, 10), log, {
117
+ incompleteOnly: true, // Only operate on incomplete videos
118
+ });
119
+ if (videos.length === 0) {
120
+ log.info("所有影片已完成(或無影片)。");
121
+ return;
122
+ }
123
+ const results = [];
124
+ for (const sv of videos) {
125
+ log.info(`處理中: ${sv.name}`);
126
+ try {
127
+ const video = await getVideoMetadata(page, sv.url, log);
128
+ if (options.dryRun) {
129
+ log.info(` [試執行] viewId=${video.viewId}, duration=${video.duration}s`);
130
+ results.push({ name: sv.name, success: true });
131
+ continue;
132
+ }
133
+ const success = await completeVideo(page, session, { ...video, cmid: sv.cmid }, log);
134
+ if (success) {
135
+ log.success(` 已完成!`);
136
+ results.push({ name: sv.name, success: true });
137
+ }
138
+ else {
139
+ log.error(` 失敗。`);
140
+ results.push({ name: sv.name, success: false, error: "Failed to complete" });
141
+ }
142
+ }
143
+ catch (err) {
144
+ const msg = err instanceof Error ? err.message : String(err);
145
+ log.error(` 錯誤: ${msg}`);
146
+ results.push({ name: sv.name, success: false, error: msg });
147
+ }
148
+ }
149
+ const completed = results.filter(r => r.success).length;
150
+ const failed = results.filter(r => !r.success).length;
151
+ log.info(`\n執行結果: ${completed} 成功, ${failed} 失敗`);
152
+ if (output !== "silent") {
153
+ formatAndOutput(results, output, log);
154
+ }
155
+ }
156
+ finally {
157
+ await closeBrowserSafely(browser, browserContext);
158
+ }
159
+ });
160
+ videosCmd
161
+ .command("complete-all")
162
+ .description("Complete all incomplete videos across all courses (requires browser)")
163
+ .option("--dry-run", "Discover videos but don't complete them")
164
+ .option("--output <format>", "Output format: json|csv|table|silent")
165
+ .action(async (options, command) => {
166
+ const context = await createSessionContext(options, command);
167
+ if (!context) {
168
+ process.exitCode = 1;
169
+ return;
170
+ }
171
+ const { log, page, session, browser, context: browserContext } = context;
172
+ const output = getOutputFormat(command);
173
+ try {
174
+ const courses = await getEnrolledCourses(page, session, log);
175
+ const allResults = [];
176
+ let totalVideos = 0;
177
+ let totalCompleted = 0;
178
+ let totalFailed = 0;
179
+ for (const course of courses) {
180
+ log.info(`\n======================================`);
181
+ log.info(`課程: ${course.fullname}`);
182
+ log.info(`======================================`);
183
+ const videos = await getSupervideosInCourse(page, session, course.id, log);
184
+ if (videos.length === 0) {
185
+ log.info(" 所有影片已完成(或無影片)。");
186
+ continue;
187
+ }
188
+ totalVideos += videos.length;
189
+ for (const sv of videos) {
190
+ log.info(` 處理中: ${sv.name}`);
191
+ try {
192
+ const video = await getVideoMetadata(page, sv.url, log);
193
+ if (options.dryRun) {
194
+ log.info(` [試執行] viewId=${video.viewId}, duration=${video.duration}s`);
195
+ allResults.push({ courseName: course.fullname, name: sv.name, success: true });
196
+ continue;
197
+ }
198
+ const success = await completeVideo(page, session, { ...video, cmid: sv.cmid }, log);
199
+ if (success) {
200
+ log.success(` 已完成!`);
201
+ allResults.push({ courseName: course.fullname, name: sv.name, success: true });
202
+ totalCompleted++;
203
+ }
204
+ else {
205
+ log.error(` 失敗。`);
206
+ allResults.push({ courseName: course.fullname, name: sv.name, success: false, error: "Failed to complete" });
207
+ totalFailed++;
208
+ }
209
+ }
210
+ catch (err) {
211
+ const msg = err instanceof Error ? err.message : String(err);
212
+ log.error(` 錯誤: ${msg}`);
213
+ allResults.push({ courseName: course.fullname, name: sv.name, success: false, error: msg });
214
+ totalFailed++;
215
+ }
216
+ }
217
+ }
218
+ log.info("\n===== 執行結果 =====");
219
+ log.info(`掃描課程數: ${courses.length}`);
220
+ log.info(`掃描影片數: ${totalVideos}`);
221
+ log.info(`執行影片數: ${totalCompleted}`);
222
+ if (totalFailed > 0)
223
+ log.warn(`失敗影片數: ${totalFailed}`);
224
+ if (output !== "silent") {
225
+ formatAndOutput(allResults, output, log);
226
+ }
227
+ }
228
+ finally {
229
+ await closeBrowserSafely(browser, browserContext);
230
+ }
231
+ });
232
+ // Helper function to sanitize filename
233
+ function sanitizeFilename(name) {
234
+ return name
235
+ .replace(/[<>:"/\\|?*]/g, "_")
236
+ .replace(/\s+/g, "_")
237
+ .substring(0, 200);
238
+ }
239
+ videosCmd
240
+ .command("download")
241
+ .description("Download videos from a course (requires browser)")
242
+ .argument("<course-id>", "Course ID")
243
+ .option("--output-dir <path>", "Output directory", "./downloads/videos")
244
+ .option("--incomplete-only", "Download only incomplete videos")
245
+ .action(async (courseId, options, command) => {
246
+ const context = await createSessionContext(options, command);
247
+ if (!context) {
248
+ process.exitCode = 1;
249
+ return;
250
+ }
251
+ const { log, page, session, browser, context: browserContext } = context;
252
+ try {
253
+ const videos = await getSupervideosInCourse(page, session, parseInt(courseId, 10), log, {
254
+ incompleteOnly: options.incompleteOnly,
255
+ });
256
+ log.info(`找到 ${videos.length} 個影片`);
257
+ const baseDir = getBaseDir();
258
+ const outputDir = path.resolve(baseDir, options.outputDir);
259
+ fs.mkdirSync(outputDir, { recursive: true });
260
+ const downloaded = [];
261
+ for (const video of videos) {
262
+ const filename = sanitizeFilename(video.name) + ".mp4";
263
+ const outputPath = path.join(outputDir, filename);
264
+ log.info(`處理中: ${video.name}`);
265
+ try {
266
+ const metadata = await getVideoMetadata(page, video.url, log);
267
+ const result = await downloadVideo(page, metadata, outputPath, log);
268
+ if (result.success) {
269
+ log.success(` 已下載: ${result.path}`);
270
+ downloaded.push({ name: video.name, path: result.path, success: true, type: result.type });
271
+ }
272
+ else {
273
+ log.warn(` 失敗: ${result.error}`);
274
+ downloaded.push({ name: video.name, path: "", success: false, error: result.error, type: result.type });
275
+ }
276
+ }
277
+ catch (err) {
278
+ const msg = err instanceof Error ? err.message : String(err);
279
+ log.error(` 錯誤: ${msg}`);
280
+ downloaded.push({ name: video.name, path: "", success: false, error: msg });
281
+ }
282
+ }
283
+ const completed = downloaded.filter(d => d.success).length;
284
+ const failed = downloaded.filter(d => !d.success).length;
285
+ log.info(`\n執行結果: ${completed} 成功, ${failed} 失敗`);
286
+ const output = {
287
+ status: "success",
288
+ timestamp: new Date().toISOString(),
289
+ course_id: courseId,
290
+ output_dir: outputDir,
291
+ total_videos: videos.length,
292
+ downloaded: completed,
293
+ failed,
294
+ videos: downloaded,
295
+ };
296
+ console.log(JSON.stringify(output));
297
+ }
298
+ finally {
299
+ await closeBrowserSafely(browser, browserContext);
300
+ }
301
+ });
302
+ }
@@ -0,0 +1,27 @@
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
@@ -0,0 +1 @@
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;AAoEnF;;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,CAmBN;AA2CD,OAAO,EAAE,YAAY,EAAE,KAAK,SAAS,EAAE,KAAK,MAAM,EAAE,KAAK,WAAW,EAAE,KAAK,YAAY,EAAE,CAAC"}
@@ -0,0 +1,149 @@
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 { registerAuthCommand } 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
+ const program = new Command();
22
+ program
23
+ .name("openape")
24
+ .description(denoJson.description)
25
+ .version(denoJson.version);
26
+ // Global options
27
+ program
28
+ .option("--config <path>", "Custom config file path")
29
+ .option("--session <path>", "Session file path", ".auth/storage-state.json")
30
+ .option("--output <format>", "Output format: json|csv|table|silent", "json")
31
+ .option("--verbose", "Enable debug logging")
32
+ .option("--silent", "Suppress all log output (JSON only)")
33
+ .option("--headed", "Run browser in visible mode");
34
+ // Register subcommands
35
+ registerAuthCommand(program);
36
+ registerCoursesCommand(program);
37
+ registerVideosCommand(program);
38
+ registerQuizzesCommand(program);
39
+ registerMaterialsCommand(program);
40
+ registerGradesCommand(program);
41
+ registerForumsCommand(program);
42
+ registerAnnouncementsCommand(program);
43
+ registerCalendarCommand(program);
44
+ registerSkillsCommand(program);
45
+ /**
46
+ * Load configuration and authenticate, returning the context for commands.
47
+ */
48
+ async function createCommandContext(options) {
49
+ const log = createLogger(options.verbose, options.silent);
50
+ const baseDir = getBaseDir();
51
+ const config = loadConfig(baseDir);
52
+ // Apply CLI overrides
53
+ if (options.headed)
54
+ config.headless = false;
55
+ if (options.session)
56
+ config.authStatePath = options.session;
57
+ return { config, log };
58
+ }
59
+ /**
60
+ * Create a session context for commands that need authentication.
61
+ */
62
+ export async function createSessionContext(options) {
63
+ const context = await createCommandContext(options);
64
+ if (!context)
65
+ return null;
66
+ const { config, log } = context;
67
+ log.info("啟動瀏覽器...");
68
+ const { browser, context: browserContext, page, wsToken } = await launchAuthenticated(config, log);
69
+ try {
70
+ const session = await extractSessionInfo(page, config, log, wsToken);
71
+ // Keep the browser context alive for the duration of the command
72
+ // Note: Caller is responsible for closing the browser
73
+ return { config, log, page, session };
74
+ }
75
+ catch (err) {
76
+ await browserContext.close();
77
+ await browser.close();
78
+ throw err;
79
+ }
80
+ }
81
+ /**
82
+ * Helper to output formatted data.
83
+ * For JSON output (agent mode), exits immediately after output.
84
+ */
85
+ export function formatAndOutput(data, format, log) {
86
+ if (format === "json") {
87
+ console.log(JSON.stringify(data));
88
+ // Exit immediately for AI agent - no need to wait for browser cleanup
89
+ process.exit(0);
90
+ }
91
+ else if (format === "csv") {
92
+ const arr = Array.isArray(data) ? data : [data];
93
+ if (arr.length === 0)
94
+ return;
95
+ const fields = Object.keys(arr[0]);
96
+ console.log(formatAsCsv(arr, fields));
97
+ }
98
+ else if (format === "table") {
99
+ const arr = Array.isArray(data) ? data : [data];
100
+ if (arr.length === 0) {
101
+ console.log("No data");
102
+ return;
103
+ }
104
+ console.log(formatAsTable(arr));
105
+ }
106
+ // "silent" produces no output
107
+ }
108
+ function formatAsCsv(data, fields) {
109
+ const headers = fields.join(",");
110
+ const rows = data.map((item) => {
111
+ return fields.map((field) => {
112
+ const value = item[field];
113
+ if (value === null || value === undefined)
114
+ return "";
115
+ if (typeof value === "string") {
116
+ if (value.includes(",") || value.includes('"') || value.includes("\n")) {
117
+ return `"${value.replace(/"/g, '""')}"`;
118
+ }
119
+ return value;
120
+ }
121
+ return String(value);
122
+ }).join(",");
123
+ });
124
+ return [headers, ...rows].join("\n");
125
+ }
126
+ function formatAsTable(data) {
127
+ const allFields = Array.from(new Set(data.flatMap((item) => Object.keys(item))));
128
+ const widths = {};
129
+ allFields.forEach((field) => {
130
+ widths[field] = Math.max(field.length, ...data.map((item) => String(item[field] ?? "").length)) + 2;
131
+ });
132
+ const header = allFields.map((f) => f.padEnd(widths[f])).join(" | ");
133
+ const separator = allFields.map((f) => "-".repeat(widths[f] - 1)).join("-+-");
134
+ const rows = data.map((item) => {
135
+ return allFields.map((f) => String(item[f] ?? "").padEnd(widths[f])).join(" | ");
136
+ });
137
+ return [header, separator, ...rows].join("\n");
138
+ }
139
+ // Export utilities for commands
140
+ export { createLogger };
141
+ // Run the program
142
+ if (globalThis[Symbol.for("import-meta-ponyfill-esmodule")](import.meta).main) {
143
+ // If no subcommand provided, show help
144
+ const args = process.argv.slice(2);
145
+ if (args.length === 0) {
146
+ program.help();
147
+ }
148
+ program.parse();
149
+ }
@@ -0,0 +1,25 @@
1
+ import { type Browser, type BrowserContext, type Page } from "playwright-core";
2
+ import type { AppConfig, Logger } 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
+ export declare function closeBrowserSafely(browser: Browser, context?: BrowserContext, timeoutMs?: number, noWait?: boolean): Promise<void>;
25
+ //# sourceMappingURL=auth.d.ts.map
@@ -0,0 +1 @@
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,MAAM,YAAY,CAAC;AAGpD;;;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;;;;GAIG;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,CA4Bf"}