fix: organize imports and apply linting fixes

This commit is contained in:
MythEclipse
2026-05-14 15:02:23 +07:00
parent 1623c612c3
commit d1282f2f57
15 changed files with 477 additions and 199 deletions
+105 -42
View File
@@ -2,7 +2,11 @@ import { config } from "../config";
import { createChildLogger } from "../logger";
import type { SqliteDatabase } from "../muxer-queue";
import { retryWithBackoff } from "../retry";
import { getMessageById, getPendingAIAnalysisMessages, updateMessageAIAnalysis } from "./messageStore";
import {
getMessageById,
getPendingAIAnalysisMessages,
updateMessageAIAnalysis,
} from "./messageStore";
import type { MessageRecord } from "./types";
const logger = createChildLogger("ai-analyzer");
@@ -37,7 +41,10 @@ function estimateTokens(text: string): number {
return Math.ceil(text.length / 4);
}
function formatMessageForAnalysis(message: MessageRecord, index: number): string {
function formatMessageForAnalysis(
message: MessageRecord,
index: number,
): string {
const text = getAnalysisText(message);
const time = new Date(message.created_at).toISOString();
return `${index + 1}. id=${message.id} time=${time} user=${message.username}: ${text}`;
@@ -49,7 +56,10 @@ function estimateMessageTokens(message: MessageRecord): number {
async function fetchJson(url: string, init: RequestInit): Promise<unknown> {
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), config.AI_ANALYSIS_TIMEOUT_MS);
const timeout = setTimeout(
() => controller.abort(),
config.AI_ANALYSIS_TIMEOUT_MS,
);
try {
const response = await fetch(url, { ...init, signal: controller.signal });
@@ -85,10 +95,16 @@ function parseLLMAnalysis(content: string): LLMAnalysis {
if (jsonStart >= 0 && jsonEnd > jsonStart) {
try {
const parsed = JSON.parse(content.slice(jsonStart, jsonEnd + 1));
const status = parsed.status === "flagged" ? "flagged" : parsed.status === "warn" ? "warn" : "clean";
const status =
parsed.status === "flagged"
? "flagged"
: parsed.status === "warn"
? "warn"
: "clean";
const flags = Array.isArray(parsed.flags) ? parsed.flags.map(String) : [];
const score = Math.max(0, Math.min(1, Number(parsed.score) || 0));
const analysis = typeof parsed.analysis === "string" ? parsed.analysis : content;
const analysis =
typeof parsed.analysis === "string" ? parsed.analysis : content;
return { status, flags, score, analysis };
} catch {
// Fall through to text-only parsing.
@@ -96,27 +112,37 @@ function parseLLMAnalysis(content: string): LLMAnalysis {
}
return {
status: /flagged|bahaya|berisiko|toxic|hate|harassment|violence|sexual|self-harm|illegal|scam|hacking/i.test(content) ? "flagged" : /warn|provokasi|hinaan|menyerang/i.test(content) ? "warn" : "clean",
status:
/flagged|bahaya|berisiko|toxic|hate|harassment|violence|sexual|self-harm|illegal|scam|hacking/i.test(
content,
)
? "flagged"
: /warn|provokasi|hinaan|menyerang/i.test(content)
? "warn"
: "clean",
flags: [],
score: 0,
analysis: content.trim() || "Tidak ada analisis dari LLM.",
};
}
async function runLLMAnalysis(messages: MessageRecord[]): Promise<{ results: LLMAnalysis[]; raw: unknown }> {
const response = await retryWithBackoff(
() => fetchJson(`${config.AI_LLM_BASE_URL}/chat/completions`, {
method: "POST",
headers: {
"Authorization": `Bearer ${config.AI_LLM_API_KEY}`,
"Content-Type": "application/json",
},
body: JSON.stringify({
model: config.AI_LLM_MODEL,
messages: [
{
role: "system",
content: `Kamu moderator Discord komunitas. Analisis setiap pesan dengan 3 kategori:
async function runLLMAnalysis(
messages: MessageRecord[],
): Promise<{ results: LLMAnalysis[]; raw: unknown }> {
const response = (await retryWithBackoff(
() =>
fetchJson(`${config.AI_LLM_BASE_URL}/chat/completions`, {
method: "POST",
headers: {
Authorization: `Bearer ${config.AI_LLM_API_KEY}`,
"Content-Type": "application/json",
},
body: JSON.stringify({
model: config.AI_LLM_MODEL,
messages: [
{
role: "system",
content: `Kamu moderator Discord komunitas. Analisis setiap pesan dengan 3 kategori:
- CLEAN: Pesan normal, tidak melanggar aturan
- WARN: Melanggar aturan minor yang menarget orang lain (tone menyerang, hinaan ringan, konflik kecil) - butuh peringatan tapi tidak dihapus
- FLAGGED: Melanggar aturan berat (NSFW, ilegal, hacking, scam, harassment, violence, SARA, gore, spam, promosi judi) - butuh review moderator untuk penghapusan
@@ -166,18 +192,18 @@ PENENTUAN STATUS:
Balas JSON array dengan schema: [{"status":"clean|warn|flagged","flags":["..."],"score":0..1,"analysis":"ringkasan Bahasa Indonesia + alasan + aksi disarankan"}]
Satu JSON object per pesan dalam array.`,
},
{
role: "user",
content: `Analisis ${messages.length} pesan berikut sebagai satu alur percakapan. Tetap kembalikan satu hasil per pesan dengan urutan yang sama:\n${messages.map(formatMessageForAnalysis).join("\n")}`,
},
],
temperature: 0.2,
},
{
role: "user",
content: `Analisis ${messages.length} pesan berikut sebagai satu alur percakapan. Tetap kembalikan satu hasil per pesan dengan urutan yang sama:\n${messages.map(formatMessageForAnalysis).join("\n")}`,
},
],
temperature: 0.2,
}),
signal: AbortSignal.timeout(config.AI_ANALYSIS_TIMEOUT_MS),
}),
signal: AbortSignal.timeout(config.AI_ANALYSIS_TIMEOUT_MS),
}),
{ retries: 2, logger },
) as ChatCompletionResponse;
)) as ChatCompletionResponse;
const content = response.choices?.[0]?.message?.content?.trim() || "";
@@ -191,12 +217,18 @@ Satu JSON object per pesan dalam array.`,
const parsed = JSON.parse(content.substring(jsonStart, jsonEnd + 1));
if (Array.isArray(parsed)) {
results = parsed.map((item: any) => {
const status = item.status === "flagged" ? "flagged" : item.status === "warn" ? "warn" : "clean";
const status =
item.status === "flagged"
? "flagged"
: item.status === "warn"
? "warn"
: "clean";
return {
status,
flags: Array.isArray(item.flags) ? item.flags.map(String) : [],
score: Math.max(0, Math.min(1, Number(item.score) || 0)),
analysis: typeof item.analysis === "string" ? item.analysis : content,
analysis:
typeof item.analysis === "string" ? item.analysis : content,
};
});
}
@@ -213,10 +245,15 @@ Satu JSON object per pesan dalam array.`,
return { results, raw: response };
}
async function analyzeAndStoreBatch(db: SqliteDatabase, messages: MessageRecord[]): Promise<void> {
async function analyzeAndStoreBatch(
db: SqliteDatabase,
messages: MessageRecord[],
): Promise<void> {
if (messages.length === 0) return;
const analyzableMessages = messages.filter((message) => getAnalysisText(message).length > 0);
const analyzableMessages = messages.filter(
(message) => getAnalysisText(message).length > 0,
);
if (analyzableMessages.length === 0) return;
activeRequests++;
@@ -228,7 +265,12 @@ async function analyzeAndStoreBatch(db: SqliteDatabase, messages: MessageRecord[
const result = results[i] || parseLLMAnalysis("");
const row = updateMessageAIAnalysis(db, message.id, {
status: result.status as "pending" | "clean" | "warn" | "flagged" | "error",
status: result.status as
| "pending"
| "clean"
| "warn"
| "flagged"
| "error",
flags: JSON.stringify(result.flags),
score: result.score,
raw: JSON.stringify(raw),
@@ -242,7 +284,11 @@ async function analyzeAndStoreBatch(db: SqliteDatabase, messages: MessageRecord[
if (analyzableMessages.length > 1) {
const midpoint = Math.ceil(analyzableMessages.length / 2);
logger.warn(
{ count: analyzableMessages.length, nextBatchSizes: [midpoint, analyzableMessages.length - midpoint], error },
{
count: analyzableMessages.length,
nextBatchSizes: [midpoint, analyzableMessages.length - midpoint],
error,
},
"AI batch failed, splitting into smaller batches",
);
await analyzeAndStoreBatch(db, analyzableMessages.slice(0, midpoint));
@@ -288,7 +334,11 @@ async function drainQueue(db: SqliteDatabase): Promise<void> {
if (!message) continue;
const messageTokens = estimateMessageTokens(message);
if (batch.length > 0 && (batch.length >= MAX_AI_BATCH_MESSAGES || tokenEstimate + messageTokens > batchTokenLimit)) {
if (
batch.length > 0 &&
(batch.length >= MAX_AI_BATCH_MESSAGES ||
tokenEstimate + messageTokens > batchTokenLimit)
) {
queuedMessageIds.add(messageId);
break;
}
@@ -298,7 +348,10 @@ async function drainQueue(db: SqliteDatabase): Promise<void> {
}
if (batch.length > 0) {
logger.info({ count: batch.length, tokenEstimate }, "Processing AI analysis batch");
logger.info(
{ count: batch.length, tokenEstimate },
"Processing AI analysis batch",
);
await analyzeAndStoreBatch(db, batch);
}
}
@@ -307,12 +360,17 @@ async function drainQueue(db: SqliteDatabase): Promise<void> {
}
}
export function queueMessageAnalysis(db: SqliteDatabase, messageId: string): void {
export function queueMessageAnalysis(
db: SqliteDatabase,
messageId: string,
): void {
if (!config.AI_ANALYSIS_ENABLED) return;
logger.debug({ messageId }, "Queueing AI analysis");
queuedMessageIds.add(messageId);
setImmediate(() => {
drainQueue(db).catch((error) => logger.error({ error }, "AI analysis queue failed"));
drainQueue(db).catch((error) =>
logger.error({ error }, "AI analysis queue failed"),
);
});
}
@@ -327,10 +385,15 @@ export function startPendingAIAnalysisWorker(db: SqliteDatabase): void {
if (isProcessing) return;
const pendingMessages = getPendingAIAnalysisMessages(db, 500);
if (pendingMessages.length === 0) return;
logger.info({ count: pendingMessages.length }, "Queueing pending AI analysis messages");
logger.info(
{ count: pendingMessages.length },
"Queueing pending AI analysis messages",
);
for (const message of pendingMessages) {
queuedMessageIds.add(message.id);
}
drainQueue(db).catch((error) => logger.error({ error }, "Pending AI analysis worker failed"));
drainQueue(db).catch((error) =>
logger.error({ error }, "Pending AI analysis worker failed"),
);
}, 15000);
}
+27 -9
View File
@@ -1,8 +1,11 @@
import { createChildLogger } from "../logger";
import { config } from "../config";
import { retryWithBackoff } from "../retry";
import { createChildLogger } from "../logger";
import type { SqliteDatabase } from "../muxer-queue";
import { updateAttachmentAsUploaded, updateAttachmentAsFailedUpload } from "./messageStore";
import { retryWithBackoff } from "../retry";
import {
updateAttachmentAsFailedUpload,
updateAttachmentAsUploaded,
} from "./messageStore";
const logger = createChildLogger("attachment-uploader");
@@ -25,7 +28,9 @@ export interface ParsedUploadResponse {
type: string;
}
export function parseUploadResponse(response: PicserUploadResponse): ParsedUploadResponse {
export function parseUploadResponse(
response: PicserUploadResponse,
): ParsedUploadResponse {
if (!response.success) {
throw new Error("Upload failed: success=false");
}
@@ -49,7 +54,9 @@ export async function uploadAttachmentToPicser(
filename: string,
): Promise<ParsedUploadResponse> {
const formData = new FormData();
const blob = new Blob([new Uint8Array(fileBuffer)], { type: "application/octet-stream" });
const blob = new Blob([new Uint8Array(fileBuffer)], {
type: "application/octet-stream",
});
formData.append("file", blob, filename);
try {
@@ -76,11 +83,17 @@ export async function uploadAttachmentToPicser(
);
const parsed = parseUploadResponse(response);
logger.info({ filename, url: parsed.url }, "Attachment uploaded successfully");
logger.info(
{ filename, url: parsed.url },
"Attachment uploaded successfully",
);
return parsed;
} catch (error) {
logger.error(
{ filename, error: error instanceof Error ? error.message : String(error) },
{
filename,
error: error instanceof Error ? error.message : String(error),
},
"Failed to upload attachment",
);
throw error;
@@ -121,13 +134,18 @@ export async function processAttachmentUpload(
const sizeMb = buffer.length / (1024 * 1024);
if (sizeMb > config.ATTACHMENT_MAX_SIZE_MB) {
throw new Error(`File size ${sizeMb.toFixed(2)}MB exceeds limit of ${config.ATTACHMENT_MAX_SIZE_MB}MB`);
throw new Error(
`File size ${sizeMb.toFixed(2)}MB exceeds limit of ${config.ATTACHMENT_MAX_SIZE_MB}MB`,
);
}
const result = await uploadAttachmentToPicser(buffer, filename);
updateAttachmentAsUploaded(db, attachmentId, result.url, Date.now());
logger.info({ attachmentId, uploadedUrl: result.url }, "Attachment upload completed");
logger.info(
{ attachmentId, uploadedUrl: result.url },
"Attachment upload completed",
);
} catch (error) {
const errorMsg = error instanceof Error ? error.message : String(error);
updateAttachmentAsFailedUpload(db, attachmentId, errorMsg);
+12 -3
View File
@@ -53,11 +53,17 @@ export async function syncBacklogMessages(
const guild = client.guilds.cache.get(config.MONITOR_GUILD_ID);
if (!guild) {
logger.warn({ guildId: config.MONITOR_GUILD_ID }, "Monitor guild not found, skipping backlog sync");
logger.warn(
{ guildId: config.MONITOR_GUILD_ID },
"Monitor guild not found, skipping backlog sync",
);
return;
}
logger.info({ guildId: guild.id }, "Backlog sync ready (will sync on-demand per selected channel)");
logger.info(
{ guildId: guild.id },
"Backlog sync ready (will sync on-demand per selected channel)",
);
}
export async function syncSelectedChannelBacklog(
@@ -86,7 +92,10 @@ export async function syncSelectedChannelBacklog(
try {
const count = await syncChannelMessages(db, channel as any, cutoffTime);
logger.info({ channelId, count }, "Backlog sync completed for selected channel");
logger.info(
{ channelId, count },
"Backlog sync completed for selected channel",
);
return count;
} catch (error) {
logger.warn(
+32 -10
View File
@@ -1,11 +1,15 @@
import type { Client, Message } from "discord.js-selfbot-v13";
import { createChildLogger } from "../logger";
import { config } from "../config";
import { createChildLogger } from "../logger";
import type { SqliteDatabase } from "../muxer-queue";
import { insertMessage, insertAttachment } from "./messageStore";
import { getDisplayContent, getMessageLocation, getMessageMetadata } from "./messageMetadata";
import { queueMessageAnalysis } from "./aiAnalyzer";
import type { MessageRecord, AttachmentRecord } from "./types";
import {
getDisplayContent,
getMessageLocation,
getMessageMetadata,
} from "./messageMetadata";
import { insertAttachment, insertMessage } from "./messageStore";
import type { AttachmentRecord, MessageRecord } from "./types";
const logger = createChildLogger("message-capture");
@@ -89,7 +93,10 @@ export async function captureMessage(
);
}
export function registerMessageCapture(client: Client, db: SqliteDatabase): void {
export function registerMessageCapture(
client: Client,
db: SqliteDatabase,
): void {
client.on("messageCreate", async (message) => {
if (!message.guildId || message.guildId !== config.MONITOR_GUILD_ID) return;
if (message.author?.bot) return;
@@ -98,14 +105,18 @@ export function registerMessageCapture(client: Client, db: SqliteDatabase): void
await captureMessage(db, message, "text");
} catch (error) {
logger.error(
{ messageId: message.id, error: error instanceof Error ? error.message : String(error) },
{
messageId: message.id,
error: error instanceof Error ? error.message : String(error),
},
"Failed to capture message",
);
}
});
client.on("messageUpdate", async (_oldMessage, newMessage) => {
if (!newMessage.guildId || newMessage.guildId !== config.MONITOR_GUILD_ID) return;
if (!newMessage.guildId || newMessage.guildId !== config.MONITOR_GUILD_ID)
return;
if (newMessage.author?.bot) return;
try {
@@ -117,7 +128,12 @@ export function registerMessageCapture(client: Client, db: SqliteDatabase): void
if (existing) {
const editedAt = Date.now();
updateMessageAsEdited(db, newMessage.id, getDisplayContent(newMessage as Message), editedAt);
updateMessageAsEdited(
db,
newMessage.id,
getDisplayContent(newMessage as Message),
editedAt,
);
queueMessageAnalysis(db, newMessage.id);
const broadcaster = globalThis as any;
@@ -133,7 +149,10 @@ export function registerMessageCapture(client: Client, db: SqliteDatabase): void
}
} catch (error) {
logger.error(
{ messageId: newMessage.id, error: error instanceof Error ? error.message : String(error) },
{
messageId: newMessage.id,
error: error instanceof Error ? error.message : String(error),
},
"Failed to capture message update",
);
}
@@ -159,7 +178,10 @@ export function registerMessageCapture(client: Client, db: SqliteDatabase): void
logger.info({ messageId: message.id }, "Message deletion captured");
} catch (error) {
logger.error(
{ messageId: message.id, error: error instanceof Error ? error.message : String(error) },
{
messageId: message.id,
error: error instanceof Error ? error.message : String(error),
},
"Failed to capture message deletion",
);
}
+35 -9
View File
@@ -1,4 +1,8 @@
import type { Message, TextChannel, ThreadChannel } from "discord.js-selfbot-v13";
import type {
Message,
TextChannel,
ThreadChannel,
} from "discord.js-selfbot-v13";
export interface MessageLocation {
channelId: string;
@@ -8,7 +12,12 @@ export interface MessageLocation {
}
export interface RichMessageMetadata {
stickers: Array<{ id: string; name: string; url: string; format: string | null }>;
stickers: Array<{
id: string;
name: string;
url: string;
format: string | null;
}>;
embeds: Array<{
title: string | null;
description: string | null;
@@ -16,7 +25,11 @@ export interface RichMessageMetadata {
color: number | null;
image: string | null;
thumbnail: string | null;
author: { name: string | null; url: string | null; iconURL: string | null } | null;
author: {
name: string | null;
url: string | null;
iconURL: string | null;
} | null;
footer: { text: string | null; iconURL: string | null } | null;
fields: Array<{ name: string; value: string; inline: boolean }>;
}>;
@@ -66,7 +79,9 @@ export function getMessageLocation(message: Message): MessageLocation {
};
}
export function getStickerMetadata(message: Message): RichMessageMetadata["stickers"] {
export function getStickerMetadata(
message: Message,
): RichMessageMetadata["stickers"] {
return Array.from(message.stickers.values()).map((sticker) => ({
id: sticker.id,
name: sticker.name,
@@ -75,7 +90,9 @@ export function getStickerMetadata(message: Message): RichMessageMetadata["stick
}));
}
export function getAttachmentMetadata(message: Message): RichMessageMetadata["attachments"] {
export function getAttachmentMetadata(
message: Message,
): RichMessageMetadata["attachments"] {
return Array.from(message.attachments.values()).map((attachment) => ({
id: attachment.id,
name: attachment.name || "unknown",
@@ -85,7 +102,9 @@ export function getAttachmentMetadata(message: Message): RichMessageMetadata["at
}));
}
export function getEmbedMetadata(message: Message): RichMessageMetadata["embeds"] {
export function getEmbedMetadata(
message: Message,
): RichMessageMetadata["embeds"] {
return message.embeds.map((embed) => ({
title: embed.title ?? null,
description: embed.description ?? null,
@@ -130,7 +149,10 @@ export function getMessageMetadata(message: Message): RichMessageMetadata {
member: member
? {
displayName: member.displayName ?? null,
roles: member.roles.cache.map((role) => ({ id: role.id, name: role.name })),
roles: member.roles.cache.map((role) => ({
id: role.id,
name: role.name,
})),
joinedTimestamp: member.joinedTimestamp ?? null,
}
: null,
@@ -155,12 +177,16 @@ export function getDisplayContent(message: Message): string {
const attachments = getAttachmentMetadata(message);
if (attachments.length > 0) {
return attachments.map((attachment) => `[Attachment: ${attachment.name}]`).join(" ");
return attachments
.map((attachment) => `[Attachment: ${attachment.name}]`)
.join(" ");
}
const embeds = getEmbedMetadata(message);
if (embeds.length > 0) {
return embeds.map((embed) => embed.title || embed.description || "[Embed]").join(" ");
return embeds
.map((embed) => embed.title || embed.description || "[Embed]")
.join(" ");
}
return "";
+80 -21
View File
@@ -1,10 +1,13 @@
import { createChildLogger } from "../logger";
import type { DatabaseAdapter } from "../database/adapter";
import type { MessageRecord, AttachmentRecord } from "./types";
import { createChildLogger } from "../logger";
import type { AttachmentRecord, MessageRecord } from "./types";
const logger = createChildLogger("message-store");
export function insertMessage(db: DatabaseAdapter, message: MessageRecord): void {
export function insertMessage(
db: DatabaseAdapter,
message: MessageRecord,
): void {
try {
const stmt = db.prepare(`
INSERT OR IGNORE INTO messages (
@@ -30,10 +33,16 @@ export function insertMessage(db: DatabaseAdapter, message: MessageRecord): void
message.metadata,
);
logger.debug({ messageId: message.id, channelId: message.channel_id }, "Message inserted");
logger.debug(
{ messageId: message.id, channelId: message.channel_id },
"Message inserted",
);
} catch (error) {
logger.error(
{ messageId: message.id, error: error instanceof Error ? error.message : String(error) },
{
messageId: message.id,
error: error instanceof Error ? error.message : String(error),
},
"Failed to insert message",
);
throw error;
@@ -57,7 +66,10 @@ export function updateMessageAsEdited(
logger.debug({ messageId }, "Message marked as edited");
} catch (error) {
logger.error(
{ messageId, error: error instanceof Error ? error.message : String(error) },
{
messageId,
error: error instanceof Error ? error.message : String(error),
},
"Failed to update message as edited",
);
throw error;
@@ -80,7 +92,10 @@ export function updateMessageAsDeleted(
logger.debug({ messageId }, "Message marked as deleted");
} catch (error) {
logger.error(
{ messageId, error: error instanceof Error ? error.message : String(error) },
{
messageId,
error: error instanceof Error ? error.message : String(error),
},
"Failed to update message as deleted",
);
throw error;
@@ -101,18 +116,29 @@ export function getMessagesByChannel(
LIMIT ? OFFSET ?
`);
const rows = stmt.all(channelId, channelId, limit, offset) as MessageRecord[];
const rows = stmt.all(
channelId,
channelId,
limit,
offset,
) as MessageRecord[];
return rows;
} catch (error) {
logger.error(
{ channelId, error: error instanceof Error ? error.message : String(error) },
{
channelId,
error: error instanceof Error ? error.message : String(error),
},
"Failed to get messages by channel",
);
throw error;
}
}
export function insertAttachment(db: DatabaseAdapter, attachment: AttachmentRecord): void {
export function insertAttachment(
db: DatabaseAdapter,
attachment: AttachmentRecord,
): void {
try {
const stmt = db.prepare(`
INSERT OR IGNORE INTO attachments (
@@ -139,10 +165,16 @@ export function insertAttachment(db: DatabaseAdapter, attachment: AttachmentReco
attachment.uploaded_at,
);
logger.debug({ attachmentId: attachment.id, messageId: attachment.message_id }, "Attachment inserted");
logger.debug(
{ attachmentId: attachment.id, messageId: attachment.message_id },
"Attachment inserted",
);
} catch (error) {
logger.error(
{ attachmentId: attachment.id, error: error instanceof Error ? error.message : String(error) },
{
attachmentId: attachment.id,
error: error instanceof Error ? error.message : String(error),
},
"Failed to insert attachment",
);
throw error;
@@ -163,11 +195,19 @@ export function getAttachmentsByChannel(
LIMIT ? OFFSET ?
`);
const rows = stmt.all(channelId, channelId, limit, offset) as AttachmentRecord[];
const rows = stmt.all(
channelId,
channelId,
limit,
offset,
) as AttachmentRecord[];
return rows;
} catch (error) {
logger.error(
{ channelId, error: error instanceof Error ? error.message : String(error) },
{
channelId,
error: error instanceof Error ? error.message : String(error),
},
"Failed to get attachments by channel",
);
throw error;
@@ -188,10 +228,16 @@ export function updateAttachmentAsUploaded(
`);
stmt.run(uploadedUrl, uploadedAt, attachmentId);
logger.debug({ attachmentId, uploadedUrl }, "Attachment marked as uploaded");
logger.debug(
{ attachmentId, uploadedUrl },
"Attachment marked as uploaded",
);
} catch (error) {
logger.error(
{ attachmentId, error: error instanceof Error ? error.message : String(error) },
{
attachmentId,
error: error instanceof Error ? error.message : String(error),
},
"Failed to update attachment as uploaded",
);
throw error;
@@ -214,7 +260,10 @@ export function updateAttachmentAsFailedUpload(
logger.debug({ attachmentId, error }, "Attachment marked as failed upload");
} catch (error) {
logger.error(
{ attachmentId, error: error instanceof Error ? error.message : String(error) },
{
attachmentId,
error: error instanceof Error ? error.message : String(error),
},
"Failed to update attachment as failed",
);
throw error;
@@ -255,11 +304,16 @@ export function updateMessageAIAnalysis(
messageId,
);
const row = db.prepare("SELECT * FROM messages WHERE id = ?").get(messageId) as MessageRecord | undefined;
const row = db
.prepare("SELECT * FROM messages WHERE id = ?")
.get(messageId) as MessageRecord | undefined;
return row ?? null;
} catch (error) {
logger.error(
{ messageId, error: error instanceof Error ? error.message : String(error) },
{
messageId,
error: error instanceof Error ? error.message : String(error),
},
"Failed to update message AI analysis",
);
throw error;
@@ -289,7 +343,12 @@ export function getPendingAIAnalysisMessages(
}
}
export function getMessageById(db: DatabaseAdapter, messageId: string): MessageRecord | null {
const row = db.prepare("SELECT * FROM messages WHERE id = ?").get(messageId) as MessageRecord | undefined;
export function getMessageById(
db: DatabaseAdapter,
messageId: string,
): MessageRecord | null {
const row = db
.prepare("SELECT * FROM messages WHERE id = ?")
.get(messageId) as MessageRecord | undefined;
return row ?? null;
}