summaryrefslogtreecommitdiffstats
path: root/melib/src/backends/imap/watch.rs
blob: 48a2e80b5dc4fc07b12a53ff1dec2884de8ca513 (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
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
/*
 * meli - imap module.
 *
 * Copyright 2019 Manos Pitsidianakis
 *
 * This file is part of meli.
 *
 * meli is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * meli is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with meli. If not, see <http://www.gnu.org/licenses/>.
 */
use super::*;
use crate::backends::SpecialUsageMailbox;
use std::sync::Arc;

/// Arguments for IMAP watching functions
pub struct ImapWatchKit {
    pub conn: ImapConnection,
    pub main_conn: Arc<FutureMutex<ImapConnection>>,
    pub uid_store: Arc<UIDStore>,
}

pub async fn poll_with_examine(kit: ImapWatchKit) -> Result<()> {
    debug!("poll with examine");
    let ImapWatchKit {
        mut conn,
        main_conn: _,
        uid_store,
    } = kit;
    conn.connect().await?;
    let mailboxes: HashMap<MailboxHash, ImapMailbox> = {
        let mailboxes_lck = timeout(uid_store.timeout, uid_store.mailboxes.lock()).await?;
        mailboxes_lck.clone()
    };
    loop {
        for (_, mailbox) in mailboxes.clone() {
            examine_updates(mailbox, &mut conn, &uid_store).await?;
        }
        //FIXME: make sleep duration configurable
        smol::Timer::after(std::time::Duration::from_secs(3 * 60)).await;
    }
}

pub async fn idle(kit: ImapWatchKit) -> Result<()> {
    debug!("IDLE");
    /* IDLE only watches the connection's selected mailbox. We will IDLE on INBOX and every ~5
     * minutes wake up and poll the others */
    let ImapWatchKit {
        mut conn,
        main_conn,
        uid_store,
    } = kit;
    conn.connect().await?;
    let mailbox: ImapMailbox = match uid_store
        .mailboxes
        .lock()
        .await
        .values()
        .find(|f| f.parent.is_none() && (f.special_usage() == SpecialUsageMailbox::Inbox))
        .map(std::clone::Clone::clone)
    {
        Some(mailbox) => mailbox,
        None => {
            return Err(MeliError::new("INBOX mailbox not found in local mailbox index. meli may have not parsed the IMAP mailboxes correctly"));
        }
    };
    let mailbox_hash = mailbox.hash();
    let mut response = Vec::with_capacity(8 * 1024);
    let select_response = conn
        .examine_mailbox(mailbox_hash, &mut response, true)
        .await?
        .unwrap();
    {
        let mut uidvalidities = uid_store.uidvalidity.lock().unwrap();

        if let Some(v) = uidvalidities.get(&mailbox_hash) {
            if *v != select_response.uidvalidity {
                if uid_store.keep_offline_cache {
                    #[cfg(not(feature = "sqlite3"))]
                    let mut cache_handle = super::cache::DefaultCache::get(uid_store.clone())?;
                    #[cfg(feature = "sqlite3")]
                    let mut cache_handle = super::cache::Sqlite3Cache::get(uid_store.clone())?;
                    cache_handle.clear(mailbox_hash, &select_response)?;
                }
                conn.add_refresh_event(RefreshEvent {
                    account_hash: uid_store.account_hash,
                    mailbox_hash,
                    kind: RefreshEventKind::Rescan,
                });
                /*
                uid_store.uid_index.lock().unwrap().clear();
                uid_store.hash_index.lock().unwrap().clear();
                uid_store.byte_cache.lock().unwrap().clear();
                */
            }
        } else {
            uidvalidities.insert(mailbox_hash, select_response.uidvalidity);
        }
    }
    let mailboxes: HashMap<MailboxHash, ImapMailbox> = {
        let mailboxes_lck = timeout(uid_store.timeout, uid_store.mailboxes.lock()).await?;
        mailboxes_lck.clone()
    };
    for (h, mailbox) in mailboxes.clone() {
        if mailbox_hash == h {
            continue;
        }
        examine_updates(mailbox, &mut conn, &uid_store).await?;
    }
    conn.send_command(b"IDLE").await?;
    let mut blockn = ImapBlockingConnection::from(conn);
    let mut watch = std::time::Instant::now();
    /* duration interval to send heartbeat */
    const _10_MINS: std::time::Duration = std::time::Duration::from_secs(10 * 60);
    /* duration interval to check other mailboxes for changes */
    const _5_MINS: std::time::Duration = std::time::Duration::from_secs(5 * 60);
    loop {
        let line = match timeout(Some(_10_MINS), blockn.as_stream()).await {
            Ok(Some(line)) => line,
            Ok(None) => {
                debug!("IDLE connection dropped: {:?}", &blockn.err());
                blockn.conn.connect().await?;
                let mut main_conn_lck = timeout(uid_store.timeout, main_conn.lock()).await?;
                main_conn_lck.connect().await?;
                continue;
            }
            Err(_) => {
                /* Timeout */
                blockn.conn.send_raw(b"DONE").await?;
                blockn
                    .conn
                    .read_response(&mut response, RequiredResponses::empty())
                    .await?;
                blockn.conn.send_command(b"IDLE").await?;
                let mut main_conn_lck = timeout(uid_store.timeout, main_conn.lock()).await?;
                main_conn_lck.connect().await?;
                continue;
            }
        };
        let now = std::time::Instant::now();
        if now.duration_since(watch) >= _5_MINS {
            /* Time to poll all inboxes */
            let mut conn = timeout(uid_store.timeout, main_conn.lock()).await?;
            for (h, mailbox) in mailboxes.clone() {
                if mailbox_hash == h {
                    continue;
                }
                examine_updates(mailbox, &mut conn, &uid_store).await?;
            }
            watch = now;
        }
        if line
            .split_rn()
            .filter(|l| {
                !l.starts_with(b"+ ")
                    && !l.starts_with(b"* ok")
                    && !l.starts_with(b"* ok")
                    && !l.starts_with(b"* Ok")
                    && !l.starts_with(b"* OK")
            })
            .count()
            == 0
        {
            continue;
        }
        {
            blockn.conn.send_raw(b"DONE").await?;
            blockn
                .conn
                .read_response(&mut response, RequiredResponses::empty())
                .await?;
            for l in line.split_rn() {
                debug!("process_untagged {:?}", &l);
                if l.starts_with(b"+ ")
                    || l.starts_with(b"* ok")
                    || l.starts_with(b"* ok")
                    || l.starts_with(b"* Ok")
                    || l.starts_with(b"* OK")
                {
                    debug!("ignore continuation mark");
                    continue;
                }
                blockn.conn.process_untagged(l).await?;
            }
            blockn.conn.send_command(b"IDLE").await?;
        }
    }
}

pub async fn examine_updates(
    mailbox: ImapMailbox,
    conn: &mut ImapConnection,
    uid_store: &Arc<UIDStore>,
) -> Result<()> {
    if mailbox.no_select {
        return Ok(());
    }
    let mailbox_hash = mailbox.hash();
    debug!("examining mailbox {} {}"