|
| 1 | +import type { CommandInteraction } from "discord.js"; |
| 2 | +import { runCliCommand, CliRunnerError } from "../bot/cli-runner.js"; |
| 3 | +import type { SlashCommandHandler } from "../interfaces/command-handler.js"; |
| 4 | + |
| 5 | +const DEFAULT_ERROR_MESSAGE = "❌ Failed to retrieve recent OpenBrain items. Please try again."; |
| 6 | + |
| 7 | +export interface RecentCommandHandlerDependencies { |
| 8 | + runCli?: typeof runCliCommand; |
| 9 | + errorMessage?: string; |
| 10 | +} |
| 11 | + |
| 12 | +export class RecentCommandHandler implements SlashCommandHandler { |
| 13 | + private readonly runCli: typeof runCliCommand; |
| 14 | + private readonly errorMessage: string; |
| 15 | + |
| 16 | + constructor(dependencies: RecentCommandHandlerDependencies = {}) { |
| 17 | + this.runCli = dependencies.runCli ?? runCliCommand; |
| 18 | + this.errorMessage = dependencies.errorMessage ?? DEFAULT_ERROR_MESSAGE; |
| 19 | + } |
| 20 | + |
| 21 | + async handleCommand(command: CommandInteraction): Promise<boolean> { |
| 22 | + if (command.commandName !== "recent") return false; |
| 23 | + |
| 24 | + await command.deferReply(); |
| 25 | + |
| 26 | + try { |
| 27 | + const opt = command.options.getInteger("limit"); |
| 28 | + const limit = opt ?? 5; |
| 29 | + |
| 30 | + if (opt !== null && (limit < 1 || limit > 100)) { |
| 31 | + await command.editReply("⚠️ Recent parameter `limit` must be between 1 and 100."); |
| 32 | + return true; |
| 33 | + } |
| 34 | + |
| 35 | + const args = ["--json", "--limit", String(limit)]; |
| 36 | + |
| 37 | + const result = await this.runCli("recent", args, { |
| 38 | + channelId: command.channelId ?? undefined, |
| 39 | + messageId: undefined, |
| 40 | + authorId: command.user?.id, |
| 41 | + }); |
| 42 | + |
| 43 | + if (result.exitCode !== 0) { |
| 44 | + await command.editReply("❌ Recent failed: CLI returned an error"); |
| 45 | + return true; |
| 46 | + } |
| 47 | + |
| 48 | + if (!result.stdout || result.stdout.length === 0) { |
| 49 | + await command.editReply("No recent items found."); |
| 50 | + return true; |
| 51 | + } |
| 52 | + |
| 53 | + const stdoutText = result.stdout.join("\n").trim(); |
| 54 | + let items: any[] = []; |
| 55 | + |
| 56 | + try { |
| 57 | + const parsed = JSON.parse(stdoutText); |
| 58 | + if (Array.isArray(parsed)) { |
| 59 | + items = parsed.slice(0, limit); |
| 60 | + } else if (parsed && typeof parsed === "object") { |
| 61 | + if (Array.isArray((parsed as any).items)) items = (parsed as any).items.slice(0, limit); |
| 62 | + else if (Array.isArray((parsed as any).results)) items = (parsed as any).results.slice(0, limit); |
| 63 | + else if (Array.isArray((parsed as any).rows)) items = (parsed as any).rows.slice(0, limit); |
| 64 | + else { |
| 65 | + const arrProp = Object.keys(parsed).find((k) => Array.isArray((parsed as any)[k])); |
| 66 | + if (arrProp) items = (parsed as any)[arrProp].slice(0, limit); |
| 67 | + else items = [parsed]; |
| 68 | + } |
| 69 | + } |
| 70 | + } catch { |
| 71 | + // Fallback: try parsing each stdout line as JSON (NDJSON style) |
| 72 | + for (const line of result.stdout) { |
| 73 | + try { |
| 74 | + const obj = JSON.parse(line); |
| 75 | + if (obj) items.push(obj); |
| 76 | + } catch { |
| 77 | + // ignore non-json lines |
| 78 | + } |
| 79 | + } |
| 80 | + items = items.slice(0, limit); |
| 81 | + } |
| 82 | + |
| 83 | + // Ensure we have an array of entries |
| 84 | + items = items.filter(Boolean); |
| 85 | + |
| 86 | + if (items.length === 0) { |
| 87 | + await command.editReply("No recent items found."); |
| 88 | + return true; |
| 89 | + } |
| 90 | + |
| 91 | + // Helper to escape stray closing bracket to avoid accidental markdown |
| 92 | + const escape = (s: unknown) => { |
| 93 | + if (s === undefined || s === null) return ""; |
| 94 | + return String(s).replace(/\]/g, "\\]").replace(/\[/g, "\\["); |
| 95 | + }; |
| 96 | + |
| 97 | + const lines: string[] = []; |
| 98 | + lines.push("🕘 Recent OpenBrain items"); |
| 99 | + lines.push(""); |
| 100 | + |
| 101 | + for (const it of items) { |
| 102 | + const id = it.id ?? it.item_id ?? it.itemId ?? it._id ?? ""; |
| 103 | + const title = it.title ?? it.name ?? it.heading ?? it.text ?? "(untitled)"; |
| 104 | + const modified = it.modified ?? it.updated_at ?? it.updated ?? it.timestamp ?? it.mtime ?? ""; |
| 105 | + const summary = it.summary ?? it.brief ?? it.description ?? it.text ?? ""; |
| 106 | + |
| 107 | + const idPart = id !== "" ? `\`${String(id)}\`` : ""; |
| 108 | + const titlePart = escape(title); |
| 109 | + const modifiedPart = modified ? ` — ${String(modified)}` : ""; |
| 110 | + |
| 111 | + lines.push(`- ${idPart} ${titlePart}${modifiedPart}`.trim()); |
| 112 | + |
| 113 | + if (summary && typeof summary === "string") { |
| 114 | + const one = summary.replace(/\s+/g, " ").trim(); |
| 115 | + const short = one.length > 200 ? one.slice(0, 197).trim() + "..." : one; |
| 116 | + if (short) lines.push(` ${short}`); |
| 117 | + } |
| 118 | + |
| 119 | + lines.push(""); |
| 120 | + } |
| 121 | + |
| 122 | + const message = lines.join("\n").trim(); |
| 123 | + const DISCORD_CONTENT_LIMIT = 1900; |
| 124 | + |
| 125 | + if (message.length <= DISCORD_CONTENT_LIMIT) { |
| 126 | + await command.editReply(message); |
| 127 | + } else { |
| 128 | + // Attach full content as a markdown file and post a short TOC |
| 129 | + const filename = `recent-${Date.now()}.md`; |
| 130 | + const summary = lines.slice(0, 20).join("\n"); |
| 131 | + const file = { attachment: Buffer.from(lines.join("\n"), "utf8"), name: filename } as any; |
| 132 | + await command.editReply({ content: `${"🕘 Recent OpenBrain items"}\n\n${summary}\n\n*(Full content attached as ${filename})*`, files: [file] } as any); |
| 133 | + } |
| 134 | + } catch (err) { |
| 135 | + try { |
| 136 | + // eslint-disable-next-line no-console |
| 137 | + console.error("RecentCommandHandler: error while retrieving recent items:", err); |
| 138 | + } catch { |
| 139 | + // ignore logging issues |
| 140 | + } |
| 141 | + |
| 142 | + if (err instanceof CliRunnerError) { |
| 143 | + const CLI_UNAVAILABLE_MESSAGE = |
| 144 | + "⚠️ OpenBrain CLI is not available. Please ensure the CLI is installed and accessible on PATH."; |
| 145 | + await command.editReply(CLI_UNAVAILABLE_MESSAGE); |
| 146 | + } else { |
| 147 | + if (process.env.NODE_ENV === "test") { |
| 148 | + await command.editReply(this.errorMessage); |
| 149 | + } else { |
| 150 | + const msg = String((err && (err as any).message) || String(err || "")); |
| 151 | + const snippet = msg.length > 500 ? msg.slice(0, 500) + "...(truncated)" : msg; |
| 152 | + await command.editReply(`${this.errorMessage}\n\nError: ${snippet}\n(See bot logs for details)`); |
| 153 | + } |
| 154 | + } |
| 155 | + } |
| 156 | + |
| 157 | + return true; |
| 158 | + } |
| 159 | +} |
0 commit comments