sync.js

9.8 KB v1.0
// IMAP 增量同步:只同步收件箱与已发送,草稿/垃圾箱在本地维护
import { ImapFlow } from 'imapflow';
import { simpleParser } from 'mailparser';
import { db } from '../db.js';
import { decrypt } from '../crypto.js';
import { getRawSettings } from '../settings.js';
import { removeAttachmentDir, saveParsedAttachments } from './attachments.js';
import { queueMailNotification } from '../notifications/telegram.js';

/** 根据邮箱属性/名称判断分类 */
export function detectFolder(mailbox) {
  const special = String(mailbox.specialUse || '').toLowerCase();
  const name = `${mailbox.name || ''} ${mailbox.path || ''}`.toLowerCase();
  if (mailbox.path === 'INBOX' || special.includes('inbox')) return 'inbox';
  if (special.includes('sent') || /(^|\s)(sent|sent items|已发送|发件箱)/.test(name)) return 'sent';
  return null;
}

function normalizeText(input, max = 200) {
  return String(input || '')
    .replace(/<style[\s\S]*?<\/style>/gi, ' ')
    .replace(/<script[\s\S]*?<\/script>/gi, ' ')
    .replace(/<[^>]+>/g, ' ')
    .replace(/&nbsp;/gi, ' ')
    .replace(/&amp;/gi, '&')
    .replace(/&lt;/gi, '<')
    .replace(/&gt;/gi, '>')
    .replace(/\s+/g, ' ')
    .trim()
    .slice(0, max);
}

function addressText(obj) {
  if (!obj) return '';
  const list = Array.isArray(obj) ? obj : obj.value;
  if (!Array.isArray(list)) return '';
  return list
    .map((a) => (a?.address ? (a.name ? `${a.name} <${a.address}>` : a.address) : ''))
    .filter(Boolean)
    .join(', ');
}

function firstAddress(obj) {
  const list = obj?.value;
  if (Array.isArray(list) && list[0]) {
    return { name: list[0].name || '', addr: list[0].address || '' };
  }
  return { name: '', addr: '' };
}

const insertMessage = db.prepare(`
  INSERT OR IGNORE 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
    (@user_id, @account_id, @folder, NULL, @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)
`);

/** 将一封 IMAP 邮件解析并写入本地库,返回是否新增 */
async function storeMessage(account, folder, msg) {
  const parsed = await simpleParser(msg.source);
  const from = firstAddress(parsed.from);
  const date = parsed.date ? parsed.date.getTime() : Date.now();
  const text = parsed.text || '';
  const html = typeof parsed.html === 'string' ? parsed.html : '';
  const attachments = parsed.attachments || [];
  const snippet = normalizeText(text || html);

  // 本地「已发送」副本与 IMAP 已发送文件夹可能出现同一封邮件,按 Message-ID 去重
  if (parsed.messageId) {
    const exists = db
      .prepare('SELECT id FROM messages WHERE account_id = ? AND message_id = ? LIMIT 1')
      .get(account.id, parsed.messageId);
    if (exists) return false;
  }

  const result = insertMessage.run({
    user_id: account.user_id,
    account_id: account.id,
    folder,
    uid: msg.uid,
    message_id: parsed.messageId || '',
    subject: parsed.subject || '(无主题)',
    from_name: from.name,
    from_addr: from.addr,
    to_addrs: addressText(parsed.to),
    cc_addrs: addressText(parsed.cc),
    bcc_addrs: addressText(parsed.bcc),
    date,
    snippet,
    body_text: text,
    body_html: html,
    seen: msg.flags?.has?.('\\Seen') ? 1 : 0,
    size: msg.source?.length || 0,
    has_attachments: attachments.length > 0 ? 1 : 0,
    created_at: Date.now(),
  });

  if (!result.changes) return false;
  const messageId = result.lastInsertRowid;
  if (attachments.length) {
    saveParsedAttachments(account.user_id, messageId, attachments);
  }

  // 仅对最近 3 天的新收件箱邮件推送 Telegram,避免首次同步推送历史邮件
  if (folder === 'inbox' && Date.now() - date < 3 * 24 * 60 * 60 * 1000) {
    queueMailNotification(account.user_id, {
      accountName: account.name,
      accountEmail: account.email,
      subject: parsed.subject || '(无主题)',
      fromName: from.name,
      fromAddr: from.addr,
      date,
      snippet,
    });
  }
  return true;
}

/** 清空某个账号某个分类下的同步邮件(UIDVALIDITY 变化时使用) */
function clearFolder(account, folder) {
  const rows = db
    .prepare('SELECT id FROM messages WHERE account_id = ? AND folder = ?')
    .all(account.id, folder);
  for (const row of rows) removeAttachmentDir(account.user_id, row.id);
  db.prepare('DELETE FROM messages WHERE account_id = ? AND folder = ?').run(account.id, folder);
}

async function syncFolder(client, account, category, mailboxPath, syncSettings) {
  const lock = await client.getMailboxLock(mailboxPath);
  try {
    const uidValidity = String(client.mailbox?.uidValidity || '');
    const state = db
      .prepare('SELECT uidvalidity, last_uid FROM sync_state WHERE account_id = ? AND folder = ?')
      .get(account.id, category);

    if (state && uidValidity && state.uidvalidity && state.uidvalidity !== uidValidity) {
      // 服务器端 UID 空间重置,需要重新同步该文件夹
      clearFolder(account, category);
      db.prepare('DELETE FROM sync_state WHERE account_id = ? AND folder = ?').run(account.id, category);
    }

    const rangeDays = Math.max(1, Number(syncSettings.rangeDays) || 30);
    const limit = Math.max(20, Number(syncSettings.folderLimit) || 300);
    const since = new Date(Date.now() - rangeDays * 24 * 60 * 60 * 1000);
    const uids = await client.search({ since }, { uid: true });
    const lastUid = Number(state?.last_uid) || 0;
    let targets = uids.filter((uid) => uid > lastUid);
    if (!state) {
      // 首次同步只拉取最近 limit 封
      targets = targets.slice(-limit);
    } else {
      targets = targets.slice(-limit * 2);
    }
    if (!targets.length) return 0;

    let count = 0;
    for await (const msg of client.fetch(targets, { uid: true, source: true, flags: true }, { uid: true })) {
      try {
        if (await storeMessage(account, category, msg)) count += 1;
      } catch (err) {
        console.error(`[xmail] 解析邮件失败 (${category} uid=${msg.uid}):`, err.message);
      }
    }

    const maxUid = Math.max(lastUid, ...targets);
    db.prepare(
      `INSERT INTO sync_state (account_id, folder, uidvalidity, last_uid) VALUES (?, ?, ?, ?)
       ON CONFLICT(account_id, folder) DO UPDATE SET uidvalidity = excluded.uidvalidity, last_uid = excluded.last_uid`
    ).run(account.id, category, uidValidity, maxUid);
    return count;
  } finally {
    lock.release();
  }
}

/**
 * 同步单个邮箱账号
 * @returns {Promise<{count:number}>}
 */
export async function syncAccount(accountId, userId) {
  const account = db
    .prepare('SELECT * FROM accounts WHERE id = ? AND user_id = ?')
    .get(accountId, userId);
  if (!account) throw new Error('邮箱账号不存在');

  const password = decrypt(account.password_enc);
  if (!password) throw new Error('邮箱密码解密失败,请编辑账号重新填写密码');

  const settings = getRawSettings(userId);
  const client = new ImapFlow({
    host: account.imap_host,
    port: account.imap_port,
    secure: Boolean(account.imap_secure),
    auth: { user: account.username, pass: password },
    logger: false,
    socketTimeout: 120000,
    greetingTimeout: 20000,
  });

  try {
    await client.connect();
    const mailboxes = await client.list();
    const chosen = {};
    for (const mb of mailboxes) {
      const cat = detectFolder(mb);
      if (cat && !chosen[cat]) chosen[cat] = mb;
    }
    if (!chosen.inbox) throw new Error('未找到收件箱文件夹');

    let count = 0;
    for (const [category, mb] of Object.entries(chosen)) {
      count += await syncFolder(client, account, category, mb.path, settings.sync);
    }
    db.prepare('UPDATE accounts SET last_sync_at = ?, sync_error = NULL WHERE id = ?').run(
      Date.now(),
      account.id
    );
    return { count };
  } catch (err) {
    db.prepare('UPDATE accounts SET sync_error = ? WHERE id = ?').run(
      String(err.message || err).slice(0, 500),
      account.id
    );
    throw err;
  } finally {
    try {
      await client.logout();
    } catch {
      /* 连接可能已经断开,忽略 */
    }
  }
}

/** 同步一个用户的所有邮箱账号(顺序执行,避免连接数过多) */
export async function syncAllAccounts(userId) {
  const accounts = db.prepare('SELECT id, name FROM accounts WHERE user_id = ?').all(userId);
  const results = [];
  for (const account of accounts) {
    try {
      const r = await syncAccount(account.id, userId);
      results.push({ id: account.id, name: account.name, ok: true, count: r.count });
    } catch (err) {
      results.push({ id: account.id, name: account.name, ok: false, error: String(err.message || err) });
    }
  }
  return results;
}

/** 正在同步的账号集合,避免重复触发 */
const syncing = new Set();

export function isSyncing(accountId) {
  return syncing.has(accountId);
}

/** 带并发保护的同步 */
export async function syncAccountSafe(accountId, userId) {
  if (syncing.has(accountId)) throw new Error('该账号正在同步中');
  syncing.add(accountId);
  try {
    return await syncAccount(accountId, userId);
  } finally {
    syncing.delete(accountId);
  }
}

/** 测试 IMAP 连接 */
export async function testImap(account) {
  const password = decrypt(account.password_enc);
  const client = new ImapFlow({
    host: account.imap_host,
    port: account.imap_port,
    secure: Boolean(account.imap_secure),
    auth: { user: account.username, pass: password },
    logger: false,
    socketTimeout: 20000,
    greetingTimeout: 15000,
  });
  try {
    await client.connect();
    return true;
  } finally {
    try {
      await client.logout();
    } catch {
      /* ignore */
    }
  }
}