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