Rocco Rutte:
[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 int mutt_buffy_check (int force)
301 {
302   BUFFY *tmp;
303   struct stat sb;
304   struct dirent *de;
305   DIR *dirp;
306   char path[_POSIX_PATH_MAX];
307   struct stat contex_sb;
308   time_t now, last1, last2;
309   CONTEXT *ctx;
310 #ifdef USE_IMAP
311   /* update postponed count as well, on force */
312   if (force)
313     mutt_update_num_postponed ();
314 #endif
315
316   /* fastest return if there are no mailboxes */
317   if (!Incoming)
318     return 0;
319   now = time (NULL);
320   if (!force && (now - BuffyTime < BuffyTimeout)
321 #ifdef USE_IMAP
322       && (now - ImapBuffyTime < ImapBuffyTimeout))
323 #else
324       )
325 #endif
326     return BuffyCount;
327
328   last1 = BuffyTime;
329   if (force || now - BuffyTime >= BuffyTimeout)
330     BuffyTime = now;
331 #ifdef USE_IMAP
332   last2 = ImapBuffyTime;
333   if (force || now - ImapBuffyTime >= ImapBuffyTimeout)
334     ImapBuffyTime = now;
335 #endif
336   BuffyCount = 0;
337   BuffyNotify = 0;
338
339 #ifdef USE_IMAP
340   if (!Context || Context->magic != M_IMAP)
341 #endif
342 #ifdef USE_POP
343   if (!Context || Context->magic != M_POP)
344 #endif
345 #ifdef USE_NNTP
346   if (!Context || Context->magic != M_NNTP)
347 #endif
348   /* check device ID and serial number instead of comparing paths */
349   if (!Context || !Context->path || stat (Context->path, &contex_sb) != 0)
350   {
351     contex_sb.st_dev=0;
352     contex_sb.st_ino=0;
353   }
354   
355   for (tmp = Incoming; tmp; tmp = tmp->next)
356   {
357 #ifdef USE_IMAP
358     if (mx_is_imap (tmp->path))
359       tmp->magic = M_IMAP;
360     else
361 #endif
362 #ifdef USE_POP
363     if (mx_is_pop (tmp->path))
364       tmp->magic = M_POP;
365     else
366 #endif
367 #ifdef USE_NNTP
368     if ((tmp->magic == M_NNTP) || mx_is_nntp (tmp->path))
369       tmp->magic = M_NNTP;
370     else
371 #endif
372     if (stat (tmp->path, &sb) != 0 || sb.st_size == 0 ||
373        (!tmp->magic && (tmp->magic = mx_get_magic (tmp->path)) <= 0))
374     {
375       /* if the mailbox still doesn't exist, set the newly created flag to
376        * be ready for when it does. */
377       tmp->newly_created = 1;
378       tmp->magic = 0;
379 #ifdef BUFFY_SIZE
380       tmp->size = 0;
381 #endif
382       continue;
383     }
384
385     /* check to see if the folder is the currently selected folder
386      * before polling */
387     if (!Context || !Context->path ||
388          (
389            (0
390 #ifdef USE_IMAP
391             || tmp->magic == M_IMAP
392 #endif
393 #ifdef USE_POP
394             || tmp->magic == M_POP
395 #endif
396 #ifdef USE_NNTP
397             || tmp->magic == M_NNTP
398 #endif
399            ) ? mutt_strcmp (tmp->path, Context->path) :
400                (sb.st_dev != contex_sb.st_dev || sb.st_ino != contex_sb.st_ino)
401          )
402        )
403     {
404       switch (tmp->magic)
405       {
406       case M_MBOX:
407       case M_MMDF:
408         /* only check on force or $mail_check reached */
409         if (force || (now - last1 >= BuffyTimeout)) {
410           tmp->new = 0;
411           tmp->msg_unread = 0;
412           if (SidebarWidth == 0 || !option (OPTMBOXPANE)) {
413             if (STAT_CHECK) {
414               BuffyCount++;
415               tmp->new = tmp->has_new = 1;
416             }
417 #ifdef BUFFY_SIZE
418             else
419             {
420               /* some other program has deleted mail from the folder */
421               tmp->size = (long) sb.st_size;
422             }
423 #endif
424           } else if (SidebarWidth > 0 && option (OPTMBOXPANE) && 
425                     (STAT_CHECK || tmp->msgcount == 0)) {
426             /* sidebar visible */
427             int msg_count = 0, msg_new = 0, msg_unread = 0;
428             BuffyCount++;
429             if ((ctx = mx_open_mailbox (tmp->path, M_READONLY | M_QUIET | M_NOSORT, NULL)) != NULL) {
430               msg_count = ctx->msgcount;
431               msg_new = ctx->new;
432               msg_unread = ctx->unread;
433               mx_close_mailbox (ctx, 0);
434             }
435             tmp->msgcount = msg_count;
436             tmp->new = msg_new;
437             tmp->msg_unread = msg_unread;
438             tmp->has_new = msg_new > 0;
439           }
440           if (tmp->newly_created &&
441               (sb.st_ctime != sb.st_mtime || sb.st_ctime != sb.st_atime))
442             tmp->newly_created = 0;
443           tmp->has_new = tmp->new > 0;
444         } else if (tmp->new > 0) {
445           /* keep current stats if !force and !$mail_check reached */
446           BuffyCount++;
447           tmp->has_new = 1;
448         }
449         break;
450
451       case M_MAILDIR:
452         /* only check on force or $mail_check reached */
453         if (force || (now - last1 >= BuffyTimeout)) {
454           snprintf (path, sizeof (path), "%s/new", tmp->path);
455           if ((dirp = opendir (path)) == NULL)
456           {
457             tmp->magic = 0;
458             break;
459           }
460           tmp->new = 0;
461           tmp->msg_unread = 0;
462           tmp->msgcount = 0;
463           while ((de = readdir (dirp)) != NULL)
464           {
465             char *p;
466             if (*de->d_name != '.' && 
467                 (!(p = strstr (de->d_name, ":2,")) || !strchr (p + 3, 'T')))
468             {
469               /* one new and undeleted message is enough */
470               if (tmp->new == 0)
471               {
472                 BuffyCount++;
473                 tmp->has_new = tmp->new = 1;
474                 if (SidebarWidth == 0 || !option (OPTMBOXPANE))
475                   /* if sidebar invisible -> done */
476                   break;
477               }
478               tmp->msgcount++;
479               tmp->msg_unread++;
480               tmp->new++;
481             }
482           }
483           closedir (dirp);
484           tmp->has_new = tmp->new > 0;
485
486           if (SidebarWidth > 0 && option (OPTMBOXPANE))
487           {
488             /* only count total mail if sidebar visible */
489             snprintf (path, sizeof (path), "%s/cur", tmp->path);
490             if ((dirp = opendir (path)) == NULL)
491             {
492               tmp->magic = 0;
493               break;
494             }
495             while ((de = readdir (dirp)) != NULL)
496             {
497               char *p;
498               if (*de->d_name != '.' && 
499                   (!(p = strstr (de->d_name, ":2,")) || !strchr (p + 3, 'T')))
500               {
501                 tmp->msgcount++;
502               }
503             }
504             closedir (dirp);
505           }
506         } else if (tmp->new > 0) {
507           /* keep current stats if !force and !$mail_check reached */
508           BuffyCount++;
509           tmp->has_new = 1;
510         }
511         break;
512
513       case M_MH:
514         /* only check on force or $mail_check reached */
515         if (force || (now - last1 >= BuffyTimeout)) {
516           tmp->new = 0;
517           tmp->msg_unread = 0;
518           if ((tmp->new = mh_buffy (tmp->path)) > 0)
519             BuffyCount++;
520           if (SidebarWidth > 0 && option (OPTMBOXPANE))
521           {
522             DIR *dp;
523             struct dirent *de;
524             if ((dp = opendir (path)) == NULL)
525               break;
526                 tmp->msgcount = 0;
527             while ((de = readdir (dp)))
528             {
529               if (mh_valid_message (de->d_name))
530               {
531                 tmp->msgcount++;
532                 tmp->msg_unread++;
533                 tmp->new++;
534               }
535             }
536             closedir (dp);
537           }
538           tmp->has_new = tmp->new > 0;
539         } else if (tmp->new > 0) {
540           /* keep current stats if !force and !$mail_check reached */
541           BuffyCount++;
542           tmp->has_new = 1;
543         }
544         break;
545
546 #ifdef USE_IMAP
547       case M_IMAP:
548         /* only check on force or $imap_mail_check reached */
549         if (force || (now - last2 >= ImapBuffyTimeout)) {
550           tmp->new = 0;
551           tmp->msg_unread = 0;
552           tmp->msgcount = imap_mailbox_check (tmp->path, 0);
553           if ((tmp->new = imap_mailbox_check (tmp->path, 1)) > 0) {
554             BuffyCount++;
555             tmp->has_new = tmp->new > 0;
556             tmp->msg_unread = tmp->new; /* for sidebar; wtf? */
557           }
558           else
559             tmp->new = 0;
560         } else if (tmp->new > 0) {
561           /* keep current stats if !force and !$imap_mail_check reached */
562           BuffyCount++;
563           tmp->has_new = 1;
564         }
565         break;
566 #endif
567
568 #ifdef USE_POP
569       case M_POP:
570         break;
571 #endif
572
573 #ifdef USE_NNTP
574       case M_NNTP:
575         break;
576 #endif
577       }
578     }
579 #ifdef BUFFY_SIZE
580     else if (Context && Context->path)
581       tmp->size = (long) sb.st_size;    /* update the size */
582 #endif
583
584     if (!tmp->new)
585       tmp->notified = 0;
586     else if (!tmp->notified)
587       BuffyNotify++;
588     tmp->has_new = tmp->new > 0;
589   }
590   if (BuffyCount > 0)
591     draw_sidebar (CurrentMenu);
592   return (BuffyCount);
593 }
594
595 int mutt_buffy_list (void)
596 {
597   BUFFY *tmp;
598   char path[_POSIX_PATH_MAX];
599   char buffylist[160];
600   int pos;
601   int first;
602
603   int have_unnotified = BuffyNotify;
604   
605   pos = 0;
606   first = 1;
607   buffylist[0] = 0;
608   pos += strlen (strncat (buffylist, _("New mail in "), sizeof (buffylist) - 1 - pos)); /* __STRNCAT_CHECKED__ */
609   for (tmp = Incoming; tmp; tmp = tmp->next)
610   {
611     /* Is there new mail in this mailbox? */
612     if (!tmp->new || (have_unnotified && tmp->notified))
613       continue;
614
615     strfcpy (path, tmp->path, sizeof (path));
616     mutt_pretty_mailbox (path);
617     
618     if (!first && pos + strlen (path) >= COLS - 7)
619       break;
620     
621     if (!first)
622       pos += strlen (strncat(buffylist + pos, ", ", sizeof(buffylist)-1-pos)); /* __STRNCAT_CHECKED__ */
623
624     /* Prepend an asterisk to mailboxes not already notified */
625     if (!tmp->notified)
626     {
627       /* pos += strlen (strncat(buffylist + pos, "*", sizeof(buffylist)-1-pos));  __STRNCAT_CHECKED__ */
628       tmp->notified = 1;
629       BuffyNotify--;
630     }
631     pos += strlen (strncat(buffylist + pos, path, sizeof(buffylist)-1-pos)); /* __STRNCAT_CHECKED__ */
632     first = 0;
633   }
634   if (!first && tmp)
635   {
636     strncat (buffylist + pos, ", ...", sizeof (buffylist) - 1 - pos); /* __STRNCAT_CHECKED__ */
637   }
638   if (!first)
639   {
640     /* on new mail: redraw sidebar */
641     draw_sidebar (CurrentMenu);
642     mutt_message ("%s", buffylist);
643     return (1);
644   }
645   /* there were no mailboxes needing to be notified, so clean up since 
646    * BuffyNotify has somehow gotten out of sync
647    */
648   BuffyNotify = 0;
649   return (0);
650 }
651
652 int mutt_buffy_notify (void)
653 {
654   if (mutt_buffy_check (0) && BuffyNotify)
655   {
656     return (mutt_buffy_list ());
657   }
658   return (0);
659 }
660
661 /* 
662  * mutt_buffy() -- incoming folders completion routine
663  *
664  * given a folder name, this routine gives the next incoming folder with new
665  * new mail.
666  */
667 void mutt_buffy (char *s, size_t slen)
668 {
669   int count;
670   BUFFY *tmp = Incoming;
671
672   mutt_expand_path (s, _POSIX_PATH_MAX);
673   switch (mutt_buffy_check (0))
674   {
675   case 0:
676
677     *s = '\0';
678     break;
679
680   case 1:
681
682     while (tmp && !tmp->new)
683       tmp = tmp->next;
684     if (!tmp)
685     {
686       *s = '\0';
687       mutt_buffy_check (1); /* buffy was wrong - resync things */
688       break;
689     }
690     strfcpy (s, tmp->path, slen);
691     mutt_pretty_mailbox (s);
692     break;
693
694   default:
695     
696     count = 0;
697     while (count < 3)
698     {
699       if (mutt_strcmp (s, tmp->path) == 0)
700         count++;
701       else if (count && tmp->new)
702         break;
703       tmp = tmp->next;
704       if (!tmp)
705       {
706         tmp = Incoming;
707         count++;
708       }
709     }
710     if (count >= 3)
711     {
712       *s = '\0';
713       mutt_buffy_check (1); /* buffy was wrong - resync things */
714       break;
715     }
716     strfcpy (s, tmp->path, slen);
717     mutt_pretty_mailbox (s);
718     break;
719   }
720 }