blob: fc154fa12aac998908d7ccd9311bb9761541b7b7 [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 Lehtinen4e6e5a02012-06-29 13:43:37 +0300717 if len(self._toc) == 0 and not self._pending:
718 # This is the first message, and the _pre_mailbox_hook
719 # hasn't yet been called. If self._pending is True,
720 # messages have been removed, so _pre_mailbox_hook must
721 # have been called already.
Petri Lehtinen45f0d982012-06-28 13:48:17 +0300722 self._pre_mailbox_hook(self._file)
R. David Murray008c0442011-02-11 23:03:13 +0000723 try:
724 self._pre_message_hook(self._file)
725 offsets = self._install_message(message)
726 self._post_message_hook(self._file)
727 except BaseException:
728 self._file.truncate(before)
729 raise
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +0000730 self._file.flush()
Andrew M. Kuchlingeca4c312006-12-20 19:48:20 +0000731 self._file_length = self._file.tell() # Record current length of mailbox
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +0000732 return offsets
733
734
735
736class _mboxMMDF(_singlefileMailbox):
737 """An mbox or MMDF mailbox."""
738
739 _mangle_from_ = True
740
741 def get_message(self, key):
742 """Return a Message representation or raise a KeyError."""
743 start, stop = self._lookup(key)
744 self._file.seek(start)
745 from_line = self._file.readline().replace(os.linesep, '')
746 string = self._file.read(stop - self._file.tell())
747 msg = self._message_factory(string.replace(os.linesep, '\n'))
748 msg.set_from(from_line[5:])
749 return msg
750
751 def get_string(self, key, from_=False):
752 """Return a string representation or raise a KeyError."""
753 start, stop = self._lookup(key)
754 self._file.seek(start)
755 if not from_:
756 self._file.readline()
757 string = self._file.read(stop - self._file.tell())
758 return string.replace(os.linesep, '\n')
759
760 def get_file(self, key, from_=False):
761 """Return a file-like representation or raise a KeyError."""
762 start, stop = self._lookup(key)
763 self._file.seek(start)
764 if not from_:
765 self._file.readline()
766 return _PartialFile(self._file, self._file.tell(), stop)
767
768 def _install_message(self, message):
769 """Format a message and blindly write to self._file."""
770 from_line = None
771 if isinstance(message, str) and message.startswith('From '):
772 newline = message.find('\n')
773 if newline != -1:
774 from_line = message[:newline]
775 message = message[newline + 1:]
776 else:
777 from_line = message
778 message = ''
779 elif isinstance(message, _mboxMMDFMessage):
780 from_line = 'From ' + message.get_from()
Georg Brandl5a096e12007-01-22 19:40:21 +0000781 elif isinstance(message, email.message.Message):
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +0000782 from_line = message.get_unixfrom() # May be None.
783 if from_line is None:
784 from_line = 'From MAILER-DAEMON %s' % time.asctime(time.gmtime())
785 start = self._file.tell()
786 self._file.write(from_line + os.linesep)
787 self._dump_message(message, self._file, self._mangle_from_)
788 stop = self._file.tell()
789 return (start, stop)
790
791
792class mbox(_mboxMMDF):
793 """A classic mbox mailbox."""
794
795 _mangle_from_ = True
796
797 def __init__(self, path, factory=None, create=True):
798 """Initialize an mbox mailbox."""
799 self._message_factory = mboxMessage
800 _mboxMMDF.__init__(self, path, factory, create)
801
802 def _pre_message_hook(self, f):
803 """Called before writing each message to file f."""
804 if f.tell() != 0:
805 f.write(os.linesep)
806
807 def _generate_toc(self):
808 """Generate key-to-(start, stop) table of contents."""
809 starts, stops = [], []
810 self._file.seek(0)
811 while True:
812 line_pos = self._file.tell()
813 line = self._file.readline()
814 if line.startswith('From '):
815 if len(stops) < len(starts):
816 stops.append(line_pos - len(os.linesep))
817 starts.append(line_pos)
818 elif line == '':
819 stops.append(line_pos)
820 break
821 self._toc = dict(enumerate(zip(starts, stops)))
822 self._next_key = len(self._toc)
Andrew M. Kuchlingeca4c312006-12-20 19:48:20 +0000823 self._file_length = self._file.tell()
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +0000824
825
826class MMDF(_mboxMMDF):
827 """An MMDF mailbox."""
828
829 def __init__(self, path, factory=None, create=True):
830 """Initialize an MMDF mailbox."""
831 self._message_factory = MMDFMessage
832 _mboxMMDF.__init__(self, path, factory, create)
833
834 def _pre_message_hook(self, f):
835 """Called before writing each message to file f."""
836 f.write('\001\001\001\001' + os.linesep)
837
838 def _post_message_hook(self, f):
839 """Called after writing each message to file f."""
840 f.write(os.linesep + '\001\001\001\001' + os.linesep)
841
842 def _generate_toc(self):
843 """Generate key-to-(start, stop) table of contents."""
844 starts, stops = [], []
845 self._file.seek(0)
846 next_pos = 0
847 while True:
848 line_pos = next_pos
849 line = self._file.readline()
850 next_pos = self._file.tell()
851 if line.startswith('\001\001\001\001' + os.linesep):
852 starts.append(next_pos)
853 while True:
854 line_pos = next_pos
855 line = self._file.readline()
856 next_pos = self._file.tell()
857 if line == '\001\001\001\001' + os.linesep:
858 stops.append(line_pos - len(os.linesep))
859 break
860 elif line == '':
861 stops.append(line_pos)
862 break
863 elif line == '':
864 break
865 self._toc = dict(enumerate(zip(starts, stops)))
866 self._next_key = len(self._toc)
Andrew M. Kuchlingeca4c312006-12-20 19:48:20 +0000867 self._file.seek(0, 2)
868 self._file_length = self._file.tell()
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +0000869
870
871class MH(Mailbox):
872 """An MH mailbox."""
873
874 def __init__(self, path, factory=None, create=True):
875 """Initialize an MH instance."""
876 Mailbox.__init__(self, path, factory, create)
877 if not os.path.exists(self._path):
878 if create:
879 os.mkdir(self._path, 0700)
880 os.close(os.open(os.path.join(self._path, '.mh_sequences'),
881 os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0600))
882 else:
883 raise NoSuchMailboxError(self._path)
884 self._locked = False
885
886 def add(self, message):
887 """Add message and return assigned key."""
888 keys = self.keys()
889 if len(keys) == 0:
890 new_key = 1
891 else:
892 new_key = max(keys) + 1
893 new_path = os.path.join(self._path, str(new_key))
894 f = _create_carefully(new_path)
R. David Murrayf9e34232011-02-12 02:03:56 +0000895 closed = False
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +0000896 try:
897 if self._locked:
898 _lock_file(f)
899 try:
R. David Murray008c0442011-02-11 23:03:13 +0000900 try:
901 self._dump_message(message, f)
902 except BaseException:
R. David Murrayf9e34232011-02-12 02:03:56 +0000903 # Unlock and close so it can be deleted on Windows
904 if self._locked:
905 _unlock_file(f)
906 _sync_close(f)
907 closed = True
R. David Murray008c0442011-02-11 23:03:13 +0000908 os.remove(new_path)
909 raise
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +0000910 if isinstance(message, MHMessage):
911 self._dump_sequences(message, new_key)
912 finally:
913 if self._locked:
914 _unlock_file(f)
915 finally:
R. David Murrayf9e34232011-02-12 02:03:56 +0000916 if not closed:
917 _sync_close(f)
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +0000918 return new_key
919
920 def remove(self, key):
921 """Remove the keyed message; raise KeyError if it doesn't exist."""
922 path = os.path.join(self._path, str(key))
923 try:
Andrew M. Kuchling214db632006-05-02 21:44:33 +0000924 f = open(path, 'rb+')
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +0000925 except IOError, e:
926 if e.errno == errno.ENOENT:
927 raise KeyError('No message with key: %s' % key)
928 else:
929 raise
Andrew M. Kuchlingb72b0eb2010-02-22 18:42:07 +0000930 else:
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +0000931 f.close()
Andrew M. Kuchlingb72b0eb2010-02-22 18:42:07 +0000932 os.remove(path)
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +0000933
934 def __setitem__(self, key, message):
935 """Replace the keyed message; raise KeyError if it doesn't exist."""
936 path = os.path.join(self._path, str(key))
937 try:
Andrew M. Kuchling214db632006-05-02 21:44:33 +0000938 f = open(path, 'rb+')
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +0000939 except IOError, e:
940 if e.errno == errno.ENOENT:
941 raise KeyError('No message with key: %s' % key)
942 else:
943 raise
944 try:
945 if self._locked:
946 _lock_file(f)
947 try:
948 os.close(os.open(path, os.O_WRONLY | os.O_TRUNC))
949 self._dump_message(message, f)
950 if isinstance(message, MHMessage):
951 self._dump_sequences(message, key)
952 finally:
953 if self._locked:
954 _unlock_file(f)
955 finally:
Andrew M. Kuchlingb5686da2006-11-09 13:51:14 +0000956 _sync_close(f)
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +0000957
958 def get_message(self, key):
959 """Return a Message representation or raise a KeyError."""
960 try:
961 if self._locked:
Andrew M. Kuchling214db632006-05-02 21:44:33 +0000962 f = open(os.path.join(self._path, str(key)), 'r+')
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +0000963 else:
Andrew M. Kuchling214db632006-05-02 21:44:33 +0000964 f = open(os.path.join(self._path, str(key)), 'r')
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +0000965 except IOError, e:
966 if e.errno == errno.ENOENT:
967 raise KeyError('No message with key: %s' % key)
968 else:
969 raise
970 try:
971 if self._locked:
972 _lock_file(f)
973 try:
974 msg = MHMessage(f)
975 finally:
976 if self._locked:
977 _unlock_file(f)
978 finally:
979 f.close()
R. David Murray52720c52009-04-02 14:05:35 +0000980 for name, key_list in self.get_sequences().iteritems():
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +0000981 if key in key_list:
982 msg.add_sequence(name)
983 return msg
984
985 def get_string(self, key):
986 """Return a string representation or raise a KeyError."""
987 try:
988 if self._locked:
Andrew M. Kuchling214db632006-05-02 21:44:33 +0000989 f = open(os.path.join(self._path, str(key)), 'r+')
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +0000990 else:
Andrew M. Kuchling214db632006-05-02 21:44:33 +0000991 f = open(os.path.join(self._path, str(key)), 'r')
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +0000992 except IOError, e:
993 if e.errno == errno.ENOENT:
994 raise KeyError('No message with key: %s' % key)
995 else:
996 raise
997 try:
998 if self._locked:
999 _lock_file(f)
1000 try:
1001 return f.read()
1002 finally:
1003 if self._locked:
1004 _unlock_file(f)
1005 finally:
1006 f.close()
1007
1008 def get_file(self, key):
1009 """Return a file-like representation or raise a KeyError."""
1010 try:
Andrew M. Kuchling214db632006-05-02 21:44:33 +00001011 f = open(os.path.join(self._path, str(key)), 'rb')
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +00001012 except IOError, e:
1013 if e.errno == errno.ENOENT:
1014 raise KeyError('No message with key: %s' % key)
1015 else:
1016 raise
1017 return _ProxyFile(f)
1018
1019 def iterkeys(self):
1020 """Return an iterator over keys."""
1021 return iter(sorted(int(entry) for entry in os.listdir(self._path)
1022 if entry.isdigit()))
1023
1024 def has_key(self, key):
1025 """Return True if the keyed message exists, False otherwise."""
1026 return os.path.exists(os.path.join(self._path, str(key)))
1027
1028 def __len__(self):
1029 """Return a count of messages in the mailbox."""
1030 return len(list(self.iterkeys()))
1031
1032 def lock(self):
1033 """Lock the mailbox."""
1034 if not self._locked:
Andrew M. Kuchling214db632006-05-02 21:44:33 +00001035 self._file = open(os.path.join(self._path, '.mh_sequences'), 'rb+')
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +00001036 _lock_file(self._file)
1037 self._locked = True
1038
1039 def unlock(self):
1040 """Unlock the mailbox if it is locked."""
1041 if self._locked:
1042 _unlock_file(self._file)
Andrew M. Kuchlingb5686da2006-11-09 13:51:14 +00001043 _sync_close(self._file)
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +00001044 del self._file
1045 self._locked = False
1046
1047 def flush(self):
1048 """Write any pending changes to the disk."""
1049 return
1050
1051 def close(self):
1052 """Flush and close the mailbox."""
1053 if self._locked:
1054 self.unlock()
1055
1056 def list_folders(self):
1057 """Return a list of folder names."""
1058 result = []
1059 for entry in os.listdir(self._path):
1060 if os.path.isdir(os.path.join(self._path, entry)):
1061 result.append(entry)
1062 return result
1063
1064 def get_folder(self, folder):
1065 """Return an MH instance for the named folder."""
Andrew M. Kuchlinga3e5d372006-11-09 13:27:07 +00001066 return MH(os.path.join(self._path, folder),
1067 factory=self._factory, create=False)
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +00001068
1069 def add_folder(self, folder):
1070 """Create a folder and return an MH instance representing it."""
Andrew M. Kuchlinga3e5d372006-11-09 13:27:07 +00001071 return MH(os.path.join(self._path, folder),
1072 factory=self._factory)
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +00001073
1074 def remove_folder(self, folder):
1075 """Delete the named folder, which must be empty."""
1076 path = os.path.join(self._path, folder)
1077 entries = os.listdir(path)
1078 if entries == ['.mh_sequences']:
1079 os.remove(os.path.join(path, '.mh_sequences'))
1080 elif entries == []:
1081 pass
1082 else:
1083 raise NotEmptyError('Folder not empty: %s' % self._path)
1084 os.rmdir(path)
1085
1086 def get_sequences(self):
1087 """Return a name-to-key-list dictionary to define each sequence."""
1088 results = {}
Andrew M. Kuchling214db632006-05-02 21:44:33 +00001089 f = open(os.path.join(self._path, '.mh_sequences'), 'r')
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +00001090 try:
1091 all_keys = set(self.keys())
1092 for line in f:
1093 try:
1094 name, contents = line.split(':')
1095 keys = set()
1096 for spec in contents.split():
1097 if spec.isdigit():
1098 keys.add(int(spec))
1099 else:
1100 start, stop = (int(x) for x in spec.split('-'))
1101 keys.update(range(start, stop + 1))
1102 results[name] = [key for key in sorted(keys) \
1103 if key in all_keys]
1104 if len(results[name]) == 0:
1105 del results[name]
1106 except ValueError:
1107 raise FormatError('Invalid sequence specification: %s' %
1108 line.rstrip())
1109 finally:
1110 f.close()
1111 return results
1112
1113 def set_sequences(self, sequences):
1114 """Set sequences using the given name-to-key-list dictionary."""
Andrew M. Kuchling214db632006-05-02 21:44:33 +00001115 f = open(os.path.join(self._path, '.mh_sequences'), 'r+')
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +00001116 try:
1117 os.close(os.open(f.name, os.O_WRONLY | os.O_TRUNC))
1118 for name, keys in sequences.iteritems():
1119 if len(keys) == 0:
1120 continue
1121 f.write('%s:' % name)
1122 prev = None
1123 completing = False
1124 for key in sorted(set(keys)):
1125 if key - 1 == prev:
1126 if not completing:
1127 completing = True
1128 f.write('-')
1129 elif completing:
1130 completing = False
1131 f.write('%s %s' % (prev, key))
1132 else:
1133 f.write(' %s' % key)
1134 prev = key
1135 if completing:
1136 f.write(str(prev) + '\n')
1137 else:
1138 f.write('\n')
1139 finally:
Andrew M. Kuchlingb5686da2006-11-09 13:51:14 +00001140 _sync_close(f)
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +00001141
1142 def pack(self):
1143 """Re-name messages to eliminate numbering gaps. Invalidates keys."""
1144 sequences = self.get_sequences()
1145 prev = 0
1146 changes = []
1147 for key in self.iterkeys():
1148 if key - 1 != prev:
1149 changes.append((key, prev + 1))
Andrew M. Kuchling8c456f32006-11-17 13:30:25 +00001150 if hasattr(os, 'link'):
1151 os.link(os.path.join(self._path, str(key)),
1152 os.path.join(self._path, str(prev + 1)))
1153 os.unlink(os.path.join(self._path, str(key)))
1154 else:
1155 os.rename(os.path.join(self._path, str(key)),
1156 os.path.join(self._path, str(prev + 1)))
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +00001157 prev += 1
1158 self._next_key = prev + 1
1159 if len(changes) == 0:
1160 return
1161 for name, key_list in sequences.items():
1162 for old, new in changes:
1163 if old in key_list:
1164 key_list[key_list.index(old)] = new
1165 self.set_sequences(sequences)
1166
1167 def _dump_sequences(self, message, key):
1168 """Inspect a new MHMessage and update sequences appropriately."""
1169 pending_sequences = message.get_sequences()
1170 all_sequences = self.get_sequences()
1171 for name, key_list in all_sequences.iteritems():
1172 if name in pending_sequences:
1173 key_list.append(key)
1174 elif key in key_list:
1175 del key_list[key_list.index(key)]
1176 for sequence in pending_sequences:
1177 if sequence not in all_sequences:
1178 all_sequences[sequence] = [key]
1179 self.set_sequences(all_sequences)
1180
1181
1182class Babyl(_singlefileMailbox):
1183 """An Rmail-style Babyl mailbox."""
1184
1185 _special_labels = frozenset(('unseen', 'deleted', 'filed', 'answered',
1186 'forwarded', 'edited', 'resent'))
1187
1188 def __init__(self, path, factory=None, create=True):
1189 """Initialize a Babyl mailbox."""
1190 _singlefileMailbox.__init__(self, path, factory, create)
1191 self._labels = {}
1192
1193 def add(self, message):
1194 """Add message and return assigned key."""
1195 key = _singlefileMailbox.add(self, message)
1196 if isinstance(message, BabylMessage):
1197 self._labels[key] = message.get_labels()
1198 return key
1199
1200 def remove(self, key):
1201 """Remove the keyed message; raise KeyError if it doesn't exist."""
1202 _singlefileMailbox.remove(self, key)
1203 if key in self._labels:
1204 del self._labels[key]
1205
1206 def __setitem__(self, key, message):
1207 """Replace the keyed message; raise KeyError if it doesn't exist."""
1208 _singlefileMailbox.__setitem__(self, key, message)
1209 if isinstance(message, BabylMessage):
1210 self._labels[key] = message.get_labels()
1211
1212 def get_message(self, key):
1213 """Return a Message representation or raise a KeyError."""
1214 start, stop = self._lookup(key)
1215 self._file.seek(start)
1216 self._file.readline() # Skip '1,' line specifying labels.
1217 original_headers = StringIO.StringIO()
1218 while True:
1219 line = self._file.readline()
1220 if line == '*** EOOH ***' + os.linesep or line == '':
1221 break
1222 original_headers.write(line.replace(os.linesep, '\n'))
1223 visible_headers = StringIO.StringIO()
1224 while True:
1225 line = self._file.readline()
1226 if line == os.linesep or line == '':
1227 break
1228 visible_headers.write(line.replace(os.linesep, '\n'))
1229 body = self._file.read(stop - self._file.tell()).replace(os.linesep,
1230 '\n')
1231 msg = BabylMessage(original_headers.getvalue() + body)
1232 msg.set_visible(visible_headers.getvalue())
1233 if key in self._labels:
1234 msg.set_labels(self._labels[key])
1235 return msg
1236
1237 def get_string(self, key):
1238 """Return a string representation or raise a KeyError."""
1239 start, stop = self._lookup(key)
1240 self._file.seek(start)
1241 self._file.readline() # Skip '1,' line specifying labels.
1242 original_headers = StringIO.StringIO()
1243 while True:
1244 line = self._file.readline()
1245 if line == '*** EOOH ***' + os.linesep or line == '':
1246 break
1247 original_headers.write(line.replace(os.linesep, '\n'))
1248 while True:
1249 line = self._file.readline()
1250 if line == os.linesep or line == '':
1251 break
1252 return original_headers.getvalue() + \
1253 self._file.read(stop - self._file.tell()).replace(os.linesep,
1254 '\n')
1255
1256 def get_file(self, key):
1257 """Return a file-like representation or raise a KeyError."""
1258 return StringIO.StringIO(self.get_string(key).replace('\n',
1259 os.linesep))
1260
1261 def get_labels(self):
1262 """Return a list of user-defined labels in the mailbox."""
1263 self._lookup()
1264 labels = set()
1265 for label_list in self._labels.values():
1266 labels.update(label_list)
1267 labels.difference_update(self._special_labels)
1268 return list(labels)
1269
1270 def _generate_toc(self):
1271 """Generate key-to-(start, stop) table of contents."""
1272 starts, stops = [], []
1273 self._file.seek(0)
1274 next_pos = 0
1275 label_lists = []
1276 while True:
1277 line_pos = next_pos
1278 line = self._file.readline()
1279 next_pos = self._file.tell()
1280 if line == '\037\014' + os.linesep:
1281 if len(stops) < len(starts):
1282 stops.append(line_pos - len(os.linesep))
1283 starts.append(next_pos)
1284 labels = [label.strip() for label
1285 in self._file.readline()[1:].split(',')
1286 if label.strip() != '']
1287 label_lists.append(labels)
1288 elif line == '\037' or line == '\037' + os.linesep:
1289 if len(stops) < len(starts):
1290 stops.append(line_pos - len(os.linesep))
1291 elif line == '':
1292 stops.append(line_pos - len(os.linesep))
1293 break
1294 self._toc = dict(enumerate(zip(starts, stops)))
1295 self._labels = dict(enumerate(label_lists))
1296 self._next_key = len(self._toc)
Andrew M. Kuchlingeca4c312006-12-20 19:48:20 +00001297 self._file.seek(0, 2)
1298 self._file_length = self._file.tell()
Tim Petersf733abb2007-01-30 03:03:46 +00001299
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +00001300 def _pre_mailbox_hook(self, f):
1301 """Called before writing the mailbox to file f."""
1302 f.write('BABYL OPTIONS:%sVersion: 5%sLabels:%s%s\037' %
1303 (os.linesep, os.linesep, ','.join(self.get_labels()),
1304 os.linesep))
1305
1306 def _pre_message_hook(self, f):
1307 """Called before writing each message to file f."""
1308 f.write('\014' + os.linesep)
1309
1310 def _post_message_hook(self, f):
1311 """Called after writing each message to file f."""
1312 f.write(os.linesep + '\037')
1313
1314 def _install_message(self, message):
1315 """Write message contents and return (start, stop)."""
1316 start = self._file.tell()
1317 if isinstance(message, BabylMessage):
1318 special_labels = []
1319 labels = []
1320 for label in message.get_labels():
1321 if label in self._special_labels:
1322 special_labels.append(label)
1323 else:
1324 labels.append(label)
1325 self._file.write('1')
1326 for label in special_labels:
1327 self._file.write(', ' + label)
1328 self._file.write(',,')
1329 for label in labels:
1330 self._file.write(' ' + label + ',')
1331 self._file.write(os.linesep)
1332 else:
1333 self._file.write('1,,' + os.linesep)
Georg Brandl5a096e12007-01-22 19:40:21 +00001334 if isinstance(message, email.message.Message):
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +00001335 orig_buffer = StringIO.StringIO()
Georg Brandl5a096e12007-01-22 19:40:21 +00001336 orig_generator = email.generator.Generator(orig_buffer, False, 0)
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +00001337 orig_generator.flatten(message)
1338 orig_buffer.seek(0)
1339 while True:
1340 line = orig_buffer.readline()
1341 self._file.write(line.replace('\n', os.linesep))
1342 if line == '\n' or line == '':
1343 break
1344 self._file.write('*** EOOH ***' + os.linesep)
1345 if isinstance(message, BabylMessage):
1346 vis_buffer = StringIO.StringIO()
Georg Brandl5a096e12007-01-22 19:40:21 +00001347 vis_generator = email.generator.Generator(vis_buffer, False, 0)
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +00001348 vis_generator.flatten(message.get_visible())
1349 while True:
1350 line = vis_buffer.readline()
1351 self._file.write(line.replace('\n', os.linesep))
1352 if line == '\n' or line == '':
1353 break
1354 else:
1355 orig_buffer.seek(0)
1356 while True:
1357 line = orig_buffer.readline()
1358 self._file.write(line.replace('\n', os.linesep))
1359 if line == '\n' or line == '':
1360 break
1361 while True:
1362 buffer = orig_buffer.read(4096) # Buffer size is arbitrary.
1363 if buffer == '':
1364 break
1365 self._file.write(buffer.replace('\n', os.linesep))
1366 elif isinstance(message, str):
1367 body_start = message.find('\n\n') + 2
1368 if body_start - 2 != -1:
1369 self._file.write(message[:body_start].replace('\n',
1370 os.linesep))
1371 self._file.write('*** EOOH ***' + os.linesep)
1372 self._file.write(message[:body_start].replace('\n',
1373 os.linesep))
1374 self._file.write(message[body_start:].replace('\n',
1375 os.linesep))
1376 else:
1377 self._file.write('*** EOOH ***' + os.linesep + os.linesep)
1378 self._file.write(message.replace('\n', os.linesep))
1379 elif hasattr(message, 'readline'):
1380 original_pos = message.tell()
1381 first_pass = True
1382 while True:
1383 line = message.readline()
1384 self._file.write(line.replace('\n', os.linesep))
1385 if line == '\n' or line == '':
1386 self._file.write('*** EOOH ***' + os.linesep)
1387 if first_pass:
1388 first_pass = False
1389 message.seek(original_pos)
1390 else:
1391 break
1392 while True:
1393 buffer = message.read(4096) # Buffer size is arbitrary.
1394 if buffer == '':
1395 break
1396 self._file.write(buffer.replace('\n', os.linesep))
1397 else:
1398 raise TypeError('Invalid message type: %s' % type(message))
1399 stop = self._file.tell()
1400 return (start, stop)
1401
1402
Georg Brandl5a096e12007-01-22 19:40:21 +00001403class Message(email.message.Message):
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +00001404 """Message with mailbox-format-specific properties."""
1405
1406 def __init__(self, message=None):
1407 """Initialize a Message instance."""
Georg Brandl5a096e12007-01-22 19:40:21 +00001408 if isinstance(message, email.message.Message):
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +00001409 self._become_message(copy.deepcopy(message))
1410 if isinstance(message, Message):
1411 message._explain_to(self)
1412 elif isinstance(message, str):
1413 self._become_message(email.message_from_string(message))
1414 elif hasattr(message, "read"):
1415 self._become_message(email.message_from_file(message))
1416 elif message is None:
Georg Brandl5a096e12007-01-22 19:40:21 +00001417 email.message.Message.__init__(self)
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +00001418 else:
1419 raise TypeError('Invalid message type: %s' % type(message))
1420
1421 def _become_message(self, message):
1422 """Assume the non-format-specific state of message."""
1423 for name in ('_headers', '_unixfrom', '_payload', '_charset',
1424 'preamble', 'epilogue', 'defects', '_default_type'):
1425 self.__dict__[name] = message.__dict__[name]
1426
1427 def _explain_to(self, message):
1428 """Copy format-specific state to message insofar as possible."""
1429 if isinstance(message, Message):
1430 return # There's nothing format-specific to explain.
1431 else:
1432 raise TypeError('Cannot convert to specified type')
1433
1434
1435class MaildirMessage(Message):
1436 """Message with Maildir-specific properties."""
1437
1438 def __init__(self, message=None):
1439 """Initialize a MaildirMessage instance."""
1440 self._subdir = 'new'
1441 self._info = ''
1442 self._date = time.time()
1443 Message.__init__(self, message)
1444
1445 def get_subdir(self):
1446 """Return 'new' or 'cur'."""
1447 return self._subdir
1448
1449 def set_subdir(self, subdir):
1450 """Set subdir to 'new' or 'cur'."""
1451 if subdir == 'new' or subdir == 'cur':
1452 self._subdir = subdir
1453 else:
1454 raise ValueError("subdir must be 'new' or 'cur': %s" % subdir)
1455
1456 def get_flags(self):
1457 """Return as a string the flags that are set."""
1458 if self._info.startswith('2,'):
1459 return self._info[2:]
1460 else:
1461 return ''
1462
1463 def set_flags(self, flags):
1464 """Set the given flags and unset all others."""
1465 self._info = '2,' + ''.join(sorted(flags))
1466
1467 def add_flag(self, flag):
1468 """Set the given flag(s) without changing others."""
1469 self.set_flags(''.join(set(self.get_flags()) | set(flag)))
1470
1471 def remove_flag(self, flag):
1472 """Unset the given string flag(s) without changing others."""
1473 if self.get_flags() != '':
1474 self.set_flags(''.join(set(self.get_flags()) - set(flag)))
1475
1476 def get_date(self):
1477 """Return delivery date of message, in seconds since the epoch."""
1478 return self._date
1479
1480 def set_date(self, date):
1481 """Set delivery date of message, in seconds since the epoch."""
1482 try:
1483 self._date = float(date)
1484 except ValueError:
1485 raise TypeError("can't convert to float: %s" % date)
1486
1487 def get_info(self):
1488 """Get the message's "info" as a string."""
1489 return self._info
1490
1491 def set_info(self, info):
1492 """Set the message's "info" string."""
1493 if isinstance(info, str):
1494 self._info = info
1495 else:
1496 raise TypeError('info must be a string: %s' % type(info))
1497
1498 def _explain_to(self, message):
1499 """Copy Maildir-specific state to message insofar as possible."""
1500 if isinstance(message, MaildirMessage):
1501 message.set_flags(self.get_flags())
1502 message.set_subdir(self.get_subdir())
1503 message.set_date(self.get_date())
1504 elif isinstance(message, _mboxMMDFMessage):
1505 flags = set(self.get_flags())
1506 if 'S' in flags:
1507 message.add_flag('R')
1508 if self.get_subdir() == 'cur':
1509 message.add_flag('O')
1510 if 'T' in flags:
1511 message.add_flag('D')
1512 if 'F' in flags:
1513 message.add_flag('F')
1514 if 'R' in flags:
1515 message.add_flag('A')
1516 message.set_from('MAILER-DAEMON', time.gmtime(self.get_date()))
1517 elif isinstance(message, MHMessage):
1518 flags = set(self.get_flags())
1519 if 'S' not in flags:
1520 message.add_sequence('unseen')
1521 if 'R' in flags:
1522 message.add_sequence('replied')
1523 if 'F' in flags:
1524 message.add_sequence('flagged')
1525 elif isinstance(message, BabylMessage):
1526 flags = set(self.get_flags())
1527 if 'S' not in flags:
1528 message.add_label('unseen')
1529 if 'T' in flags:
1530 message.add_label('deleted')
1531 if 'R' in flags:
1532 message.add_label('answered')
1533 if 'P' in flags:
1534 message.add_label('forwarded')
1535 elif isinstance(message, Message):
1536 pass
1537 else:
1538 raise TypeError('Cannot convert to specified type: %s' %
1539 type(message))
1540
1541
1542class _mboxMMDFMessage(Message):
1543 """Message with mbox- or MMDF-specific properties."""
1544
1545 def __init__(self, message=None):
1546 """Initialize an mboxMMDFMessage instance."""
1547 self.set_from('MAILER-DAEMON', True)
Georg Brandl5a096e12007-01-22 19:40:21 +00001548 if isinstance(message, email.message.Message):
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +00001549 unixfrom = message.get_unixfrom()
1550 if unixfrom is not None and unixfrom.startswith('From '):
1551 self.set_from(unixfrom[5:])
1552 Message.__init__(self, message)
1553
1554 def get_from(self):
1555 """Return contents of "From " line."""
1556 return self._from
1557
1558 def set_from(self, from_, time_=None):
1559 """Set "From " line, formatting and appending time_ if specified."""
1560 if time_ is not None:
1561 if time_ is True:
1562 time_ = time.gmtime()
1563 from_ += ' ' + time.asctime(time_)
1564 self._from = from_
1565
1566 def get_flags(self):
1567 """Return as a string the flags that are set."""
1568 return self.get('Status', '') + self.get('X-Status', '')
1569
1570 def set_flags(self, flags):
1571 """Set the given flags and unset all others."""
1572 flags = set(flags)
1573 status_flags, xstatus_flags = '', ''
1574 for flag in ('R', 'O'):
1575 if flag in flags:
1576 status_flags += flag
1577 flags.remove(flag)
1578 for flag in ('D', 'F', 'A'):
1579 if flag in flags:
1580 xstatus_flags += flag
1581 flags.remove(flag)
1582 xstatus_flags += ''.join(sorted(flags))
1583 try:
1584 self.replace_header('Status', status_flags)
1585 except KeyError:
1586 self.add_header('Status', status_flags)
1587 try:
1588 self.replace_header('X-Status', xstatus_flags)
1589 except KeyError:
1590 self.add_header('X-Status', xstatus_flags)
1591
1592 def add_flag(self, flag):
1593 """Set the given flag(s) without changing others."""
1594 self.set_flags(''.join(set(self.get_flags()) | set(flag)))
1595
1596 def remove_flag(self, flag):
1597 """Unset the given string flag(s) without changing others."""
1598 if 'Status' in self or 'X-Status' in self:
1599 self.set_flags(''.join(set(self.get_flags()) - set(flag)))
1600
1601 def _explain_to(self, message):
1602 """Copy mbox- or MMDF-specific state to message insofar as possible."""
1603 if isinstance(message, MaildirMessage):
1604 flags = set(self.get_flags())
1605 if 'O' in flags:
1606 message.set_subdir('cur')
1607 if 'F' in flags:
1608 message.add_flag('F')
1609 if 'A' in flags:
1610 message.add_flag('R')
1611 if 'R' in flags:
1612 message.add_flag('S')
1613 if 'D' in flags:
1614 message.add_flag('T')
1615 del message['status']
1616 del message['x-status']
1617 maybe_date = ' '.join(self.get_from().split()[-5:])
1618 try:
1619 message.set_date(calendar.timegm(time.strptime(maybe_date,
1620 '%a %b %d %H:%M:%S %Y')))
1621 except (ValueError, OverflowError):
1622 pass
1623 elif isinstance(message, _mboxMMDFMessage):
1624 message.set_flags(self.get_flags())
1625 message.set_from(self.get_from())
1626 elif isinstance(message, MHMessage):
1627 flags = set(self.get_flags())
1628 if 'R' not in flags:
1629 message.add_sequence('unseen')
1630 if 'A' in flags:
1631 message.add_sequence('replied')
1632 if 'F' in flags:
1633 message.add_sequence('flagged')
1634 del message['status']
1635 del message['x-status']
1636 elif isinstance(message, BabylMessage):
1637 flags = set(self.get_flags())
1638 if 'R' not in flags:
1639 message.add_label('unseen')
1640 if 'D' in flags:
1641 message.add_label('deleted')
1642 if 'A' in flags:
1643 message.add_label('answered')
1644 del message['status']
1645 del message['x-status']
1646 elif isinstance(message, Message):
1647 pass
1648 else:
1649 raise TypeError('Cannot convert to specified type: %s' %
1650 type(message))
1651
1652
1653class mboxMessage(_mboxMMDFMessage):
1654 """Message with mbox-specific properties."""
1655
1656
1657class MHMessage(Message):
1658 """Message with MH-specific properties."""
1659
1660 def __init__(self, message=None):
1661 """Initialize an MHMessage instance."""
1662 self._sequences = []
1663 Message.__init__(self, message)
1664
1665 def get_sequences(self):
1666 """Return a list of sequences that include the message."""
1667 return self._sequences[:]
1668
1669 def set_sequences(self, sequences):
1670 """Set the list of sequences that include the message."""
1671 self._sequences = list(sequences)
1672
1673 def add_sequence(self, sequence):
1674 """Add sequence to list of sequences including the message."""
1675 if isinstance(sequence, str):
1676 if not sequence in self._sequences:
1677 self._sequences.append(sequence)
1678 else:
1679 raise TypeError('sequence must be a string: %s' % type(sequence))
1680
1681 def remove_sequence(self, sequence):
1682 """Remove sequence from the list of sequences including the message."""
1683 try:
1684 self._sequences.remove(sequence)
1685 except ValueError:
1686 pass
1687
1688 def _explain_to(self, message):
1689 """Copy MH-specific state to message insofar as possible."""
1690 if isinstance(message, MaildirMessage):
1691 sequences = set(self.get_sequences())
1692 if 'unseen' in sequences:
1693 message.set_subdir('cur')
1694 else:
1695 message.set_subdir('cur')
1696 message.add_flag('S')
1697 if 'flagged' in sequences:
1698 message.add_flag('F')
1699 if 'replied' in sequences:
1700 message.add_flag('R')
1701 elif isinstance(message, _mboxMMDFMessage):
1702 sequences = set(self.get_sequences())
1703 if 'unseen' not in sequences:
1704 message.add_flag('RO')
1705 else:
1706 message.add_flag('O')
1707 if 'flagged' in sequences:
1708 message.add_flag('F')
1709 if 'replied' in sequences:
1710 message.add_flag('A')
1711 elif isinstance(message, MHMessage):
1712 for sequence in self.get_sequences():
1713 message.add_sequence(sequence)
1714 elif isinstance(message, BabylMessage):
1715 sequences = set(self.get_sequences())
1716 if 'unseen' in sequences:
1717 message.add_label('unseen')
1718 if 'replied' in sequences:
1719 message.add_label('answered')
1720 elif isinstance(message, Message):
1721 pass
1722 else:
1723 raise TypeError('Cannot convert to specified type: %s' %
1724 type(message))
1725
1726
1727class BabylMessage(Message):
1728 """Message with Babyl-specific properties."""
1729
1730 def __init__(self, message=None):
1731 """Initialize an BabylMessage instance."""
1732 self._labels = []
1733 self._visible = Message()
1734 Message.__init__(self, message)
1735
1736 def get_labels(self):
1737 """Return a list of labels on the message."""
1738 return self._labels[:]
1739
1740 def set_labels(self, labels):
1741 """Set the list of labels on the message."""
1742 self._labels = list(labels)
1743
1744 def add_label(self, label):
1745 """Add label to list of labels on the message."""
1746 if isinstance(label, str):
1747 if label not in self._labels:
1748 self._labels.append(label)
1749 else:
1750 raise TypeError('label must be a string: %s' % type(label))
1751
1752 def remove_label(self, label):
1753 """Remove label from the list of labels on the message."""
1754 try:
1755 self._labels.remove(label)
1756 except ValueError:
1757 pass
Tim Peters6d7cd7d2006-04-22 05:52:59 +00001758
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +00001759 def get_visible(self):
1760 """Return a Message representation of visible headers."""
1761 return Message(self._visible)
1762
1763 def set_visible(self, visible):
1764 """Set the Message representation of visible headers."""
1765 self._visible = Message(visible)
1766
1767 def update_visible(self):
1768 """Update and/or sensibly generate a set of visible headers."""
1769 for header in self._visible.keys():
1770 if header in self:
1771 self._visible.replace_header(header, self[header])
1772 else:
1773 del self._visible[header]
1774 for header in ('Date', 'From', 'Reply-To', 'To', 'CC', 'Subject'):
1775 if header in self and header not in self._visible:
1776 self._visible[header] = self[header]
1777
1778 def _explain_to(self, message):
1779 """Copy Babyl-specific state to message insofar as possible."""
1780 if isinstance(message, MaildirMessage):
1781 labels = set(self.get_labels())
1782 if 'unseen' in labels:
1783 message.set_subdir('cur')
1784 else:
1785 message.set_subdir('cur')
1786 message.add_flag('S')
1787 if 'forwarded' in labels or 'resent' in labels:
1788 message.add_flag('P')
1789 if 'answered' in labels:
1790 message.add_flag('R')
1791 if 'deleted' in labels:
1792 message.add_flag('T')
1793 elif isinstance(message, _mboxMMDFMessage):
1794 labels = set(self.get_labels())
1795 if 'unseen' not in labels:
1796 message.add_flag('RO')
1797 else:
1798 message.add_flag('O')
1799 if 'deleted' in labels:
1800 message.add_flag('D')
1801 if 'answered' in labels:
1802 message.add_flag('A')
1803 elif isinstance(message, MHMessage):
1804 labels = set(self.get_labels())
1805 if 'unseen' in labels:
1806 message.add_sequence('unseen')
1807 if 'answered' in labels:
1808 message.add_sequence('replied')
1809 elif isinstance(message, BabylMessage):
1810 message.set_visible(self.get_visible())
1811 for label in self.get_labels():
1812 message.add_label(label)
1813 elif isinstance(message, Message):
1814 pass
1815 else:
1816 raise TypeError('Cannot convert to specified type: %s' %
1817 type(message))
1818
1819
1820class MMDFMessage(_mboxMMDFMessage):
1821 """Message with MMDF-specific properties."""
1822
1823
1824class _ProxyFile:
1825 """A read-only wrapper of a file."""
1826
1827 def __init__(self, f, pos=None):
1828 """Initialize a _ProxyFile."""
1829 self._file = f
1830 if pos is None:
1831 self._pos = f.tell()
1832 else:
1833 self._pos = pos
1834
1835 def read(self, size=None):
1836 """Read bytes."""
1837 return self._read(size, self._file.read)
1838
1839 def readline(self, size=None):
1840 """Read a line."""
1841 return self._read(size, self._file.readline)
1842
1843 def readlines(self, sizehint=None):
1844 """Read multiple lines."""
1845 result = []
1846 for line in self:
1847 result.append(line)
1848 if sizehint is not None:
1849 sizehint -= len(line)
1850 if sizehint <= 0:
1851 break
1852 return result
1853
1854 def __iter__(self):
1855 """Iterate over lines."""
1856 return iter(self.readline, "")
1857
1858 def tell(self):
1859 """Return the position."""
1860 return self._pos
1861
1862 def seek(self, offset, whence=0):
1863 """Change position."""
1864 if whence == 1:
1865 self._file.seek(self._pos)
1866 self._file.seek(offset, whence)
1867 self._pos = self._file.tell()
1868
1869 def close(self):
1870 """Close the file."""
R David Murrayf1138bb2011-06-17 22:23:04 -04001871 if hasattr(self, '_file'):
1872 if hasattr(self._file, 'close'):
1873 self._file.close()
1874 del self._file
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +00001875
1876 def _read(self, size, read_method):
1877 """Read size bytes using read_method."""
1878 if size is None:
1879 size = -1
1880 self._file.seek(self._pos)
1881 result = read_method(size)
1882 self._pos = self._file.tell()
1883 return result
1884
1885
1886class _PartialFile(_ProxyFile):
1887 """A read-only wrapper of part of a file."""
1888
1889 def __init__(self, f, start=None, stop=None):
1890 """Initialize a _PartialFile."""
1891 _ProxyFile.__init__(self, f, start)
1892 self._start = start
1893 self._stop = stop
1894
1895 def tell(self):
1896 """Return the position with respect to start."""
1897 return _ProxyFile.tell(self) - self._start
1898
1899 def seek(self, offset, whence=0):
1900 """Change position, possibly with respect to start or stop."""
1901 if whence == 0:
1902 self._pos = self._start
1903 whence = 1
1904 elif whence == 2:
1905 self._pos = self._stop
1906 whence = 1
1907 _ProxyFile.seek(self, offset, whence)
1908
1909 def _read(self, size, read_method):
1910 """Read size bytes using read_method, honoring start and stop."""
1911 remaining = self._stop - self._pos
1912 if remaining <= 0:
1913 return ''
1914 if size is None or size < 0 or size > remaining:
1915 size = remaining
1916 return _ProxyFile._read(self, size, read_method)
1917
R David Murrayf1138bb2011-06-17 22:23:04 -04001918 def close(self):
1919 # do *not* close the underlying file object for partial files,
1920 # since it's global to the mailbox object
1921 if hasattr(self, '_file'):
1922 del self._file
1923
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +00001924
1925def _lock_file(f, dotlock=True):
Andrew M. Kuchling55732592006-06-26 13:12:16 +00001926 """Lock file f using lockf and dot locking."""
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +00001927 dotlock_done = False
1928 try:
1929 if fcntl:
1930 try:
1931 fcntl.lockf(f, fcntl.LOCK_EX | fcntl.LOCK_NB)
1932 except IOError, e:
R. David Murray1a337902011-03-03 18:17:40 +00001933 if e.errno in (errno.EAGAIN, errno.EACCES, errno.EROFS):
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +00001934 raise ExternalClashError('lockf: lock unavailable: %s' %
1935 f.name)
1936 else:
1937 raise
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +00001938 if dotlock:
1939 try:
1940 pre_lock = _create_temporary(f.name + '.lock')
1941 pre_lock.close()
1942 except IOError, e:
R. David Murray1a337902011-03-03 18:17:40 +00001943 if e.errno in (errno.EACCES, errno.EROFS):
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +00001944 return # Without write access, just skip dotlocking.
1945 else:
1946 raise
1947 try:
1948 if hasattr(os, 'link'):
1949 os.link(pre_lock.name, f.name + '.lock')
1950 dotlock_done = True
1951 os.unlink(pre_lock.name)
1952 else:
1953 os.rename(pre_lock.name, f.name + '.lock')
1954 dotlock_done = True
1955 except OSError, e:
Andrew MacIntyreafa358f2006-07-23 13:04:00 +00001956 if e.errno == errno.EEXIST or \
1957 (os.name == 'os2' and e.errno == errno.EACCES):
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +00001958 os.remove(pre_lock.name)
Tim Peters6d7cd7d2006-04-22 05:52:59 +00001959 raise ExternalClashError('dot lock unavailable: %s' %
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +00001960 f.name)
1961 else:
1962 raise
1963 except:
1964 if fcntl:
1965 fcntl.lockf(f, fcntl.LOCK_UN)
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +00001966 if dotlock_done:
1967 os.remove(f.name + '.lock')
1968 raise
1969
1970def _unlock_file(f):
Andrew M. Kuchling55732592006-06-26 13:12:16 +00001971 """Unlock file f using lockf and dot locking."""
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +00001972 if fcntl:
1973 fcntl.lockf(f, fcntl.LOCK_UN)
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +00001974 if os.path.exists(f.name + '.lock'):
1975 os.remove(f.name + '.lock')
1976
1977def _create_carefully(path):
1978 """Create a file if it doesn't exist and open for reading and writing."""
Andrew M. Kuchling70a6dbd2008-08-04 01:43:43 +00001979 fd = os.open(path, os.O_CREAT | os.O_EXCL | os.O_RDWR, 0666)
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +00001980 try:
Andrew M. Kuchling214db632006-05-02 21:44:33 +00001981 return open(path, 'rb+')
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +00001982 finally:
1983 os.close(fd)
1984
1985def _create_temporary(path):
1986 """Create a temp file based on path and open for reading and writing."""
1987 return _create_carefully('%s.%s.%s.%s' % (path, int(time.time()),
1988 socket.gethostname(),
1989 os.getpid()))
1990
Andrew M. Kuchlingb5686da2006-11-09 13:51:14 +00001991def _sync_flush(f):
1992 """Ensure changes to file f are physically on disk."""
1993 f.flush()
Andrew M. Kuchling16465682006-12-14 18:57:53 +00001994 if hasattr(os, 'fsync'):
1995 os.fsync(f.fileno())
Andrew M. Kuchlingb5686da2006-11-09 13:51:14 +00001996
1997def _sync_close(f):
1998 """Close file f, ensuring all changes are physically on disk."""
1999 _sync_flush(f)
2000 f.close()
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +00002001
2002## Start: classes from the original module (for backward compatibility).
2003
2004# Note that the Maildir class, whose name is unchanged, itself offers a next()
2005# method for backward compatibility.
Skip Montanaro17ab1232001-01-24 06:27:27 +00002006
Guido van Rossumc7b68821994-04-28 09:53:33 +00002007class _Mailbox:
Guido van Rossum4bf12542002-09-12 05:08:00 +00002008
Barry Warsaw81ad67c2001-01-31 22:13:15 +00002009 def __init__(self, fp, factory=rfc822.Message):
Fred Drakedbbf76b2000-07-09 16:44:26 +00002010 self.fp = fp
2011 self.seekp = 0
Barry Warsaw81ad67c2001-01-31 22:13:15 +00002012 self.factory = factory
Guido van Rossum8ca84201998-03-26 20:56:10 +00002013
Fred Drake72987a42001-05-02 20:20:53 +00002014 def __iter__(self):
Guido van Rossum93a696f2001-09-13 01:29:13 +00002015 return iter(self.next, None)
Fred Drake72987a42001-05-02 20:20:53 +00002016
Fred Drakedbbf76b2000-07-09 16:44:26 +00002017 def next(self):
2018 while 1:
2019 self.fp.seek(self.seekp)
2020 try:
2021 self._search_start()
2022 except EOFError:
2023 self.seekp = self.fp.tell()
2024 return None
2025 start = self.fp.tell()
2026 self._search_end()
2027 self.seekp = stop = self.fp.tell()
Fred Drake8152d322000-12-12 23:20:45 +00002028 if start != stop:
Fred Drakedbbf76b2000-07-09 16:44:26 +00002029 break
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +00002030 return self.factory(_PartialFile(self.fp, start, stop))
Guido van Rossumc7b68821994-04-28 09:53:33 +00002031
Barry Warsawffd05ee2002-03-01 22:39:14 +00002032# Recommended to use PortableUnixMailbox instead!
Guido van Rossumc7b68821994-04-28 09:53:33 +00002033class UnixMailbox(_Mailbox):
Guido van Rossum4bf12542002-09-12 05:08:00 +00002034
Fred Drakedbbf76b2000-07-09 16:44:26 +00002035 def _search_start(self):
2036 while 1:
2037 pos = self.fp.tell()
2038 line = self.fp.readline()
2039 if not line:
2040 raise EOFError
2041 if line[:5] == 'From ' and self._isrealfromline(line):
2042 self.fp.seek(pos)
2043 return
Guido van Rossum8ca84201998-03-26 20:56:10 +00002044
Fred Drakedbbf76b2000-07-09 16:44:26 +00002045 def _search_end(self):
2046 self.fp.readline() # Throw away header line
2047 while 1:
2048 pos = self.fp.tell()
2049 line = self.fp.readline()
2050 if not line:
2051 return
2052 if line[:5] == 'From ' and self._isrealfromline(line):
2053 self.fp.seek(pos)
2054 return
Guido van Rossumc7b68821994-04-28 09:53:33 +00002055
Barry Warsaw81ad67c2001-01-31 22:13:15 +00002056 # An overridable mechanism to test for From-line-ness. You can either
2057 # specify a different regular expression or define a whole new
2058 # _isrealfromline() method. Note that this only gets called for lines
2059 # starting with the 5 characters "From ".
2060 #
2061 # BAW: According to
2062 #http://home.netscape.com/eng/mozilla/2.0/relnotes/demo/content-length.html
2063 # the only portable, reliable way to find message delimiters in a BSD (i.e
2064 # Unix mailbox) style folder is to search for "\n\nFrom .*\n", or at the
2065 # beginning of the file, "^From .*\n". While _fromlinepattern below seems
2066 # like a good idea, in practice, there are too many variations for more
2067 # strict parsing of the line to be completely accurate.
2068 #
2069 # _strict_isrealfromline() is the old version which tries to do stricter
2070 # parsing of the From_ line. _portable_isrealfromline() simply returns
2071 # true, since it's never called if the line doesn't already start with
2072 # "From ".
2073 #
2074 # This algorithm, and the way it interacts with _search_start() and
2075 # _search_end() may not be completely correct, because it doesn't check
2076 # that the two characters preceding "From " are \n\n or the beginning of
2077 # the file. Fixing this would require a more extensive rewrite than is
Barry Warsawda5628f2002-08-26 16:44:56 +00002078 # necessary. For convenience, we've added a PortableUnixMailbox class
Andrew M. Kuchlingb94c0c32007-01-22 20:27:50 +00002079 # which does no checking of the format of the 'From' line.
Guido van Rossumc7b68821994-04-28 09:53:33 +00002080
Andrew M. Kuchlingb78bb742007-01-22 20:26:40 +00002081 _fromlinepattern = (r"From \s*[^\s]+\s+\w\w\w\s+\w\w\w\s+\d?\d\s+"
2082 r"\d?\d:\d\d(:\d\d)?(\s+[^\s]+)?\s+\d\d\d\d\s*"
2083 r"[^\s]*\s*"
2084 "$")
Fred Drakedbbf76b2000-07-09 16:44:26 +00002085 _regexp = None
Guido van Rossumfbe63de1998-04-03 16:04:05 +00002086
Barry Warsaw81ad67c2001-01-31 22:13:15 +00002087 def _strict_isrealfromline(self, line):
Fred Drakedbbf76b2000-07-09 16:44:26 +00002088 if not self._regexp:
2089 import re
2090 self._regexp = re.compile(self._fromlinepattern)
2091 return self._regexp.match(line)
Guido van Rossumfbe63de1998-04-03 16:04:05 +00002092
Barry Warsaw81ad67c2001-01-31 22:13:15 +00002093 def _portable_isrealfromline(self, line):
Tim Petersbc0e9102002-04-04 22:55:58 +00002094 return True
Barry Warsaw81ad67c2001-01-31 22:13:15 +00002095
2096 _isrealfromline = _strict_isrealfromline
2097
2098
2099class PortableUnixMailbox(UnixMailbox):
2100 _isrealfromline = UnixMailbox._portable_isrealfromline
2101
Guido van Rossumfbe63de1998-04-03 16:04:05 +00002102
Guido van Rossumc7b68821994-04-28 09:53:33 +00002103class MmdfMailbox(_Mailbox):
Guido van Rossum4bf12542002-09-12 05:08:00 +00002104
Fred Drakedbbf76b2000-07-09 16:44:26 +00002105 def _search_start(self):
2106 while 1:
2107 line = self.fp.readline()
2108 if not line:
2109 raise EOFError
2110 if line[:5] == '\001\001\001\001\n':
2111 return
Guido van Rossum8ca84201998-03-26 20:56:10 +00002112
Fred Drakedbbf76b2000-07-09 16:44:26 +00002113 def _search_end(self):
2114 while 1:
2115 pos = self.fp.tell()
2116 line = self.fp.readline()
2117 if not line:
2118 return
2119 if line == '\001\001\001\001\n':
2120 self.fp.seek(pos)
2121 return
Guido van Rossumc7b68821994-04-28 09:53:33 +00002122
Guido van Rossumc7b68821994-04-28 09:53:33 +00002123
Jack Jansen97157791995-10-23 13:59:53 +00002124class MHMailbox:
Guido van Rossum4bf12542002-09-12 05:08:00 +00002125
Barry Warsaw81ad67c2001-01-31 22:13:15 +00002126 def __init__(self, dirname, factory=rfc822.Message):
Fred Drakedbbf76b2000-07-09 16:44:26 +00002127 import re
Guido van Rossum0707fea2000-08-10 03:05:26 +00002128 pat = re.compile('^[1-9][0-9]*$')
Fred Drakedbbf76b2000-07-09 16:44:26 +00002129 self.dirname = dirname
Sjoerd Mullenderd2653a92000-08-11 07:48:36 +00002130 # the three following lines could be combined into:
2131 # list = map(long, filter(pat.match, os.listdir(self.dirname)))
2132 list = os.listdir(self.dirname)
2133 list = filter(pat.match, list)
Guido van Rossum0707fea2000-08-10 03:05:26 +00002134 list = map(long, list)
2135 list.sort()
2136 # This only works in Python 1.6 or later;
2137 # before that str() added 'L':
2138 self.boxes = map(str, list)
Raymond Hettingerb5ba8d72004-02-07 02:16:24 +00002139 self.boxes.reverse()
Barry Warsaw81ad67c2001-01-31 22:13:15 +00002140 self.factory = factory
Jack Jansen97157791995-10-23 13:59:53 +00002141
Fred Drake72987a42001-05-02 20:20:53 +00002142 def __iter__(self):
Guido van Rossum93a696f2001-09-13 01:29:13 +00002143 return iter(self.next, None)
Fred Drake72987a42001-05-02 20:20:53 +00002144
Fred Drakedbbf76b2000-07-09 16:44:26 +00002145 def next(self):
2146 if not self.boxes:
2147 return None
Raymond Hettingerb5ba8d72004-02-07 02:16:24 +00002148 fn = self.boxes.pop()
Fred Drakedbbf76b2000-07-09 16:44:26 +00002149 fp = open(os.path.join(self.dirname, fn))
Guido van Rossum4bf12542002-09-12 05:08:00 +00002150 msg = self.factory(fp)
2151 try:
2152 msg._mh_msgno = fn
2153 except (AttributeError, TypeError):
2154 pass
2155 return msg
Guido van Rossum8ca84201998-03-26 20:56:10 +00002156
Guido van Rossum9a4d6371998-12-23 22:05:42 +00002157
Guido van Rossumfdf58fe1997-05-15 14:33:09 +00002158class BabylMailbox(_Mailbox):
Guido van Rossum4bf12542002-09-12 05:08:00 +00002159
Fred Drakedbbf76b2000-07-09 16:44:26 +00002160 def _search_start(self):
2161 while 1:
2162 line = self.fp.readline()
2163 if not line:
2164 raise EOFError
2165 if line == '*** EOOH ***\n':
2166 return
Guido van Rossumfdf58fe1997-05-15 14:33:09 +00002167
Fred Drakedbbf76b2000-07-09 16:44:26 +00002168 def _search_end(self):
2169 while 1:
2170 pos = self.fp.tell()
2171 line = self.fp.readline()
2172 if not line:
2173 return
Johannes Gijsbers6abc6852004-08-21 12:30:26 +00002174 if line == '\037\014\n' or line == '\037':
Fred Drakedbbf76b2000-07-09 16:44:26 +00002175 self.fp.seek(pos)
2176 return
Guido van Rossumfdf58fe1997-05-15 14:33:09 +00002177
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +00002178## End: classes from the original module (for backward compatibility).
Guido van Rossum62448671996-09-17 21:33:15 +00002179
2180
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +00002181class Error(Exception):
2182 """Raised for module-specific errors."""
2183
2184class NoSuchMailboxError(Error):
2185 """The specified mailbox does not exist and won't be created."""
2186
2187class NotEmptyError(Error):
2188 """The specified mailbox is not empty and deletion was requested."""
2189
2190class ExternalClashError(Error):
2191 """Another process caused an action to fail."""
2192
2193class FormatError(Error):
2194 """A file appears to have an invalid format."""