Nico Golde:
[apps/madmutt.git] / buffy.c
1 /* 
2  * Copyright (C) 1996-2000 Michael R. Elkins <me@mutt.org>
3  * 
4  *     This program is free software; you can redistribute it and/or modify
5  *     it under the terms of the GNU General Public License as published by
6  *     the Free Software Foundation; either version 2 of the License, or
7  *     (at your option) any later version.
8  * 
9  *     This program is distributed in the hope that it will be useful,
10  *     but WITHOUT ANY WARRANTY; without even the implied warranty of
11  *     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  *     GNU General Public License for more details.
13  * 
14  *     You should have received a copy of the GNU General Public License
15  *     along with this program; if not, write to the Free Software
16  *     Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111, USA.
17  */
18
19 #if HAVE_CONFIG_H
20 # include "config.h"
21 #endif
22
23 #include "mutt.h"
24 #include "buffy.h"
25 #include "mailbox.h"
26 #include "mx.h"
27 #include "sidebar.h"
28
29 #include "mutt_curses.h"
30
31 #ifdef USE_IMAP
32 #include "imap.h"
33 #endif
34
35 #include <string.h>
36 #include <sys/stat.h>
37 #include <dirent.h>
38 #include <utime.h>
39 #include <ctype.h>
40 #include <unistd.h>
41
42 #include <stdio.h>
43
44 static time_t BuffyTime = 0;            /* last time we started checking for mail */
45 #ifdef USE_IMAP
46 static time_t ImapBuffyTime = 0;        /* last time we started checking for mail */
47 #endif
48 static short BuffyCount = 0;            /* how many boxes with new mail */
49 static short BuffyNotify = 0;           /* # of unnotified new boxes */
50
51 #ifdef BUFFY_SIZE
52
53 /* Find the last message in the file. 
54  * upon success return 0. If no message found - return -1 */
55
56 int fseek_last_message (FILE * f)
57 {
58   long int pos;
59   char buffer[BUFSIZ + 9];      /* 7 for "\n\nFrom " */
60   int bytes_read;
61   int i;                        /* Index into `buffer' for scanning.  */
62
63   memset (buffer, 0, sizeof(buffer));
64   fseek (f, 0, SEEK_END);
65   pos = ftell (f);
66
67   /* Set `bytes_read' to the size of the last, probably partial, buffer; 0 <
68    * `bytes_read' <= `BUFSIZ'.  */
69   bytes_read = pos % BUFSIZ;
70   if (bytes_read == 0)
71     bytes_read = BUFSIZ;
72   /* Make `pos' a multiple of `BUFSIZ' (0 if the file is short), so that all
73    * reads will be on block boundaries, which might increase efficiency.  */
74   while ((pos -= bytes_read) >= 0)
75   {
76     /* we save in the buffer at the end the first 7 chars from the last read */
77     strncpy (buffer + BUFSIZ, buffer, 5+2); /* 2 == 2 * mutt_strlen(CRLF) */
78     fseek (f, pos, SEEK_SET);
79     bytes_read = fread (buffer, sizeof (char), bytes_read, f);
80     if (bytes_read == -1)
81       return -1;
82     for (i = bytes_read; --i >= 0;)
83       if (!mutt_strncmp (buffer + i, "\n\nFrom ", mutt_strlen ("\n\nFrom ")))
84       {                         /* found it - go to the beginning of the From */
85         fseek (f, pos + i + 2, SEEK_SET);
86         return 0;
87       }
88     bytes_read = BUFSIZ;
89   }
90
91   /* here we are at the beginning of the file */
92   if (!mutt_strncmp ("From ", buffer, 5))
93   {
94     fseek (f, 0, 0);
95     return (0);
96   }
97
98   return (-1);
99 }
100
101 /* Return 1 if the last message is new */
102 int test_last_status_new (FILE * f)
103 {
104   HEADER *hdr;
105   ENVELOPE* tmp_envelope;
106   int result = 0;
107
108   if (fseek_last_message (f) == -1)
109     return (0);
110
111   hdr = mutt_new_header ();
112   tmp_envelope = mutt_read_rfc822_header (f, hdr, 0, 0);
113   if (!(hdr->read || hdr->old))
114     result = 1;
115
116   mutt_free_envelope(&tmp_envelope);
117   mutt_free_header (&hdr);
118
119   return result;
120 }
121
122 int test_new_folder (const char *path)
123 {
124   FILE *f;
125   int rc = 0;
126   int typ;
127
128   typ = mx_get_magic (path);
129
130   if (typ != M_MBOX && typ != M_MMDF)
131     return 0;
132
133   if ((f = fopen (path, "rb")))
134   {
135     rc = test_last_status_new (f);
136     fclose (f);
137   }
138
139   return rc;
140 }
141
142 BUFFY *mutt_find_mailbox (const char *path)
143 {
144   BUFFY *tmp = NULL;
145   struct stat sb;
146   struct stat tmp_sb;
147   
148   if (stat (path,&sb) != 0)
149     return NULL;
150
151   for (tmp = Incoming; tmp; tmp = tmp->next)
152   {
153     if (stat (tmp->path,&tmp_sb) ==0 && 
154         sb.st_dev == tmp_sb.st_dev && sb.st_ino == tmp_sb.st_ino)
155       break;
156   }
157   return tmp;
158 }
159
160 void mutt_update_mailbox (BUFFY * b)
161 {
162   struct stat sb;
163
164   if (!b)
165     return;
166
167   if (stat (b->path, &sb) == 0)
168     b->size = (long) sb.st_size;
169   else
170     b->size = 0;
171   return;
172 }
173 #endif
174
175 int mutt_parse_mailboxes (BUFFER *path, BUFFER *s, unsigned long data, BUFFER *err)
176 {
177   BUFFY **tmp,*tmp1,*last;
178   char buf[_POSIX_PATH_MAX];
179   int dup = 0;
180 #ifdef BUFFY_SIZE
181   struct stat sb;
182 #endif /* BUFFY_SIZE */
183
184   /*
185    * FIXME
186    * to get rid of correcting the ->prev pointers in sidebar.c,
187    * correct them right here
188    */
189
190   /*
191    * FIXME
192    * if we really want to make the sort order of the sidebar
193    * configurable, this has to go right here
194    */
195   
196   while (MoreArgs (s))
197   {
198     mutt_extract_token (path, s, 0);
199     strfcpy (buf, path->data, sizeof (buf));
200
201     if(data == M_UNMAILBOXES && mutt_strcmp(buf,"*") == 0)
202     {
203       for (tmp = &Incoming; *tmp;)
204       {
205         FREE (&((*tmp)->path));
206         tmp1=(*tmp)->next;
207         FREE (tmp);
208         *tmp=tmp1;
209       }
210       return 0;
211     }
212
213     mutt_expand_path (buf, sizeof (buf));
214
215     /* Skip empty tokens. */
216     if(!*buf) continue;
217
218     /* simple check to avoid duplicates */
219     dup = 0;
220     for (tmp = &Incoming; *tmp && dup == 0; tmp = &((*tmp)->next))
221     {
222       if (mutt_strcmp (buf, (*tmp)->path) == 0) {
223         dup = 1;
224         break;
225       }
226     }
227
228     if (dup == 1)
229       continue;
230     tmp = &Incoming;
231
232     if(data == M_UNMAILBOXES)
233     {
234       if(*tmp)
235       {
236         FREE (&((*tmp)->path));
237         tmp1=(*tmp)->next;
238         FREE (tmp);
239         *tmp=tmp1;
240       }
241       continue;
242     }
243
244     /* loop over list while it's sorted */
245     tmp1 = NULL;
246     last = NULL;
247     for (tmp = &Incoming; *tmp ; tmp = &((*tmp)->next)) {
248       /*
249        * FIXME
250        * change this to get whatever sorting order
251        */
252       if (mutt_strcmp (buf, (*tmp)->path) < 0) {
253         tmp1 = (*tmp);
254         break;
255       }
256       last = (*tmp);
257     }
258
259     /* we want: last -> tmp -> tmp1 */
260     *tmp = (BUFFY *) safe_calloc (1, sizeof (BUFFY));
261     (*tmp)->path = safe_strdup (buf);
262     (*tmp)->magic = 0;
263
264     /* correct pointers */
265     (*tmp)->next = tmp1;
266     if (last)
267       last->next = (*tmp);
268
269     /* left as-is */
270     (*tmp)->new = 0;
271     (*tmp)->notified = 1;
272     (*tmp)->newly_created = 0;
273
274 #ifdef BUFFY_SIZE
275     /* for buffy_size, it is important that if the folder is new (tested by
276      * reading it), the size is set to 0 so that later when we check we see
277      * that it increased .  without buffy_size we probably don't care.
278      */
279     if (stat ((*tmp)->path, &sb) == 0 && !test_new_folder ((*tmp)->path))
280     {
281       /* some systems out there don't have an off_t type */
282       (*tmp)->size = (long) sb.st_size;
283     }
284     else
285       (*tmp)->size = 0;
286 #endif /* BUFFY_SIZE */
287   }
288   return 0;
289 }
290
291 #ifdef BUFFY_SIZE
292 /* people use buffy_size on systems where modified time attributes are BADLY
293  * broken. Ignore them.
294  */
295 #define STAT_CHECK (sb.st_size > tmp->size)
296 #else
297 #define STAT_CHECK (sb.st_mtime > sb.st_atime || (tmp->newly_created && sb.st_ctime == sb.st_mtime && sb.st_ctime == sb.st_atime))
298 #endif /* BUFFY_SIZE */
299
300 /* values for force:
301  * 0    don't force any checks + update sidebar
302  * 1    force all checks + update sidebar
303  * 2    force all checks + _don't_ update sidebar
304  */
305 int mutt_buffy_check (int force)
306 {
307   BUFFY *tmp;
308   struct stat sb;
309   struct dirent *de;
310   DIR *dirp;
311   char path[_POSIX_PATH_MAX];
312   struct stat contex_sb;
313   time_t now, last1, last2;
314   CONTEXT *ctx;
315 #ifdef USE_IMAP
316   /* update postponed count as well, on force */
317   if (force != 0)
318     mutt_update_num_postponed ();
319 #endif
320
321   /* fastest return if there are no mailboxes */
322   if (!Incoming)
323     return 0;
324   now = time (NULL);
325   if (force == 0 && (now - BuffyTime < BuffyTimeout)
326 #ifdef USE_IMAP
327       && (now - ImapBuffyTime < ImapBuffyTimeout))
328 #else
329       )
330 #endif
331     return BuffyCount;
332
333   last1 = BuffyTime;
334   if (force != 0 || now - BuffyTime >= BuffyTimeout)
335     BuffyTime = now;
336 #ifdef USE_IMAP
337   last2 = ImapBuffyTime;
338   if (force != 0 || now - ImapBuffyTime >= ImapBuffyTimeout)
339     ImapBuffyTime = now;
340 #endif
341   BuffyCount = 0;
342   BuffyNotify = 0;
343
344 #ifdef USE_IMAP
345   if (!Context || Context->magic != M_IMAP)
346 #endif
347 #ifdef USE_POP
348   if (!Context || Context->magic != M_POP)
349 #endif
350 #ifdef USE_NNTP
351   if (!Context || Context->magic != M_NNTP)
352 #endif
353   /* check device ID and serial number instead of comparing paths */
354   if (!Context || !Context->path || stat (Context->path, &contex_sb) != 0)
355   {
356     contex_sb.st_dev=0;
357     contex_sb.st_ino=0;
358   }
359   
360   for (tmp = Incoming; tmp; tmp = tmp->next)
361   {
362 #ifdef USE_IMAP
363     if (mx_is_imap (tmp->path))
364       tmp->magic = M_IMAP;
365     else
366 #endif
367 #ifdef USE_POP
368     if (mx_is_pop (tmp->path))
369       tmp->magic = M_POP;
370     else
371 #endif
372 #ifdef USE_NNTP
373     if ((tmp->magic == M_NNTP) || mx_is_nntp (tmp->path))
374       tmp->magic = M_NNTP;
375     else
376 #endif
377     if (stat (tmp->path, &sb) != 0 || sb.st_size == 0 ||
378        (!tmp->magic && (tmp->magic = mx_get_magic (tmp->path)) <= 0))
379     {
380       /* if the mailbox still doesn't exist, set the newly created flag to
381        * be ready for when it does. */
382       tmp->newly_created = 1;
383       tmp->magic = 0;
384 #ifdef BUFFY_SIZE
385       tmp->size = 0;
386 #endif
387       continue;
388     }
389
390     /* check to see if the folder is the currently selected folder
391      * before polling */
392     if (!Context || !Context->path ||
393          (
394            (0
395 #ifdef USE_IMAP
396             || tmp->magic == M_IMAP
397 #endif
398 #ifdef USE_POP
399             || tmp->magic == M_POP
400 #endif
401 #ifdef USE_NNTP
402             || tmp->magic == M_NNTP
403 #endif
404            ) ? mutt_strcmp (tmp->path, Context->path) :
405                (sb.st_dev != contex_sb.st_dev || sb.st_ino != contex_sb.st_ino)
406          )
407        )
408     {
409       switch (tmp->magic)
410       {
411       case M_MBOX:
412       case M_MMDF:
413         /* only check on force or $mail_check reached */
414         if (force != 0 || (now - last1 >= BuffyTimeout)) {
415           if (SidebarWidth == 0 || !option (OPTMBOXPANE)) {
416             if (STAT_CHECK) {
417               BuffyCount++;
418               tmp->new = 1;
419             }
420 #ifdef BUFFY_SIZE
421             else
422             {
423               /* some other program has deleted mail from the folder */
424               tmp->size = (long) sb.st_size;
425             }
426 #endif
427           } else if (SidebarWidth > 0 && option (OPTMBOXPANE) && 
428                     (STAT_CHECK || tmp->msgcount == 0)) {
429             /* sidebar visible */
430             BuffyCount++;
431             if ((ctx = mx_open_mailbox (tmp->path, M_READONLY | M_QUIET | M_NOSORT, NULL)) != NULL) {
432               tmp->msgcount = ctx->msgcount;
433               tmp->new = ctx->new;
434               tmp->msg_unread = ctx->new;       /* for sidebar, wtf? */
435               tmp->msg_flagged = ctx->flagged;
436               mx_close_mailbox (ctx, 0);
437             }
438           }
439           if (tmp->newly_created &&
440               (sb.st_ctime != sb.st_mtime || sb.st_ctime != sb.st_atime))
441             tmp->newly_created = 0;
442         } else if (tmp->new > 0)
443           BuffyCount++;
444         break;
445
446       case M_MAILDIR:
447         /* only check on force or $mail_check reached */
448         if (force != 0 || (now - last1 >= BuffyTimeout)) {
449           snprintf (path, sizeof (path), "%s/new", tmp->path);
450           if ((dirp = opendir (path)) == NULL)
451           {
452             tmp->magic = 0;
453             break;
454           }
455           tmp->new = 0;
456           tmp->msg_unread = 0;
457           tmp->msgcount = 0;
458           while ((de = readdir (dirp)) != NULL)
459           {
460             char *p;
461             if (*de->d_name != '.' && 
462                 (!(p = strstr (de->d_name, ":2,")) || !strchr (p + 3, 'T')))
463             {
464               /* one new and undeleted message is enough */
465               if (tmp->new == 0)
466               {
467                 BuffyCount++;
468                 tmp->new = 1;
469                 if (SidebarWidth == 0 || !option (OPTMBOXPANE))
470                   /* if sidebar invisible -> done */
471                   break;
472               }
473               tmp->msgcount++;
474               tmp->msg_unread++;
475               tmp->new++;
476             }
477           }
478           closedir (dirp);
479
480           if (SidebarWidth > 0 && option (OPTMBOXPANE))
481           {
482             /* only count total mail if sidebar visible */
483             snprintf (path, sizeof (path), "%s/cur", tmp->path);
484             if ((dirp = opendir (path)) == NULL)
485             {
486               tmp->magic = 0;
487               break;
488             }
489             tmp->msg_flagged = 0;
490             while ((de = readdir (dirp)) != NULL)
491             {
492               char *p;
493               if (*de->d_name != '.' && (p = strstr (de->d_name, ":2,")) != NULL) {
494                 if (!strchr (p + 3, 'T'))
495                   tmp->msgcount++;
496                 if (strchr (p + 3, 'F'))
497                   tmp->msg_flagged++;
498               }
499             }
500             closedir (dirp);
501           }
502         } else if (tmp->new > 0)
503           /* keep current stats if !force and !$mail_check reached */
504           BuffyCount++;
505         break;
506
507       case M_MH:
508         /* only check on force or $mail_check reached */
509         if (force != 0 || (now - last1 >= BuffyTimeout)) {
510           if ((tmp->new = mh_buffy (tmp->path)) > 0)
511             BuffyCount++;
512           if (SidebarWidth > 0 && option (OPTMBOXPANE))
513           {
514             DIR *dp;
515             struct dirent *de;
516             if ((dp = opendir (path)) == NULL)
517               break;
518             tmp->new = 0;
519             tmp->msgcount = 0;
520             tmp->msg_unread = 0;
521             while ((de = readdir (dp)))
522             {
523               if (mh_valid_message (de->d_name))
524               {
525                 tmp->msgcount++;
526                 tmp->msg_unread++;
527                 tmp->new++;
528               }
529             }
530             closedir (dp);
531           }
532         } else if (tmp->new > 0)
533           /* keep current stats if !force and !$mail_check reached */
534           BuffyCount++;
535         break;
536
537 #ifdef USE_IMAP
538       case M_IMAP:
539         /* only check on force or $imap_mail_check reached */
540         if (force != 0 || (now - last2 >= ImapBuffyTimeout)) {
541           tmp->msgcount = imap_mailbox_check (tmp->path, 0);
542           if ((tmp->new = imap_mailbox_check (tmp->path, 1)) > 0) {
543             BuffyCount++;
544             tmp->msg_unread = tmp->new; /* for sidebar; wtf? */
545           }
546           else {
547             tmp->new = 0;
548             tmp->msg_unread = 0;
549           }
550         } else if (tmp->new > 0)
551           /* keep current stats if !force and !$imap_mail_check reached */
552           BuffyCount++;
553         break;
554 #endif
555
556 #ifdef USE_POP
557       case M_POP:
558         break;
559 #endif
560
561 #ifdef USE_NNTP
562       case M_NNTP:
563         break;
564 #endif
565       }
566     }
567 #ifdef BUFFY_SIZE
568     else if (Context && Context->path)
569       tmp->size = (long) sb.st_size;    /* update the size */
570 #endif
571
572     if (!tmp->new)
573       tmp->notified = 0;
574     else if (!tmp->notified)
575       BuffyNotify++;
576     tmp->has_new = tmp->new > 0;
577   }
578   if (BuffyCount > 0 && force != 2)
579     draw_sidebar (CurrentMenu);
580   return (BuffyCount);
581 }
582
583 int mutt_buffy_list (void)
584 {
585   BUFFY *tmp;
586   char path[_POSIX_PATH_MAX];
587   char buffylist[160];
588   int pos;
589   int first;
590   int have_unnotified = BuffyNotify;
591
592   if (option (OPTFORCEBUFFYCHECK))
593     mutt_buffy_check (1);
594
595   pos = 0;
596   first = 1;
597   buffylist[0] = 0;
598   pos += strlen (strncat (buffylist, _("New mail in "), sizeof (buffylist) - 1 - pos)); /* __STRNCAT_CHECKED__ */
599   for (tmp = Incoming; tmp; tmp = tmp->next)
600   {
601     /* Is there new mail in this mailbox? */
602     if (!tmp->new || (have_unnotified && tmp->notified))
603       continue;
604
605     strfcpy (path, tmp->path, sizeof (path));
606     mutt_pretty_mailbox (path);
607     
608     if (!first && pos + strlen (path) >= COLS - 7)
609       break;
610     
611     if (!first)
612       pos += strlen (strncat(buffylist + pos, ", ", sizeof(buffylist)-1-pos)); /* __STRNCAT_CHECKED__ */
613
614     /* Prepend an asterisk to mailboxes not already notified */
615     if (!tmp->notified)
616     {
617       /* pos += strlen (strncat(buffylist + pos, "*", sizeof(buffylist)-1-pos));  __STRNCAT_CHECKED__ */
618       tmp->notified = 1;
619       BuffyNotify--;
620     }
621     pos += strlen (strncat(buffylist + pos, path, sizeof(buffylist)-1-pos)); /* __STRNCAT_CHECKED__ */
622     first = 0;
623   }
624   if (!first && tmp)
625   {
626     strncat (buffylist + pos, ", ...", sizeof (buffylist) - 1 - pos); /* __STRNCAT_CHECKED__ */
627   }
628   if (!first)
629   {
630     /* on new mail: redraw sidebar */
631     draw_sidebar (CurrentMenu);
632     mutt_message ("%s", buffylist);
633     return (1);
634   }
635   /* there were no mailboxes needing to be notified, so clean up since 
636    * BuffyNotify has somehow gotten out of sync
637    */
638   BuffyNotify = 0;
639   return (0);
640 }
641
642 int mutt_buffy_notify (void)
643 {
644   if (mutt_buffy_check (0) && BuffyNotify)
645   {
646     return (mutt_buffy_list ());
647   }
648   return (0);
649 }
650
651 /* 
652  * mutt_buffy() -- incoming folders completion routine
653  *
654  * given a folder name, this routine gives the next incoming folder with new
655  * new mail.
656  */
657 void mutt_buffy (char *s, size_t slen)
658 {
659   int count;
660   BUFFY *tmp = Incoming;
661
662   mutt_expand_path (s, _POSIX_PATH_MAX);
663   switch (mutt_buffy_check (0))
664   {
665   case 0:
666
667     *s = '\0';
668     break;
669
670   case 1:
671
672     while (tmp && !tmp->new)
673       tmp = tmp->next;
674     if (!tmp)
675     {
676       *s = '\0';
677       mutt_buffy_check (1); /* buffy was wrong - resync things */
678       break;
679     }
680     strfcpy (s, tmp->path, slen);
681     mutt_pretty_mailbox (s);
682     break;
683
684   default:
685     
686     count = 0;
687     while (count < 3)
688     {
689       if (mutt_strcmp (s, tmp->path) == 0)
690         count++;
691       else if (count && tmp->new)
692         break;
693       tmp = tmp->next;
694       if (!tmp)
695       {
696         tmp = Incoming;
697         count++;
698       }
699     }
700     if (count >= 3)
701     {
702       *s = '\0';
703       mutt_buffy_check (1); /* buffy was wrong - resync things */
704       break;
705     }
706     strfcpy (s, tmp->path, slen);
707     mutt_pretty_mailbox (s);
708     break;
709   }
710 }