blob: 84d07f6a77422df497c9a50e9d962323c38f214f [file] [log] [blame]
Tor Norbye3a2425a2013-11-04 10:16:08 -08001#! /usr/bin/env python
2
3"""Read/write support for Maildir, mbox, MH, Babyl, and MMDF mailboxes."""
4
5# Notes for authors of new mailbox subclasses:
6#
7# Remember to fsync() changes to disk before closing a modified file
8# or returning from a flush() method. See functions _sync_flush() and
9# _sync_close().
10
11import sys
12import os
13import time
14import calendar
15import socket
16import errno
17import copy
18import email
19import email.Message
20import email.Generator
21import rfc822
22import StringIO
23try:
24 if sys.platform == 'os2emx':
25 # OS/2 EMX fcntl() not adequate
26 raise ImportError
27 import fcntl
28except ImportError:
29 fcntl = None
30
31__all__ = [ 'Mailbox', 'Maildir', 'mbox', 'MH', 'Babyl', 'MMDF',
32 'Message', 'MaildirMessage', 'mboxMessage', 'MHMessage',
33 'BabylMessage', 'MMDFMessage', 'UnixMailbox',
34 'PortableUnixMailbox', 'MmdfMailbox', 'MHMailbox', 'BabylMailbox' ]
35
36class Mailbox:
37 """A group of messages in a particular place."""
38
39 def __init__(self, path, factory=None, create=True):
40 """Initialize a Mailbox instance."""
41 self._path = os.path.abspath(os.path.expanduser(path))
42 self._factory = factory
43
44 def add(self, message):
45 """Add message and return assigned key."""
46 raise NotImplementedError('Method must be implemented by subclass')
47
48 def remove(self, key):
49 """Remove the keyed message; raise KeyError if it doesn't exist."""
50 raise NotImplementedError('Method must be implemented by subclass')
51
52 def __delitem__(self, key):
53 self.remove(key)
54
55 def discard(self, key):
56 """If the keyed message exists, remove it."""
57 try:
58 self.remove(key)
59 except KeyError:
60 pass
61
62 def __setitem__(self, key, message):
63 """Replace the keyed message; raise KeyError if it doesn't exist."""
64 raise NotImplementedError('Method must be implemented by subclass')
65
66 def get(self, key, default=None):
67 """Return the keyed message, or default if it doesn't exist."""
68 try:
69 return self.__getitem__(key)
70 except KeyError:
71 return default
72
73 def __getitem__(self, key):
74 """Return the keyed message; raise KeyError if it doesn't exist."""
75 if not self._factory:
76 return self.get_message(key)
77 else:
78 return self._factory(self.get_file(key))
79
80 def get_message(self, key):
81 """Return a Message representation or raise a KeyError."""
82 raise NotImplementedError('Method must be implemented by subclass')
83
84 def get_string(self, key):
85 """Return a string representation or raise a KeyError."""
86 raise NotImplementedError('Method must be implemented by subclass')
87
88 def get_file(self, key):
89 """Return a file-like representation or raise a KeyError."""
90 raise NotImplementedError('Method must be implemented by subclass')
91
92 def iterkeys(self):
93 """Return an iterator over keys."""
94 raise NotImplementedError('Method must be implemented by subclass')
95
96 def keys(self):
97 """Return a list of keys."""
98 return list(self.iterkeys())
99
100 def itervalues(self):
101 """Return an iterator over all messages."""
102 for key in self.iterkeys():
103 try:
104 value = self[key]
105 except KeyError:
106 continue
107 yield value
108
109 def __iter__(self):
110 return self.itervalues()
111
112 def values(self):
113 """Return a list of messages. Memory intensive."""
114 return list(self.itervalues())
115
116 def iteritems(self):
117 """Return an iterator over (key, message) tuples."""
118 for key in self.iterkeys():
119 try:
120 value = self[key]
121 except KeyError:
122 continue
123 yield (key, value)
124
125 def items(self):
126 """Return a list of (key, message) tuples. Memory intensive."""
127 return list(self.iteritems())
128
129 def has_key(self, key):
130 """Return True if the keyed message exists, False otherwise."""
131 raise NotImplementedError('Method must be implemented by subclass')
132
133 def __contains__(self, key):
134 return self.has_key(key)
135
136 def __len__(self):
137 """Return a count of messages in the mailbox."""
138 raise NotImplementedError('Method must be implemented by subclass')
139
140 def clear(self):
141 """Delete all messages."""
142 for key in self.iterkeys():
143 self.discard(key)
144
145 def pop(self, key, default=None):
146 """Delete the keyed message and return it, or default."""
147 try:
148 result = self[key]
149 except KeyError:
150 return default
151 self.discard(key)
152 return result
153
154 def popitem(self):
155 """Delete an arbitrary (key, message) pair and return it."""
156 for key in self.iterkeys():
157 return (key, self.pop(key)) # This is only run once.
158 else:
159 raise KeyError('No messages in mailbox')
160
161 def update(self, arg=None):
162 """Change the messages that correspond to certain keys."""
163 if hasattr(arg, 'iteritems'):
164 source = arg.iteritems()
165 elif hasattr(arg, 'items'):
166 source = arg.items()
167 else:
168 source = arg
169 bad_key = False
170 for key, message in source:
171 try:
172 self[key] = message
173 except KeyError:
174 bad_key = True
175 if bad_key:
176 raise KeyError('No message with key(s)')
177
178 def flush(self):
179 """Write any pending changes to the disk."""
180 raise NotImplementedError('Method must be implemented by subclass')
181
182 def lock(self):
183 """Lock the mailbox."""
184 raise NotImplementedError('Method must be implemented by subclass')
185
186 def unlock(self):
187 """Unlock the mailbox if it is locked."""
188 raise NotImplementedError('Method must be implemented by subclass')
189
190 def close(self):
191 """Flush and close the mailbox."""
192 raise NotImplementedError('Method must be implemented by subclass')
193
194 def _dump_message(self, message, target, mangle_from_=False):
195 # Most files are opened in binary mode to allow predictable seeking.
196 # To get native line endings on disk, the user-friendly \n line endings
197 # used in strings and by email.Message are translated here.
198 """Dump message contents to target file."""
199 if isinstance(message, email.Message.Message):
200 buffer = StringIO.StringIO()
201 gen = email.Generator.Generator(buffer, mangle_from_, 0)
202 gen.flatten(message)
203 buffer.seek(0)
204 target.write(buffer.read().replace('\n', os.linesep))
205 elif isinstance(message, str):
206 if mangle_from_:
207 message = message.replace('\nFrom ', '\n>From ')
208 message = message.replace('\n', os.linesep)
209 target.write(message)
210 elif hasattr(message, 'read'):
211 while True:
212 line = message.readline()
213 if line == '':
214 break
215 if mangle_from_ and line.startswith('From '):
216 line = '>From ' + line[5:]
217 line = line.replace('\n', os.linesep)
218 target.write(line)
219 else:
220 raise TypeError('Invalid message type: %s' % type(message))
221
222
223class Maildir(Mailbox):
224 """A qmail-style Maildir mailbox."""
225
226 colon = ':'
227
228 def __init__(self, dirname, factory=rfc822.Message, create=True):
229 """Initialize a Maildir instance."""
230 Mailbox.__init__(self, dirname, factory, create)
231 if not os.path.exists(self._path):
232 if create:
233 os.mkdir(self._path, 0700)
234 os.mkdir(os.path.join(self._path, 'tmp'), 0700)
235 os.mkdir(os.path.join(self._path, 'new'), 0700)
236 os.mkdir(os.path.join(self._path, 'cur'), 0700)
237 else:
238 raise NoSuchMailboxError(self._path)
239 self._toc = {}
240
241 def add(self, message):
242 """Add message and return assigned key."""
243 tmp_file = self._create_tmp()
244 try:
245 self._dump_message(message, tmp_file)
246 finally:
247 _sync_close(tmp_file)
248 if isinstance(message, MaildirMessage):
249 subdir = message.get_subdir()
250 suffix = self.colon + message.get_info()
251 if suffix == self.colon:
252 suffix = ''
253 else:
254 subdir = 'new'
255 suffix = ''
256 uniq = os.path.basename(tmp_file.name).split(self.colon)[0]
257 dest = os.path.join(self._path, subdir, uniq + suffix)
258 try:
259 if hasattr(os, 'link'):
260 os.link(tmp_file.name, dest)
261 os.remove(tmp_file.name)
262 else:
263 os.rename(tmp_file.name, dest)
264 except OSError, e:
265 os.remove(tmp_file.name)
266 if e.errno == errno.EEXIST:
267 raise ExternalClashError('Name clash with existing message: %s'
268 % dest)
269 else:
270 raise
271 if isinstance(message, MaildirMessage):
272 os.utime(dest, (os.path.getatime(dest), message.get_date()))
273 return uniq
274
275 def remove(self, key):
276 """Remove the keyed message; raise KeyError if it doesn't exist."""
277 os.remove(os.path.join(self._path, self._lookup(key)))
278
279 def discard(self, key):
280 """If the keyed message exists, remove it."""
281 # This overrides an inapplicable implementation in the superclass.
282 try:
283 self.remove(key)
284 except KeyError:
285 pass
286 except OSError, e:
287 if e.errno != errno.ENOENT:
288 raise
289
290 def __setitem__(self, key, message):
291 """Replace the keyed message; raise KeyError if it doesn't exist."""
292 old_subpath = self._lookup(key)
293 temp_key = self.add(message)
294 temp_subpath = self._lookup(temp_key)
295 if isinstance(message, MaildirMessage):
296 # temp's subdir and suffix were specified by message.
297 dominant_subpath = temp_subpath
298 else:
299 # temp's subdir and suffix were defaults from add().
300 dominant_subpath = old_subpath
301 subdir = os.path.dirname(dominant_subpath)
302 if self.colon in dominant_subpath:
303 suffix = self.colon + dominant_subpath.split(self.colon)[-1]
304 else:
305 suffix = ''
306 self.discard(key)
307 new_path = os.path.join(self._path, subdir, key + suffix)
308 os.rename(os.path.join(self._path, temp_subpath), new_path)
309 if isinstance(message, MaildirMessage):
310 os.utime(new_path, (os.path.getatime(new_path),
311 message.get_date()))
312
313 def get_message(self, key):
314 """Return a Message representation or raise a KeyError."""
315 subpath = self._lookup(key)
316 f = open(os.path.join(self._path, subpath), 'r')
317 try:
318 if self._factory:
319 msg = self._factory(f)
320 else:
321 msg = MaildirMessage(f)
322 finally:
323 f.close()
324 subdir, name = os.path.split(subpath)
325 msg.set_subdir(subdir)
326 if self.colon in name:
327 msg.set_info(name.split(self.colon)[-1])
328 msg.set_date(os.path.getmtime(os.path.join(self._path, subpath)))
329 return msg
330
331 def get_string(self, key):
332 """Return a string representation or raise a KeyError."""
333 f = open(os.path.join(self._path, self._lookup(key)), 'r')
334 try:
335 return f.read()
336 finally:
337 f.close()
338
339 def get_file(self, key):
340 """Return a file-like representation or raise a KeyError."""
341 f = open(os.path.join(self._path, self._lookup(key)), 'rb')
342 return _ProxyFile(f)
343
344 def iterkeys(self):
345 """Return an iterator over keys."""
346 self._refresh()
347 for key in self._toc:
348 try:
349 self._lookup(key)
350 except KeyError:
351 continue
352 yield key
353
354 def has_key(self, key):
355 """Return True if the keyed message exists, False otherwise."""
356 self._refresh()
357 return key in self._toc
358
359 def __len__(self):
360 """Return a count of messages in the mailbox."""
361 self._refresh()
362 return len(self._toc)
363
364 def flush(self):
365 """Write any pending changes to disk."""
366 return # Maildir changes are always written immediately.
367
368 def lock(self):
369 """Lock the mailbox."""
370 return
371
372 def unlock(self):
373 """Unlock the mailbox if it is locked."""
374 return
375
376 def close(self):
377 """Flush and close the mailbox."""
378 return
379
380 def list_folders(self):
381 """Return a list of folder names."""
382 result = []
383 for entry in os.listdir(self._path):
384 if len(entry) > 1 and entry[0] == '.' and \
385 os.path.isdir(os.path.join(self._path, entry)):
386 result.append(entry[1:])
387 return result
388
389 def get_folder(self, folder):
390 """Return a Maildir instance for the named folder."""
391 return Maildir(os.path.join(self._path, '.' + folder),
392 factory=self._factory,
393 create=False)
394
395 def add_folder(self, folder):
396 """Create a folder and return a Maildir instance representing it."""
397 path = os.path.join(self._path, '.' + folder)
398 result = Maildir(path, factory=self._factory)
399 maildirfolder_path = os.path.join(path, 'maildirfolder')
400 if not os.path.exists(maildirfolder_path):
401 os.close(os.open(maildirfolder_path, os.O_CREAT | os.O_WRONLY))
402 return result
403
404 def remove_folder(self, folder):
405 """Delete the named folder, which must be empty."""
406 path = os.path.join(self._path, '.' + folder)
407 for entry in os.listdir(os.path.join(path, 'new')) + \
408 os.listdir(os.path.join(path, 'cur')):
409 if len(entry) < 1 or entry[0] != '.':
410 raise NotEmptyError('Folder contains message(s): %s' % folder)
411 for entry in os.listdir(path):
412 if entry != 'new' and entry != 'cur' and entry != 'tmp' and \
413 os.path.isdir(os.path.join(path, entry)):
414 raise NotEmptyError("Folder contains subdirectory '%s': %s" %
415 (folder, entry))
416 for root, dirs, files in os.walk(path, topdown=False):
417 for entry in files:
418 os.remove(os.path.join(root, entry))
419 for entry in dirs:
420 os.rmdir(os.path.join(root, entry))
421 os.rmdir(path)
422
423 def clean(self):
424 """Delete old files in "tmp"."""
425 now = time.time()
426 for entry in os.listdir(os.path.join(self._path, 'tmp')):
427 path = os.path.join(self._path, 'tmp', entry)
428 if now - os.path.getatime(path) > 129600: # 60 * 60 * 36
429 os.remove(path)
430
431 _count = 1 # This is used to generate unique file names.
432
433 def _create_tmp(self):
434 """Create a file in the tmp subdirectory and open and return it."""
435 now = time.time()
436 hostname = socket.gethostname()
437 if '/' in hostname:
438 hostname = hostname.replace('/', r'\057')
439 if ':' in hostname:
440 hostname = hostname.replace(':', r'\072')
441 uniq = "%s.M%sP%sQ%s.%s" % (int(now), int(now % 1 * 1e6), os.getpid(),
442 Maildir._count, hostname)
443 path = os.path.join(self._path, 'tmp', uniq)
444 try:
445 os.stat(path)
446 except OSError, e:
447 if e.errno == errno.ENOENT:
448 Maildir._count += 1
449 try:
450 return _create_carefully(path)
451 except OSError, e:
452 if e.errno != errno.EEXIST:
453 raise
454 else:
455 raise
456
457 # Fall through to here if stat succeeded or open raised EEXIST.
458 raise ExternalClashError('Name clash prevented file creation: %s' %
459 path)
460
461 def _refresh(self):
462 """Update table of contents mapping."""
463 self._toc = {}
464 for subdir in ('new', 'cur'):
465 subdir_path = os.path.join(self._path, subdir)
466 for entry in os.listdir(subdir_path):
467 p = os.path.join(subdir_path, entry)
468 if os.path.isdir(p):
469 continue
470 uniq = entry.split(self.colon)[0]
471 self._toc[uniq] = os.path.join(subdir, entry)
472
473 def _lookup(self, key):
474 """Use TOC to return subpath for given key, or raise a KeyError."""
475 try:
476 if os.path.exists(os.path.join(self._path, self._toc[key])):
477 return self._toc[key]
478 except KeyError:
479 pass
480 self._refresh()
481 try:
482 return self._toc[key]
483 except KeyError:
484 raise KeyError('No message with key: %s' % key)
485
486 # This method is for backward compatibility only.
487 def next(self):
488 """Return the next message in a one-time iteration."""
489 if not hasattr(self, '_onetime_keys'):
490 self._onetime_keys = self.iterkeys()
491 while True:
492 try:
493 return self[self._onetime_keys.next()]
494 except StopIteration:
495 return None
496 except KeyError:
497 continue
498
499
500class _singlefileMailbox(Mailbox):
501 """A single-file mailbox."""
502
503 def __init__(self, path, factory=None, create=True):
504 """Initialize a single-file mailbox."""
505 Mailbox.__init__(self, path, factory, create)
506 try:
507 f = open(self._path, 'rb+')
508 except IOError, e:
509 if e.errno == errno.ENOENT:
510 if create:
511 f = open(self._path, 'wb+')
512 else:
513 raise NoSuchMailboxError(self._path)
514 elif e.errno == errno.EACCES:
515 f = open(self._path, 'rb')
516 else:
517 raise
518 self._file = f
519 self._toc = None
520 self._next_key = 0
521 self._pending = False # No changes require rewriting the file.
522 self._locked = False
523
524 def add(self, message):
525 """Add message and return assigned key."""
526 self._lookup()
527 self._toc[self._next_key] = self._append_message(message)
528 self._next_key += 1
529 self._pending = True
530 return self._next_key - 1
531
532 def remove(self, key):
533 """Remove the keyed message; raise KeyError if it doesn't exist."""
534 self._lookup(key)
535 del self._toc[key]
536 self._pending = True
537
538 def __setitem__(self, key, message):
539 """Replace the keyed message; raise KeyError if it doesn't exist."""
540 self._lookup(key)
541 self._toc[key] = self._append_message(message)
542 self._pending = True
543
544 def iterkeys(self):
545 """Return an iterator over keys."""
546 self._lookup()
547 for key in self._toc.keys():
548 yield key
549
550 def has_key(self, key):
551 """Return True if the keyed message exists, False otherwise."""
552 self._lookup()
553 return key in self._toc
554
555 def __len__(self):
556 """Return a count of messages in the mailbox."""
557 self._lookup()
558 return len(self._toc)
559
560 def lock(self):
561 """Lock the mailbox."""
562 if not self._locked:
563 _lock_file(self._file)
564 self._locked = True
565
566 def unlock(self):
567 """Unlock the mailbox if it is locked."""
568 if self._locked:
569 _unlock_file(self._file)
570 self._locked = False
571
572 def flush(self):
573 """Write any pending changes to disk."""
574 if not self._pending:
575 return
576 self._lookup()
577 new_file = _create_temporary(self._path)
578 try:
579 new_toc = {}
580 self._pre_mailbox_hook(new_file)
581 for key in sorted(self._toc.keys()):
582 start, stop = self._toc[key]
583 self._file.seek(start)
584 self._pre_message_hook(new_file)
585 new_start = new_file.tell()
586 while True:
587 buffer = self._file.read(min(4096,
588 stop - self._file.tell()))
589 if buffer == '':
590 break
591 new_file.write(buffer)
592 new_toc[key] = (new_start, new_file.tell())
593 self._post_message_hook(new_file)
594 except:
595 new_file.close()
596 os.remove(new_file.name)
597 raise
598 _sync_close(new_file)
599 # self._file is about to get replaced, so no need to sync.
600 self._file.close()
601 try:
602 os.rename(new_file.name, self._path)
603 except OSError, e:
604 if e.errno == errno.EEXIST or \
605 (os.name == 'os2' and e.errno == errno.EACCES):
606 os.remove(self._path)
607 os.rename(new_file.name, self._path)
608 else:
609 raise
610 self._file = open(self._path, 'rb+')
611 self._toc = new_toc
612 self._pending = False
613 if self._locked:
614 _lock_file(self._file, dotlock=False)
615
616 def _pre_mailbox_hook(self, f):
617 """Called before writing the mailbox to file f."""
618 return
619
620 def _pre_message_hook(self, f):
621 """Called before writing each message to file f."""
622 return
623
624 def _post_message_hook(self, f):
625 """Called after writing each message to file f."""
626 return
627
628 def close(self):
629 """Flush and close the mailbox."""
630 self.flush()
631 if self._locked:
632 self.unlock()
633 self._file.close() # Sync has been done by self.flush() above.
634
635 def _lookup(self, key=None):
636 """Return (start, stop) or raise KeyError."""
637 if self._toc is None:
638 self._generate_toc()
639 if key is not None:
640 try:
641 return self._toc[key]
642 except KeyError:
643 raise KeyError('No message with key: %s' % key)
644
645 def _append_message(self, message):
646 """Append message to mailbox and return (start, stop) offsets."""
647 self._file.seek(0, 2)
648 self._pre_message_hook(self._file)
649 offsets = self._install_message(message)
650 self._post_message_hook(self._file)
651 self._file.flush()
652 return offsets
653
654
655
656class _mboxMMDF(_singlefileMailbox):
657 """An mbox or MMDF mailbox."""
658
659 _mangle_from_ = True
660
661 def get_message(self, key):
662 """Return a Message representation or raise a KeyError."""
663 start, stop = self._lookup(key)
664 self._file.seek(start)
665 from_line = self._file.readline().replace(os.linesep, '')
666 string = self._file.read(stop - self._file.tell())
667 msg = self._message_factory(string.replace(os.linesep, '\n'))
668 msg.set_from(from_line[5:])
669 return msg
670
671 def get_string(self, key, from_=False):
672 """Return a string representation or raise a KeyError."""
673 start, stop = self._lookup(key)
674 self._file.seek(start)
675 if not from_:
676 self._file.readline()
677 string = self._file.read(stop - self._file.tell())
678 return string.replace(os.linesep, '\n')
679
680 def get_file(self, key, from_=False):
681 """Return a file-like representation or raise a KeyError."""
682 start, stop = self._lookup(key)
683 self._file.seek(start)
684 if not from_:
685 self._file.readline()
686 return _PartialFile(self._file, self._file.tell(), stop)
687
688 def _install_message(self, message):
689 """Format a message and blindly write to self._file."""
690 from_line = None
691 if isinstance(message, str) and message.startswith('From '):
692 newline = message.find('\n')
693 if newline != -1:
694 from_line = message[:newline]
695 message = message[newline + 1:]
696 else:
697 from_line = message
698 message = ''
699 elif isinstance(message, _mboxMMDFMessage):
700 from_line = 'From ' + message.get_from()
701 elif isinstance(message, email.Message.Message):
702 from_line = message.get_unixfrom() # May be None.
703 if from_line is None:
704 from_line = 'From MAILER-DAEMON %s' % time.asctime(time.gmtime())
705 start = self._file.tell()
706 self._file.write(from_line + os.linesep)
707 self._dump_message(message, self._file, self._mangle_from_)
708 stop = self._file.tell()
709 return (start, stop)
710
711
712class mbox(_mboxMMDF):
713 """A classic mbox mailbox."""
714
715 _mangle_from_ = True
716
717 def __init__(self, path, factory=None, create=True):
718 """Initialize an mbox mailbox."""
719 self._message_factory = mboxMessage
720 _mboxMMDF.__init__(self, path, factory, create)
721
722 def _pre_message_hook(self, f):
723 """Called before writing each message to file f."""
724 if f.tell() != 0:
725 f.write(os.linesep)
726
727 def _generate_toc(self):
728 """Generate key-to-(start, stop) table of contents."""
729 starts, stops = [], []
730 self._file.seek(0)
731 while True:
732 line_pos = self._file.tell()
733 line = self._file.readline()
734 if line.startswith('From '):
735 if len(stops) < len(starts):
736 stops.append(line_pos - len(os.linesep))
737 starts.append(line_pos)
738 elif line == '':
739 stops.append(line_pos)
740 break
741 self._toc = dict(enumerate(zip(starts, stops)))
742 self._next_key = len(self._toc)
743
744
745class MMDF(_mboxMMDF):
746 """An MMDF mailbox."""
747
748 def __init__(self, path, factory=None, create=True):
749 """Initialize an MMDF mailbox."""
750 self._message_factory = MMDFMessage
751 _mboxMMDF.__init__(self, path, factory, create)
752
753 def _pre_message_hook(self, f):
754 """Called before writing each message to file f."""
755 f.write('\001\001\001\001' + os.linesep)
756
757 def _post_message_hook(self, f):
758 """Called after writing each message to file f."""
759 f.write(os.linesep + '\001\001\001\001' + os.linesep)
760
761 def _generate_toc(self):
762 """Generate key-to-(start, stop) table of contents."""
763 starts, stops = [], []
764 self._file.seek(0)
765 next_pos = 0
766 while True:
767 line_pos = next_pos
768 line = self._file.readline()
769 next_pos = self._file.tell()
770 if line.startswith('\001\001\001\001' + os.linesep):
771 starts.append(next_pos)
772 while True:
773 line_pos = next_pos
774 line = self._file.readline()
775 next_pos = self._file.tell()
776 if line == '\001\001\001\001' + os.linesep:
777 stops.append(line_pos - len(os.linesep))
778 break
779 elif line == '':
780 stops.append(line_pos)
781 break
782 elif line == '':
783 break
784 self._toc = dict(enumerate(zip(starts, stops)))
785 self._next_key = len(self._toc)
786
787
788class MH(Mailbox):
789 """An MH mailbox."""
790
791 def __init__(self, path, factory=None, create=True):
792 """Initialize an MH instance."""
793 Mailbox.__init__(self, path, factory, create)
794 if not os.path.exists(self._path):
795 if create:
796 os.mkdir(self._path, 0700)
797 os.close(os.open(os.path.join(self._path, '.mh_sequences'),
798 os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0600))
799 else:
800 raise NoSuchMailboxError(self._path)
801 self._locked = False
802
803 def add(self, message):
804 """Add message and return assigned key."""
805 keys = self.keys()
806 if len(keys) == 0:
807 new_key = 1
808 else:
809 new_key = max(keys) + 1
810 new_path = os.path.join(self._path, str(new_key))
811 f = _create_carefully(new_path)
812 try:
813 if self._locked:
814 _lock_file(f)
815 try:
816 self._dump_message(message, f)
817 if isinstance(message, MHMessage):
818 self._dump_sequences(message, new_key)
819 finally:
820 if self._locked:
821 _unlock_file(f)
822 finally:
823 _sync_close(f)
824 return new_key
825
826 def remove(self, key):
827 """Remove the keyed message; raise KeyError if it doesn't exist."""
828 path = os.path.join(self._path, str(key))
829 try:
830 f = open(path, 'rb+')
831 except IOError, e:
832 if e.errno == errno.ENOENT:
833 raise KeyError('No message with key: %s' % key)
834 else:
835 raise
836 try:
837 if self._locked:
838 _lock_file(f)
839 try:
840 f.close()
841 os.remove(os.path.join(self._path, str(key)))
842 finally:
843 if self._locked:
844 _unlock_file(f)
845 finally:
846 f.close()
847
848 def __setitem__(self, key, message):
849 """Replace the keyed message; raise KeyError if it doesn't exist."""
850 path = os.path.join(self._path, str(key))
851 try:
852 f = open(path, 'rb+')
853 except IOError, e:
854 if e.errno == errno.ENOENT:
855 raise KeyError('No message with key: %s' % key)
856 else:
857 raise
858 try:
859 if self._locked:
860 _lock_file(f)
861 try:
862 os.close(os.open(path, os.O_WRONLY | os.O_TRUNC))
863 self._dump_message(message, f)
864 if isinstance(message, MHMessage):
865 self._dump_sequences(message, key)
866 finally:
867 if self._locked:
868 _unlock_file(f)
869 finally:
870 _sync_close(f)
871
872 def get_message(self, key):
873 """Return a Message representation or raise a KeyError."""
874 try:
875 if self._locked:
876 f = open(os.path.join(self._path, str(key)), 'r+')
877 else:
878 f = open(os.path.join(self._path, str(key)), 'r')
879 except IOError, e:
880 if e.errno == errno.ENOENT:
881 raise KeyError('No message with key: %s' % key)
882 else:
883 raise
884 try:
885 if self._locked:
886 _lock_file(f)
887 try:
888 msg = MHMessage(f)
889 finally:
890 if self._locked:
891 _unlock_file(f)
892 finally:
893 f.close()
894 for name, key_list in self.get_sequences():
895 if key in key_list:
896 msg.add_sequence(name)
897 return msg
898
899 def get_string(self, key):
900 """Return a string representation or raise a KeyError."""
901 try:
902 if self._locked:
903 f = open(os.path.join(self._path, str(key)), 'r+')
904 else:
905 f = open(os.path.join(self._path, str(key)), 'r')
906 except IOError, e:
907 if e.errno == errno.ENOENT:
908 raise KeyError('No message with key: %s' % key)
909 else:
910 raise
911 try:
912 if self._locked:
913 _lock_file(f)
914 try:
915 return f.read()
916 finally:
917 if self._locked:
918 _unlock_file(f)
919 finally:
920 f.close()
921
922 def get_file(self, key):
923 """Return a file-like representation or raise a KeyError."""
924 try:
925 f = open(os.path.join(self._path, str(key)), 'rb')
926 except IOError, e:
927 if e.errno == errno.ENOENT:
928 raise KeyError('No message with key: %s' % key)
929 else:
930 raise
931 return _ProxyFile(f)
932
933 def iterkeys(self):
934 """Return an iterator over keys."""
935 return iter(sorted(int(entry) for entry in os.listdir(self._path)
936 if entry.isdigit()))
937
938 def has_key(self, key):
939 """Return True if the keyed message exists, False otherwise."""
940 return os.path.exists(os.path.join(self._path, str(key)))
941
942 def __len__(self):
943 """Return a count of messages in the mailbox."""
944 return len(list(self.iterkeys()))
945
946 def lock(self):
947 """Lock the mailbox."""
948 if not self._locked:
949 self._file = open(os.path.join(self._path, '.mh_sequences'), 'rb+')
950 _lock_file(self._file)
951 self._locked = True
952
953 def unlock(self):
954 """Unlock the mailbox if it is locked."""
955 if self._locked:
956 _unlock_file(self._file)
957 _sync_close(self._file)
958 self._file.close()
959 del self._file
960 self._locked = False
961
962 def flush(self):
963 """Write any pending changes to the disk."""
964 return
965
966 def close(self):
967 """Flush and close the mailbox."""
968 if self._locked:
969 self.unlock()
970
971 def list_folders(self):
972 """Return a list of folder names."""
973 result = []
974 for entry in os.listdir(self._path):
975 if os.path.isdir(os.path.join(self._path, entry)):
976 result.append(entry)
977 return result
978
979 def get_folder(self, folder):
980 """Return an MH instance for the named folder."""
981 return MH(os.path.join(self._path, folder),
982 factory=self._factory, create=False)
983
984 def add_folder(self, folder):
985 """Create a folder and return an MH instance representing it."""
986 return MH(os.path.join(self._path, folder),
987 factory=self._factory)
988
989 def remove_folder(self, folder):
990 """Delete the named folder, which must be empty."""
991 path = os.path.join(self._path, folder)
992 entries = os.listdir(path)
993 if entries == ['.mh_sequences']:
994 os.remove(os.path.join(path, '.mh_sequences'))
995 elif entries == []:
996 pass
997 else:
998 raise NotEmptyError('Folder not empty: %s' % self._path)
999 os.rmdir(path)
1000
1001 def get_sequences(self):
1002 """Return a name-to-key-list dictionary to define each sequence."""
1003 results = {}
1004 f = open(os.path.join(self._path, '.mh_sequences'), 'r')
1005 try:
1006 all_keys = set(self.keys())
1007 for line in f:
1008 try:
1009 name, contents = line.split(':')
1010 keys = set()
1011 for spec in contents.split():
1012 if spec.isdigit():
1013 keys.add(int(spec))
1014 else:
1015 start, stop = (int(x) for x in spec.split('-'))
1016 keys.update(range(start, stop + 1))
1017 results[name] = [key for key in sorted(keys) \
1018 if key in all_keys]
1019 if len(results[name]) == 0:
1020 del results[name]
1021 except ValueError:
1022 raise FormatError('Invalid sequence specification: %s' %
1023 line.rstrip())
1024 finally:
1025 f.close()
1026 return results
1027
1028 def set_sequences(self, sequences):
1029 """Set sequences using the given name-to-key-list dictionary."""
1030 f = open(os.path.join(self._path, '.mh_sequences'), 'r+')
1031 try:
1032 os.close(os.open(f.name, os.O_WRONLY | os.O_TRUNC))
1033 for name, keys in sequences.iteritems():
1034 if len(keys) == 0:
1035 continue
1036 f.write('%s:' % name)
1037 prev = None
1038 completing = False
1039 for key in sorted(set(keys)):
1040 if key - 1 == prev:
1041 if not completing:
1042 completing = True
1043 f.write('-')
1044 elif completing:
1045 completing = False
1046 f.write('%s %s' % (prev, key))
1047 else:
1048 f.write(' %s' % key)
1049 prev = key
1050 if completing:
1051 f.write(str(prev) + '\n')
1052 else:
1053 f.write('\n')
1054 finally:
1055 _sync_close(f)
1056
1057 def pack(self):
1058 """Re-name messages to eliminate numbering gaps. Invalidates keys."""
1059 sequences = self.get_sequences()
1060 prev = 0
1061 changes = []
1062 for key in self.iterkeys():
1063 if key - 1 != prev:
1064 changes.append((key, prev + 1))
1065 if hasattr(os, 'link'):
1066 os.link(os.path.join(self._path, str(key)),
1067 os.path.join(self._path, str(prev + 1)))
1068 os.unlink(os.path.join(self._path, str(key)))
1069 else:
1070 os.rename(os.path.join(self._path, str(key)),
1071 os.path.join(self._path, str(prev + 1)))
1072 prev += 1
1073 self._next_key = prev + 1
1074 if len(changes) == 0:
1075 return
1076 for name, key_list in sequences.items():
1077 for old, new in changes:
1078 if old in key_list:
1079 key_list[key_list.index(old)] = new
1080 self.set_sequences(sequences)
1081
1082 def _dump_sequences(self, message, key):
1083 """Inspect a new MHMessage and update sequences appropriately."""
1084 pending_sequences = message.get_sequences()
1085 all_sequences = self.get_sequences()
1086 for name, key_list in all_sequences.iteritems():
1087 if name in pending_sequences:
1088 key_list.append(key)
1089 elif key in key_list:
1090 del key_list[key_list.index(key)]
1091 for sequence in pending_sequences:
1092 if sequence not in all_sequences:
1093 all_sequences[sequence] = [key]
1094 self.set_sequences(all_sequences)
1095
1096
1097class Babyl(_singlefileMailbox):
1098 """An Rmail-style Babyl mailbox."""
1099
1100 _special_labels = frozenset(('unseen', 'deleted', 'filed', 'answered',
1101 'forwarded', 'edited', 'resent'))
1102
1103 def __init__(self, path, factory=None, create=True):
1104 """Initialize a Babyl mailbox."""
1105 _singlefileMailbox.__init__(self, path, factory, create)
1106 self._labels = {}
1107
1108 def add(self, message):
1109 """Add message and return assigned key."""
1110 key = _singlefileMailbox.add(self, message)
1111 if isinstance(message, BabylMessage):
1112 self._labels[key] = message.get_labels()
1113 return key
1114
1115 def remove(self, key):
1116 """Remove the keyed message; raise KeyError if it doesn't exist."""
1117 _singlefileMailbox.remove(self, key)
1118 if key in self._labels:
1119 del self._labels[key]
1120
1121 def __setitem__(self, key, message):
1122 """Replace the keyed message; raise KeyError if it doesn't exist."""
1123 _singlefileMailbox.__setitem__(self, key, message)
1124 if isinstance(message, BabylMessage):
1125 self._labels[key] = message.get_labels()
1126
1127 def get_message(self, key):
1128 """Return a Message representation or raise a KeyError."""
1129 start, stop = self._lookup(key)
1130 self._file.seek(start)
1131 self._file.readline() # Skip '1,' line specifying labels.
1132 original_headers = StringIO.StringIO()
1133 while True:
1134 line = self._file.readline()
1135 if line == '*** EOOH ***' + os.linesep or line == '':
1136 break
1137 original_headers.write(line.replace(os.linesep, '\n'))
1138 visible_headers = StringIO.StringIO()
1139 while True:
1140 line = self._file.readline()
1141 if line == os.linesep or line == '':
1142 break
1143 visible_headers.write(line.replace(os.linesep, '\n'))
1144 body = self._file.read(stop - self._file.tell()).replace(os.linesep,
1145 '\n')
1146 msg = BabylMessage(original_headers.getvalue() + body)
1147 msg.set_visible(visible_headers.getvalue())
1148 if key in self._labels:
1149 msg.set_labels(self._labels[key])
1150 return msg
1151
1152 def get_string(self, key):
1153 """Return a string representation or raise a KeyError."""
1154 start, stop = self._lookup(key)
1155 self._file.seek(start)
1156 self._file.readline() # Skip '1,' line specifying labels.
1157 original_headers = StringIO.StringIO()
1158 while True:
1159 line = self._file.readline()
1160 if line == '*** EOOH ***' + os.linesep or line == '':
1161 break
1162 original_headers.write(line.replace(os.linesep, '\n'))
1163 while True:
1164 line = self._file.readline()
1165 if line == os.linesep or line == '':
1166 break
1167 return original_headers.getvalue() + \
1168 self._file.read(stop - self._file.tell()).replace(os.linesep,
1169 '\n')
1170
1171 def get_file(self, key):
1172 """Return a file-like representation or raise a KeyError."""
1173 return StringIO.StringIO(self.get_string(key).replace('\n',
1174 os.linesep))
1175
1176 def get_labels(self):
1177 """Return a list of user-defined labels in the mailbox."""
1178 self._lookup()
1179 labels = set()
1180 for label_list in self._labels.values():
1181 labels.update(label_list)
1182 labels.difference_update(self._special_labels)
1183 return list(labels)
1184
1185 def _generate_toc(self):
1186 """Generate key-to-(start, stop) table of contents."""
1187 starts, stops = [], []
1188 self._file.seek(0)
1189 next_pos = 0
1190 label_lists = []
1191 while True:
1192 line_pos = next_pos
1193 line = self._file.readline()
1194 next_pos = self._file.tell()
1195 if line == '\037\014' + os.linesep:
1196 if len(stops) < len(starts):
1197 stops.append(line_pos - len(os.linesep))
1198 starts.append(next_pos)
1199 labels = [label.strip() for label
1200 in self._file.readline()[1:].split(',')
1201 if label.strip() != '']
1202 label_lists.append(labels)
1203 elif line == '\037' or line == '\037' + os.linesep:
1204 if len(stops) < len(starts):
1205 stops.append(line_pos - len(os.linesep))
1206 elif line == '':
1207 stops.append(line_pos - len(os.linesep))
1208 break
1209 self._toc = dict(enumerate(zip(starts, stops)))
1210 self._labels = dict(enumerate(label_lists))
1211 self._next_key = len(self._toc)
1212
1213 def _pre_mailbox_hook(self, f):
1214 """Called before writing the mailbox to file f."""
1215 f.write('BABYL OPTIONS:%sVersion: 5%sLabels:%s%s\037' %
1216 (os.linesep, os.linesep, ','.join(self.get_labels()),
1217 os.linesep))
1218
1219 def _pre_message_hook(self, f):
1220 """Called before writing each message to file f."""
1221 f.write('\014' + os.linesep)
1222
1223 def _post_message_hook(self, f):
1224 """Called after writing each message to file f."""
1225 f.write(os.linesep + '\037')
1226
1227 def _install_message(self, message):
1228 """Write message contents and return (start, stop)."""
1229 start = self._file.tell()
1230 if isinstance(message, BabylMessage):
1231 special_labels = []
1232 labels = []
1233 for label in message.get_labels():
1234 if label in self._special_labels:
1235 special_labels.append(label)
1236 else:
1237 labels.append(label)
1238 self._file.write('1')
1239 for label in special_labels:
1240 self._file.write(', ' + label)
1241 self._file.write(',,')
1242 for label in labels:
1243 self._file.write(' ' + label + ',')
1244 self._file.write(os.linesep)
1245 else:
1246 self._file.write('1,,' + os.linesep)
1247 if isinstance(message, email.Message.Message):
1248 orig_buffer = StringIO.StringIO()
1249 orig_generator = email.Generator.Generator(orig_buffer, False, 0)
1250 orig_generator.flatten(message)
1251 orig_buffer.seek(0)
1252 while True:
1253 line = orig_buffer.readline()
1254 self._file.write(line.replace('\n', os.linesep))
1255 if line == '\n' or line == '':
1256 break
1257 self._file.write('*** EOOH ***' + os.linesep)
1258 if isinstance(message, BabylMessage):
1259 vis_buffer = StringIO.StringIO()
1260 vis_generator = email.Generator.Generator(vis_buffer, False, 0)
1261 vis_generator.flatten(message.get_visible())
1262 while True:
1263 line = vis_buffer.readline()
1264 self._file.write(line.replace('\n', os.linesep))
1265 if line == '\n' or line == '':
1266 break
1267 else:
1268 orig_buffer.seek(0)
1269 while True:
1270 line = orig_buffer.readline()
1271 self._file.write(line.replace('\n', os.linesep))
1272 if line == '\n' or line == '':
1273 break
1274 while True:
1275 buffer = orig_buffer.read(4096) # Buffer size is arbitrary.
1276 if buffer == '':
1277 break
1278 self._file.write(buffer.replace('\n', os.linesep))
1279 elif isinstance(message, str):
1280 body_start = message.find('\n\n') + 2
1281 if body_start - 2 != -1:
1282 self._file.write(message[:body_start].replace('\n',
1283 os.linesep))
1284 self._file.write('*** EOOH ***' + os.linesep)
1285 self._file.write(message[:body_start].replace('\n',
1286 os.linesep))
1287 self._file.write(message[body_start:].replace('\n',
1288 os.linesep))
1289 else:
1290 self._file.write('*** EOOH ***' + os.linesep + os.linesep)
1291 self._file.write(message.replace('\n', os.linesep))
1292 elif hasattr(message, 'readline'):
1293 original_pos = message.tell()
1294 first_pass = True
1295 while True:
1296 line = message.readline()
1297 self._file.write(line.replace('\n', os.linesep))
1298 if line == '\n' or line == '':
1299 self._file.write('*** EOOH ***' + os.linesep)
1300 if first_pass:
1301 first_pass = False
1302 message.seek(original_pos)
1303 else:
1304 break
1305 while True:
1306 buffer = message.read(4096) # Buffer size is arbitrary.
1307 if buffer == '':
1308 break
1309 self._file.write(buffer.replace('\n', os.linesep))
1310 else:
1311 raise TypeError('Invalid message type: %s' % type(message))
1312 stop = self._file.tell()
1313 return (start, stop)
1314
1315
1316class Message(email.Message.Message):
1317 """Message with mailbox-format-specific properties."""
1318
1319 def __init__(self, message=None):
1320 """Initialize a Message instance."""
1321 if isinstance(message, email.Message.Message):
1322 self._become_message(copy.deepcopy(message))
1323 if isinstance(message, Message):
1324 message._explain_to(self)
1325 elif isinstance(message, str):
1326 self._become_message(email.message_from_string(message))
1327 elif hasattr(message, "read"):
1328 self._become_message(email.message_from_file(message))
1329 elif message is None:
1330 email.Message.Message.__init__(self)
1331 else:
1332 raise TypeError('Invalid message type: %s' % type(message))
1333
1334 def _become_message(self, message):
1335 """Assume the non-format-specific state of message."""
1336 for name in ('_headers', '_unixfrom', '_payload', '_charset',
1337 'preamble', 'epilogue', 'defects', '_default_type'):
1338 self.__dict__[name] = message.__dict__[name]
1339
1340 def _explain_to(self, message):
1341 """Copy format-specific state to message insofar as possible."""
1342 if isinstance(message, Message):
1343 return # There's nothing format-specific to explain.
1344 else:
1345 raise TypeError('Cannot convert to specified type')
1346
1347
1348class MaildirMessage(Message):
1349 """Message with Maildir-specific properties."""
1350
1351 def __init__(self, message=None):
1352 """Initialize a MaildirMessage instance."""
1353 self._subdir = 'new'
1354 self._info = ''
1355 self._date = time.time()
1356 Message.__init__(self, message)
1357
1358 def get_subdir(self):
1359 """Return 'new' or 'cur'."""
1360 return self._subdir
1361
1362 def set_subdir(self, subdir):
1363 """Set subdir to 'new' or 'cur'."""
1364 if subdir == 'new' or subdir == 'cur':
1365 self._subdir = subdir
1366 else:
1367 raise ValueError("subdir must be 'new' or 'cur': %s" % subdir)
1368
1369 def get_flags(self):
1370 """Return as a string the flags that are set."""
1371 if self._info.startswith('2,'):
1372 return self._info[2:]
1373 else:
1374 return ''
1375
1376 def set_flags(self, flags):
1377 """Set the given flags and unset all others."""
1378 self._info = '2,' + ''.join(sorted(flags))
1379
1380 def add_flag(self, flag):
1381 """Set the given flag(s) without changing others."""
1382 self.set_flags(''.join(set(self.get_flags()) | set(flag)))
1383
1384 def remove_flag(self, flag):
1385 """Unset the given string flag(s) without changing others."""
1386 if self.get_flags() != '':
1387 self.set_flags(''.join(set(self.get_flags()) - set(flag)))
1388
1389 def get_date(self):
1390 """Return delivery date of message, in seconds since the epoch."""
1391 return self._date
1392
1393 def set_date(self, date):
1394 """Set delivery date of message, in seconds since the epoch."""
1395 try:
1396 self._date = float(date)
1397 except ValueError:
1398 raise TypeError("can't convert to float: %s" % date)
1399
1400 def get_info(self):
1401 """Get the message's "info" as a string."""
1402 return self._info
1403
1404 def set_info(self, info):
1405 """Set the message's "info" string."""
1406 if isinstance(info, str):
1407 self._info = info
1408 else:
1409 raise TypeError('info must be a string: %s' % type(info))
1410
1411 def _explain_to(self, message):
1412 """Copy Maildir-specific state to message insofar as possible."""
1413 if isinstance(message, MaildirMessage):
1414 message.set_flags(self.get_flags())
1415 message.set_subdir(self.get_subdir())
1416 message.set_date(self.get_date())
1417 elif isinstance(message, _mboxMMDFMessage):
1418 flags = set(self.get_flags())
1419 if 'S' in flags:
1420 message.add_flag('R')
1421 if self.get_subdir() == 'cur':
1422 message.add_flag('O')
1423 if 'T' in flags:
1424 message.add_flag('D')
1425 if 'F' in flags:
1426 message.add_flag('F')
1427 if 'R' in flags:
1428 message.add_flag('A')
1429 message.set_from('MAILER-DAEMON', time.gmtime(self.get_date()))
1430 elif isinstance(message, MHMessage):
1431 flags = set(self.get_flags())
1432 if 'S' not in flags:
1433 message.add_sequence('unseen')
1434 if 'R' in flags:
1435 message.add_sequence('replied')
1436 if 'F' in flags:
1437 message.add_sequence('flagged')
1438 elif isinstance(message, BabylMessage):
1439 flags = set(self.get_flags())
1440 if 'S' not in flags:
1441 message.add_label('unseen')
1442 if 'T' in flags:
1443 message.add_label('deleted')
1444 if 'R' in flags:
1445 message.add_label('answered')
1446 if 'P' in flags:
1447 message.add_label('forwarded')
1448 elif isinstance(message, Message):
1449 pass
1450 else:
1451 raise TypeError('Cannot convert to specified type: %s' %
1452 type(message))
1453
1454
1455class _mboxMMDFMessage(Message):
1456 """Message with mbox- or MMDF-specific properties."""
1457
1458 def __init__(self, message=None):
1459 """Initialize an mboxMMDFMessage instance."""
1460 self.set_from('MAILER-DAEMON', True)
1461 if isinstance(message, email.Message.Message):
1462 unixfrom = message.get_unixfrom()
1463 if unixfrom is not None and unixfrom.startswith('From '):
1464 self.set_from(unixfrom[5:])
1465 Message.__init__(self, message)
1466
1467 def get_from(self):
1468 """Return contents of "From " line."""
1469 return self._from
1470
1471 def set_from(self, from_, time_=None):
1472 """Set "From " line, formatting and appending time_ if specified."""
1473 if time_ is not None:
1474 if time_ is True:
1475 time_ = time.gmtime()
1476 from_ += ' ' + time.asctime(time_)
1477 self._from = from_
1478
1479 def get_flags(self):
1480 """Return as a string the flags that are set."""
1481 return self.get('Status', '') + self.get('X-Status', '')
1482
1483 def set_flags(self, flags):
1484 """Set the given flags and unset all others."""
1485 flags = set(flags)
1486 status_flags, xstatus_flags = '', ''
1487 for flag in ('R', 'O'):
1488 if flag in flags:
1489 status_flags += flag
1490 flags.remove(flag)
1491 for flag in ('D', 'F', 'A'):
1492 if flag in flags:
1493 xstatus_flags += flag
1494 flags.remove(flag)
1495 xstatus_flags += ''.join(sorted(flags))
1496 try:
1497 self.replace_header('Status', status_flags)
1498 except KeyError:
1499 self.add_header('Status', status_flags)
1500 try:
1501 self.replace_header('X-Status', xstatus_flags)
1502 except KeyError:
1503 self.add_header('X-Status', xstatus_flags)
1504
1505 def add_flag(self, flag):
1506 """Set the given flag(s) without changing others."""
1507 self.set_flags(''.join(set(self.get_flags()) | set(flag)))
1508
1509 def remove_flag(self, flag):
1510 """Unset the given string flag(s) without changing others."""
1511 if 'Status' in self or 'X-Status' in self:
1512 self.set_flags(''.join(set(self.get_flags()) - set(flag)))
1513
1514 def _explain_to(self, message):
1515 """Copy mbox- or MMDF-specific state to message insofar as possible."""
1516 if isinstance(message, MaildirMessage):
1517 flags = set(self.get_flags())
1518 if 'O' in flags:
1519 message.set_subdir('cur')
1520 if 'F' in flags:
1521 message.add_flag('F')
1522 if 'A' in flags:
1523 message.add_flag('R')
1524 if 'R' in flags:
1525 message.add_flag('S')
1526 if 'D' in flags:
1527 message.add_flag('T')
1528 del message['status']
1529 del message['x-status']
1530 maybe_date = ' '.join(self.get_from().split()[-5:])
1531 try:
1532 message.set_date(calendar.timegm(time.strptime(maybe_date,
1533 '%a %b %d %H:%M:%S %Y')))
1534 except (ValueError, OverflowError):
1535 pass
1536 elif isinstance(message, _mboxMMDFMessage):
1537 message.set_flags(self.get_flags())
1538 message.set_from(self.get_from())
1539 elif isinstance(message, MHMessage):
1540 flags = set(self.get_flags())
1541 if 'R' not in flags:
1542 message.add_sequence('unseen')
1543 if 'A' in flags:
1544 message.add_sequence('replied')
1545 if 'F' in flags:
1546 message.add_sequence('flagged')
1547 del message['status']
1548 del message['x-status']
1549 elif isinstance(message, BabylMessage):
1550 flags = set(self.get_flags())
1551 if 'R' not in flags:
1552 message.add_label('unseen')
1553 if 'D' in flags:
1554 message.add_label('deleted')
1555 if 'A' in flags:
1556 message.add_label('answered')
1557 del message['status']
1558 del message['x-status']
1559 elif isinstance(message, Message):
1560 pass
1561 else:
1562 raise TypeError('Cannot convert to specified type: %s' %
1563 type(message))
1564
1565
1566class mboxMessage(_mboxMMDFMessage):
1567 """Message with mbox-specific properties."""
1568
1569
1570class MHMessage(Message):
1571 """Message with MH-specific properties."""
1572
1573 def __init__(self, message=None):
1574 """Initialize an MHMessage instance."""
1575 self._sequences = []
1576 Message.__init__(self, message)
1577
1578 def get_sequences(self):
1579 """Return a list of sequences that include the message."""
1580 return self._sequences[:]
1581
1582 def set_sequences(self, sequences):
1583 """Set the list of sequences that include the message."""
1584 self._sequences = list(sequences)
1585
1586 def add_sequence(self, sequence):
1587 """Add sequence to list of sequences including the message."""
1588 if isinstance(sequence, str):
1589 if not sequence in self._sequences:
1590 self._sequences.append(sequence)
1591 else:
1592 raise TypeError('sequence must be a string: %s' % type(sequence))
1593
1594 def remove_sequence(self, sequence):
1595 """Remove sequence from the list of sequences including the message."""
1596 try:
1597 self._sequences.remove(sequence)
1598 except ValueError:
1599 pass
1600
1601 def _explain_to(self, message):
1602 """Copy MH-specific state to message insofar as possible."""
1603 if isinstance(message, MaildirMessage):
1604 sequences = set(self.get_sequences())
1605 if 'unseen' in sequences:
1606 message.set_subdir('cur')
1607 else:
1608 message.set_subdir('cur')
1609 message.add_flag('S')
1610 if 'flagged' in sequences:
1611 message.add_flag('F')
1612 if 'replied' in sequences:
1613 message.add_flag('R')
1614 elif isinstance(message, _mboxMMDFMessage):
1615 sequences = set(self.get_sequences())
1616 if 'unseen' not in sequences:
1617 message.add_flag('RO')
1618 else:
1619 message.add_flag('O')
1620 if 'flagged' in sequences:
1621 message.add_flag('F')
1622 if 'replied' in sequences:
1623 message.add_flag('A')
1624 elif isinstance(message, MHMessage):
1625 for sequence in self.get_sequences():
1626 message.add_sequence(sequence)
1627 elif isinstance(message, BabylMessage):
1628 sequences = set(self.get_sequences())
1629 if 'unseen' in sequences:
1630 message.add_label('unseen')
1631 if 'replied' in sequences:
1632 message.add_label('answered')
1633 elif isinstance(message, Message):
1634 pass
1635 else:
1636 raise TypeError('Cannot convert to specified type: %s' %
1637 type(message))
1638
1639
1640class BabylMessage(Message):
1641 """Message with Babyl-specific properties."""
1642
1643 def __init__(self, message=None):
1644 """Initialize an BabylMessage instance."""
1645 self._labels = []
1646 self._visible = Message()
1647 Message.__init__(self, message)
1648
1649 def get_labels(self):
1650 """Return a list of labels on the message."""
1651 return self._labels[:]
1652
1653 def set_labels(self, labels):
1654 """Set the list of labels on the message."""
1655 self._labels = list(labels)
1656
1657 def add_label(self, label):
1658 """Add label to list of labels on the message."""
1659 if isinstance(label, str):
1660 if label not in self._labels:
1661 self._labels.append(label)
1662 else:
1663 raise TypeError('label must be a string: %s' % type(label))
1664
1665 def remove_label(self, label):
1666 """Remove label from the list of labels on the message."""
1667 try:
1668 self._labels.remove(label)
1669 except ValueError:
1670 pass
1671
1672 def get_visible(self):
1673 """Return a Message representation of visible headers."""
1674 return Message(self._visible)
1675
1676 def set_visible(self, visible):
1677 """Set the Message representation of visible headers."""
1678 self._visible = Message(visible)
1679
1680 def update_visible(self):
1681 """Update and/or sensibly generate a set of visible headers."""
1682 for header in self._visible.keys():
1683 if header in self:
1684 self._visible.replace_header(header, self[header])
1685 else:
1686 del self._visible[header]
1687 for header in ('Date', 'From', 'Reply-To', 'To', 'CC', 'Subject'):
1688 if header in self and header not in self._visible:
1689 self._visible[header] = self[header]
1690
1691 def _explain_to(self, message):
1692 """Copy Babyl-specific state to message insofar as possible."""
1693 if isinstance(message, MaildirMessage):
1694 labels = set(self.get_labels())
1695 if 'unseen' in labels:
1696 message.set_subdir('cur')
1697 else:
1698 message.set_subdir('cur')
1699 message.add_flag('S')
1700 if 'forwarded' in labels or 'resent' in labels:
1701 message.add_flag('P')
1702 if 'answered' in labels:
1703 message.add_flag('R')
1704 if 'deleted' in labels:
1705 message.add_flag('T')
1706 elif isinstance(message, _mboxMMDFMessage):
1707 labels = set(self.get_labels())
1708 if 'unseen' not in labels:
1709 message.add_flag('RO')
1710 else:
1711 message.add_flag('O')
1712 if 'deleted' in labels:
1713 message.add_flag('D')
1714 if 'answered' in labels:
1715 message.add_flag('A')
1716 elif isinstance(message, MHMessage):
1717 labels = set(self.get_labels())
1718 if 'unseen' in labels:
1719 message.add_sequence('unseen')
1720 if 'answered' in labels:
1721 message.add_sequence('replied')
1722 elif isinstance(message, BabylMessage):
1723 message.set_visible(self.get_visible())
1724 for label in self.get_labels():
1725 message.add_label(label)
1726 elif isinstance(message, Message):
1727 pass
1728 else:
1729 raise TypeError('Cannot convert to specified type: %s' %
1730 type(message))
1731
1732
1733class MMDFMessage(_mboxMMDFMessage):
1734 """Message with MMDF-specific properties."""
1735
1736
1737class _ProxyFile:
1738 """A read-only wrapper of a file."""
1739
1740 def __init__(self, f, pos=None):
1741 """Initialize a _ProxyFile."""
1742 self._file = f
1743 if pos is None:
1744 self._pos = f.tell()
1745 else:
1746 self._pos = pos
1747
1748 def read(self, size=None):
1749 """Read bytes."""
1750 return self._read(size, self._file.read)
1751
1752 def readline(self, size=None):
1753 """Read a line."""
1754 return self._read(size, self._file.readline)
1755
1756 def readlines(self, sizehint=None):
1757 """Read multiple lines."""
1758 result = []
1759 for line in self:
1760 result.append(line)
1761 if sizehint is not None:
1762 sizehint -= len(line)
1763 if sizehint <= 0:
1764 break
1765 return result
1766
1767 def __iter__(self):
1768 """Iterate over lines."""
1769 return iter(self.readline, "")
1770
1771 def tell(self):
1772 """Return the position."""
1773 return self._pos
1774
1775 def seek(self, offset, whence=0):
1776 """Change position."""
1777 if whence == 1:
1778 self._file.seek(self._pos)
1779 self._file.seek(offset, whence)
1780 self._pos = self._file.tell()
1781
1782 def close(self):
1783 """Close the file."""
1784 self._file.close()
1785 del self._file
1786
1787 def _read(self, size, read_method):
1788 """Read size bytes using read_method."""
1789 if size is None:
1790 size = -1
1791 self._file.seek(self._pos)
1792 result = read_method(size)
1793 self._pos = self._file.tell()
1794 return result
1795
1796
1797class _PartialFile(_ProxyFile):
1798 """A read-only wrapper of part of a file."""
1799
1800 def __init__(self, f, start=None, stop=None):
1801 """Initialize a _PartialFile."""
1802 _ProxyFile.__init__(self, f, start)
1803 self._start = start
1804 self._stop = stop
1805
1806 def tell(self):
1807 """Return the position with respect to start."""
1808 return _ProxyFile.tell(self) - self._start
1809
1810 def seek(self, offset, whence=0):
1811 """Change position, possibly with respect to start or stop."""
1812 if whence == 0:
1813 self._pos = self._start
1814 whence = 1
1815 elif whence == 2:
1816 self._pos = self._stop
1817 whence = 1
1818 _ProxyFile.seek(self, offset, whence)
1819
1820 def _read(self, size, read_method):
1821 """Read size bytes using read_method, honoring start and stop."""
1822 remaining = self._stop - self._pos
1823 if remaining <= 0:
1824 return ''
1825 if size is None or size < 0 or size > remaining:
1826 size = remaining
1827 return _ProxyFile._read(self, size, read_method)
1828
1829
1830def _lock_file(f, dotlock=True):
1831 """Lock file f using lockf and dot locking."""
1832 dotlock_done = False
1833 try:
1834 if fcntl:
1835 try:
1836 fcntl.lockf(f, fcntl.LOCK_EX | fcntl.LOCK_NB)
1837 except IOError, e:
1838 if e.errno in (errno.EAGAIN, errno.EACCES):
1839 raise ExternalClashError('lockf: lock unavailable: %s' %
1840 f.name)
1841 else:
1842 raise
1843 if dotlock:
1844 try:
1845 pre_lock = _create_temporary(f.name + '.lock')
1846 pre_lock.close()
1847 except IOError, e:
1848 if e.errno == errno.EACCES:
1849 return # Without write access, just skip dotlocking.
1850 else:
1851 raise
1852 try:
1853 if hasattr(os, 'link'):
1854 os.link(pre_lock.name, f.name + '.lock')
1855 dotlock_done = True
1856 os.unlink(pre_lock.name)
1857 else:
1858 os.rename(pre_lock.name, f.name + '.lock')
1859 dotlock_done = True
1860 except OSError, e:
1861 if e.errno == errno.EEXIST or \
1862 (os.name == 'os2' and e.errno == errno.EACCES):
1863 os.remove(pre_lock.name)
1864 raise ExternalClashError('dot lock unavailable: %s' %
1865 f.name)
1866 else:
1867 raise
1868 except:
1869 if fcntl:
1870 fcntl.lockf(f, fcntl.LOCK_UN)
1871 if dotlock_done:
1872 os.remove(f.name + '.lock')
1873 raise
1874
1875def _unlock_file(f):
1876 """Unlock file f using lockf and dot locking."""
1877 if fcntl:
1878 fcntl.lockf(f, fcntl.LOCK_UN)
1879 if os.path.exists(f.name + '.lock'):
1880 os.remove(f.name + '.lock')
1881
1882def _create_carefully(path):
1883 """Create a file if it doesn't exist and open for reading and writing."""
1884 fd = os.open(path, os.O_CREAT | os.O_EXCL | os.O_RDWR)
1885 try:
1886 return open(path, 'rb+')
1887 finally:
1888 os.close(fd)
1889
1890def _create_temporary(path):
1891 """Create a temp file based on path and open for reading and writing."""
1892 return _create_carefully('%s.%s.%s.%s' % (path, int(time.time()),
1893 socket.gethostname(),
1894 os.getpid()))
1895
1896def _sync_flush(f):
1897 """Ensure changes to file f are physically on disk."""
1898 f.flush()
1899 if hasattr(os, 'fsync'):
1900 os.fsync(f.fileno())
1901
1902def _sync_close(f):
1903 """Close file f, ensuring all changes are physically on disk."""
1904 _sync_flush(f)
1905 f.close()
1906
1907## Start: classes from the original module (for backward compatibility).
1908
1909# Note that the Maildir class, whose name is unchanged, itself offers a next()
1910# method for backward compatibility.
1911
1912class _Mailbox:
1913
1914 def __init__(self, fp, factory=rfc822.Message):
1915 self.fp = fp
1916 self.seekp = 0
1917 self.factory = factory
1918
1919 def __iter__(self):
1920 return iter(self.next, None)
1921
1922 def next(self):
1923 while 1:
1924 self.fp.seek(self.seekp)
1925 try:
1926 self._search_start()
1927 except EOFError:
1928 self.seekp = self.fp.tell()
1929 return None
1930 start = self.fp.tell()
1931 self._search_end()
1932 self.seekp = stop = self.fp.tell()
1933 if start != stop:
1934 break
1935 return self.factory(_PartialFile(self.fp, start, stop))
1936
1937# Recommended to use PortableUnixMailbox instead!
1938class UnixMailbox(_Mailbox):
1939
1940 def _search_start(self):
1941 while 1:
1942 pos = self.fp.tell()
1943 line = self.fp.readline()
1944 if not line:
1945 raise EOFError
1946 if line[:5] == 'From ' and self._isrealfromline(line):
1947 self.fp.seek(pos)
1948 return
1949
1950 def _search_end(self):
1951 self.fp.readline() # Throw away header line
1952 while 1:
1953 pos = self.fp.tell()
1954 line = self.fp.readline()
1955 if not line:
1956 return
1957 if line[:5] == 'From ' and self._isrealfromline(line):
1958 self.fp.seek(pos)
1959 return
1960
1961 # An overridable mechanism to test for From-line-ness. You can either
1962 # specify a different regular expression or define a whole new
1963 # _isrealfromline() method. Note that this only gets called for lines
1964 # starting with the 5 characters "From ".
1965 #
1966 # BAW: According to
1967 #http://home.netscape.com/eng/mozilla/2.0/relnotes/demo/content-length.html
1968 # the only portable, reliable way to find message delimiters in a BSD (i.e
1969 # Unix mailbox) style folder is to search for "\n\nFrom .*\n", or at the
1970 # beginning of the file, "^From .*\n". While _fromlinepattern below seems
1971 # like a good idea, in practice, there are too many variations for more
1972 # strict parsing of the line to be completely accurate.
1973 #
1974 # _strict_isrealfromline() is the old version which tries to do stricter
1975 # parsing of the From_ line. _portable_isrealfromline() simply returns
1976 # true, since it's never called if the line doesn't already start with
1977 # "From ".
1978 #
1979 # This algorithm, and the way it interacts with _search_start() and
1980 # _search_end() may not be completely correct, because it doesn't check
1981 # that the two characters preceding "From " are \n\n or the beginning of
1982 # the file. Fixing this would require a more extensive rewrite than is
1983 # necessary. For convenience, we've added a PortableUnixMailbox class
1984 # which does no checking of the format of the 'From' line.
1985
1986 _fromlinepattern = (r"From \s*[^\s]+\s+\w\w\w\s+\w\w\w\s+\d?\d\s+"
1987 r"\d?\d:\d\d(:\d\d)?(\s+[^\s]+)?\s+\d\d\d\d\s*"
1988 r"[^\s]*\s*"
1989 "$")
1990 _regexp = None
1991
1992 def _strict_isrealfromline(self, line):
1993 if not self._regexp:
1994 import re
1995 self._regexp = re.compile(self._fromlinepattern)
1996 return self._regexp.match(line)
1997
1998 def _portable_isrealfromline(self, line):
1999 return True
2000
2001 _isrealfromline = _strict_isrealfromline
2002
2003
2004class PortableUnixMailbox(UnixMailbox):
2005 _isrealfromline = UnixMailbox._portable_isrealfromline
2006
2007
2008class MmdfMailbox(_Mailbox):
2009
2010 def _search_start(self):
2011 while 1:
2012 line = self.fp.readline()
2013 if not line:
2014 raise EOFError
2015 if line[:5] == '\001\001\001\001\n':
2016 return
2017
2018 def _search_end(self):
2019 while 1:
2020 pos = self.fp.tell()
2021 line = self.fp.readline()
2022 if not line:
2023 return
2024 if line == '\001\001\001\001\n':
2025 self.fp.seek(pos)
2026 return
2027
2028
2029class MHMailbox:
2030
2031 def __init__(self, dirname, factory=rfc822.Message):
2032 import re
2033 pat = re.compile('^[1-9][0-9]*$')
2034 self.dirname = dirname
2035 # the three following lines could be combined into:
2036 # list = map(long, filter(pat.match, os.listdir(self.dirname)))
2037 list = os.listdir(self.dirname)
2038 list = filter(pat.match, list)
2039 list = map(long, list)
2040 list.sort()
2041 # This only works in Python 1.6 or later;
2042 # before that str() added 'L':
2043 self.boxes = map(str, list)
2044 self.boxes.reverse()
2045 self.factory = factory
2046
2047 def __iter__(self):
2048 return iter(self.next, None)
2049
2050 def next(self):
2051 if not self.boxes:
2052 return None
2053 fn = self.boxes.pop()
2054 fp = open(os.path.join(self.dirname, fn))
2055 msg = self.factory(fp)
2056 try:
2057 msg._mh_msgno = fn
2058 except (AttributeError, TypeError):
2059 pass
2060 return msg
2061
2062
2063class BabylMailbox(_Mailbox):
2064
2065 def _search_start(self):
2066 while 1:
2067 line = self.fp.readline()
2068 if not line:
2069 raise EOFError
2070 if line == '*** EOOH ***\n':
2071 return
2072
2073 def _search_end(self):
2074 while 1:
2075 pos = self.fp.tell()
2076 line = self.fp.readline()
2077 if not line:
2078 return
2079 if line == '\037\014\n' or line == '\037':
2080 self.fp.seek(pos)
2081 return
2082
2083## End: classes from the original module (for backward compatibility).
2084
2085
2086class Error(Exception):
2087 """Raised for module-specific errors."""
2088
2089class NoSuchMailboxError(Error):
2090 """The specified mailbox does not exist and won't be created."""
2091
2092class NotEmptyError(Error):
2093 """The specified mailbox is not empty and deletion was requested."""
2094
2095class ExternalClashError(Error):
2096 """Another process caused an action to fail."""
2097
2098class FormatError(Error):
2099 """A file appears to have an invalid format."""