generalize the idea of tokens a bit more, don't restrict it to the rfc822
[apps/madmutt.git] / buffy.c
1 /*
2  * Copyright notice from original mutt:
3  * Copyright (C) 1996-2000 Michael R. Elkins <me@mutt.org>
4  *
5  * Parts were written/modified by:
6  * Rocco Rutte <pdmef@cs.tu-berlin.de>
7  *
8  * This file is part of mutt-ng, see http://www.muttng.org/.
9  * It's licensed under the GNU General Public License,
10  * please see the file GPL in the top level source directory.
11  */
12
13 #if HAVE_CONFIG_H
14 # include "config.h"
15 #endif
16
17 #include <lib-lib/mem.h>
18 #include <lib-lib/buffer.h>
19 #include <lib-lib/macros.h>
20
21 #include <imap/imap.h>
22
23 #include "mutt.h"
24 #include "buffy.h"
25 #include "mx.h"
26 #include "mh.h"
27 #include "sidebar.h"
28
29 #include "mutt_curses.h"
30
31 #include <string.h>
32 #include <sys/stat.h>
33 #include <dirent.h>
34 #include <utime.h>
35 #include <ctype.h>
36 #include <unistd.h>
37
38 #include <stdio.h>
39
40 static time_t BuffyTime = 0;    /* last time we started checking for mail */
41
42 static time_t ImapBuffyTime = 0;        /* last time we started checking for mail */
43 static short BuffyCount = 0;    /* how many boxes with new mail */
44 static short BuffyNotify = 0;   /* # of unnotified new boxes */
45
46 #ifdef BUFFY_SIZE
47
48 /* Find the last message in the file. 
49  * upon success return 0. If no message found - return -1 */
50
51 static int fseeko_last_message (FILE * f)
52 {
53   LOFF_T pos;
54   char buffer[BUFSIZ + 9];      /* 7 for "\n\nFrom " */
55   int bytes_read;
56   int i;                        /* Index into `buffer' for scanning.  */
57
58   p_clear(buffer, 1);
59   fseeko (f, 0, SEEK_END);
60   pos = ftello (f);
61
62   /* Set `bytes_read' to the size of the last, probably partial, buffer; 0 <
63    * `bytes_read' <= `BUFSIZ'.  */
64   bytes_read = pos % BUFSIZ;
65   if (bytes_read == 0)
66     bytes_read = BUFSIZ;
67   /* Make `pos' a multiple of `BUFSIZ' (0 if the file is short), so that all
68    * reads will be on block boundaries, which might increase efficiency.  */
69   while ((pos -= bytes_read) >= 0) {
70     /* we save in the buffer at the end the first 7 chars from the last read */
71     strncpy (buffer + BUFSIZ, buffer, 5 + 2);   /* 2 == 2 * m_strlen(CRLF) */
72     fseeko (f, pos, SEEK_SET);
73     bytes_read = fread (buffer, sizeof (char), bytes_read, f);
74     if (bytes_read == -1)
75       return -1;
76     for (i = bytes_read; --i >= 0;)
77       if (!m_strncmp(buffer + i, "\n\nFrom ", m_strlen("\n\nFrom "))) { /* found it - go to the beginning of the From */
78         fseeko (f, pos + i + 2, SEEK_SET);
79         return 0;
80       }
81     bytes_read = BUFSIZ;
82   }
83
84   /* here we are at the beginning of the file */
85   if (!m_strncmp("From ", buffer, 5)) {
86     fseeko (f, 0, 0);
87     return (0);
88   }
89
90   return (-1);
91 }
92
93 /* Return 1 if the last message is new */
94 static int test_last_status_new (FILE * f)
95 {
96   HEADER *hdr;
97   ENVELOPE *tmp_envelope;
98   int result = 0;
99
100   if (fseeko_last_message (f) == -1)
101     return (0);
102
103   hdr = header_new();
104   tmp_envelope = mutt_read_rfc822_header (f, hdr, 0, 0);
105   if (!(hdr->read || hdr->old))
106     result = 1;
107
108   envelope_delete(&tmp_envelope);
109   header_delete(&hdr);
110
111   return result;
112 }
113
114 static int test_new_folder (const char *path)
115 {
116   FILE *f;
117   int rc = 0;
118   int typ;
119
120   typ = mx_get_magic (path);
121
122   if (typ != M_MBOX && typ != M_MMDF)
123     return 0;
124
125   if ((f = fopen (path, "rb"))) {
126     rc = test_last_status_new (f);
127     fclose (f);
128   }
129
130   return rc;
131 }
132
133 BUFFY *buffy_find_mailbox (const char *path)
134 {
135   struct stat sb;
136   struct stat tmp_sb;
137   int i = 0;
138
139   if (stat (path, &sb) != 0)
140     return NULL;
141
142   if (!list_empty(Incoming)) {
143     for (i = 0; i < Incoming->length; i++) {
144       if (stat (Incoming->data[i], &tmp_sb) == 0 &&
145           sb.st_dev == tmp_sb.st_dev && sb.st_ino == tmp_sb.st_ino)
146         return ((BUFFY*) Incoming->data[i]);
147     }
148   }
149   return (NULL);
150 }
151
152 void buffy_update_mailbox (BUFFY * b)
153 {
154   struct stat sb;
155
156   if (!b)
157     return;
158
159   if (stat (b->path, &sb) == 0)
160     b->size = (long) sb.st_size;
161   else
162     b->size = 0;
163   return;
164 }
165 #endif
166
167 /* func to free buffy for list_del() */
168 static void buffy_free (BUFFY** p) {
169   p_delete(&(*p)->path);
170   p_delete(p);
171 }
172
173 int buffy_lookup (const char* path) {
174   unsigned int i = 0;
175   if (list_empty(Incoming) || !path || !*path)
176     return (-1);
177   for (i = 0; i < Incoming->length; i++) {
178     if (!m_strcmp(((BUFFY*)Incoming->data[i])->path, path) )
179       return (i);
180   }
181   return (-1);
182 }
183
184 int buffy_parse_mailboxes (BUFFER * path, BUFFER * s, unsigned long data,
185                           BUFFER * err __attribute__ ((unused)))
186 {
187   BUFFY* tmp;
188   char buf[_POSIX_PATH_MAX];
189   int i = 0;
190 #ifdef BUFFY_SIZE
191   struct stat sb;
192 #endif /* BUFFY_SIZE */
193
194   while (MoreArgs (s)) {
195     mutt_extract_token (path, s, 0);
196     m_strcpy(buf, sizeof(buf), path->data);
197
198     if (data == M_UNMAILBOXES && !strcmp(buf, "*")) {
199       list_del (&Incoming, (list_del_t*) buffy_free);
200       return 0;
201     }
202
203     /* Skip empty tokens. */
204     if (!*buf)
205       continue;
206
207     mutt_expand_path (buf, sizeof (buf));
208     i = buffy_lookup (buf);
209
210     if (data == M_UNMAILBOXES) {
211       if (i >= 0) {
212         tmp = (BUFFY*) list_pop_idx (Incoming, i);
213         buffy_free (&tmp);
214       }
215       continue;
216     }
217
218     if (i < 0) {
219       tmp = p_new(BUFFY, 1);
220       tmp->path = m_strdup(buf);
221       tmp->magic = 0;
222       list_push_back (&Incoming, tmp);
223       i = Incoming->length-1;
224     } else
225       tmp = (BUFFY*) Incoming->data[i];
226
227     tmp->new = 0;
228     tmp->notified = 1;
229     tmp->newly_created = 0;
230
231 #ifdef BUFFY_SIZE
232     /* for buffy_size, it is important that if the folder is new (tested by
233      * reading it), the size is set to 0 so that later when we check we see
234      * that it increased .  without buffy_size we probably don't care.
235      */
236     if (stat (tmp->path, &sb) == 0 && !test_new_folder (tmp->path)) {
237       /* some systems out there don't have an off_t type */
238       tmp->size = (long) sb.st_size;
239     }
240     else
241       tmp->size = 0;
242 #endif /* BUFFY_SIZE */
243   }
244   return 0;
245 }
246
247 #ifdef BUFFY_SIZE
248 /* people use buffy_size on systems where modified time attributes are BADLY
249  * broken. Ignore them.
250  */
251 #define STAT_CHECK (sb.st_size > tmp->size)
252 #else
253 #define STAT_CHECK (sb.st_mtime > sb.st_atime || (tmp->newly_created && sb.st_ctime == sb.st_mtime && sb.st_ctime == sb.st_atime))
254 #endif /* BUFFY_SIZE */
255
256 /* values for force:
257  * 0    don't force any checks + update sidebar
258  * 1    force all checks + update sidebar
259  * 2    don't force any checks + _don't_ update sidebar
260  */
261 int buffy_check (int force)
262 {
263   BUFFY *tmp;
264   struct stat sb;
265   struct dirent *de;
266   DIR *dirp;
267   char path[_POSIX_PATH_MAX];
268   struct stat contex_sb;
269   time_t now, last1;
270   CONTEXT *ctx;
271   unsigned int i = 0;
272   int local = 0, count = 0;
273   time_t last2;
274
275   /* update postponed count as well, on force */
276   if (force == 1)
277     mutt_update_num_postponed ();
278
279   /* fastest return if there are no mailboxes */
280   if (list_empty(Incoming))
281     return 0;
282   now = time (NULL);
283   if (force == 0 && (now - BuffyTime < BuffyTimeout)
284       && (now - ImapBuffyTime < ImapBuffyTimeout))
285     return BuffyCount;
286
287   last1 = BuffyTime;
288   if (force == 1 || now - BuffyTime >= BuffyTimeout)
289     BuffyTime = now;
290   last2 = ImapBuffyTime;
291   if (force == 1 || now - ImapBuffyTime >= ImapBuffyTimeout)
292     ImapBuffyTime = now;
293   BuffyCount = 0;
294   BuffyNotify = 0;
295
296   count = sidebar_need_count ();
297
298   if (!Context || !Context->path || 
299       (mx_is_local (Context->magic-1) && stat (Context->path, &contex_sb) != 0)) {
300     /* check device ID and serial number instead of comparing paths */
301     contex_sb.st_dev = 0;
302     contex_sb.st_ino = 0;
303   }
304
305   for (i = 0; i < Incoming->length; i++) {
306     tmp = (BUFFY*) Incoming->data[i];
307     tmp->magic = mx_get_magic (tmp->path);
308     local = mx_is_local (tmp->magic-1);
309     if ((tmp->magic <= 0 || local) && (stat (tmp->path, &sb) != 0 || sb.st_size == 0)) {
310       /* if the mailbox still doesn't exist, set the newly created flag to
311        * be ready for when it does. */
312       tmp->newly_created = 1;
313       tmp->magic = -1;
314 #ifdef BUFFY_SIZE
315       tmp->size = 0;
316 #endif
317       continue;
318     }
319
320     /* check to see if the folder is the currently selected folder
321      * before polling */
322     if (!Context || !Context->path || (local ? (sb.st_dev != contex_sb.st_dev ||
323                                                 sb.st_ino != contex_sb.st_ino) : 
324                                        m_strcmp(tmp->path, Context->path))) {
325       switch (tmp->magic) {
326       case M_MBOX:
327       case M_MMDF:
328         /* only check on force or $mail_check reached */
329         if (force == 1 || (now - last1 >= BuffyTimeout)) {
330           if (!count) {
331             if (STAT_CHECK) {
332               BuffyCount++;
333               tmp->new = 1;
334             }
335 #ifdef BUFFY_SIZE
336             else {
337               /* some other program has deleted mail from the folder */
338               tmp->size = (long) sb.st_size;
339             }
340 #endif
341           }
342           else if (STAT_CHECK || tmp->msgcount == 0) {
343             /* sidebar visible */
344             BuffyCount++;
345             if ((ctx =
346                  mx_open_mailbox (tmp->path, M_READONLY | M_QUIET | M_NOSORT | M_COUNT,
347                                   NULL)) != NULL) {
348               tmp->msgcount = ctx->msgcount;
349               tmp->new = ctx->new;
350               tmp->msg_unread = ctx->new;       /* for sidebar, wtf? */
351               tmp->msg_flagged = ctx->flagged;
352               mx_close_mailbox (ctx, 0);
353             }
354           }
355           if (tmp->newly_created &&
356               (sb.st_ctime != sb.st_mtime || sb.st_ctime != sb.st_atime))
357             tmp->newly_created = 0;
358         }
359         else if (tmp->new > 0)
360           BuffyCount++;
361         break;
362
363       case M_MAILDIR:
364         /* only check on force or $mail_check reached */
365         if (force == 1 || (now - last1 >= BuffyTimeout)) {
366           snprintf (path, sizeof (path), "%s/new", tmp->path);
367           if ((dirp = opendir (path)) == NULL) {
368             tmp->magic = 0;
369             break;
370           }
371           tmp->new = 0;
372           tmp->msg_unread = 0;
373           tmp->msgcount = 0;
374           while ((de = readdir (dirp)) != NULL) {
375             char *p;
376
377             if (*de->d_name != '.' &&
378                 (!(p = strstr (de->d_name, ":2,")) || !strchr (p + 3, 'T'))) {
379               /* one new and undeleted message is enough */
380               if (tmp->new == 0) {
381                 BuffyCount++;
382                 if (!count) {
383                   /* if sidebar invisible -> done */
384                   tmp->new = 1;
385                   break;
386                 }
387               }
388               tmp->msgcount++;
389               tmp->msg_unread++;
390               tmp->new++;
391             }
392           }
393           closedir (dirp);
394
395           if (count) {
396             /* only count total mail if sidebar visible */
397             snprintf (path, sizeof (path), "%s/cur", tmp->path);
398             if ((dirp = opendir (path)) == NULL) {
399               tmp->magic = 0;
400               break;
401             }
402             tmp->msg_flagged = 0;
403             while ((de = readdir (dirp)) != NULL) {
404               char *p;
405
406               if (*de->d_name != '.'
407                   && (p = strstr (de->d_name, ":2,")) != NULL) {
408                 if (!strchr (p + 3, 'T'))
409                   tmp->msgcount++;
410                 if (strchr (p + 3, 'F'))
411                   tmp->msg_flagged++;
412               }
413             }
414             closedir (dirp);
415           }
416         }
417         else if (tmp->new > 0)
418           /* keep current stats if !force and !$mail_check reached */
419           BuffyCount++;
420         break;
421
422       case M_MH:
423         /* only check on force or $mail_check reached */
424         if (force == 1 || (now - last1 >= BuffyTimeout)) {
425           if ((tmp->new = mh_buffy (tmp->path)) > 0)
426             BuffyCount++;
427           if (count) {
428             DIR *dp;
429
430             if ((dp = opendir (path)) == NULL)
431               break;
432             tmp->new = 0;
433             tmp->msgcount = 0;
434             tmp->msg_unread = 0;
435             while ((de = readdir (dp))) {
436               if (mh_valid_message (de->d_name)) {
437                 tmp->msgcount++;
438                 tmp->msg_unread++;
439                 tmp->new++;
440               }
441             }
442             closedir (dp);
443           }
444         }
445         else if (tmp->new > 0)
446           /* keep current stats if !force and !$mail_check reached */
447           BuffyCount++;
448         break;
449
450       case M_IMAP:
451         /* only check on force or $imap_mail_check reached */
452         if (force == 1 || (now - last2 >= ImapBuffyTimeout)) {
453           tmp->msgcount = imap_mailbox_check (tmp->path, 0);
454           tmp->new = imap_mailbox_check (tmp->path, 1);
455           tmp->msg_unread = imap_mailbox_check (tmp->path, 2);
456           if (tmp->new > 0)
457             BuffyCount++;
458           else
459             tmp->new = 0;
460           if (tmp->msg_unread < 0)
461             tmp->msg_unread = 0;
462         }
463         else if (tmp->new > 0)
464           /* keep current stats if !force and !$imap_mail_check reached */
465           BuffyCount++;
466         break;
467
468       }
469     }
470 #ifdef BUFFY_SIZE
471     else if (Context && Context->path)
472       tmp->size = (long) sb.st_size;    /* update the size */
473 #endif
474
475     if (tmp->new <= 0)
476       tmp->notified = 0;
477     else if (!tmp->notified)
478       BuffyNotify++;
479     tmp->has_new = tmp->new > 0;
480   }
481   if (BuffyCount > 0 && force != 2)
482     sidebar_draw (CurrentMenu);
483   return (BuffyCount);
484 }
485
486 int buffy_list (void)
487 {
488   BUFFY *tmp;
489   char path[_POSIX_PATH_MAX];
490   char buffylist[160];
491   int pos;
492   int first;
493   int have_unnotified = BuffyNotify;
494   unsigned int i = 0;
495
496   pos = 0;
497   first = 1;
498   buffylist[0] = 0;
499   pos += m_strlen(strncat (buffylist, _("New mail in "), sizeof (buffylist) - 1 - pos)); /* __STRNCAT_CHECKED__ */
500   if (Incoming) {
501     for (i = 0; i < Incoming->length; i++) {
502       tmp = (BUFFY*) Incoming->data[i];
503       /* Is there new mail in this mailbox? */
504       if (tmp->new <= 0 || (have_unnotified && tmp->notified))
505         continue;
506
507       m_strcpy(path, sizeof(path), tmp->path);
508       mutt_pretty_mailbox (path);
509
510       if (!first && pos + m_strlen(path) >= COLS - 7)
511         break;
512
513       if (!first)
514         pos += m_strlen(strncat (buffylist + pos, ", ", sizeof (buffylist) - 1 - pos));    /* __STRNCAT_CHECKED__ */
515
516       /* Prepend an asterisk to mailboxes not already notified */
517       if (!tmp->notified) {
518         /* pos += m_strlen(strncat(buffylist + pos, "*", sizeof(buffylist)-1-pos));  __STRNCAT_CHECKED__ */
519         tmp->notified = 1;
520         BuffyNotify--;
521       }
522       pos += m_strlen(strncat (buffylist + pos, path, sizeof (buffylist) - 1 - pos));      /* __STRNCAT_CHECKED__ */
523       first = 0;
524     }
525   }
526   if (!first && i < Incoming->length) {
527     strncat (buffylist + pos, ", ...", sizeof (buffylist) - 1 - pos);   /* __STRNCAT_CHECKED__ */
528   }
529   if (!first) {
530     /* on new mail: redraw sidebar */
531     sidebar_draw (CurrentMenu);
532     mutt_message ("%s", buffylist);
533     return (1);
534   }
535   /* there were no mailboxes needing to be notified, so clean up since 
536    * BuffyNotify has somehow gotten out of sync
537    */
538   BuffyNotify = 0;
539   return (0);
540 }
541
542 int buffy_notify (void)
543 {
544   if (buffy_check (0) && BuffyNotify) {
545     return (buffy_list ());
546   }
547   return (0);
548 }
549
550 /* 
551  * mutt_buffy() -- incoming folders completion routine
552  *
553  * given a folder name, this routine gives the next incoming folder with new
554  * new mail.
555  */
556 void buffy_next (char *s, size_t slen)
557 {
558   unsigned int l = 0;
559   int c = 0, i = 0;
560
561   if (list_empty(Incoming))
562     return;
563
564   mutt_expand_path (s, _POSIX_PATH_MAX);
565   if (buffy_check (0) == 0) {
566     *s = '\0';
567     return;
568   }
569
570   /*
571    * If buffy_lookup returns the index,
572    * or -1 if not found (-1..Incoming->length-1);
573    * plus one --> (0..Incoming->length).
574    * Modulo mapps it into the correct range.
575    */
576   i = 1 + buffy_lookup (s);
577   for (l=0; l < Incoming->length; l++) {
578     c = (l+i) % Incoming->length;
579     if ((!Context || !Context->path || m_strcmp(((BUFFY*) Incoming->data[c])->path, Context->path)) &&
580         ((BUFFY*) Incoming->data[c])->new > 0)
581       break;
582   }
583   if (l >= Incoming->length) {
584     *s = '\0';
585     /* something went wrong since we're here when buffy_check
586      * reported new mail */
587     buffy_check (0);
588   } else {
589     m_strcpy(s, slen, ((BUFFY*)Incoming->data[c])->path);
590     mutt_pretty_mailbox (s);
591   }
592 }