This commit is contained in:
2026-02-25 01:34:09 +00:00
parent 6e8ee69311
commit 0226608d8f
8 changed files with 296 additions and 43 deletions
+55 -27
View File
@@ -1,17 +1,11 @@
import { readdir } from 'node:fs/promises';
import { mkdir, readdir } from 'node:fs/promises';
import { join } from 'node:path';
import { simpleParser } from 'mailparser';
import type { EmailSummary, EmailMessage } from 'types';
import { rebuildIndex } from '@@/queue/handlers/gmail-sync';
import { createRouter } from '../../create-router';
import { getUserEmailDir } from '@@/data-path';
type CacheEntry = {
summaries: EmailSummary[];
fileCount: number;
};
const cache = new Map<string, CacheEntry>();
const parseHeadersOnly = async (filePath: string, id: string): Promise<EmailSummary | null> => {
try {
const file = Bun.file(filePath);
@@ -20,6 +14,7 @@ const parseHeadersOnly = async (filePath: string, id: string): Promise<EmailSumm
const text = parsed.text ?? '';
const snippet = text.slice(0, 120).replace(/\s+/g, ' ').trim();
const attachmentCount = parsed.attachments?.length ?? 0;
return {
id,
@@ -28,6 +23,7 @@ const parseHeadersOnly = async (filePath: string, id: string): Promise<EmailSumm
subject: parsed.subject ?? '(no subject)',
date: (parsed.date ?? new Date()).toISOString(),
snippet,
...(attachmentCount > 0 ? { attachmentCount } : {}),
};
} catch {
return null;
@@ -48,28 +44,25 @@ emailRouter.get('/messages', async (ctx) => {
return ctx.json({ messages: [], total: 0 });
}
const cached = cache.get(email);
if (cached && cached.fileCount === filenames.length) {
const page = Number(ctx.req.query('page') ?? '1');
const limit = Number(ctx.req.query('limit') ?? '50');
const start = (page - 1) * limit;
return ctx.json({ messages: cached.summaries.slice(start, start + limit), total: cached.summaries.length });
}
const summaries: EmailSummary[] = [];
for (const filename of filenames) {
const id = filename.replace(/\.eml$/, '');
const summary = await parseHeadersOnly(join(dir, filename), id);
if (summary) summaries.push(summary);
}
summaries.sort((a, b) => new Date(b.date).getTime() - new Date(a.date).getTime());
cache.set(email, { summaries, fileCount: filenames.length });
const page = Number(ctx.req.query('page') ?? '1');
const limit = Number(ctx.req.query('limit') ?? '50');
const start = (page - 1) * limit;
const indexFile = Bun.file(join(dir, 'index.json'));
if (await indexFile.exists()) {
try {
const raw = await indexFile.json();
const index = Array.isArray(raw) ? null : (raw as { v?: number; entries: EmailSummary[] });
if (index?.v === 3 && index.entries.length === filenames.length) {
return ctx.json({ messages: index.entries.slice(start, start + limit), total: index.entries.length });
}
} catch {
/* index corrupted, fall through to rebuild */
}
}
// Fallback: rebuild index from .eml files
const summaries = rebuildIndex(dir);
return ctx.json({ messages: summaries.slice(start, start + limit), total: summaries.length });
});
@@ -111,3 +104,38 @@ emailRouter.get('/messages/:id', async (ctx) => {
return ctx.text('Failed to parse email', 500);
}
});
emailRouter.post('/messages/:id/attachments/:index/extract', async (ctx) => {
const email = ctx.get('user').email;
const id = ctx.req.param('id');
const index = Number(ctx.req.param('index'));
const filePath = join(getUserEmailDir(email), `${id}.eml`);
const file = Bun.file(filePath);
if (!(await file.exists())) {
return ctx.text('Not found', 404);
}
try {
const buffer = Buffer.from(await file.arrayBuffer());
const parsed = await simpleParser(buffer);
const attachment = parsed.attachments[index];
if (!attachment) {
return ctx.text('Attachment not found', 404);
}
const fileName = attachment.filename ?? 'unknown';
const attachDir = join(getUserEmailDir(email), 'attachments');
const destPath = join(attachDir, fileName);
const destFile = Bun.file(destPath);
if (!(await destFile.exists())) {
await mkdir(attachDir, { recursive: true });
await Bun.write(destPath, attachment.content);
}
return ctx.json({ filePath: `Gmail/emails/attachments/${fileName}`, fileName, root: 'user-data' });
} catch {
return ctx.text('Failed to extract attachment', 500);
}
});
+9 -4
View File
@@ -54,7 +54,7 @@ function collectExtensionFlags(email: string, containerPaths?: PathOverrides): s
return flags;
}
function generateResourceSkill(outputDir: string): string | null {
export function generateResourceSkill(outputDir: string): string | null {
const nativeDir = getNativeResourcesDir();
const globalDir = getGlobalResourcesDir();
@@ -114,9 +114,14 @@ function generateResourceSkill(outputDir: string): string | null {
].join('\n');
const skillDir = join(outputDir, '.generated', 'available-resources');
mkdirSync(skillDir, { recursive: true });
writeFileSync(join(skillDir, 'SKILL.md'), skillContent, 'utf-8');
return skillDir;
try {
mkdirSync(skillDir, { recursive: true });
writeFileSync(join(skillDir, 'SKILL.md'), skillContent, 'utf-8');
return skillDir;
} catch {
logger.error(`Failed to write resource skill to ${skillDir}`);
return null;
}
}
function buildResourcesEnv(): string {