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