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, "*") == 0) {
203       list_del (&Incoming, (list_del_t*) buffy_free);
204       return 0;
205     }
206
207     /* Skip empty tokens. */
208     if (!*buf)
209       continue;
210
211     mutt_expand_path (buf, sizeof (buf));
212     i = buffy_lookup (buf);
213
214     if (data == M_UNMAILBOXES) {
215       if (i >= 0) {
216         tmp = (BUFFY*) list_pop_idx (Incoming, i);
217         buffy_free (&tmp);
218       }
219       continue;
220     }
221
222     if (i < 0) {
223       tmp = mem_calloc (1, sizeof (BUFFY));
224       tmp->path = str_dup (buf);
225       tmp->magic = 0;
226       list_push_back (&Incoming, tmp);
227       i = Incoming->length-1;
228     } else
229       tmp = (BUFFY*) Incoming->data[i];
230
231     tmp->new = 0;
232     tmp->notified = 1;
233     tmp->newly_created = 0;
234
235 #ifdef BUFFY_SIZE
236     /* for buffy_size, it is important that if the folder is new (tested by
237      * reading it), the size is set to 0 so that later when we check we see
238      * that it increased .  without buffy_size we probably don't care.
239      */
240     if (stat (tmp->path, &sb) == 0 && !test_new_folder (tmp->path)) {
241       /* some systems out there don't have an off_t type */
242       tmp->size = (long) sb.st_size;
243     }
244     else
245       tmp->size = 0;
246 #endif /* BUFFY_SIZE */
247   }
248   return 0;
249 }
250
251 #ifdef BUFFY_SIZE
252 /* people use buffy_size on systems where modified time attributes are BADLY
253  * broken. Ignore them.
254  */
255 #define STAT_CHECK (sb.st_size > tmp->size)
256 #else
257 #define STAT_CHECK (sb.st_mtime > sb.st_atime || (tmp->newly_created && sb.st_ctime == sb.st_mtime && sb.st_ctime == sb.st_atime))
258 #endif /* BUFFY_SIZE */
259
260 /* values for force:
261  * 0    don't force any checks + update sidebar
262  * 1    force all checks + update sidebar
263  * 2    force all checks + _don't_ update sidebar
264  */
265 int buffy_check (int force)
266 {
267   BUFFY *tmp;
268   struct stat sb;
269   struct dirent *de;
270   DIR *dirp;
271   char path[_POSIX_PATH_MAX];
272   struct stat contex_sb;
273   time_t now, last1;
274   CONTEXT *ctx;
275   int i = 0, local = 0, count = 0;
276 #ifdef USE_IMAP
277   time_t last2;
278
279   /* update postponed count as well, on force */
280   if (force != 0)
281     mutt_update_num_postponed ();
282 #endif
283
284   /* fastest return if there are no mailboxes */
285   if (list_empty(Incoming))
286     return 0;
287   now = time (NULL);
288   if (force == 0 && (now - BuffyTime < BuffyTimeout)
289 #ifdef USE_IMAP
290       && (now - ImapBuffyTime < ImapBuffyTimeout))
291 #else
292     )
293 #endif
294     return BuffyCount;
295
296   last1 = BuffyTime;
297   if (force != 0 || now - BuffyTime >= BuffyTimeout)
298     BuffyTime = now;
299 #ifdef USE_IMAP
300   last2 = ImapBuffyTime;
301   if (force != 0 || now - ImapBuffyTime >= ImapBuffyTimeout)
302     ImapBuffyTime = now;
303 #endif
304   BuffyCount = 0;
305   BuffyNotify = 0;
306
307   count = sidebar_need_count ();
308
309   if (!Context || !Context->path || 
310       (mx_is_local (Context->magic-1) && stat (Context->path, &contex_sb) != 0)) {
311     /* check device ID and serial number instead of comparing paths */
312     contex_sb.st_dev = 0;
313     contex_sb.st_ino = 0;
314   }
315
316   for (i = 0; i < Incoming->length; i++) {
317     tmp = (BUFFY*) Incoming->data[i];
318     tmp->magic = mx_get_magic (tmp->path);
319     local = mx_is_local (tmp->magic-1);
320     if ((tmp->magic <= 0 || local) && (stat (tmp->path, &sb) != 0 || sb.st_size == 0)) {
321       /* if the mailbox still doesn't exist, set the newly created flag to
322        * be ready for when it does. */
323       tmp->newly_created = 1;
324       tmp->magic = -1;
325 #ifdef BUFFY_SIZE
326       tmp->size = 0;
327 #endif
328       continue;
329     }
330
331     /* check to see if the folder is the currently selected folder
332      * before polling */
333     if (!Context || !Context->path || (local ? (sb.st_dev != contex_sb.st_dev ||
334                                                 sb.st_ino != contex_sb.st_ino) : 
335                                        !str_eq (tmp->path, Context->path))) {
336       switch (tmp->magic) {
337       case M_MBOX:
338       case M_MMDF:
339         /* only check on force or $mail_check reached */
340         if (force != 0 || (now - last1 >= BuffyTimeout)) {
341           if (!count) {
342             if (STAT_CHECK) {
343               BuffyCount++;
344               tmp->new = 1;
345             }
346 #ifdef BUFFY_SIZE
347             else {
348               /* some other program has deleted mail from the folder */
349               tmp->size = (long) sb.st_size;
350             }
351 #endif
352           }
353           else if (STAT_CHECK || tmp->msgcount == 0) {
354             /* sidebar visible */
355             BuffyCount++;
356             if ((ctx =
357                  mx_open_mailbox (tmp->path, M_READONLY | M_QUIET | M_NOSORT | M_COUNT,
358                                   NULL)) != NULL) {
359               tmp->msgcount = ctx->msgcount;
360               tmp->new = ctx->new;
361               tmp->msg_unread = ctx->new;       /* for sidebar, wtf? */
362               tmp->msg_flagged = ctx->flagged;
363               mx_close_mailbox (ctx, 0);
364             }
365           }
366           if (tmp->newly_created &&
367               (sb.st_ctime != sb.st_mtime || sb.st_ctime != sb.st_atime))
368             tmp->newly_created = 0;
369         }
370         else if (tmp->new > 0)
371           BuffyCount++;
372         break;
373
374       case M_MAILDIR:
375         /* only check on force or $mail_check reached */
376         if (force != 0 || (now - last1 >= BuffyTimeout)) {
377           snprintf (path, sizeof (path), "%s/new", tmp->path);
378           if ((dirp = opendir (path)) == NULL) {
379             tmp->magic = 0;
380             break;
381           }
382           tmp->new = 0;
383           tmp->msg_unread = 0;
384           tmp->msgcount = 0;
385           while ((de = readdir (dirp)) != NULL) {
386             char *p;
387
388             if (*de->d_name != '.' &&
389                 (!(p = strstr (de->d_name, ":2,")) || !strchr (p + 3, 'T'))) {
390               /* one new and undeleted message is enough */
391               if (tmp->new == 0) {
392                 BuffyCount++;
393                 tmp->new = 1;
394                 if (!count)
395                   /* if sidebar invisible -> done */
396                   break;
397               }
398               tmp->msgcount++;
399               tmp->msg_unread++;
400               tmp->new++;
401             }
402           }
403           closedir (dirp);
404
405           if (count) {
406             /* only count total mail if sidebar visible */
407             snprintf (path, sizeof (path), "%s/cur", tmp->path);
408             if ((dirp = opendir (path)) == NULL) {
409               tmp->magic = 0;
410               break;
411             }
412             tmp->msg_flagged = 0;
413             while ((de = readdir (dirp)) != NULL) {
414               char *p;
415
416               if (*de->d_name != '.'
417                   && (p = strstr (de->d_name, ":2,")) != NULL) {
418                 if (!strchr (p + 3, 'T'))
419                   tmp->msgcount++;
420                 if (strchr (p + 3, 'F'))
421                   tmp->msg_flagged++;
422               }
423             }
424             closedir (dirp);
425           }
426         }
427         else if (tmp->new > 0)
428           /* keep current stats if !force and !$mail_check reached */
429           BuffyCount++;
430         break;
431
432       case M_MH:
433         /* only check on force or $mail_check reached */
434         if (force != 0 || (now - last1 >= BuffyTimeout)) {
435           if ((tmp->new = mh_buffy (tmp->path)) > 0)
436             BuffyCount++;
437           if (count) {
438             DIR *dp;
439             struct dirent *de;
440
441             if ((dp = opendir (path)) == NULL)
442               break;
443             tmp->new = 0;
444             tmp->msgcount = 0;
445             tmp->msg_unread = 0;
446             while ((de = readdir (dp))) {
447               if (mh_valid_message (de->d_name)) {
448                 tmp->msgcount++;
449                 tmp->msg_unread++;
450                 tmp->new++;
451               }
452             }
453             closedir (dp);
454           }
455         }
456         else if (tmp->new > 0)
457           /* keep current stats if !force and !$mail_check reached */
458           BuffyCount++;
459         break;
460
461 #ifdef USE_IMAP
462       case M_IMAP:
463         /* only check on force or $imap_mail_check reached */
464         if (force != 0 || (now - last2 >= ImapBuffyTimeout)) {
465           tmp->msgcount = imap_mailbox_check (tmp->path, 0);
466           if ((tmp->new = imap_mailbox_check (tmp->path, 1)) > 0) {
467             BuffyCount++;
468             tmp->msg_unread = tmp->new; /* for sidebar; wtf? */
469           }
470           else {
471             tmp->new = 0;
472             tmp->msg_unread = 0;
473           }
474         }
475         else if (tmp->new > 0)
476           /* keep current stats if !force and !$imap_mail_check reached */
477           BuffyCount++;
478         break;
479 #endif
480
481       }
482     }
483 #ifdef BUFFY_SIZE
484     else if (Context && Context->path)
485       tmp->size = (long) sb.st_size;    /* update the size */
486 #endif
487
488     if (tmp->new <= 0)
489       tmp->notified = 0;
490     else if (!tmp->notified)
491       BuffyNotify++;
492     tmp->has_new = tmp->new > 0;
493   }
494   if (BuffyCount > 0 && force != 2)
495     sidebar_draw (CurrentMenu);
496   return (BuffyCount);
497 }
498
499 int buffy_list (void)
500 {
501   BUFFY *tmp;
502   char path[_POSIX_PATH_MAX];
503   char buffylist[160];
504   int pos;
505   int first;
506   int have_unnotified = BuffyNotify;
507   int i = 0;
508
509   pos = 0;
510   first = 1;
511   buffylist[0] = 0;
512   pos += str_len (strncat (buffylist, _("New mail in "), sizeof (buffylist) - 1 - pos)); /* __STRNCAT_CHECKED__ */
513   if (Incoming) {
514     for (i = 0; i < Incoming->length; i++) {
515       tmp = (BUFFY*) Incoming->data[i];
516       /* Is there new mail in this mailbox? */
517       if (tmp->new <= 0 || (have_unnotified && tmp->notified))
518         continue;
519
520       strfcpy (path, tmp->path, sizeof (path));
521       mutt_pretty_mailbox (path);
522
523       if (!first && pos + str_len (path) >= COLS - 7)
524         break;
525
526       if (!first)
527         pos += str_len (strncat (buffylist + pos, ", ", sizeof (buffylist) - 1 - pos));    /* __STRNCAT_CHECKED__ */
528
529       /* Prepend an asterisk to mailboxes not already notified */
530       if (!tmp->notified) {
531         /* pos += str_len (strncat(buffylist + pos, "*", sizeof(buffylist)-1-pos));  __STRNCAT_CHECKED__ */
532         tmp->notified = 1;
533         BuffyNotify--;
534       }
535       pos += str_len (strncat (buffylist + pos, path, sizeof (buffylist) - 1 - pos));      /* __STRNCAT_CHECKED__ */
536       first = 0;
537     }
538   }
539   if (!first && i < Incoming->length) {
540     strncat (buffylist + pos, ", ...", sizeof (buffylist) - 1 - pos);   /* __STRNCAT_CHECKED__ */
541   }
542   if (!first) {
543     /* on new mail: redraw sidebar */
544     sidebar_draw (CurrentMenu);
545     mutt_message ("%s", buffylist);
546     return (1);
547   }
548   /* there were no mailboxes needing to be notified, so clean up since 
549    * BuffyNotify has somehow gotten out of sync
550    */
551   BuffyNotify = 0;
552   return (0);
553 }
554
555 int buffy_notify (void)
556 {
557   if (buffy_check (0) && BuffyNotify) {
558     return (buffy_list ());
559   }
560   return (0);
561 }
562
563 /* 
564  * mutt_buffy() -- incoming folders completion routine
565  *
566  * given a folder name, this routine gives the next incoming folder with new
567  * new mail.
568  */
569 void buffy_next (char *s, size_t slen)
570 {
571   int i = 0, c = 0, l = 0;
572
573   if (list_empty(Incoming))
574     return;
575
576   mutt_expand_path (s, _POSIX_PATH_MAX);
577   if (buffy_check (0) == 0) {
578     *s = '\0';
579     return;
580   }
581
582   /*
583    * If buffy_lookup returns the index,
584    * or -1 if not found (-1..Incoming->length-1);
585    * plus one --> (0..Incoming->length).
586    * Modulo mapps it into the correct range.
587    */
588   i = 1 + buffy_lookup (s);
589   for (l=0; l < Incoming->length; l++) {
590     c = (l+i) % Incoming->length;
591     if ((!Context || !Context->path || !str_eq (((BUFFY*) Incoming->data[c])->path, Context->path)) &&
592         ((BUFFY*) Incoming->data[c])->new > 0)
593       break;
594   }
595   if (l >= Incoming->length) {
596     *s = '\0';
597     /* something went wrong since we're here when buffy_check
598      * reported new mail */
599     buffy_check (0);
600   } else {
601     strfcpy (s, ((BUFFY*) Incoming->data[c])->path, slen);
602     mutt_pretty_mailbox (s);
603   }
604 }