// 草稿:仅保存在本地(folder = drafts),可随时编辑后发送
import { Router } from 'express';
import { db } from '../db.js';
import { requireAuth } from '../auth.js';
import { saveAttachmentBuffer, removeAttachmentDir } from '../mail/attachments.js';
const router = Router();
router.use(requireAuth);
function textToHtml(text) {
return String(text || '')
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/\n/g, '<br>');
}
function loadDraft(userId, id) {
const row = db
.prepare(`SELECT * FROM messages WHERE id = ? AND user_id = ? AND folder = 'drafts'`)
.get(id, userId);
if (!row) return null;
row.attachments = db
.prepare('SELECT id, filename, mime, size FROM attachments WHERE message_id = ?')
.all(row.id);
return row;
}
function draftView(row) {
return {
id: row.id,
accountId: row.account_id,
subject: row.subject,
to: row.to_addrs,
cc: row.cc_addrs,
bcc: row.bcc_addrs,
bodyText: row.body_text,
date: row.date,
attachments: row.attachments || [],
};
}
router.post('/', (req, res) => {
const accountId = Number(req.body?.accountId) || 0;
const account = db
.prepare('SELECT id, name, email FROM accounts WHERE id = ? AND user_id = ?')
.get(accountId, req.user.id);
if (!account) return res.status(400).json({ error: '请选择发件账号' });
const to = String(req.body?.to || '');
const cc = String(req.body?.cc || '');
const bcc = String(req.body?.bcc || '');
const subject = String(req.body?.subject || '');
const bodyText = String(req.body?.bodyText ?? req.body?.body ?? '');
const snippet = bodyText.replace(/\s+/g, ' ').trim().slice(0, 200);
const newAttachments = Array.isArray(req.body?.attachments) ? req.body.attachments : [];
const hasKeep = Array.isArray(req.body?.keepAttachmentIds);
const keepIds = hasKeep ? req.body.keepAttachmentIds.map(Number) : null;
const draftId = Number(req.body?.id) || 0;
const existing = draftId ? loadDraft(req.user.id, draftId) : null;
if (draftId && !existing) return res.status(404).json({ error: '草稿不存在' });
let messageId;
if (existing) {
db.prepare(
`UPDATE messages SET account_id = ?, subject = ?, to_addrs = ?, cc_addrs = ?, bcc_addrs = ?,
body_text = ?, body_html = ?, snippet = ?, date = ?
WHERE id = ?`
).run(
accountId,
subject,
to,
cc,
bcc,
bodyText,
textToHtml(bodyText),
snippet,
Date.now(),
existing.id
);
messageId = existing.id;
const keep = keepIds || existing.attachments.map((a) => a.id);
for (const att of existing.attachments) {
if (!keep.includes(att.id)) {
db.prepare('DELETE FROM attachments WHERE id = ?').run(att.id);
}
}
} else {
const info = db
.prepare(
`INSERT INTO messages
(user_id, account_id, folder, prev_folder, uid, message_id, subject, from_name, from_addr,
to_addrs, cc_addrs, bcc_addrs, date, snippet, body_text, body_html, seen, size, has_attachments, created_at)
VALUES (?, ?, 'drafts', NULL, NULL, '', ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1, 0, 0, ?)`
)
.run(
req.user.id,
accountId,
subject,
account.name || '',
account.email,
to,
cc,
bcc,
Date.now(),
snippet,
bodyText,
textToHtml(bodyText),
Date.now()
);
messageId = Number(info.lastInsertRowid);
}
for (const att of newAttachments) {
const buffer = Buffer.from(String(att?.data || ''), 'base64');
if (!buffer.length) continue;
saveAttachmentBuffer(req.user.id, messageId, att.filename || 'attachment', att.mime, buffer);
}
const count = db
.prepare('SELECT COUNT(*) AS n FROM attachments WHERE message_id = ?')
.get(messageId).n;
db.prepare('UPDATE messages SET has_attachments = ? WHERE id = ?').run(count ? 1 : 0, messageId);
res.json(draftView(loadDraft(req.user.id, messageId)));
});
router.delete('/:id', (req, res) => {
const draft = db
.prepare(`SELECT id FROM messages WHERE id = ? AND user_id = ? AND folder = 'drafts'`)
.get(Number(req.params.id), req.user.id);
if (!draft) return res.status(404).json({ error: '草稿不存在' });
removeAttachmentDir(req.user.id, draft.id);
db.prepare('DELETE FROM messages WHERE id = ?').run(draft.id);
res.json({ ok: true });
});
export default router;