aboutsummaryrefslogtreecommitdiffstats
path: root/src/wamail/sync.js
blob: ce244e10bc3a424f7a027263ba2376ea48b989bf (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
// wamail sync: WhatsApp (the wa-cli daemon) <-> Maildir, one folder per chat.
//
// local -> WhatsApp (diff against the saved state):
//   read every unread message of a chat -> chats.read    mark one as unread -> chats.unread
//   F (flag) -> messages.star / unstar                   delete -> local only (not downloaded again)
// WhatsApp -> local:
//   new messages (backfill of the last N days the first time), media up to mediaMaxBytes,
//   read/unread when the remote counter changes, names/archived state for the sidebar.

import fs from 'node:fs';
import path from 'node:path';
import { messageToEml } from '../format/mail.js';
import { writeMailboxes } from './neomutt.js';
import {
    chatDirName, expandHome, loadState, saveState, scanDir, setFlags, stanzaFileId, writeMessage,
} from './store.js';

export const DEFAULTS = {
    backfillDays: 30,         // first time: messages from the last N days...
    backfillLimit: 100,       // ...and at most N per chat
    fetchLimit: 50,
    mediaMaxBytes: 16 * 1024 * 1024,
    skipChats: [],            // JIDs to ignore
};

const SKIP_TYPES = new Set([
    'e2e_notification', 'notification_template', 'notification', 'gp2', 'protocol', 'ciphertext',
    'broadcast_notification', 'debug', 'unknown', 'reaction', 'revoked',
]);
const SUPPORTED_CHAT = /@(c\.us|g\.us|lid)$/;

export function wamailConfig(account, cfg = {}) {
    return {
        maildir: account === 'default' ? '~/Mail/whatsapp' : `~/Mail/whatsapp-${account}`,
        ...DEFAULTS,
        ...cfg,
    };
}

const flagString = (flags) => [...flags].filter((f) => f === 'S' || f === 'F').sort().join('');

// Message deleted for everyone: remove the local copy and do not download it again.
export function dropLocal({ account, config, stanzaId }) {
    const state = loadState(account);
    const fid = stanzaFileId(stanzaId);
    const sm = state.msgs[fid];
    if (!sm) return false;
    const dir = state.chats[sm.chat]?.dir;
    const entry = dir && scanDir(path.join(expandHome(config.maildir), dir))[fid];
    if (entry) fs.rmSync(entry.path, { force: true });
    state.tombstones[fid] = sm;
    delete state.msgs[fid];
    saveState(account, state);
    return true;
}

export async function syncAccount({ account, rpc, config, onlyChat, log = () => {}, now = Date.now }) {
    const root = expandHome(config.maildir);
    const state = loadState(account);
    const nowSec = Math.floor(now() / 1000);
    const skipped = (id) => !SUPPORTED_CHAT.test(id) || config.skipChats.includes(id);
    const stats = { nuevos: 0, leidos: 0, noLeidos: 0, estrellas: 0, borrados: 0 };

    // ---- chats remotos
    const remote = (onlyChat ? [await rpc('chats.get', { chatId: onlyChat })] : await rpc('chats.list', {}))
        .filter((c) => !skipped(c.id));
    const scope = new Set(onlyChat ? remote.map((c) => c.id) : [...remote.map((c) => c.id), ...Object.keys(state.chats)]);
    try {
        const me = (await rpc('auth.status', {})).me;
        if (me?.id) state.me = me;
    } catch { /* not critical */ }

    // ---- escaneo local
    const local = {};
    const scanChat = (chatId) => {
        const st = state.chats[chatId];
        if (!st?.dir) return {};
        const dir = path.join(root, st.dir);
        const found = scanDir(dir);
        for (const [fid, e] of Object.entries(found)) local[fid] = { ...e, chat: chatId, dir };
        return found;
    };
    for (const id of scope) scanChat(id);
    for (const fid of Object.keys(local)) {
        if (state.tombstones[fid]) {
            // deleted by mistake (e.g. a race with neomutt): the file is still there
            state.msgs[fid] = state.tombstones[fid];
            delete state.tombstones[fid];
        }
    }

    // ---- push: cambios locales -> WhatsApp
    const failed = new Set();
    const touched = new Map();   // chatId -> 'read' | 'unread'
    const perChat = new Map();
    for (const [fid, sm] of Object.entries(state.msgs)) {
        if (!scope.has(sm.chat)) continue;
        let loc = local[fid];
        if (!loc) {
            loc = scanChat(sm.chat)[fid] && local[fid];   // second attempt before treating it as deleted
        }
        if (!loc || loc.flags.has('T')) {
            if (loc) fs.rmSync(loc.path, { force: true });
            state.tombstones[fid] = sm;
            delete state.msgs[fid];
            delete local[fid];
            stats.borrados++;
            continue;
        }
        const agg = perChat.get(sm.chat) ?? { had: 0, now: 0, becameUnread: false };
        perChat.set(sm.chat, agg);
        const wasSeen = sm.fl.includes('S');
        const isSeen = loc.flags.has('S');
        if (!sm.fromMe) {
            if (!wasSeen) agg.had++;
            if (!isSeen) agg.now++;
            if (wasSeen && !isSeen) agg.becameUnread = true;
        }
        if (sm.fl.includes('F') !== loc.flags.has('F')) {
            try {
                await rpc(loc.flags.has('F') ? 'messages.star' : 'messages.unstar', { messageId: sm.id });
                stats.estrellas++;
            } catch (e) {
                log(`could not change the star of ${fid}: ${e.message}`);
                failed.add(fid);
            }
        }
    }
    for (const [chatId, agg] of perChat) {
        const name = state.chats[chatId]?.name ?? chatId;
        try {
            if (agg.becameUnread) {
                await rpc('chats.unread', { chatId });
                touched.set(chatId, 'unread');
                stats.noLeidos++;
                log(`${name}: marked as unread`);
            } else if (agg.had > 0 && agg.now === 0) {
                await rpc('chats.read', { chatId });
                touched.set(chatId, 'read');
                stats.leidos++;
                log(`${name}: marked as read`);
            }
        } catch (e) {
            log(`${name}: could not sync read state: ${e.message}`);
            for (const [fid, sm] of Object.entries(state.msgs)) if (sm.chat === chatId) failed.add(fid);
        }
    }

    // ---- pull: WhatsApp -> local
    const takenDirs = () => new Set(Object.values(state.chats).map((c) => c.dir).filter(Boolean));
    for (const c of remote) {
        const isNew = !state.chats[c.id];
        const st = (state.chats[c.id] ||= { dir: null, lastTs: 0, unread: null });
        Object.assign(st, { name: c.name, isGroup: c.isGroup, archived: c.archived, pinned: c.pinned, timestamp: c.timestamp });

        let msgs = [];
        try {
            if (isNew || !st.lastTs) {
                const cutoff = nowSec - config.backfillDays * 86400;
                if ((c.timestamp ?? 0) >= cutoff) {
                    msgs = (await rpc('messages.list', { chatId: c.id, limit: config.backfillLimit }))
                        .filter((m) => m.timestamp >= cutoff);
                }
            } else if ((c.timestamp ?? 0) > st.lastTs || onlyChat) {
                msgs = await rpc('messages.list', { chatId: c.id, since: st.lastTs, limit: config.fetchLimit });
            }
        } catch (e) {
            log(`${c.name}: could not fetch messages: ${e.message}`);