// 附件落盘与读取
import fs from 'node:fs';
import path from 'node:path';
import crypto from 'node:crypto';
import { DATA_DIR, ATTACH_DIR } from '../config.js';
import { db } from '../db.js';
/** 清理文件名中的不安全字符 */
export function safeFilename(name) {
const base = path.basename(String(name || 'attachment')).replace(/[\\/:*?"<>|\x00-\x1f]/g, '_');
return base.slice(0, 180) || 'attachment';
}
/** 保存一个附件到数据目录,返回相对路径(相对 DATA_DIR) */
export function saveAttachmentBuffer(userId, messageId, filename, mime, buffer) {
const dir = path.join(ATTACH_DIR, String(userId), String(messageId));
fs.mkdirSync(dir, { recursive: true });
const stored = `${crypto.randomBytes(4).toString('hex')}-${safeFilename(filename)}`;
const abs = path.join(dir, stored);
fs.writeFileSync(abs, buffer);
const rel = path.relative(DATA_DIR, abs).split(path.sep).join('/');
const info = db
.prepare(
'INSERT INTO attachments (message_id, filename, mime, size, storage_path, content_id) VALUES (?, ?, ?, ?, ?, ?)'
)
.run(messageId, safeFilename(filename), mime || 'application/octet-stream', buffer.length, rel, null);
return { id: info.lastInsertRowid, storagePath: rel, size: buffer.length };
}
/** 把解析出的邮件附件批量入库 */
export function saveParsedAttachments(userId, messageId, attachments) {
const saved = [];
for (const att of attachments || []) {
if (!att?.content) continue;
const result = saveAttachmentBuffer(
userId,
messageId,
att.filename || 'attachment',
att.contentType,
att.content
);
saved.push(result);
}
return saved;
}
/** 删除某封邮件的附件目录(数据库行由外键级联删除) */
export function removeAttachmentDir(userId, messageId) {
const dir = path.join(ATTACH_DIR, String(userId), String(messageId));
fs.rmSync(dir, { recursive: true, force: true });
}
/** 将 storage_path 解析为绝对路径,并防止越权访问数据目录 */
export function resolveStoragePath(storagePath) {
const abs = path.resolve(DATA_DIR, storagePath || '');
const root = path.resolve(DATA_DIR);
if (abs !== root && !abs.startsWith(root + path.sep)) return null;
return abs;
}