const { ipcMain } = require('electron'); const { ImapFlow } = require('imapflow'); ipcMain.on('imap:listTree:from', listTreeFrom); ipcMain.on('imap:listTree:to', listTreeTo); ipcMain.on('imap:migrate', migrate); async function connect (options) { const client = new ImapFlow({ host: options.server, port: options.port, auth: { user: options.username, pass: options.password, }, }); await client.connect(); return client; } async function listTreeFrom (event, options) { const client = await connect(options); event.reply('imap:listTree:from:reply', await client.listTree()); await client.logout(); } async function listTreeTo (event, options) { const client = await connect(options); event.reply('imap:listTree:to:reply', await client.listTree()); await client.logout(); } async function migrate (event, { from, to }) { const fromClient = await connect(from); const toClient = await connect(to); const fromFolders = (await fromClient.list()).filter((folder) => folder.subscribed); for (const fromFolder of fromFolders) { try { await toClient.mailboxCreate(fromFolder.path); } catch (e) {} const fromMailbox = await fromClient.getMailboxLock(fromFolder.path); const toMailbox = await toClient.getMailboxLock(fromFolder.path); try { const toMsgsGenerator = await toClient.fetch('1:*', { flags: true, envelope: true, source: true }); const toMsgs = []; for await (const toMsg of toMsgsGenerator) { toMsgs.push(toMsg); } const fromMsgsGenerator = await fromClient.fetch('1:*', { flags: true, envelope: true, source: true }); for await (const fromMsg of fromMsgsGenerator) { if (toMsgs.some((toMsg) => Buffer.compare(toMsg.source, fromMsg.source) === 0)) { continue; } await toClient.append(fromFolder.path, fromMsg.source, Array.from(fromMsg.flags), fromMsg.envelope.date); } } finally { fromMailbox.release(); toMailbox.release(); } } await fromClient.logout(); await toClient.logout(); }