blob: ecd9f61d76aacaa4450a6ea18ec5865912c5cd7d [file] [log] [blame]
Guido van Rossumf06ee5f1996-11-27 19:52:01 +00001#! /usr/bin/env python
Guido van Rossum62448671996-09-17 21:33:15 +00002
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +00003"""Read/write support for Maildir, mbox, MH, Babyl, and MMDF mailboxes."""
Guido van Rossum62448671996-09-17 21:33:15 +00004
Andrew M. Kuchlingb5686da2006-11-09 13:51:14 +00005# 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
Martin v. Löwis08041d52006-05-04 14:27:52 +000011import sys
Jack Jansen97157791995-10-23 13:59:53 +000012import os
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +000013import time
14import calendar
15import socket
16import errno
17import copy
18import email
Georg Brandl5a096e12007-01-22 19:40:21 +000019import email.message
20import email.generator
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +000021import StringIO
22try:
Andrew MacIntyreafa358f2006-07-23 13:04:00 +000023 if sys.platform == 'os2emx':
24 # OS/2 EMX fcntl() not adequate
25 raise ImportError
Andrew M. Kuchlinga7ee9eb2006-06-26 13:08:24 +000026 import fcntl
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +000027except ImportError:
28 fcntl = None
Guido van Rossumc7b68821994-04-28 09:53:33 +000029
Antoine Pitroub9d49632010-01-04 23:22:44 +000030import warnings
31with warnings.catch_warnings():
32 if sys.py3kwarning:
33 warnings.filterwarnings("ignore", ".*rfc822 has been removed",
34 DeprecationWarning)
35 import rfc822
36
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +000037__all__ = [ 'Mailbox', 'Maildir', 'mbox', 'MH', 'Babyl', 'MMDF',
38 'Message', 'MaildirMessage', 'mboxMessage', 'MHMessage',
39 'BabylMessage', 'MMDFMessage', 'UnixMailbox',
40 'PortableUnixMailbox', 'MmdfMailbox', 'MHMailbox', 'BabylMailbox' ]
41
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +000042class Mailbox:
43 """A group of messages in a particular place."""
44
45 def __init__(self, path, factory=None, create=True):
46 """Initialize a Mailbox instance."""
47 self._path = os.path.abspath(os.path.expanduser(path))
48 self._factory = factory
49
50 def add(self, message):
51 """Add message and return assigned key."""
52 raise NotImplementedError('Method must be implemented by subclass')
53
54 def remove(self, key):
55 """Remove the keyed message; raise KeyError if it doesn't exist."""
56 raise NotImplementedError('Method must be implemented by subclass')
57
58 def __delitem__(self, key):
59 self.remove(key)
60
61 def discard(self, key):
62 """If the keyed message exists, remove it."""
63 try:
64 self.remove(key)
65 except KeyError:
66 pass
67
68 def __setitem__(self, key, message):
69 """Replace the keyed message; raise KeyError if it doesn't exist."""
70 raise NotImplementedError('Method must be implemented by subclass')
71
72 def get(self, key, default=None):
73 """Return the keyed message, or default if it doesn't exist."""
74 try:
75 return self.__getitem__(key)
76 except KeyError:
77 return default
78
79 def __getitem__(self, key):
80 """Return the keyed message; raise KeyError if it doesn't exist."""
81 if not self._factory:
82 return self.get_message(key)
83 else:
84 return self._factory(self.get_file(key))
85
86 def get_message(self, key):
87 """Return a Message representation or raise a KeyError."""
88 raise NotImplementedError('Method must be implemented by subclass')
89
90 def get_string(self, key):
91 """Return a string representation or raise a KeyError."""
92 raise NotImplementedError('Method must be implemented by subclass')
93
94 def get_file(self, key):
95 """Return a file-like representation or raise a KeyError."""
96 raise NotImplementedError('Method must be implemented by subclass')
97
98 def iterkeys(self):
99 """Return an iterator over keys."""
100 raise NotImplementedError('Method must be implemented by subclass')
101
102 def keys(self):
103 """Return a list of keys."""
104 return list(self.iterkeys())
105
106 def itervalues(self):
107 """Return an iterator over all messages."""
108 for key in self.iterkeys():
109 try:
110 value = self[key]
111 except KeyError:
112 continue
113 yield value
114
115 def __iter__(self):
116 return self.itervalues()
117
118 def values(self):
119 """Return a list of messages. Memory intensive."""
120 return list(self.itervalues())
121
122 def iteritems(self):
123 """Return an iterator over (key, message) tuples."""
124 for key in self.iterkeys():
125 try:
126 value = self[key]
127 except KeyError:
128 continue
129 yield (key, value)
130
131 def items(self):
132 """Return a list of (key, message) tuples. Memory intensive."""
133 return list(self.iteritems())
134
135 def has_key(self, key):
136 """Return True if the keyed message exists, False otherwise."""
137 raise NotImplementedError('Method must be implemented by subclass')
138
139 def __contains__(self, key):
140 return self.has_key(key)
141
142 def __len__(self):
143 """Return a count of messages in the mailbox."""
144 raise NotImplementedError('Method must be implemented by subclass')
145
146 def clear(self):
147 """Delete all messages."""
148 for key in self.iterkeys():
149 self.discard(key)
150
151 def pop(self, key, default=None):
152 """Delete the keyed message and return it, or default."""
153 try:
154 result = self[key]
155 except KeyError:
156 return default
157 self.discard(key)
158 return result
159
160 def popitem(self):
161 """Delete an arbitrary (key, message) pair and return it."""
162 for key in self.iterkeys():
163 return (key, self.pop(key)) # This is only run once.
164 else:
165 raise KeyError('No messages in mailbox')
166
167 def update(self, arg=None):
168 """Change the messages that correspond to certain keys."""
169 if hasattr(arg, 'iteritems'):
170 source = arg.iteritems()
171 elif hasattr(arg, 'items'):
172 source = arg.items()
173 else:
174 source = arg
175 bad_key = False
176 for key, message in source:
177 try:
178 self[key] = message
179 except KeyError:
180 bad_key = True
181 if bad_key:
182 raise KeyError('No message with key(s)')
183
184 def flush(self):
185 """Write any pending changes to the disk."""
186 raise NotImplementedError('Method must be implemented by subclass')
187
188 def lock(self):
189 """Lock the mailbox."""
190 raise NotImplementedError('Method must be implemented by subclass')
191
192 def unlock(self):
193 """Unlock the mailbox if it is locked."""
194 raise NotImplementedError('Method must be implemented by subclass')
195
196 def close(self):
197 """Flush and close the mailbox."""
198 raise NotImplementedError('Method must be implemented by subclass')
199
200 def _dump_message(self, message, target, mangle_from_=False):
201 # Most files are opened in binary mode to allow predictable seeking.
202 # To get native line endings on disk, the user-friendly \n line endings
203 # used in strings and by email.Message are translated here.
204 """Dump message contents to target file."""
Georg Brandl5a096e12007-01-22 19:40:21 +0000205 if isinstance(message, email.message.Message):
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +0000206 buffer = StringIO.StringIO()
Georg Brandl5a096e12007-01-22 19:40:21 +0000207 gen = email.generator.Generator(buffer, mangle_from_, 0)
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +0000208 gen.flatten(message)
209 buffer.seek(0)
210 target.write(buffer.read().replace('\n', os.linesep))
211 elif isinstance(message, str):
212 if mangle_from_:
213 message = message.replace('\nFrom ', '\n>From ')
214 message = message.replace('\n', os.linesep)
215 target.write(message)
216 elif hasattr(message, 'read'):
217 while True:
218 line = message.readline()
219 if line == '':
220 break
221 if mangle_from_ and line.startswith('From '):
222 line = '>From ' + line[5:]
223 line = line.replace('\n', os.linesep)
224 target.write(line)
225 else:
226 raise TypeError('Invalid message type: %s' % type(message))
227
228
229class Maildir(Mailbox):
230 """A qmail-style Maildir mailbox."""
231
232 colon = ':'
233
234 def __init__(self, dirname, factory=rfc822.Message, create=True):
235 """Initialize a Maildir instance."""
236 Mailbox.__init__(self, dirname, factory, create)
R David Murray8b26c4b2011-05-06 21:56:22 -0400237 self._paths = {
238 'tmp': os.path.join(self._path, 'tmp'),
239 'new': os.path.join(self._path, 'new'),
240 'cur': os.path.join(self._path, 'cur'),
241 }
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +0000242 if not os.path.exists(self._path):
243 if create:
244 os.mkdir(self._path, 0700)
R David Murray8b26c4b2011-05-06 21:56:22 -0400245 for path in self._paths.values():
246 os.mkdir(path, 0o700)
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +0000247 else:
248 raise NoSuchMailboxError(self._path)
249 self._toc = {}
Petri Lehtinen49aa72e2011-11-05 09:50:37 +0200250 self._toc_mtimes = {'cur': 0, 'new': 0}
251 self._last_read = 0 # Records last time we read cur/new
252 self._skewfactor = 0.1 # Adjust if os/fs clocks are skewing
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +0000253
254 def add(self, message):
255 """Add message and return assigned key."""
256 tmp_file = self._create_tmp()
257 try:
258 self._dump_message(message, tmp_file)
R. David Murray008c0442011-02-11 23:03:13 +0000259 except BaseException:
260 tmp_file.close()
261 os.remove(tmp_file.name)
262 raise
263 _sync_close(tmp_file)
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +0000264 if isinstance(message, MaildirMessage):
265 subdir = message.get_subdir()
266 suffix = self.colon + message.get_info()
267 if suffix == self.colon:
268 suffix = ''
269 else:
270 subdir = 'new'
271 suffix = ''
272 uniq = os.path.basename(tmp_file.name).split(self.colon)[0]
273 dest = os.path.join(self._path, subdir, uniq + suffix)
Andrew M. Kuchling978d8282006-11-09 21:16:46 +0000274 try:
275 if hasattr(os, 'link'):
276 os.link(tmp_file.name, dest)
277 os.remove(tmp_file.name)
278 else:
279 os.rename(tmp_file.name, dest)
280 except OSError, e:
281 os.remove(tmp_file.name)
282 if e.errno == errno.EEXIST:
283 raise ExternalClashError('Name clash with existing message: %s'
284 % dest)
285 else:
286 raise
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +0000287 if isinstance(message, MaildirMessage):
288 os.utime(dest, (os.path.getatime(dest), message.get_date()))
289 return uniq
290
291 def remove(self, key):
292 """Remove the keyed message; raise KeyError if it doesn't exist."""
293 os.remove(os.path.join(self._path, self._lookup(key)))
294
295 def discard(self, key):
296 """If the keyed message exists, remove it."""
297 # This overrides an inapplicable implementation in the superclass.
298 try:
299 self.remove(key)
300 except KeyError:
301 pass
302 except OSError, e:
Martin v. Löwis08041d52006-05-04 14:27:52 +0000303 if e.errno != errno.ENOENT:
Tim Peters6d7cd7d2006-04-22 05:52:59 +0000304 raise
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +0000305
306 def __setitem__(self, key, message):
307 """Replace the keyed message; raise KeyError if it doesn't exist."""
308 old_subpath = self._lookup(key)
309 temp_key = self.add(message)
310 temp_subpath = self._lookup(temp_key)
311 if isinstance(message, MaildirMessage):
312 # temp's subdir and suffix were specified by message.
313 dominant_subpath = temp_subpath
314 else:
315 # temp's subdir and suffix were defaults from add().
316 dominant_subpath = old_subpath
317 subdir = os.path.dirname(dominant_subpath)
318 if self.colon in dominant_subpath:
319 suffix = self.colon + dominant_subpath.split(self.colon)[-1]
320 else:
321 suffix = ''
322 self.discard(key)
323 new_path = os.path.join(self._path, subdir, key + suffix)
324 os.rename(os.path.join(self._path, temp_subpath), new_path)
325 if isinstance(message, MaildirMessage):
326 os.utime(new_path, (os.path.getatime(new_path),
327 message.get_date()))
328
329 def get_message(self, key):
330 """Return a Message representation or raise a KeyError."""
331 subpath = self._lookup(key)
Andrew M. Kuchling214db632006-05-02 21:44:33 +0000332 f = open(os.path.join(self._path, subpath), 'r')
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +0000333 try:
Andrew M. Kuchling15ce8802008-01-19 20:12:04 +0000334 if self._factory:
335 msg = self._factory(f)
336 else:
337 msg = MaildirMessage(f)
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +0000338 finally:
339 f.close()
340 subdir, name = os.path.split(subpath)
341 msg.set_subdir(subdir)
342 if self.colon in name:
343 msg.set_info(name.split(self.colon)[-1])
344 msg.set_date(os.path.getmtime(os.path.join(self._path, subpath)))
345 return msg
346
347 def get_string(self, key):
348 """Return a string representation or raise a KeyError."""
Andrew M. Kuchling214db632006-05-02 21:44:33 +0000349 f = open(os.path.join(self._path, self._lookup(key)), 'r')
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +0000350 try:
351 return f.read()
352 finally:
353 f.close()
354
355 def get_file(self, key):
356 """Return a file-like representation or raise a KeyError."""
Andrew M. Kuchling214db632006-05-02 21:44:33 +0000357 f = open(os.path.join(self._path, self._lookup(key)), 'rb')
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +0000358 return _ProxyFile(f)
359
360 def iterkeys(self):
361 """Return an iterator over keys."""
362 self._refresh()
363 for key in self._toc:
364 try:
365 self._lookup(key)
366 except KeyError:
367 continue
368 yield key
369
370 def has_key(self, key):
371 """Return True if the keyed message exists, False otherwise."""
372 self._refresh()
373 return key in self._toc
374
375 def __len__(self):
376 """Return a count of messages in the mailbox."""
377 self._refresh()
378 return len(self._toc)
379
380 def flush(self):
381 """Write any pending changes to disk."""
Antoine Pitroue4c6b162009-11-01 21:29:33 +0000382 # Maildir changes are always written immediately, so there's nothing
R David Murray8b26c4b2011-05-06 21:56:22 -0400383 # to do.
384 pass
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +0000385
386 def lock(self):
387 """Lock the mailbox."""
388 return
389
390 def unlock(self):
391 """Unlock the mailbox if it is locked."""
392 return
393
394 def close(self):
395 """Flush and close the mailbox."""
396 return
397
398 def list_folders(self):
399 """Return a list of folder names."""
400 result = []
401 for entry in os.listdir(self._path):
402 if len(entry) > 1 and entry[0] == '.' and \
403 os.path.isdir(os.path.join(self._path, entry)):
404 result.append(entry[1:])
405 return result
406
407 def get_folder(self, folder):
408 """Return a Maildir instance for the named folder."""
Andrew M. Kuchlinga3e5d372006-11-09 13:27:07 +0000409 return Maildir(os.path.join(self._path, '.' + folder),
410 factory=self._factory,
411 create=False)
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +0000412
413 def add_folder(self, folder):
414 """Create a folder and return a Maildir instance representing it."""
415 path = os.path.join(self._path, '.' + folder)
Andrew M. Kuchlinga3e5d372006-11-09 13:27:07 +0000416 result = Maildir(path, factory=self._factory)
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +0000417 maildirfolder_path = os.path.join(path, 'maildirfolder')
418 if not os.path.exists(maildirfolder_path):
Andrew M. Kuchling70a6dbd2008-08-04 01:43:43 +0000419 os.close(os.open(maildirfolder_path, os.O_CREAT | os.O_WRONLY,
420 0666))
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +0000421 return result
422
423 def remove_folder(self, folder):
424 """Delete the named folder, which must be empty."""
425 path = os.path.join(self._path, '.' + folder)
426 for entry in os.listdir(os.path.join(path, 'new')) + \
427 os.listdir(os.path.join(path, 'cur')):
428 if len(entry) < 1 or entry[0] != '.':
429 raise NotEmptyError('Folder contains message(s): %s' % folder)
430 for entry in os.listdir(path):
431 if entry != 'new' and entry != 'cur' and entry != 'tmp' and \
432 os.path.isdir(os.path.join(path, entry)):
433 raise NotEmptyError("Folder contains subdirectory '%s': %s" %
434 (folder, entry))
435 for root, dirs, files in os.walk(path, topdown=False):
436 for entry in files:
437 os.remove(os.path.join(root, entry))
438 for entry in dirs:
439 os.rmdir(os.path.join(root, entry))
440 os.rmdir(path)
441
442 def clean(self):
443 """Delete old files in "tmp"."""
444 now = time.time()
445 for entry in os.listdir(os.path.join(self._path, 'tmp')):
446 path = os.path.join(self._path, 'tmp', entry)
447 if now - os.path.getatime(path) > 129600: # 60 * 60 * 36
448 os.remove(path)
449
450 _count = 1 # This is used to generate unique file names.
451
452 def _create_tmp(self):
453 """Create a file in the tmp subdirectory and open and return it."""
454 now = time.time()
455 hostname = socket.gethostname()
456 if '/' in hostname:
457 hostname = hostname.replace('/', r'\057')
458 if ':' in hostname:
459 hostname = hostname.replace(':', r'\072')
460 uniq = "%s.M%sP%sQ%s.%s" % (int(now), int(now % 1 * 1e6), os.getpid(),
461 Maildir._count, hostname)
462 path = os.path.join(self._path, 'tmp', uniq)
463 try:
464 os.stat(path)
465 except OSError, e:
466 if e.errno == errno.ENOENT:
467 Maildir._count += 1
Andrew M. Kuchling978d8282006-11-09 21:16:46 +0000468 try:
469 return _create_carefully(path)
470 except OSError, e:
471 if e.errno != errno.EEXIST:
472 raise
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +0000473 else:
474 raise
Andrew M. Kuchling978d8282006-11-09 21:16:46 +0000475
476 # Fall through to here if stat succeeded or open raised EEXIST.
477 raise ExternalClashError('Name clash prevented file creation: %s' %
478 path)
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +0000479
480 def _refresh(self):
481 """Update table of contents mapping."""
R David Murray8b26c4b2011-05-06 21:56:22 -0400482 # If it has been less than two seconds since the last _refresh() call,
483 # we have to unconditionally re-read the mailbox just in case it has
484 # been modified, because os.path.mtime() has a 2 sec resolution in the
485 # most common worst case (FAT) and a 1 sec resolution typically. This
486 # results in a few unnecessary re-reads when _refresh() is called
487 # multiple times in that interval, but once the clock ticks over, we
488 # will only re-read as needed. Because the filesystem might be being
489 # served by an independent system with its own clock, we record and
490 # compare with the mtimes from the filesystem. Because the other
491 # system's clock might be skewing relative to our clock, we add an
492 # extra delta to our wait. The default is one tenth second, but is an
493 # instance variable and so can be adjusted if dealing with a
494 # particularly skewed or irregular system.
495 if time.time() - self._last_read > 2 + self._skewfactor:
496 refresh = False
497 for subdir in self._toc_mtimes:
498 mtime = os.path.getmtime(self._paths[subdir])
499 if mtime > self._toc_mtimes[subdir]:
500 refresh = True
501 self._toc_mtimes[subdir] = mtime
502 if not refresh:
Antoine Pitroud35b8c72009-11-01 00:30:13 +0000503 return
R David Murray8b26c4b2011-05-06 21:56:22 -0400504 # Refresh toc
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +0000505 self._toc = {}
R David Murray8b26c4b2011-05-06 21:56:22 -0400506 for subdir in self._toc_mtimes:
507 path = self._paths[subdir]
Andrew M. Kuchling420d4eb2009-05-02 19:17:28 +0000508 for entry in os.listdir(path):
509 p = os.path.join(path, entry)
Andrew M. Kuchling2b09ef02007-07-14 21:56:19 +0000510 if os.path.isdir(p):
511 continue
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +0000512 uniq = entry.split(self.colon)[0]
513 self._toc[uniq] = os.path.join(subdir, entry)
R David Murray8b26c4b2011-05-06 21:56:22 -0400514 self._last_read = time.time()
Andrew M. Kuchling420d4eb2009-05-02 19:17:28 +0000515
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +0000516 def _lookup(self, key):
517 """Use TOC to return subpath for given key, or raise a KeyError."""
518 try:
519 if os.path.exists(os.path.join(self._path, self._toc[key])):
520 return self._toc[key]
521 except KeyError:
522 pass
523 self._refresh()
524 try:
525 return self._toc[key]
526 except KeyError:
527 raise KeyError('No message with key: %s' % key)
528
529 # This method is for backward compatibility only.
530 def next(self):
531 """Return the next message in a one-time iteration."""
532 if not hasattr(self, '_onetime_keys'):
533 self._onetime_keys = self.iterkeys()
534 while True:
535 try:
536 return self[self._onetime_keys.next()]
537 except StopIteration:
538 return None
539 except KeyError:
540 continue
541
542
543class _singlefileMailbox(Mailbox):
544 """A single-file mailbox."""
545
546 def __init__(self, path, factory=None, create=True):
547 """Initialize a single-file mailbox."""
548 Mailbox.__init__(self, path, factory, create)
549 try:
Andrew M. Kuchling214db632006-05-02 21:44:33 +0000550 f = open(self._path, 'rb+')
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +0000551 except IOError, e:
552 if e.errno == errno.ENOENT:
553 if create:
Andrew M. Kuchling214db632006-05-02 21:44:33 +0000554 f = open(self._path, 'wb+')
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +0000555 else:
556 raise NoSuchMailboxError(self._path)
R. David Murray1a337902011-03-03 18:17:40 +0000557 elif e.errno in (errno.EACCES, errno.EROFS):
Andrew M. Kuchling214db632006-05-02 21:44:33 +0000558 f = open(self._path, 'rb')
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +0000559 else:
560 raise
561 self._file = f
562 self._toc = None
563 self._next_key = 0
Petri Lehtinen45f0d982012-06-28 13:48:17 +0300564 self._pending = False # No changes require rewriting the file.
565 self._pending_sync = False # No need to sync the file
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +0000566 self._locked = False
Petri Lehtinen45f0d982012-06-28 13:48:17 +0300567 self._file_length = None # Used to record mailbox size
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +0000568
569 def add(self, message):
570 """Add message and return assigned key."""
571 self._lookup()
572 self._toc[self._next_key] = self._append_message(message)
573 self._next_key += 1
Petri Lehtinen45f0d982012-06-28 13:48:17 +0300574 # _append_message appends the message to the mailbox file. We
575 # don't need a full rewrite + rename, sync is enough.
576 self._pending_sync = True
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +0000577 return self._next_key - 1
578
579 def remove(self, key):
580 """Remove the keyed message; raise KeyError if it doesn't exist."""
581 self._lookup(key)
582 del self._toc[key]
583 self._pending = True
584
585 def __setitem__(self, key, message):
586 """Replace the keyed message; raise KeyError if it doesn't exist."""
587 self._lookup(key)
588 self._toc[key] = self._append_message(message)
589 self._pending = True
590
591 def iterkeys(self):
592 """Return an iterator over keys."""
593 self._lookup()
594 for key in self._toc.keys():
595 yield key
596
597 def has_key(self, key):
598 """Return True if the keyed message exists, False otherwise."""
599 self._lookup()
600 return key in self._toc
601
602 def __len__(self):
603 """Return a count of messages in the mailbox."""
604 self._lookup()
605 return len(self._toc)
606
607 def lock(self):
608 """Lock the mailbox."""
609 if not self._locked:
610 _lock_file(self._file)
611 self._locked = True
612
613 def unlock(self):
614 """Unlock the mailbox if it is locked."""
615 if self._locked:
616 _unlock_file(self._file)
617 self._locked = False
618
619 def flush(self):
620 """Write any pending changes to disk."""
621 if not self._pending:
Petri Lehtinen45f0d982012-06-28 13:48:17 +0300622 if self._pending_sync:
623 # Messages have only been added, so syncing the file
624 # is enough.
625 _sync_flush(self._file)
626 self._pending_sync = False
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +0000627 return
Andrew M. Kuchlingeca4c312006-12-20 19:48:20 +0000628
629 # In order to be writing anything out at all, self._toc must
630 # already have been generated (and presumably has been modified
631 # by adding or deleting an item).
632 assert self._toc is not None
Tim Petersf733abb2007-01-30 03:03:46 +0000633
Andrew M. Kuchlingeca4c312006-12-20 19:48:20 +0000634 # Check length of self._file; if it's changed, some other process
635 # has modified the mailbox since we scanned it.
636 self._file.seek(0, 2)
637 cur_len = self._file.tell()
638 if cur_len != self._file_length:
639 raise ExternalClashError('Size of mailbox file changed '
640 '(expected %i, found %i)' %
641 (self._file_length, cur_len))
Tim Petersf733abb2007-01-30 03:03:46 +0000642
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +0000643 new_file = _create_temporary(self._path)
644 try:
645 new_toc = {}
646 self._pre_mailbox_hook(new_file)
647 for key in sorted(self._toc.keys()):
648 start, stop = self._toc[key]
649 self._file.seek(start)
650 self._pre_message_hook(new_file)
651 new_start = new_file.tell()
652 while True:
653 buffer = self._file.read(min(4096,
654 stop - self._file.tell()))
655 if buffer == '':
656 break
657 new_file.write(buffer)
658 new_toc[key] = (new_start, new_file.tell())
659 self._post_message_hook(new_file)
Petri Lehtinen7cf66992012-06-15 20:50:51 +0300660 self._file_length = new_file.tell()
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +0000661 except:
662 new_file.close()
663 os.remove(new_file.name)
664 raise
Andrew M. Kuchlingb5686da2006-11-09 13:51:14 +0000665 _sync_close(new_file)
666 # self._file is about to get replaced, so no need to sync.
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +0000667 self._file.close()
668 try:
669 os.rename(new_file.name, self._path)
670 except OSError, e:
Andrew MacIntyreafa358f2006-07-23 13:04:00 +0000671 if e.errno == errno.EEXIST or \
672 (os.name == 'os2' and e.errno == errno.EACCES):
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +0000673 os.remove(self._path)
674 os.rename(new_file.name, self._path)
675 else:
676 raise
Andrew M. Kuchling214db632006-05-02 21:44:33 +0000677 self._file = open(self._path, 'rb+')
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +0000678 self._toc = new_toc
679 self._pending = False
Petri Lehtinen45f0d982012-06-28 13:48:17 +0300680 self._pending_sync = False
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +0000681 if self._locked:
Andrew M. Kuchling0f871832006-10-27 16:55:34 +0000682 _lock_file(self._file, dotlock=False)
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +0000683
684 def _pre_mailbox_hook(self, f):
685 """Called before writing the mailbox to file f."""
686 return
687
688 def _pre_message_hook(self, f):
689 """Called before writing each message to file f."""
690 return
691
692 def _post_message_hook(self, f):
693 """Called after writing each message to file f."""
694 return
695
696 def close(self):
697 """Flush and close the mailbox."""
698 self.flush()
699 if self._locked:
700 self.unlock()
Andrew M. Kuchlingb5686da2006-11-09 13:51:14 +0000701 self._file.close() # Sync has been done by self.flush() above.
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +0000702
703 def _lookup(self, key=None):
704 """Return (start, stop) or raise KeyError."""
705 if self._toc is None:
706 self._generate_toc()
707 if key is not None:
708 try:
709 return self._toc[key]
710 except KeyError:
711 raise KeyError('No message with key: %s' % key)
712
713 def _append_message(self, message):
714 """Append message to mailbox and return (start, stop) offsets."""
715 self._file.seek(0, 2)
R. David Murray008c0442011-02-11 23:03:13 +0000716 before = self._file.tell()
Petri Lehtinen45f0d982012-06-28 13:48:17 +0300717 if len(self._toc) == 0:
718 # This is the first message
719 self._pre_mailbox_hook(self._file)
R. David Murray008c0442011-02-11 23:03:13 +0000720 try:
721 self._pre_message_hook(self._file)
722 offsets = self._install_message(message)
723 self._post_message_hook(self._file)
724 except BaseException:
725 self._file.truncate(before)
726 raise
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +0000727 self._file.flush()
Andrew M. Kuchlingeca4c312006-12-20 19:48:20 +0000728 self._file_length = self._file.tell() # Record current length of mailbox
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +0000729 return offsets
730
731
732
733class _mboxMMDF(_singlefileMailbox):
734 """An mbox or MMDF mailbox."""
735
736 _mangle_from_ = True
737
738 def get_message(self, key):
739 """Return a Message representation or raise a KeyError."""
740 start, stop = self._lookup(key)
741 self._file.seek(start)
742 from_line = self._file.readline().replace(os.linesep, '')
743 string = self._file.read(stop - self._file.tell())
744 msg = self._message_factory(string.replace(os.linesep, '\n'))
745 msg.set_from(from_line[5:])
746 return msg
747
748 def get_string(self, key, from_=False):
749 """Return a string representation or raise a KeyError."""
750 start, stop = self._lookup(key)
751 self._file.seek(start)
752 if not from_:
753 self._file.readline()
754 string = self._file.read(stop - self._file.tell())
755 return string.replace(os.linesep, '\n')
756
757 def get_file(self, key, from_=False):
758 """Return a file-like representation or raise a KeyError."""
759 start, stop = self._lookup(key)
760 self._file.seek(start)
761 if not from_:
762 self._file.readline()
763 return _PartialFile(self._file, self._file.tell(), stop)
764
765 def _install_message(self, message):
766 """Format a message and blindly write to self._file."""
767 from_line = None
768 if isinstance(message, str) and message.startswith('From '):
769 newline = message.find('\n')
770 if newline != -1:
771 from_line = message[:newline]
772 message = message[newline + 1:]
773 else:
774 from_line = message
775 message = ''
776 elif isinstance(message, _mboxMMDFMessage):
777 from_line = 'From ' + message.get_from()
Georg Brandl5a096e12007-01-22 19:40:21 +0000778 elif isinstance(message, email.message.Message):
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +0000779 from_line = message.get_unixfrom() # May be None.
780 if from_line is None:
781 from_line = 'From MAILER-DAEMON %s' % time.asctime(time.gmtime())
782 start = self._file.tell()
783 self._file.write(from_line + os.linesep)
784 self._dump_message(message, self._file, self._mangle_from_)
785 stop = self._file.tell()
786 return (start, stop)
787
788
789class mbox(_mboxMMDF):
790 """A classic mbox mailbox."""
791
792 _mangle_from_ = True
793
794 def __init__(self, path, factory=None, create=True):
795 """Initialize an mbox mailbox."""
796 self._message_factory = mboxMessage
797 _mboxMMDF.__init__(self, path, factory, create)
798
799 def _pre_message_hook(self, f):
800 """Called before writing each message to file f."""
801 if f.tell() != 0:
802 f.write(os.linesep)
803
804 def _generate_toc(self):
805 """Generate key-to-(start, stop) table of contents."""
806 starts, stops = [], []
807 self._file.seek(0)
808 while True:
809 line_pos = self._file.tell()
810 line = self._file.readline()
811 if line.startswith('From '):
812 if len(stops) < len(starts):
813 stops.append(line_pos - len(os.linesep))
814 starts.append(line_pos)
815 elif line == '':
816 stops.append(line_pos)
817 break
818 self._toc = dict(enumerate(zip(starts, stops)))
819 self._next_key = len(self._toc)
Andrew M. Kuchlingeca4c312006-12-20 19:48:20 +0000820 self._file_length = self._file.tell()
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +0000821
822
823class MMDF(_mboxMMDF):
824 """An MMDF mailbox."""
825
826 def __init__(self, path, factory=None, create=True):
827 """Initialize an MMDF mailbox."""
828 self._message_factory = MMDFMessage
829 _mboxMMDF.__init__(self, path, factory, create)
830
831 def _pre_message_hook(self, f):
832 """Called before writing each message to file f."""
833 f.write('\001\001\001\001' + os.linesep)
834
835 def _post_message_hook(self, f):
836 """Called after writing each message to file f."""
837 f.write(os.linesep + '\001\001\001\001' + os.linesep)
838
839 def _generate_toc(self):
840 """Generate key-to-(start, stop) table of contents."""
841 starts, stops = [], []
842 self._file.seek(0)
843 next_pos = 0
844 while True:
845 line_pos = next_pos
846 line = self._file.readline()
847 next_pos = self._file.tell()
848 if line.startswith('\001\001\001\001' + os.linesep):
849 starts.append(next_pos)
850 while True:
851 line_pos = next_pos
852 line = self._file.readline()
853 next_pos = self._file.tell()
854 if line == '\001\001\001\001' + os.linesep:
855 stops.append(line_pos - len(os.linesep))
856 break
857 elif line == '':
858 stops.append(line_pos)
859 break
860 elif line == '':
861 break
862 self._toc = dict(enumerate(zip(starts, stops)))
863 self._next_key = len(self._toc)
Andrew M. Kuchlingeca4c312006-12-20 19:48:20 +0000864 self._file.seek(0, 2)
865 self._file_length = self._file.tell()
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +0000866
867
868class MH(Mailbox):
869 """An MH mailbox."""
870
871 def __init__(self, path, factory=None, create=True):
872 """Initialize an MH instance."""
873 Mailbox.__init__(self, path, factory, create)
874 if not os.path.exists(self._path):
875 if create:
876 os.mkdir(self._path, 0700)
877 os.close(os.open(os.path.join(self._path, '.mh_sequences'),
878 os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0600))
879 else:
880 raise NoSuchMailboxError(self._path)
881 self._locked = False
882
883 def add(self, message):
884 """Add message and return assigned key."""
885 keys = self.keys()
886 if len(keys) == 0:
887 new_key = 1
888 else:
889 new_key = max(keys) + 1
890 new_path = os.path.join(self._path, str(new_key))
891 f = _create_carefully(new_path)
R. David Murrayf9e34232011-02-12 02:03:56 +0000892 closed = False
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +0000893 try:
894 if self._locked:
895 _lock_file(f)
896 try:
R. David Murray008c0442011-02-11 23:03:13 +0000897 try:
898 self._dump_message(message, f)
899 except BaseException:
R. David Murrayf9e34232011-02-12 02:03:56 +0000900 # Unlock and close so it can be deleted on Windows
901 if self._locked:
902 _unlock_file(f)
903 _sync_close(f)
904 closed = True
R. David Murray008c0442011-02-11 23:03:13 +0000905 os.remove(new_path)
906 raise
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +0000907 if isinstance(message, MHMessage):
908 self._dump_sequences(message, new_key)
909 finally:
910 if self._locked:
911 _unlock_file(f)
912 finally:
R. David Murrayf9e34232011-02-12 02:03:56 +0000913 if not closed:
914 _sync_close(f)
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +0000915 return new_key
916
917 def remove(self, key):
918 """Remove the keyed message; raise KeyError if it doesn't exist."""
919 path = os.path.join(self._path, str(key))
920 try:
Andrew M. Kuchling214db632006-05-02 21:44:33 +0000921 f = open(path, 'rb+')
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +0000922 except IOError, e:
923 if e.errno == errno.ENOENT:
924 raise KeyError('No message with key: %s' % key)
925 else:
926 raise
Andrew M. Kuchlingb72b0eb2010-02-22 18:42:07 +0000927 else:
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +0000928 f.close()
Andrew M. Kuchlingb72b0eb2010-02-22 18:42:07 +0000929 os.remove(path)
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +0000930
931 def __setitem__(self, key, message):
932 """Replace the keyed message; raise KeyError if it doesn't exist."""
933 path = os.path.join(self._path, str(key))
934 try:
Andrew M. Kuchling214db632006-05-02 21:44:33 +0000935 f = open(path, 'rb+')
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +0000936 except IOError, e:
937 if e.errno == errno.ENOENT:
938 raise KeyError('No message with key: %s' % key)
939 else:
940 raise
941 try:
942 if self._locked:
943 _lock_file(f)
944 try:
945 os.close(os.open(path, os.O_WRONLY | os.O_TRUNC))
946 self._dump_message(message, f)
947 if isinstance(message, MHMessage):
948 self._dump_sequences(message, key)
949 finally:
950 if self._locked:
951 _unlock_file(f)
952 finally:
Andrew M. Kuchlingb5686da2006-11-09 13:51:14 +0000953 _sync_close(f)
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +0000954
955 def get_message(self, key):
956 """Return a Message representation or raise a KeyError."""
957 try:
958 if self._locked:
Andrew M. Kuchling214db632006-05-02 21:44:33 +0000959 f = open(os.path.join(self._path, str(key)), 'r+')
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +0000960 else:
Andrew M. Kuchling214db632006-05-02 21:44:33 +0000961 f = open(os.path.join(self._path, str(key)), 'r')
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +0000962 except IOError, e:
963 if e.errno == errno.ENOENT:
964 raise KeyError('No message with key: %s' % key)
965 else:
966 raise
967 try:
968 if self._locked:
969 _lock_file(f)
970 try:
971 msg = MHMessage(f)
972 finally:
973 if self._locked:
974 _unlock_file(f)
975 finally:
976 f.close()
R. David Murray52720c52009-04-02 14:05:35 +0000977 for name, key_list in self.get_sequences().iteritems():
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +0000978 if key in key_list:
979 msg.add_sequence(name)
980 return msg
981
982 def get_string(self, key):
983 """Return a string representation or raise a KeyError."""
984 try:
985 if self._locked:
Andrew M. Kuchling214db632006-05-02 21:44:33 +0000986 f = open(os.path.join(self._path, str(key)), 'r+')
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +0000987 else:
Andrew M. Kuchling214db632006-05-02 21:44:33 +0000988 f = open(os.path.join(self._path, str(key)), 'r')
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +0000989 except IOError, e:
990 if e.errno == errno.ENOENT:
991 raise KeyError('No message with key: %s' % key)
992 else:
993 raise
994 try:
995 if self._locked:
996 _lock_file(f)
997 try:
998 return f.read()
999 finally:
1000 if self._locked:
1001 _unlock_file(f)
1002 finally:
1003 f.close()
1004
1005 def get_file(self, key):
1006 """Return a file-like representation or raise a KeyError."""
1007 try:
Andrew M. Kuchling214db632006-05-02 21:44:33 +00001008 f = open(os.path.join(self._path, str(key)), 'rb')
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +00001009 except IOError, e:
1010 if e.errno == errno.ENOENT:
1011 raise KeyError('No message with key: %s' % key)
1012 else:
1013 raise
1014 return _ProxyFile(f)
1015
1016 def iterkeys(self):
1017 """Return an iterator over keys."""
1018 return iter(sorted(int(entry) for entry in os.listdir(self._path)
1019 if entry.isdigit()))
1020
1021 def has_key(self, key):
1022 """Return True if the keyed message exists, False otherwise."""
1023 return os.path.exists(os.path.join(self._path, str(key)))
1024
1025 def __len__(self):
1026 """Return a count of messages in the mailbox."""
1027 return len(list(self.iterkeys()))
1028
1029 def lock(self):
1030 """Lock the mailbox."""
1031 if not self._locked:
Andrew M. Kuchling214db632006-05-02 21:44:33 +00001032 self._file = open(os.path.join(self._path, '.mh_sequences'), 'rb+')
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +00001033 _lock_file(self._file)
1034 self._locked = True
1035
1036 def unlock(self):
1037 """Unlock the mailbox if it is locked."""
1038 if self._locked:
1039 _unlock_file(self._file)
Andrew M. Kuchlingb5686da2006-11-09 13:51:14 +00001040 _sync_close(self._file)
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +00001041 del self._file
1042 self._locked = False
1043
1044 def flush(self):
1045 """Write any pending changes to the disk."""
1046 return
1047
1048 def close(self):
1049 """Flush and close the mailbox."""
1050 if self._locked:
1051 self.unlock()
1052
1053 def list_folders(self):
1054 """Return a list of folder names."""
1055 result = []
1056 for entry in os.listdir(self._path):
1057 if os.path.isdir(os.path.join(self._path, entry)):
1058 result.append(entry)
1059 return result
1060
1061 def get_folder(self, folder):
1062 """Return an MH instance for the named folder."""
Andrew M. Kuchlinga3e5d372006-11-09 13:27:07 +00001063 return MH(os.path.join(self._path, folder),
1064 factory=self._factory, create=False)
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +00001065
1066 def add_folder(self, folder):
1067 """Create a folder and return an MH instance representing it."""
Andrew M. Kuchlinga3e5d372006-11-09 13:27:07 +00001068 return MH(os.path.join(self._path, folder),
1069 factory=self._factory)
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +00001070
1071 def remove_folder(self, folder):
1072 """Delete the named folder, which must be empty."""
1073 path = os.path.join(self._path, folder)
1074 entries = os.listdir(path)
1075 if entries == ['.mh_sequences']:
1076 os.remove(os.path.join(path, '.mh_sequences'))
1077 elif entries == []:
1078 pass
1079 else:
1080 raise NotEmptyError('Folder not empty: %s' % self._path)
1081 os.rmdir(path)
1082
1083 def get_sequences(self):
1084 """Return a name-to-key-list dictionary to define each sequence."""
1085 results = {}
Andrew M. Kuchling214db632006-05-02 21:44:33 +00001086 f = open(os.path.join(self._path, '.mh_sequences'), 'r')
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +00001087 try:
1088 all_keys = set(self.keys())
1089 for line in f:
1090 try:
1091 name, contents = line.split(':')
1092 keys = set()
1093 for spec in contents.split():
1094 if spec.isdigit():
1095 keys.add(int(spec))
1096 else:
1097 start, stop = (int(x) for x in spec.split('-'))
1098 keys.update(range(start, stop + 1))
1099 results[name] = [key for key in sorted(keys) \
1100 if key in all_keys]
1101 if len(results[name]) == 0:
1102 del results[name]
1103 except ValueError:
1104 raise FormatError('Invalid sequence specification: %s' %
1105 line.rstrip())
1106 finally:
1107 f.close()
1108 return results
1109
1110 def set_sequences(self, sequences):
1111 """Set sequences using the given name-to-key-list dictionary."""
Andrew M. Kuchling214db632006-05-02 21:44:33 +00001112 f = open(os.path.join(self._path, '.mh_sequences'), 'r+')
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +00001113 try:
1114 os.close(os.open(f.name, os.O_WRONLY | os.O_TRUNC))
1115 for name, keys in sequences.iteritems():
1116 if len(keys) == 0:
1117 continue
1118 f.write('%s:' % name)
1119 prev = None
1120 completing = False
1121 for key in sorted(set(keys)):
1122 if key - 1 == prev:
1123 if not completing:
1124 completing = True
1125 f.write('-')
1126 elif completing:
1127 completing = False
1128 f.write('%s %s' % (prev, key))
1129 else:
1130 f.write(' %s' % key)
1131 prev = key
1132 if completing:
1133 f.write(str(prev) + '\n')
1134 else:
1135 f.write('\n')
1136 finally:
Andrew M. Kuchlingb5686da2006-11-09 13:51:14 +00001137 _sync_close(f)
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +00001138
1139 def pack(self):
1140 """Re-name messages to eliminate numbering gaps. Invalidates keys."""
1141 sequences = self.get_sequences()
1142 prev = 0
1143 changes = []
1144 for key in self.iterkeys():
1145 if key - 1 != prev:
1146 changes.append((key, prev + 1))
Andrew M. Kuchling8c456f32006-11-17 13:30:25 +00001147 if hasattr(os, 'link'):
1148 os.link(os.path.join(self._path, str(key)),
1149 os.path.join(self._path, str(prev + 1)))
1150 os.unlink(os.path.join(self._path, str(key)))
1151 else:
1152 os.rename(os.path.join(self._path, str(key)),
1153 os.path.join(self._path, str(prev + 1)))
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +00001154 prev += 1
1155 self._next_key = prev + 1
1156 if len(changes) == 0:
1157 return
1158 for name, key_list in sequences.items():
1159 for old, new in changes:
1160 if old in key_list:
1161 key_list[key_list.index(old)] = new
1162 self.set_sequences(sequences)
1163
1164 def _dump_sequences(self, message, key):
1165 """Inspect a new MHMessage and update sequences appropriately."""
1166 pending_sequences = message.get_sequences()
1167 all_sequences = self.get_sequences()
1168 for name, key_list in all_sequences.iteritems():
1169 if name in pending_sequences:
1170 key_list.append(key)
1171 elif key in key_list:
1172 del key_list[key_list.index(key)]
1173 for sequence in pending_sequences:
1174 if sequence not in all_sequences:
1175 all_sequences[sequence] = [key]
1176 self.set_sequences(all_sequences)
1177
1178
1179class Babyl(_singlefileMailbox):
1180 """An Rmail-style Babyl mailbox."""
1181
1182 _special_labels = frozenset(('unseen', 'deleted', 'filed', 'answered',
1183 'forwarded', 'edited', 'resent'))
1184
1185 def __init__(self, path, factory=None, create=True):
1186 """Initialize a Babyl mailbox."""
1187 _singlefileMailbox.__init__(self, path, factory, create)
1188 self._labels = {}
1189
1190 def add(self, message):
1191 """Add message and return assigned key."""
1192 key = _singlefileMailbox.add(self, message)
1193 if isinstance(message, BabylMessage):
1194 self._labels[key] = message.get_labels()
1195 return key
1196
1197 def remove(self, key):
1198 """Remove the keyed message; raise KeyError if it doesn't exist."""
1199 _singlefileMailbox.remove(self, key)
1200 if key in self._labels:
1201 del self._labels[key]
1202
1203 def __setitem__(self, key, message):
1204 """Replace the keyed message; raise KeyError if it doesn't exist."""
1205 _singlefileMailbox.__setitem__(self, key, message)
1206 if isinstance(message, BabylMessage):
1207 self._labels[key] = message.get_labels()
1208
1209 def get_message(self, key):
1210 """Return a Message representation or raise a KeyError."""
1211 start, stop = self._lookup(key)
1212 self._file.seek(start)
1213 self._file.readline() # Skip '1,' line specifying labels.
1214 original_headers = StringIO.StringIO()
1215 while True:
1216 line = self._file.readline()
1217 if line == '*** EOOH ***' + os.linesep or line == '':
1218 break
1219 original_headers.write(line.replace(os.linesep, '\n'))
1220 visible_headers = StringIO.StringIO()
1221 while True:
1222 line = self._file.readline()
1223 if line == os.linesep or line == '':
1224 break
1225 visible_headers.write(line.replace(os.linesep, '\n'))
1226 body = self._file.read(stop - self._file.tell()).replace(os.linesep,
1227 '\n')
1228 msg = BabylMessage(original_headers.getvalue() + body)
1229 msg.set_visible(visible_headers.getvalue())
1230 if key in self._labels:
1231 msg.set_labels(self._labels[key])
1232 return msg
1233
1234 def get_string(self, key):
1235 """Return a string representation or raise a KeyError."""
1236 start, stop = self._lookup(key)
1237 self._file.seek(start)
1238 self._file.readline() # Skip '1,' line specifying labels.
1239 original_headers = StringIO.StringIO()
1240 while True:
1241 line = self._file.readline()
1242 if line == '*** EOOH ***' + os.linesep or line == '':
1243 break
1244 original_headers.write(line.replace(os.linesep, '\n'))
1245 while True:
1246 line = self._file.readline()
1247 if line == os.linesep or line == '':
1248 break
1249 return original_headers.getvalue() + \
1250 self._file.read(stop - self._file.tell()).replace(os.linesep,
1251 '\n')
1252
1253 def get_file(self, key):
1254 """Return a file-like representation or raise a KeyError."""
1255 return StringIO.StringIO(self.get_string(key).replace('\n',
1256 os.linesep))
1257
1258 def get_labels(self):
1259 """Return a list of user-defined labels in the mailbox."""
1260 self._lookup()
1261 labels = set()
1262 for label_list in self._labels.values():
1263 labels.update(label_list)
1264 labels.difference_update(self._special_labels)
1265 return list(labels)
1266
1267 def _generate_toc(self):
1268 """Generate key-to-(start, stop) table of contents."""
1269 starts, stops = [], []
1270 self._file.seek(0)
1271 next_pos = 0
1272 label_lists = []
1273 while True:
1274 line_pos = next_pos
1275 line = self._file.readline()
1276 next_pos = self._file.tell()
1277 if line == '\037\014' + os.linesep:
1278 if len(stops) < len(starts):
1279 stops.append(line_pos - len(os.linesep))
1280 starts.append(next_pos)
1281 labels = [label.strip() for label
1282 in self._file.readline()[1:].split(',')
1283 if label.strip() != '']
1284 label_lists.append(labels)
1285 elif line == '\037' or line == '\037' + os.linesep:
1286 if len(stops) < len(starts):
1287 stops.append(line_pos - len(os.linesep))
1288 elif line == '':
1289 stops.append(line_pos - len(os.linesep))
1290 break
1291 self._toc = dict(enumerate(zip(starts, stops)))
1292 self._labels = dict(enumerate(label_lists))
1293 self._next_key = len(self._toc)
Andrew M. Kuchlingeca4c312006-12-20 19:48:20 +00001294 self._file.seek(0, 2)
1295 self._file_length = self._file.tell()
Tim Petersf733abb2007-01-30 03:03:46 +00001296
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +00001297 def _pre_mailbox_hook(self, f):
1298 """Called before writing the mailbox to file f."""
1299 f.write('BABYL OPTIONS:%sVersion: 5%sLabels:%s%s\037' %
1300 (os.linesep, os.linesep, ','.join(self.get_labels()),
1301 os.linesep))
1302
1303 def _pre_message_hook(self, f):
1304 """Called before writing each message to file f."""
1305 f.write('\014' + os.linesep)
1306
1307 def _post_message_hook(self, f):
1308 """Called after writing each message to file f."""
1309 f.write(os.linesep + '\037')
1310
1311 def _install_message(self, message):
1312 """Write message contents and return (start, stop)."""
1313 start = self._file.tell()
1314 if isinstance(message, BabylMessage):
1315 special_labels = []
1316 labels = []
1317 for label in message.get_labels():
1318 if label in self._special_labels:
1319 special_labels.append(label)
1320 else:
1321 labels.append(label)
1322 self._file.write('1')
1323 for label in special_labels:
1324 self._file.write(', ' + label)
1325 self._file.write(',,')
1326 for label in labels:
1327 self._file.write(' ' + label + ',')
1328 self._file.write(os.linesep)
1329 else:
1330 self._file.write('1,,' + os.linesep)
Georg Brandl5a096e12007-01-22 19:40:21 +00001331 if isinstance(message, email.message.Message):
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +00001332 orig_buffer = StringIO.StringIO()
Georg Brandl5a096e12007-01-22 19:40:21 +00001333 orig_generator = email.generator.Generator(orig_buffer, False, 0)
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +00001334 orig_generator.flatten(message)
1335 orig_buffer.seek(0)
1336 while True:
1337 line = orig_buffer.readline()
1338 self._file.write(line.replace('\n', os.linesep))
1339 if line == '\n' or line == '':
1340 break
1341 self._file.write('*** EOOH ***' + os.linesep)
1342 if isinstance(message, BabylMessage):
1343 vis_buffer = StringIO.StringIO()
Georg Brandl5a096e12007-01-22 19:40:21 +00001344 vis_generator = email.generator.Generator(vis_buffer, False, 0)
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +00001345 vis_generator.flatten(message.get_visible())
1346 while True:
1347 line = vis_buffer.readline()
1348 self._file.write(line.replace('\n', os.linesep))
1349 if line == '\n' or line == '':
1350 break
1351 else:
1352 orig_buffer.seek(0)
1353 while True:
1354 line = orig_buffer.readline()
1355 self._file.write(line.replace('\n', os.linesep))
1356 if line == '\n' or line == '':
1357 break
1358 while True:
1359 buffer = orig_buffer.read(4096) # Buffer size is arbitrary.
1360 if buffer == '':
1361 break
1362 self._file.write(buffer.replace('\n', os.linesep))
1363 elif isinstance(message, str):
1364 body_start = message.find('\n\n') + 2
1365 if body_start - 2 != -1:
1366 self._file.write(message[:body_start].replace('\n',
1367 os.linesep))
1368 self._file.write('*** EOOH ***' + os.linesep)
1369 self._file.write(message[:body_start].replace('\n',
1370 os.linesep))
1371 self._file.write(message[body_start:].replace('\n',
1372 os.linesep))
1373 else:
1374 self._file.write('*** EOOH ***' + os.linesep + os.linesep)
1375 self._file.write(message.replace('\n', os.linesep))
1376 elif hasattr(message, 'readline'):
1377 original_pos = message.tell()
1378 first_pass = True
1379 while True:
1380 line = message.readline()
1381 self._file.write(line.replace('\n', os.linesep))
1382 if line == '\n' or line == '':
1383 self._file.write('*** EOOH ***' + os.linesep)
1384 if first_pass:
1385 first_pass = False
1386 message.seek(original_pos)
1387 else:
1388 break
1389 while True:
1390 buffer = message.read(4096) # Buffer size is arbitrary.
1391 if buffer == '':
1392 break
1393 self._file.write(buffer.replace('\n', os.linesep))
1394 else:
1395 raise TypeError('Invalid message type: %s' % type(message))
1396 stop = self._file.tell()
1397 return (start, stop)
1398
1399
Georg Brandl5a096e12007-01-22 19:40:21 +00001400class Message(email.message.Message):
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +00001401 """Message with mailbox-format-specific properties."""
1402
1403 def __init__(self, message=None):
1404 """Initialize a Message instance."""
Georg Brandl5a096e12007-01-22 19:40:21 +00001405 if isinstance(message, email.message.Message):
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +00001406 self._become_message(copy.deepcopy(message))
1407 if isinstance(message, Message):
1408 message._explain_to(self)
1409 elif isinstance(message, str):
1410 self._become_message(email.message_from_string(message))
1411 elif hasattr(message, "read"):
1412 self._become_message(email.message_from_file(message))
1413 elif message is None:
Georg Brandl5a096e12007-01-22 19:40:21 +00001414 email.message.Message.__init__(self)
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +00001415 else:
1416 raise TypeError('Invalid message type: %s' % type(message))
1417
1418 def _become_message(self, message):
1419 """Assume the non-format-specific state of message."""
1420 for name in ('_headers', '_unixfrom', '_payload', '_charset',
1421 'preamble', 'epilogue', 'defects', '_default_type'):
1422 self.__dict__[name] = message.__dict__[name]
1423
1424 def _explain_to(self, message):
1425 """Copy format-specific state to message insofar as possible."""
1426 if isinstance(message, Message):
1427 return # There's nothing format-specific to explain.
1428 else:
1429 raise TypeError('Cannot convert to specified type')
1430
1431
1432class MaildirMessage(Message):
1433 """Message with Maildir-specific properties."""
1434
1435 def __init__(self, message=None):
1436 """Initialize a MaildirMessage instance."""
1437 self._subdir = 'new'
1438 self._info = ''
1439 self._date = time.time()
1440 Message.__init__(self, message)
1441
1442 def get_subdir(self):
1443 """Return 'new' or 'cur'."""
1444 return self._subdir
1445
1446 def set_subdir(self, subdir):
1447 """Set subdir to 'new' or 'cur'."""
1448 if subdir == 'new' or subdir == 'cur':
1449 self._subdir = subdir
1450 else:
1451 raise ValueError("subdir must be 'new' or 'cur': %s" % subdir)
1452
1453 def get_flags(self):
1454 """Return as a string the flags that are set."""
1455 if self._info.startswith('2,'):
1456 return self._info[2:]
1457 else:
1458 return ''
1459
1460 def set_flags(self, flags):
1461 """Set the given flags and unset all others."""
1462 self._info = '2,' + ''.join(sorted(flags))
1463
1464 def add_flag(self, flag):
1465 """Set the given flag(s) without changing others."""
1466 self.set_flags(''.join(set(self.get_flags()) | set(flag)))
1467
1468 def remove_flag(self, flag):
1469 """Unset the given string flag(s) without changing others."""
1470 if self.get_flags() != '':
1471 self.set_flags(''.join(set(self.get_flags()) - set(flag)))
1472
1473 def get_date(self):
1474 """Return delivery date of message, in seconds since the epoch."""
1475 return self._date
1476
1477 def set_date(self, date):
1478 """Set delivery date of message, in seconds since the epoch."""
1479 try:
1480 self._date = float(date)
1481 except ValueError:
1482 raise TypeError("can't convert to float: %s" % date)
1483
1484 def get_info(self):
1485 """Get the message's "info" as a string."""
1486 return self._info
1487
1488 def set_info(self, info):
1489 """Set the message's "info" string."""
1490 if isinstance(info, str):
1491 self._info = info
1492 else:
1493 raise TypeError('info must be a string: %s' % type(info))
1494
1495 def _explain_to(self, message):
1496 """Copy Maildir-specific state to message insofar as possible."""
1497 if isinstance(message, MaildirMessage):
1498 message.set_flags(self.get_flags())
1499 message.set_subdir(self.get_subdir())
1500 message.set_date(self.get_date())
1501 elif isinstance(message, _mboxMMDFMessage):
1502 flags = set(self.get_flags())
1503 if 'S' in flags:
1504 message.add_flag('R')
1505 if self.get_subdir() == 'cur':
1506 message.add_flag('O')
1507 if 'T' in flags:
1508 message.add_flag('D')
1509 if 'F' in flags:
1510 message.add_flag('F')
1511 if 'R' in flags:
1512 message.add_flag('A')
1513 message.set_from('MAILER-DAEMON', time.gmtime(self.get_date()))
1514 elif isinstance(message, MHMessage):
1515 flags = set(self.get_flags())
1516 if 'S' not in flags:
1517 message.add_sequence('unseen')
1518 if 'R' in flags:
1519 message.add_sequence('replied')
1520 if 'F' in flags:
1521 message.add_sequence('flagged')
1522 elif isinstance(message, BabylMessage):
1523 flags = set(self.get_flags())
1524 if 'S' not in flags:
1525 message.add_label('unseen')
1526 if 'T' in flags:
1527 message.add_label('deleted')
1528 if 'R' in flags:
1529 message.add_label('answered')
1530 if 'P' in flags:
1531 message.add_label('forwarded')
1532 elif isinstance(message, Message):
1533 pass
1534 else:
1535 raise TypeError('Cannot convert to specified type: %s' %
1536 type(message))
1537
1538
1539class _mboxMMDFMessage(Message):
1540 """Message with mbox- or MMDF-specific properties."""
1541
1542 def __init__(self, message=None):
1543 """Initialize an mboxMMDFMessage instance."""
1544 self.set_from('MAILER-DAEMON', True)
Georg Brandl5a096e12007-01-22 19:40:21 +00001545 if isinstance(message, email.message.Message):
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +00001546 unixfrom = message.get_unixfrom()
1547 if unixfrom is not None and unixfrom.startswith('From '):
1548 self.set_from(unixfrom[5:])
1549 Message.__init__(self, message)
1550
1551 def get_from(self):
1552 """Return contents of "From " line."""
1553 return self._from
1554
1555 def set_from(self, from_, time_=None):
1556 """Set "From " line, formatting and appending time_ if specified."""
1557 if time_ is not None:
1558 if time_ is True:
1559 time_ = time.gmtime()
1560 from_ += ' ' + time.asctime(time_)
1561 self._from = from_
1562
1563 def get_flags(self):
1564 """Return as a string the flags that are set."""
1565 return self.get('Status', '') + self.get('X-Status', '')
1566
1567 def set_flags(self, flags):
1568 """Set the given flags and unset all others."""
1569 flags = set(flags)
1570 status_flags, xstatus_flags = '', ''
1571 for flag in ('R', 'O'):
1572 if flag in flags:
1573 status_flags += flag
1574 flags.remove(flag)
1575 for flag in ('D', 'F', 'A'):
1576 if flag in flags:
1577 xstatus_flags += flag
1578 flags.remove(flag)
1579 xstatus_flags += ''.join(sorted(flags))
1580 try:
1581 self.replace_header('Status', status_flags)
1582 except KeyError:
1583 self.add_header('Status', status_flags)
1584 try:
1585 self.replace_header('X-Status', xstatus_flags)
1586 except KeyError:
1587 self.add_header('X-Status', xstatus_flags)
1588
1589 def add_flag(self, flag):
1590 """Set the given flag(s) without changing others."""
1591 self.set_flags(''.join(set(self.get_flags()) | set(flag)))
1592
1593 def remove_flag(self, flag):
1594 """Unset the given string flag(s) without changing others."""
1595 if 'Status' in self or 'X-Status' in self:
1596 self.set_flags(''.join(set(self.get_flags()) - set(flag)))
1597
1598 def _explain_to(self, message):
1599 """Copy mbox- or MMDF-specific state to message insofar as possible."""
1600 if isinstance(message, MaildirMessage):
1601 flags = set(self.get_flags())
1602 if 'O' in flags:
1603 message.set_subdir('cur')
1604 if 'F' in flags:
1605 message.add_flag('F')
1606 if 'A' in flags:
1607 message.add_flag('R')
1608 if 'R' in flags:
1609 message.add_flag('S')
1610 if 'D' in flags:
1611 message.add_flag('T')
1612 del message['status']
1613 del message['x-status']
1614 maybe_date = ' '.join(self.get_from().split()[-5:])
1615 try:
1616 message.set_date(calendar.timegm(time.strptime(maybe_date,
1617 '%a %b %d %H:%M:%S %Y')))
1618 except (ValueError, OverflowError):
1619 pass
1620 elif isinstance(message, _mboxMMDFMessage):
1621 message.set_flags(self.get_flags())
1622 message.set_from(self.get_from())
1623 elif isinstance(message, MHMessage):
1624 flags = set(self.get_flags())
1625 if 'R' not in flags:
1626 message.add_sequence('unseen')
1627 if 'A' in flags:
1628 message.add_sequence('replied')
1629 if 'F' in flags:
1630 message.add_sequence('flagged')
1631 del message['status']
1632 del message['x-status']
1633 elif isinstance(message, BabylMessage):
1634 flags = set(self.get_flags())
1635 if 'R' not in flags:
1636 message.add_label('unseen')
1637 if 'D' in flags:
1638 message.add_label('deleted')
1639 if 'A' in flags:
1640 message.add_label('answered')
1641 del message['status']
1642 del message['x-status']
1643 elif isinstance(message, Message):
1644 pass
1645 else:
1646 raise TypeError('Cannot convert to specified type: %s' %
1647 type(message))
1648
1649
1650class mboxMessage(_mboxMMDFMessage):
1651 """Message with mbox-specific properties."""
1652
1653
1654class MHMessage(Message):
1655 """Message with MH-specific properties."""
1656
1657 def __init__(self, message=None):
1658 """Initialize an MHMessage instance."""
1659 self._sequences = []
1660 Message.__init__(self, message)
1661
1662 def get_sequences(self):
1663 """Return a list of sequences that include the message."""
1664 return self._sequences[:]
1665
1666 def set_sequences(self, sequences):
1667 """Set the list of sequences that include the message."""
1668 self._sequences = list(sequences)
1669
1670 def add_sequence(self, sequence):
1671 """Add sequence to list of sequences including the message."""
1672 if isinstance(sequence, str):
1673 if not sequence in self._sequences:
1674 self._sequences.append(sequence)
1675 else:
1676 raise TypeError('sequence must be a string: %s' % type(sequence))
1677
1678 def remove_sequence(self, sequence):
1679 """Remove sequence from the list of sequences including the message."""
1680 try:
1681 self._sequences.remove(sequence)
1682 except ValueError:
1683 pass
1684
1685 def _explain_to(self, message):
1686 """Copy MH-specific state to message insofar as possible."""
1687 if isinstance(message, MaildirMessage):
1688 sequences = set(self.get_sequences())
1689 if 'unseen' in sequences:
1690 message.set_subdir('cur')
1691 else:
1692 message.set_subdir('cur')
1693 message.add_flag('S')
1694 if 'flagged' in sequences:
1695 message.add_flag('F')
1696 if 'replied' in sequences:
1697 message.add_flag('R')
1698 elif isinstance(message, _mboxMMDFMessage):
1699 sequences = set(self.get_sequences())
1700 if 'unseen' not in sequences:
1701 message.add_flag('RO')
1702 else:
1703 message.add_flag('O')
1704 if 'flagged' in sequences:
1705 message.add_flag('F')
1706 if 'replied' in sequences:
1707 message.add_flag('A')
1708 elif isinstance(message, MHMessage):
1709 for sequence in self.get_sequences():
1710 message.add_sequence(sequence)
1711 elif isinstance(message, BabylMessage):
1712 sequences = set(self.get_sequences())
1713 if 'unseen' in sequences:
1714 message.add_label('unseen')
1715 if 'replied' in sequences:
1716 message.add_label('answered')
1717 elif isinstance(message, Message):
1718 pass
1719 else:
1720 raise TypeError('Cannot convert to specified type: %s' %
1721 type(message))
1722
1723
1724class BabylMessage(Message):
1725 """Message with Babyl-specific properties."""
1726
1727 def __init__(self, message=None):
1728 """Initialize an BabylMessage instance."""
1729 self._labels = []
1730 self._visible = Message()
1731 Message.__init__(self, message)
1732
1733 def get_labels(self):
1734 """Return a list of labels on the message."""
1735 return self._labels[:]
1736
1737 def set_labels(self, labels):
1738 """Set the list of labels on the message."""
1739 self._labels = list(labels)
1740
1741 def add_label(self, label):
1742 """Add label to list of labels on the message."""
1743 if isinstance(label, str):
1744 if label not in self._labels:
1745 self._labels.append(label)
1746 else:
1747 raise TypeError('label must be a string: %s' % type(label))
1748
1749 def remove_label(self, label):
1750 """Remove label from the list of labels on the message."""
1751 try:
1752 self._labels.remove(label)
1753 except ValueError:
1754 pass
Tim Peters6d7cd7d2006-04-22 05:52:59 +00001755
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +00001756 def get_visible(self):
1757 """Return a Message representation of visible headers."""
1758 return Message(self._visible)
1759
1760 def set_visible(self, visible):
1761 """Set the Message representation of visible headers."""
1762 self._visible = Message(visible)
1763
1764 def update_visible(self):
1765 """Update and/or sensibly generate a set of visible headers."""
1766 for header in self._visible.keys():
1767 if header in self:
1768 self._visible.replace_header(header, self[header])
1769 else:
1770 del self._visible[header]
1771 for header in ('Date', 'From', 'Reply-To', 'To', 'CC', 'Subject'):
1772 if header in self and header not in self._visible:
1773 self._visible[header] = self[header]
1774
1775 def _explain_to(self, message):
1776 """Copy Babyl-specific state to message insofar as possible."""
1777 if isinstance(message, MaildirMessage):
1778 labels = set(self.get_labels())
1779 if 'unseen' in labels:
1780 message.set_subdir('cur')
1781 else:
1782 message.set_subdir('cur')
1783 message.add_flag('S')
1784 if 'forwarded' in labels or 'resent' in labels:
1785 message.add_flag('P')
1786 if 'answered' in labels:
1787 message.add_flag('R')
1788 if 'deleted' in labels:
1789 message.add_flag('T')
1790 elif isinstance(message, _mboxMMDFMessage):
1791 labels = set(self.get_labels())
1792 if 'unseen' not in labels:
1793 message.add_flag('RO')
1794 else:
1795 message.add_flag('O')
1796 if 'deleted' in labels:
1797 message.add_flag('D')
1798 if 'answered' in labels:
1799 message.add_flag('A')
1800 elif isinstance(message, MHMessage):
1801 labels = set(self.get_labels())
1802 if 'unseen' in labels:
1803 message.add_sequence('unseen')
1804 if 'answered' in labels:
1805 message.add_sequence('replied')
1806 elif isinstance(message, BabylMessage):
1807 message.set_visible(self.get_visible())
1808 for label in self.get_labels():
1809 message.add_label(label)
1810 elif isinstance(message, Message):
1811 pass
1812 else:
1813 raise TypeError('Cannot convert to specified type: %s' %
1814 type(message))
1815
1816
1817class MMDFMessage(_mboxMMDFMessage):
1818 """Message with MMDF-specific properties."""
1819
1820
1821class _ProxyFile:
1822 """A read-only wrapper of a file."""
1823
1824 def __init__(self, f, pos=None):
1825 """Initialize a _ProxyFile."""
1826 self._file = f
1827 if pos is None:
1828 self._pos = f.tell()
1829 else:
1830 self._pos = pos
1831
1832 def read(self, size=None):
1833 """Read bytes."""
1834 return self._read(size, self._file.read)
1835
1836 def readline(self, size=None):
1837 """Read a line."""
1838 return self._read(size, self._file.readline)
1839
1840 def readlines(self, sizehint=None):
1841 """Read multiple lines."""
1842 result = []
1843 for line in self:
1844 result.append(line)
1845 if sizehint is not None:
1846 sizehint -= len(line)
1847 if sizehint <= 0:
1848 break
1849 return result
1850
1851 def __iter__(self):
1852 """Iterate over lines."""
1853 return iter(self.readline, "")
1854
1855 def tell(self):
1856 """Return the position."""
1857 return self._pos
1858
1859 def seek(self, offset, whence=0):
1860 """Change position."""
1861 if whence == 1:
1862 self._file.seek(self._pos)
1863 self._file.seek(offset, whence)
1864 self._pos = self._file.tell()
1865
1866 def close(self):
1867 """Close the file."""
R David Murrayf1138bb2011-06-17 22:23:04 -04001868 if hasattr(self, '_file'):
1869 if hasattr(self._file, 'close'):
1870 self._file.close()
1871 del self._file
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +00001872
1873 def _read(self, size, read_method):
1874 """Read size bytes using read_method."""
1875 if size is None:
1876 size = -1
1877 self._file.seek(self._pos)
1878 result = read_method(size)
1879 self._pos = self._file.tell()
1880 return result
1881
1882
1883class _PartialFile(_ProxyFile):
1884 """A read-only wrapper of part of a file."""
1885
1886 def __init__(self, f, start=None, stop=None):
1887 """Initialize a _PartialFile."""
1888 _ProxyFile.__init__(self, f, start)
1889 self._start = start
1890 self._stop = stop
1891
1892 def tell(self):
1893 """Return the position with respect to start."""
1894 return _ProxyFile.tell(self) - self._start
1895
1896 def seek(self, offset, whence=0):
1897 """Change position, possibly with respect to start or stop."""
1898 if whence == 0:
1899 self._pos = self._start
1900 whence = 1
1901 elif whence == 2:
1902 self._pos = self._stop
1903 whence = 1
1904 _ProxyFile.seek(self, offset, whence)
1905
1906 def _read(self, size, read_method):
1907 """Read size bytes using read_method, honoring start and stop."""
1908 remaining = self._stop - self._pos
1909 if remaining <= 0:
1910 return ''
1911 if size is None or size < 0 or size > remaining:
1912 size = remaining
1913 return _ProxyFile._read(self, size, read_method)
1914
R David Murrayf1138bb2011-06-17 22:23:04 -04001915 def close(self):
1916 # do *not* close the underlying file object for partial files,
1917 # since it's global to the mailbox object
1918 if hasattr(self, '_file'):
1919 del self._file
1920
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +00001921
1922def _lock_file(f, dotlock=True):
Andrew M. Kuchling55732592006-06-26 13:12:16 +00001923 """Lock file f using lockf and dot locking."""
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +00001924 dotlock_done = False
1925 try:
1926 if fcntl:
1927 try:
1928 fcntl.lockf(f, fcntl.LOCK_EX | fcntl.LOCK_NB)
1929 except IOError, e:
R. David Murray1a337902011-03-03 18:17:40 +00001930 if e.errno in (errno.EAGAIN, errno.EACCES, errno.EROFS):
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +00001931 raise ExternalClashError('lockf: lock unavailable: %s' %
1932 f.name)
1933 else:
1934 raise
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +00001935 if dotlock:
1936 try:
1937 pre_lock = _create_temporary(f.name + '.lock')
1938 pre_lock.close()
1939 except IOError, e:
R. David Murray1a337902011-03-03 18:17:40 +00001940 if e.errno in (errno.EACCES, errno.EROFS):
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +00001941 return # Without write access, just skip dotlocking.
1942 else:
1943 raise
1944 try:
1945 if hasattr(os, 'link'):
1946 os.link(pre_lock.name, f.name + '.lock')
1947 dotlock_done = True
1948 os.unlink(pre_lock.name)
1949 else:
1950 os.rename(pre_lock.name, f.name + '.lock')
1951 dotlock_done = True
1952 except OSError, e:
Andrew MacIntyreafa358f2006-07-23 13:04:00 +00001953 if e.errno == errno.EEXIST or \
1954 (os.name == 'os2' and e.errno == errno.EACCES):
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +00001955 os.remove(pre_lock.name)
Tim Peters6d7cd7d2006-04-22 05:52:59 +00001956 raise ExternalClashError('dot lock unavailable: %s' %
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +00001957 f.name)
1958 else:
1959 raise
1960 except:
1961 if fcntl:
1962 fcntl.lockf(f, fcntl.LOCK_UN)
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +00001963 if dotlock_done:
1964 os.remove(f.name + '.lock')
1965 raise
1966
1967def _unlock_file(f):
Andrew M. Kuchling55732592006-06-26 13:12:16 +00001968 """Unlock file f using lockf and dot locking."""
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +00001969 if fcntl:
1970 fcntl.lockf(f, fcntl.LOCK_UN)
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +00001971 if os.path.exists(f.name + '.lock'):
1972 os.remove(f.name + '.lock')
1973
1974def _create_carefully(path):
1975 """Create a file if it doesn't exist and open for reading and writing."""
Andrew M. Kuchling70a6dbd2008-08-04 01:43:43 +00001976 fd = os.open(path, os.O_CREAT | os.O_EXCL | os.O_RDWR, 0666)
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +00001977 try:
Andrew M. Kuchling214db632006-05-02 21:44:33 +00001978 return open(path, 'rb+')
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +00001979 finally:
1980 os.close(fd)
1981
1982def _create_temporary(path):
1983 """Create a temp file based on path and open for reading and writing."""
1984 return _create_carefully('%s.%s.%s.%s' % (path, int(time.time()),
1985 socket.gethostname(),
1986 os.getpid()))
1987
Andrew M. Kuchlingb5686da2006-11-09 13:51:14 +00001988def _sync_flush(f):
1989 """Ensure changes to file f are physically on disk."""
1990 f.flush()
Andrew M. Kuchling16465682006-12-14 18:57:53 +00001991 if hasattr(os, 'fsync'):
1992 os.fsync(f.fileno())
Andrew M. Kuchlingb5686da2006-11-09 13:51:14 +00001993
1994def _sync_close(f):
1995 """Close file f, ensuring all changes are physically on disk."""
1996 _sync_flush(f)
1997 f.close()
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +00001998
1999## Start: classes from the original module (for backward compatibility).
2000
2001# Note that the Maildir class, whose name is unchanged, itself offers a next()
2002# method for backward compatibility.
Skip Montanaro17ab1232001-01-24 06:27:27 +00002003
Guido van Rossumc7b68821994-04-28 09:53:33 +00002004class _Mailbox:
Guido van Rossum4bf12542002-09-12 05:08:00 +00002005
Barry Warsaw81ad67c2001-01-31 22:13:15 +00002006 def __init__(self, fp, factory=rfc822.Message):
Fred Drakedbbf76b2000-07-09 16:44:26 +00002007 self.fp = fp
2008 self.seekp = 0
Barry Warsaw81ad67c2001-01-31 22:13:15 +00002009 self.factory = factory
Guido van Rossum8ca84201998-03-26 20:56:10 +00002010
Fred Drake72987a42001-05-02 20:20:53 +00002011 def __iter__(self):
Guido van Rossum93a696f2001-09-13 01:29:13 +00002012 return iter(self.next, None)
Fred Drake72987a42001-05-02 20:20:53 +00002013
Fred Drakedbbf76b2000-07-09 16:44:26 +00002014 def next(self):
2015 while 1:
2016 self.fp.seek(self.seekp)
2017 try:
2018 self._search_start()
2019 except EOFError:
2020 self.seekp = self.fp.tell()
2021 return None
2022 start = self.fp.tell()
2023 self._search_end()
2024 self.seekp = stop = self.fp.tell()
Fred Drake8152d322000-12-12 23:20:45 +00002025 if start != stop:
Fred Drakedbbf76b2000-07-09 16:44:26 +00002026 break
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +00002027 return self.factory(_PartialFile(self.fp, start, stop))
Guido van Rossumc7b68821994-04-28 09:53:33 +00002028
Barry Warsawffd05ee2002-03-01 22:39:14 +00002029# Recommended to use PortableUnixMailbox instead!
Guido van Rossumc7b68821994-04-28 09:53:33 +00002030class UnixMailbox(_Mailbox):
Guido van Rossum4bf12542002-09-12 05:08:00 +00002031
Fred Drakedbbf76b2000-07-09 16:44:26 +00002032 def _search_start(self):
2033 while 1:
2034 pos = self.fp.tell()
2035 line = self.fp.readline()
2036 if not line:
2037 raise EOFError
2038 if line[:5] == 'From ' and self._isrealfromline(line):
2039 self.fp.seek(pos)
2040 return
Guido van Rossum8ca84201998-03-26 20:56:10 +00002041
Fred Drakedbbf76b2000-07-09 16:44:26 +00002042 def _search_end(self):
2043 self.fp.readline() # Throw away header line
2044 while 1:
2045 pos = self.fp.tell()
2046 line = self.fp.readline()
2047 if not line:
2048 return
2049 if line[:5] == 'From ' and self._isrealfromline(line):
2050 self.fp.seek(pos)
2051 return
Guido van Rossumc7b68821994-04-28 09:53:33 +00002052
Barry Warsaw81ad67c2001-01-31 22:13:15 +00002053 # An overridable mechanism to test for From-line-ness. You can either
2054 # specify a different regular expression or define a whole new
2055 # _isrealfromline() method. Note that this only gets called for lines
2056 # starting with the 5 characters "From ".
2057 #
2058 # BAW: According to
2059 #http://home.netscape.com/eng/mozilla/2.0/relnotes/demo/content-length.html
2060 # the only portable, reliable way to find message delimiters in a BSD (i.e
2061 # Unix mailbox) style folder is to search for "\n\nFrom .*\n", or at the
2062 # beginning of the file, "^From .*\n". While _fromlinepattern below seems
2063 # like a good idea, in practice, there are too many variations for more
2064 # strict parsing of the line to be completely accurate.
2065 #
2066 # _strict_isrealfromline() is the old version which tries to do stricter
2067 # parsing of the From_ line. _portable_isrealfromline() simply returns
2068 # true, since it's never called if the line doesn't already start with
2069 # "From ".
2070 #
2071 # This algorithm, and the way it interacts with _search_start() and
2072 # _search_end() may not be completely correct, because it doesn't check
2073 # that the two characters preceding "From " are \n\n or the beginning of
2074 # the file. Fixing this would require a more extensive rewrite than is
Barry Warsawda5628f2002-08-26 16:44:56 +00002075 # necessary. For convenience, we've added a PortableUnixMailbox class
Andrew M. Kuchlingb94c0c32007-01-22 20:27:50 +00002076 # which does no checking of the format of the 'From' line.
Guido van Rossumc7b68821994-04-28 09:53:33 +00002077
Andrew M. Kuchlingb78bb742007-01-22 20:26:40 +00002078 _fromlinepattern = (r"From \s*[^\s]+\s+\w\w\w\s+\w\w\w\s+\d?\d\s+"
2079 r"\d?\d:\d\d(:\d\d)?(\s+[^\s]+)?\s+\d\d\d\d\s*"
2080 r"[^\s]*\s*"
2081 "$")
Fred Drakedbbf76b2000-07-09 16:44:26 +00002082 _regexp = None
Guido van Rossumfbe63de1998-04-03 16:04:05 +00002083
Barry Warsaw81ad67c2001-01-31 22:13:15 +00002084 def _strict_isrealfromline(self, line):
Fred Drakedbbf76b2000-07-09 16:44:26 +00002085 if not self._regexp:
2086 import re
2087 self._regexp = re.compile(self._fromlinepattern)
2088 return self._regexp.match(line)
Guido van Rossumfbe63de1998-04-03 16:04:05 +00002089
Barry Warsaw81ad67c2001-01-31 22:13:15 +00002090 def _portable_isrealfromline(self, line):
Tim Petersbc0e9102002-04-04 22:55:58 +00002091 return True
Barry Warsaw81ad67c2001-01-31 22:13:15 +00002092
2093 _isrealfromline = _strict_isrealfromline
2094
2095
2096class PortableUnixMailbox(UnixMailbox):
2097 _isrealfromline = UnixMailbox._portable_isrealfromline
2098
Guido van Rossumfbe63de1998-04-03 16:04:05 +00002099
Guido van Rossumc7b68821994-04-28 09:53:33 +00002100class MmdfMailbox(_Mailbox):
Guido van Rossum4bf12542002-09-12 05:08:00 +00002101
Fred Drakedbbf76b2000-07-09 16:44:26 +00002102 def _search_start(self):
2103 while 1:
2104 line = self.fp.readline()
2105 if not line:
2106 raise EOFError
2107 if line[:5] == '\001\001\001\001\n':
2108 return
Guido van Rossum8ca84201998-03-26 20:56:10 +00002109
Fred Drakedbbf76b2000-07-09 16:44:26 +00002110 def _search_end(self):
2111 while 1:
2112 pos = self.fp.tell()
2113 line = self.fp.readline()
2114 if not line:
2115 return
2116 if line == '\001\001\001\001\n':
2117 self.fp.seek(pos)
2118 return
Guido van Rossumc7b68821994-04-28 09:53:33 +00002119
Guido van Rossumc7b68821994-04-28 09:53:33 +00002120
Jack Jansen97157791995-10-23 13:59:53 +00002121class MHMailbox:
Guido van Rossum4bf12542002-09-12 05:08:00 +00002122
Barry Warsaw81ad67c2001-01-31 22:13:15 +00002123 def __init__(self, dirname, factory=rfc822.Message):
Fred Drakedbbf76b2000-07-09 16:44:26 +00002124 import re
Guido van Rossum0707fea2000-08-10 03:05:26 +00002125 pat = re.compile('^[1-9][0-9]*$')
Fred Drakedbbf76b2000-07-09 16:44:26 +00002126 self.dirname = dirname
Sjoerd Mullenderd2653a92000-08-11 07:48:36 +00002127 # the three following lines could be combined into:
2128 # list = map(long, filter(pat.match, os.listdir(self.dirname)))
2129 list = os.listdir(self.dirname)
2130 list = filter(pat.match, list)
Guido van Rossum0707fea2000-08-10 03:05:26 +00002131 list = map(long, list)
2132 list.sort()
2133 # This only works in Python 1.6 or later;
2134 # before that str() added 'L':
2135 self.boxes = map(str, list)
Raymond Hettingerb5ba8d72004-02-07 02:16:24 +00002136 self.boxes.reverse()
Barry Warsaw81ad67c2001-01-31 22:13:15 +00002137 self.factory = factory
Jack Jansen97157791995-10-23 13:59:53 +00002138
Fred Drake72987a42001-05-02 20:20:53 +00002139 def __iter__(self):
Guido van Rossum93a696f2001-09-13 01:29:13 +00002140 return iter(self.next, None)
Fred Drake72987a42001-05-02 20:20:53 +00002141
Fred Drakedbbf76b2000-07-09 16:44:26 +00002142 def next(self):
2143 if not self.boxes:
2144 return None
Raymond Hettingerb5ba8d72004-02-07 02:16:24 +00002145 fn = self.boxes.pop()
Fred Drakedbbf76b2000-07-09 16:44:26 +00002146 fp = open(os.path.join(self.dirname, fn))
Guido van Rossum4bf12542002-09-12 05:08:00 +00002147 msg = self.factory(fp)
2148 try:
2149 msg._mh_msgno = fn
2150 except (AttributeError, TypeError):
2151 pass
2152 return msg
Guido van Rossum8ca84201998-03-26 20:56:10 +00002153
Guido van Rossum9a4d6371998-12-23 22:05:42 +00002154
Guido van Rossumfdf58fe1997-05-15 14:33:09 +00002155class BabylMailbox(_Mailbox):
Guido van Rossum4bf12542002-09-12 05:08:00 +00002156
Fred Drakedbbf76b2000-07-09 16:44:26 +00002157 def _search_start(self):
2158 while 1:
2159 line = self.fp.readline()
2160 if not line:
2161 raise EOFError
2162 if line == '*** EOOH ***\n':
2163 return
Guido van Rossumfdf58fe1997-05-15 14:33:09 +00002164
Fred Drakedbbf76b2000-07-09 16:44:26 +00002165 def _search_end(self):
2166 while 1:
2167 pos = self.fp.tell()
2168 line = self.fp.readline()
2169 if not line:
2170 return
Johannes Gijsbers6abc6852004-08-21 12:30:26 +00002171 if line == '\037\014\n' or line == '\037':
Fred Drakedbbf76b2000-07-09 16:44:26 +00002172 self.fp.seek(pos)
2173 return
Guido van Rossumfdf58fe1997-05-15 14:33:09 +00002174
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +00002175## End: classes from the original module (for backward compatibility).
Guido van Rossum62448671996-09-17 21:33:15 +00002176
2177
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +00002178class Error(Exception):
2179 """Raised for module-specific errors."""
2180
2181class NoSuchMailboxError(Error):
2182 """The specified mailbox does not exist and won't be created."""
2183
2184class NotEmptyError(Error):
2185 """The specified mailbox is not empty and deletion was requested."""
2186
2187class ExternalClashError(Error):
2188 """Another process caused an action to fail."""
2189
2190class FormatError(Error):
2191 """A file appears to have an invalid format."""