snapshot.js

11.7 KB v1.0
// 完整数据快照的生成、序列化、本地安全备份与恢复
import fs from 'node:fs';
import path from 'node:path';
import zlib from 'node:zlib';
import { db } from '../db.js';
import { LOCAL_BACKUP_DIR } from '../config.js';
import { getRawSettings, saveSettings, DEFAULT_SETTINGS, deepMerge } from '../settings.js';
import {
  resolveStoragePath,
  saveAttachmentBuffer,
  removeAttachmentDir,
} from '../mail/attachments.js';

export const SNAPSHOT_FORMAT = 'xmail-backup';
export const SNAPSHOT_VERSION = 1;
const KEEP_LOCAL_BACKUPS = 8;

/**
 * 生成当前用户的完整快照
 * @param {number} userId
 * @param {object} opts { includeBodies, includeAttachments, accountIds, days }
 */
export function buildSnapshot(userId, opts = {}) {
  const user = db.prepare('SELECT username FROM users WHERE id = ?').get(userId);
  const settings = getRawSettings(userId);
  const allAccounts = db.prepare('SELECT * FROM accounts WHERE user_id = ? ORDER BY id').all(userId);

  const filterIds =
    Array.isArray(opts.accountIds) && opts.accountIds.length
      ? opts.accountIds.map(Number)
      : allAccounts.map((a) => a.id);
  const accounts = allAccounts.filter((a) => filterIds.includes(a.id));

  const includeBodies = Boolean(opts.includeBodies);
  const includeAttachments = Boolean(opts.includeAttachments);
  const days = Number(opts.days) > 0 ? Number(opts.days) : 0;
  const cutoff = days ? Date.now() - days * 24 * 60 * 60 * 1000 : 0;

  const messages = [];
  if (includeBodies || includeAttachments) {
    const rows = db
      .prepare(
        `SELECT * FROM messages WHERE user_id = ? AND date >= ? ORDER BY id ASC`
      )
      .all(userId, cutoff)
      .filter((row) => filterIds.includes(row.account_id));

    for (const row of rows) {
      const attachmentRows = db
        .prepare('SELECT * FROM attachments WHERE message_id = ? ORDER BY id')
        .all(row.id);
      const attachments = attachmentRows.map((att) => {
        const item = { filename: att.filename, mime: att.mime, size: att.size };
        if (includeAttachments) {
          const abs = resolveStoragePath(att.storage_path);
          if (abs && fs.existsSync(abs)) {
            item.data = fs.readFileSync(abs).toString('base64');
          }
        }
        return item;
      });

      messages.push({
        accountId: row.account_id,
        folder: row.folder,
        prevFolder: row.prev_folder,
        uid: row.uid,
        messageId: row.message_id,
        subject: row.subject,
        fromName: row.from_name,
        fromAddr: row.from_addr,
        to: row.to_addrs,
        cc: row.cc_addrs,
        bcc: row.bcc_addrs,
        date: row.date,
        snippet: includeBodies ? row.snippet : '',
        bodyText: includeBodies ? row.body_text : '',
        bodyHtml: includeBodies ? row.body_html : '',
        seen: row.seen,
        size: row.size,
        createdAt: row.created_at,
        attachments: includeAttachments ? attachments : [],
      });
    }
  }

  return {
    format: SNAPSHOT_FORMAT,
    version: SNAPSHOT_VERSION,
    app: 'xmail',
    createdAt: Date.now(),
    user: { username: user?.username || '' },
    options: { includeBodies, includeAttachments, days },
    settings,
    accounts: accounts.map((a) => ({
      oldId: a.id,
      name: a.name,
      email: a.email,
      imapHost: a.imap_host,
      imapPort: a.imap_port,
      imapSecure: a.imap_secure,
      smtpHost: a.smtp_host,
      smtpPort: a.smtp_port,
      smtpSecure: a.smtp_secure,
      username: a.username,
      passwordEnc: a.password_enc,
      color: a.color,
      createdAt: a.created_at,
    })),
    messages,
  };
}

/** JSON 快照压缩为 .json.gz 缓冲 */
export function packSnapshot(snapshot) {
  return zlib.gzipSync(Buffer.from(JSON.stringify(snapshot), 'utf8'), { level: 6 });
}

/** 解压并解析备份文件(兼容未压缩 JSON) */
export function unpackSnapshot(buffer) {
  let jsonBuffer = buffer;
  if (buffer.length > 2 && buffer[0] === 0x1f && buffer[1] === 0x8b) {
    jsonBuffer = zlib.gunzipSync(buffer);
  }
  const data = JSON.parse(jsonBuffer.toString('utf8'));
  if (data?.format !== SNAPSHOT_FORMAT) throw new Error('不是有效的 xmail 备份文件');
  return data;
}

/**
 * 恢复前生成本地安全备份,返回文件名
 */
export function createLocalSafetyBackup(userId) {
  const snapshot = buildSnapshot(userId, {
    includeBodies: true,
    includeAttachments: true,
  });
  const name = `user-${userId}-${new Date().toISOString().replace(/[:.]/g, '-')}.json.gz`;
  const file = path.join(LOCAL_BACKUP_DIR, name);
  fs.writeFileSync(file, packSnapshot(snapshot));

  // 仅保留最近若干份
  const files = fs
    .readdirSync(LOCAL_BACKUP_DIR)
    .filter((f) => f.startsWith(`user-${userId}-`) && f.endsWith('.json.gz'))
    .sort();
  while (files.length > KEEP_LOCAL_BACKUPS) {
    const oldest = files.shift();
    try {
      fs.unlinkSync(path.join(LOCAL_BACKUP_DIR, oldest));
    } catch {
      /* ignore */
    }
  }
  return name;
}

/**
 * 恢复快照
 * @param {number} userId
 * @param {object} snapshot
 * @param {'config'|'full'} mode
 */
export function restoreSnapshot(userId, snapshot, mode = 'config') {
  if (!snapshot || snapshot.format !== SNAPSHOT_FORMAT) {
    throw new Error('不是有效的 xmail 备份文件');
  }
  if (Number(snapshot.version) > SNAPSHOT_VERSION) {
    throw new Error('备份版本高于当前程序版本,请先升级 xmail');
  }

  const existingAccounts = db.prepare('SELECT * FROM accounts WHERE user_id = ?').all(userId);
  const existingByEmail = new Map(
    existingAccounts.map((account) => [String(account.email || '').toLowerCase(), account])
  );
  const backupAccounts = Array.isArray(snapshot.accounts) ? snapshot.accounts : [];
  const backupEmails = new Set(
    backupAccounts.map((account) => String(account.email || '').toLowerCase()).filter(Boolean)
  );
  // 仅配置恢复时,备份中不存在的账号(及其邮件)会被移除
  const removedAccounts = existingAccounts.filter(
    (account) => !backupEmails.has(String(account.email || '').toLowerCase())
  );

  const accountMap = new Map();
  let messageCount = 0;
  let attachmentCount = 0;

  const tx = db.transaction(() => {
    if (mode === 'full') {
      // 配置 + 邮件:清空当前全部账号与邮件后按快照重建
      const oldMessages = db.prepare('SELECT id FROM messages WHERE user_id = ?').all(userId);
      for (const row of oldMessages) removeAttachmentDir(userId, row.id);
      db.prepare('DELETE FROM messages WHERE user_id = ?').run(userId);
      for (const acc of existingAccounts) {
        db.prepare('DELETE FROM sync_state WHERE account_id = ?').run(acc.id);
      }
      db.prepare('DELETE FROM accounts WHERE user_id = ?').run(userId);
    } else {
      // 仅恢复配置:删除快照中已不存在的账号,保留其余账号及其本地邮件
      for (const account of removedAccounts) {
        const messages = db
          .prepare('SELECT id FROM messages WHERE account_id = ? AND user_id = ?')
          .all(account.id, userId);
        for (const msg of messages) removeAttachmentDir(userId, msg.id);
        db.prepare('DELETE FROM messages WHERE account_id = ? AND user_id = ?').run(account.id, userId);
        db.prepare('DELETE FROM sync_state WHERE account_id = ?').run(account.id);
        db.prepare('DELETE FROM accounts WHERE id = ? AND user_id = ?').run(account.id, userId);
      }
    }

    // 恢复邮箱账号:仅配置模式下按邮箱地址复用已有账号,避免丢失本地邮件
    for (const acc of backupAccounts) {
      const email = String(acc.email || '').toLowerCase();
      const existing = mode === 'config' ? existingByEmail.get(email) : null;

      if (existing) {
        db.prepare(
          `UPDATE accounts
             SET name = ?, email = ?, imap_host = ?, imap_port = ?, imap_secure = ?,
                 smtp_host = ?, smtp_port = ?, smtp_secure = ?, username = ?, password_enc = ?, color = ?
           WHERE id = ? AND user_id = ?`
        ).run(
          acc.name || acc.email || existing.name,
          acc.email || existing.email,
          acc.imapHost || '',
          Number(acc.imapPort) || 993,
          acc.imapSecure ? 1 : 0,
          acc.smtpHost || '',
          Number(acc.smtpPort) || 465,
          acc.smtpSecure ? 1 : 0,
          acc.username || '',
          acc.passwordEnc || '',
          acc.color || 'blue',
          existing.id,
          userId
        );
        accountMap.set(Number(acc.oldId), existing.id);
        continue;
      }

      const info = db
        .prepare(
          `INSERT INTO accounts
            (user_id, name, email, imap_host, imap_port, imap_secure, smtp_host, smtp_port, smtp_secure,
             username, password_enc, color, created_at)
           VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`
        )
        .run(
          userId,
          acc.name || acc.email,
          acc.email || '',
          acc.imapHost || '',
          Number(acc.imapPort) || 993,
          acc.imapSecure ? 1 : 0,
          acc.smtpHost || '',
          Number(acc.smtpPort) || 465,
          acc.smtpSecure ? 1 : 0,
          acc.username || '',
          acc.passwordEnc || '',
          acc.color || 'blue',
          Number(acc.createdAt) || Date.now()
        );
      accountMap.set(Number(acc.oldId), Number(info.lastInsertRowid));
    }

    // 恢复设置(修正账号引用)
    const settings = deepMerge(DEFAULT_SETTINGS, snapshot.settings || {});
    if (settings.backup && Array.isArray(settings.backup.accountIds)) {
      settings.backup.accountIds = settings.backup.accountIds
        .map((id) => accountMap.get(Number(id)))
        .filter(Boolean);
    }
    if (settings.editor?.defaultAccountId) {
      const mapped = accountMap.get(Number(settings.editor.defaultAccountId));
      settings.editor.defaultAccountId = mapped || null;
    }
    saveSettings(userId, settings);

    // 恢复邮件(仅「配置+邮件」模式)
    if (mode === 'full' && Array.isArray(snapshot.messages)) {
      const insert = 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 (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`
      );
      for (const msg of snapshot.messages) {
        const accountId = accountMap.get(Number(msg.accountId));
        if (!accountId) continue;
        const folder = ['inbox', 'sent', 'drafts', 'trash'].includes(msg.folder) ? msg.folder : 'inbox';
        const attachments = Array.isArray(msg.attachments) ? msg.attachments : [];
        const result = insert.run(
          userId,
          accountId,
          folder,
          msg.prevFolder || null,
          msg.uid ?? null,
          msg.messageId || '',
          msg.subject || '',
          msg.fromName || '',
          msg.fromAddr || '',
          msg.to || '',
          msg.cc || '',
          msg.bcc || '',
          Number(msg.date) || Date.now(),
          msg.snippet || '',
          msg.bodyText || '',
          msg.bodyHtml || '',
          msg.seen ? 1 : 0,
          Number(msg.size) || 0,
          attachments.length ? 1 : 0,
          Number(msg.createdAt) || Date.now()
        );
        const newId = Number(result.lastInsertRowid);
        messageCount += 1;
        for (const att of attachments) {
          if (!att?.data) continue;
          const buffer = Buffer.from(att.data, 'base64');
          if (!buffer.length) continue;
          saveAttachmentBuffer(userId, newId, att.filename || 'attachment', att.mime, buffer);
          attachmentCount += 1;
        }
      }
    }
  });

  tx();
  return {
    accounts: accountMap.size,
    messages: messageCount,
    attachments: attachmentCount,
  };
}