blob: ba497530872db06178cf3a5c073c9af2e50b667b [file] [log] [blame]
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +00001"""Read/write support for Maildir, mbox, MH, Babyl, and MMDF mailboxes."""
Guido van Rossum62448671996-09-17 21:33:15 +00002
Andrew M. Kuchlingb5686da2006-11-09 13:51:14 +00003# Notes for authors of new mailbox subclasses:
4#
5# Remember to fsync() changes to disk before closing a modified file
6# or returning from a flush() method. See functions _sync_flush() and
7# _sync_close().
8
Martin v. Löwis08041d52006-05-04 14:27:52 +00009import sys
Jack Jansen97157791995-10-23 13:59:53 +000010import os
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +000011import time
12import calendar
13import socket
14import errno
15import copy
16import email
Georg Brandl5a096e12007-01-22 19:40:21 +000017import email.message
18import email.generator
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +000019import StringIO
20try:
Andrew MacIntyreafa358f2006-07-23 13:04:00 +000021 if sys.platform == 'os2emx':
22 # OS/2 EMX fcntl() not adequate
23 raise ImportError
Andrew M. Kuchlinga7ee9eb2006-06-26 13:08:24 +000024 import fcntl
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +000025except ImportError:
26 fcntl = None
Guido van Rossumc7b68821994-04-28 09:53:33 +000027
Antoine Pitroub9d49632010-01-04 23:22:44 +000028import warnings
29with warnings.catch_warnings():
30 if sys.py3kwarning:
31 warnings.filterwarnings("ignore", ".*rfc822 has been removed",
32 DeprecationWarning)
33 import rfc822
34
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +000035__all__ = [ 'Mailbox', 'Maildir', 'mbox', 'MH', 'Babyl', 'MMDF',
36 'Message', 'MaildirMessage', 'mboxMessage', 'MHMessage',
37 'BabylMessage', 'MMDFMessage', 'UnixMailbox',
38 'PortableUnixMailbox', 'MmdfMailbox', 'MHMailbox', 'BabylMailbox' ]
39
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +000040class Mailbox:
41 """A group of messages in a particular place."""
42
43 def __init__(self, path, factory=None, create=True):
44 """Initialize a Mailbox instance."""
45 self._path = os.path.abspath(os.path.expanduser(path))
46 self._factory = factory
47
48 def add(self, message):
49 """Add message and return assigned key."""
50 raise NotImplementedError('Method must be implemented by subclass')
51
52 def remove(self, key):
53 """Remove the keyed message; raise KeyError if it doesn't exist."""
54 raise NotImplementedError('Method must be implemented by subclass')
55
56 def __delitem__(self, key):
57 self.remove(key)
58
59 def discard(self, key):
60 """If the keyed message exists, remove it."""
61 try:
62 self.remove(key)
63 except KeyError:
64 pass
65
66 def __setitem__(self, key, message):
67 """Replace the keyed message; raise KeyError if it doesn't exist."""
68 raise NotImplementedError('Method must be implemented by subclass')
69
70 def get(self, key, default=None):
71 """Return the keyed message, or default if it doesn't exist."""
72 try:
73 return self.__getitem__(key)
74 except KeyError:
75 return default
76
77 def __getitem__(self, key):
78 """Return the keyed message; raise KeyError if it doesn't exist."""
79 if not self._factory:
80 return self.get_message(key)
81 else:
82 return self._factory(self.get_file(key))
83
84 def get_message(self, key):
85 """Return a Message representation or raise a KeyError."""
86 raise NotImplementedError('Method must be implemented by subclass')
87
88 def get_string(self, key):
89 """Return a string representation or raise a KeyError."""
90 raise NotImplementedError('Method must be implemented by subclass')
91
92 def get_file(self, key):
93 """Return a file-like representation or raise a KeyError."""
94 raise NotImplementedError('Method must be implemented by subclass')
95
96 def iterkeys(self):
97 """Return an iterator over keys."""
98 raise NotImplementedError('Method must be implemented by subclass')
99
100 def keys(self):
101 """Return a list of keys."""
102 return list(self.iterkeys())
103
104 def itervalues(self):
105 """Return an iterator over all messages."""
106 for key in self.iterkeys():
107 try:
108 value = self[key]
109 except KeyError:
110 continue
111 yield value
112
113 def __iter__(self):
114 return self.itervalues()
115
116 def values(self):
117 """Return a list of messages. Memory intensive."""
118 return list(self.itervalues())
119
120 def iteritems(self):
121 """Return an iterator over (key, message) tuples."""
122 for key in self.iterkeys():
123 try:
124 value = self[key]
125 except KeyError:
126 continue
127 yield (key, value)
128
129 def items(self):
130 """Return a list of (key, message) tuples. Memory intensive."""
131 return list(self.iteritems())
132
133 def has_key(self, key):
134 """Return True if the keyed message exists, False otherwise."""
135 raise NotImplementedError('Method must be implemented by subclass')
136
137 def __contains__(self, key):
138 return self.has_key(key)
139
140 def __len__(self):
141 """Return a count of messages in the mailbox."""
142 raise NotImplementedError('Method must be implemented by subclass')
143
144 def clear(self):
145 """Delete all messages."""
146 for key in self.iterkeys():
147 self.discard(key)
148
149 def pop(self, key, default=None):
150 """Delete the keyed message and return it, or default."""
151 try:
152 result = self[key]
153 except KeyError:
154 return default
155 self.discard(key)
156 return result
157
158 def popitem(self):
159 """Delete an arbitrary (key, message) pair and return it."""
160 for key in self.iterkeys():
161 return (key, self.pop(key)) # This is only run once.
162 else:
163 raise KeyError('No messages in mailbox')
164
165 def update(self, arg=None):
166 """Change the messages that correspond to certain keys."""
167 if hasattr(arg, 'iteritems'):
168 source = arg.iteritems()
169 elif hasattr(arg, 'items'):
170 source = arg.items()
171 else:
172 source = arg
173 bad_key = False
174 for key, message in source:
175 try:
176 self[key] = message
177 except KeyError:
178 bad_key = True
179 if bad_key:
180 raise KeyError('No message with key(s)')
181
182 def flush(self):
183 """Write any pending changes to the disk."""
184 raise NotImplementedError('Method must be implemented by subclass')
185
186 def lock(self):
187 """Lock the mailbox."""
188 raise NotImplementedError('Method must be implemented by subclass')
189
190 def unlock(self):
191 """Unlock the mailbox if it is locked."""
192 raise NotImplementedError('Method must be implemented by subclass')
193
194 def close(self):
195 """Flush and close the mailbox."""
196 raise NotImplementedError('Method must be implemented by subclass')
197
Petri Lehtinena4fd0dc2012-09-25 21:57:59 +0300198 # Whether each message must end in a newline
199 _append_newline = False
200
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +0000201 def _dump_message(self, message, target, mangle_from_=False):
202 # Most files are opened in binary mode to allow predictable seeking.
203 # To get native line endings on disk, the user-friendly \n line endings
204 # used in strings and by email.Message are translated here.
205 """Dump message contents to target file."""
Georg Brandl5a096e12007-01-22 19:40:21 +0000206 if isinstance(message, email.message.Message):
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +0000207 buffer = StringIO.StringIO()
Georg Brandl5a096e12007-01-22 19:40:21 +0000208 gen = email.generator.Generator(buffer, mangle_from_, 0)
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +0000209 gen.flatten(message)
210 buffer.seek(0)
Petri Lehtinena4fd0dc2012-09-25 21:57:59 +0300211 data = buffer.read().replace('\n', os.linesep)
212 target.write(data)
213 if self._append_newline and not data.endswith(os.linesep):
214 # Make sure the message ends with a newline
215 target.write(os.linesep)
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +0000216 elif isinstance(message, str):
217 if mangle_from_:
218 message = message.replace('\nFrom ', '\n>From ')
219 message = message.replace('\n', os.linesep)
220 target.write(message)
Petri Lehtinena4fd0dc2012-09-25 21:57:59 +0300221 if self._append_newline and not message.endswith(os.linesep):
222 # Make sure the message ends with a newline
223 target.write(os.linesep)
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +0000224 elif hasattr(message, 'read'):
Petri Lehtinena4fd0dc2012-09-25 21:57:59 +0300225 lastline = None
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +0000226 while True:
227 line = message.readline()
228 if line == '':
229 break
230 if mangle_from_ and line.startswith('From '):
231 line = '>From ' + line[5:]
232 line = line.replace('\n', os.linesep)
233 target.write(line)
Petri Lehtinena4fd0dc2012-09-25 21:57:59 +0300234 lastline = line
235 if self._append_newline and lastline and not lastline.endswith(os.linesep):
236 # Make sure the message ends with a newline
237 target.write(os.linesep)
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +0000238 else:
239 raise TypeError('Invalid message type: %s' % type(message))
240
241
242class Maildir(Mailbox):
243 """A qmail-style Maildir mailbox."""
244
245 colon = ':'
246
247 def __init__(self, dirname, factory=rfc822.Message, create=True):
248 """Initialize a Maildir instance."""
249 Mailbox.__init__(self, dirname, factory, create)
R David Murray8b26c4b2011-05-06 21:56:22 -0400250 self._paths = {
251 'tmp': os.path.join(self._path, 'tmp'),
252 'new': os.path.join(self._path, 'new'),
253 'cur': os.path.join(self._path, 'cur'),
254 }
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +0000255 if not os.path.exists(self._path):
256 if create:
257 os.mkdir(self._path, 0700)
R David Murray8b26c4b2011-05-06 21:56:22 -0400258 for path in self._paths.values():
259 os.mkdir(path, 0o700)
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +0000260 else:
261 raise NoSuchMailboxError(self._path)
262 self._toc = {}
Petri Lehtinen49aa72e2011-11-05 09:50:37 +0200263 self._toc_mtimes = {'cur': 0, 'new': 0}
264 self._last_read = 0 # Records last time we read cur/new
265 self._skewfactor = 0.1 # Adjust if os/fs clocks are skewing
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +0000266
267 def add(self, message):
268 """Add message and return assigned key."""
269 tmp_file = self._create_tmp()
270 try:
271 self._dump_message(message, tmp_file)
R. David Murray008c0442011-02-11 23:03:13 +0000272 except BaseException:
273 tmp_file.close()
274 os.remove(tmp_file.name)
275 raise
276 _sync_close(tmp_file)
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +0000277 if isinstance(message, MaildirMessage):
278 subdir = message.get_subdir()
279 suffix = self.colon + message.get_info()
280 if suffix == self.colon:
281 suffix = ''
282 else:
283 subdir = 'new'
284 suffix = ''
285 uniq = os.path.basename(tmp_file.name).split(self.colon)[0]
286 dest = os.path.join(self._path, subdir, uniq + suffix)
R David Murrayc64566e2013-09-18 08:35:45 -0400287 if isinstance(message, MaildirMessage):
288 os.utime(tmp_file.name,
289 (os.path.getatime(tmp_file.name), message.get_date()))
290 # No file modification should be done after the file is moved to its
291 # final position in order to prevent race conditions with changes
292 # from other programs
Andrew M. Kuchling978d8282006-11-09 21:16:46 +0000293 try:
294 if hasattr(os, 'link'):
295 os.link(tmp_file.name, dest)
296 os.remove(tmp_file.name)
297 else:
298 os.rename(tmp_file.name, dest)
299 except OSError, e:
300 os.remove(tmp_file.name)
301 if e.errno == errno.EEXIST:
302 raise ExternalClashError('Name clash with existing message: %s'
303 % dest)
304 else:
305 raise
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +0000306 return uniq
307
308 def remove(self, key):
309 """Remove the keyed message; raise KeyError if it doesn't exist."""
310 os.remove(os.path.join(self._path, self._lookup(key)))
311
312 def discard(self, key):
313 """If the keyed message exists, remove it."""
314 # This overrides an inapplicable implementation in the superclass.
315 try:
316 self.remove(key)
317 except KeyError:
318 pass
319 except OSError, e:
Martin v. Löwis08041d52006-05-04 14:27:52 +0000320 if e.errno != errno.ENOENT:
Tim Peters6d7cd7d2006-04-22 05:52:59 +0000321 raise
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +0000322
323 def __setitem__(self, key, message):
324 """Replace the keyed message; raise KeyError if it doesn't exist."""
325 old_subpath = self._lookup(key)
326 temp_key = self.add(message)
327 temp_subpath = self._lookup(temp_key)
328 if isinstance(message, MaildirMessage):
329 # temp's subdir and suffix were specified by message.
330 dominant_subpath = temp_subpath
331 else:
332 # temp's subdir and suffix were defaults from add().
333 dominant_subpath = old_subpath
334 subdir = os.path.dirname(dominant_subpath)
335 if self.colon in dominant_subpath:
336 suffix = self.colon + dominant_subpath.split(self.colon)[-1]
337 else:
338 suffix = ''
339 self.discard(key)
R David Murrayc64566e2013-09-18 08:35:45 -0400340 tmp_path = os.path.join(self._path, temp_subpath)
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +0000341 new_path = os.path.join(self._path, subdir, key + suffix)
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +0000342 if isinstance(message, MaildirMessage):
R David Murrayc64566e2013-09-18 08:35:45 -0400343 os.utime(tmp_path,
344 (os.path.getatime(tmp_path), message.get_date()))
345 # No file modification should be done after the file is moved to its
346 # final position in order to prevent race conditions with changes
347 # from other programs
348 os.rename(tmp_path, new_path)
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +0000349
350 def get_message(self, key):
351 """Return a Message representation or raise a KeyError."""
352 subpath = self._lookup(key)
Andrew M. Kuchling214db632006-05-02 21:44:33 +0000353 f = open(os.path.join(self._path, subpath), 'r')
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +0000354 try:
Andrew M. Kuchling15ce8802008-01-19 20:12:04 +0000355 if self._factory:
356 msg = self._factory(f)
357 else:
358 msg = MaildirMessage(f)
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +0000359 finally:
360 f.close()
361 subdir, name = os.path.split(subpath)
362 msg.set_subdir(subdir)
363 if self.colon in name:
364 msg.set_info(name.split(self.colon)[-1])
365 msg.set_date(os.path.getmtime(os.path.join(self._path, subpath)))
366 return msg
367
368 def get_string(self, key):
369 """Return a string representation or raise a KeyError."""
Andrew M. Kuchling214db632006-05-02 21:44:33 +0000370 f = open(os.path.join(self._path, self._lookup(key)), 'r')
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +0000371 try:
372 return f.read()
373 finally:
374 f.close()
375
376 def get_file(self, key):
377 """Return a file-like representation or raise a KeyError."""
Andrew M. Kuchling214db632006-05-02 21:44:33 +0000378 f = open(os.path.join(self._path, self._lookup(key)), 'rb')
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +0000379 return _ProxyFile(f)
380
381 def iterkeys(self):
382 """Return an iterator over keys."""
383 self._refresh()
384 for key in self._toc:
385 try:
386 self._lookup(key)
387 except KeyError:
388 continue
389 yield key
390
391 def has_key(self, key):
392 """Return True if the keyed message exists, False otherwise."""
393 self._refresh()
394 return key in self._toc
395
396 def __len__(self):
397 """Return a count of messages in the mailbox."""
398 self._refresh()
399 return len(self._toc)
400
401 def flush(self):
402 """Write any pending changes to disk."""
Antoine Pitroue4c6b162009-11-01 21:29:33 +0000403 # Maildir changes are always written immediately, so there's nothing
R David Murray8b26c4b2011-05-06 21:56:22 -0400404 # to do.
405 pass
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +0000406
407 def lock(self):
408 """Lock the mailbox."""
409 return
410
411 def unlock(self):
412 """Unlock the mailbox if it is locked."""
413 return
414
415 def close(self):
416 """Flush and close the mailbox."""
417 return
418
419 def list_folders(self):
420 """Return a list of folder names."""
421 result = []
422 for entry in os.listdir(self._path):
423 if len(entry) > 1 and entry[0] == '.' and \
424 os.path.isdir(os.path.join(self._path, entry)):
425 result.append(entry[1:])
426 return result
427
428 def get_folder(self, folder):
429 """Return a Maildir instance for the named folder."""
Andrew M. Kuchlinga3e5d372006-11-09 13:27:07 +0000430 return Maildir(os.path.join(self._path, '.' + folder),
431 factory=self._factory,
432 create=False)
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +0000433
434 def add_folder(self, folder):
435 """Create a folder and return a Maildir instance representing it."""
436 path = os.path.join(self._path, '.' + folder)
Andrew M. Kuchlinga3e5d372006-11-09 13:27:07 +0000437 result = Maildir(path, factory=self._factory)
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +0000438 maildirfolder_path = os.path.join(path, 'maildirfolder')
439 if not os.path.exists(maildirfolder_path):
Andrew M. Kuchling70a6dbd2008-08-04 01:43:43 +0000440 os.close(os.open(maildirfolder_path, os.O_CREAT | os.O_WRONLY,
441 0666))
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +0000442 return result
443
444 def remove_folder(self, folder):
445 """Delete the named folder, which must be empty."""
446 path = os.path.join(self._path, '.' + folder)
447 for entry in os.listdir(os.path.join(path, 'new')) + \
448 os.listdir(os.path.join(path, 'cur')):
449 if len(entry) < 1 or entry[0] != '.':
450 raise NotEmptyError('Folder contains message(s): %s' % folder)
451 for entry in os.listdir(path):
452 if entry != 'new' and entry != 'cur' and entry != 'tmp' and \
453 os.path.isdir(os.path.join(path, entry)):
454 raise NotEmptyError("Folder contains subdirectory '%s': %s" %
455 (folder, entry))
456 for root, dirs, files in os.walk(path, topdown=False):
457 for entry in files:
458 os.remove(os.path.join(root, entry))
459 for entry in dirs:
460 os.rmdir(os.path.join(root, entry))
461 os.rmdir(path)
462
463 def clean(self):
464 """Delete old files in "tmp"."""
465 now = time.time()
466 for entry in os.listdir(os.path.join(self._path, 'tmp')):
467 path = os.path.join(self._path, 'tmp', entry)
468 if now - os.path.getatime(path) > 129600: # 60 * 60 * 36
469 os.remove(path)
470
471 _count = 1 # This is used to generate unique file names.
472
473 def _create_tmp(self):
474 """Create a file in the tmp subdirectory and open and return it."""
475 now = time.time()
476 hostname = socket.gethostname()
477 if '/' in hostname:
478 hostname = hostname.replace('/', r'\057')
479 if ':' in hostname:
480 hostname = hostname.replace(':', r'\072')
481 uniq = "%s.M%sP%sQ%s.%s" % (int(now), int(now % 1 * 1e6), os.getpid(),
482 Maildir._count, hostname)
483 path = os.path.join(self._path, 'tmp', uniq)
484 try:
485 os.stat(path)
486 except OSError, e:
487 if e.errno == errno.ENOENT:
488 Maildir._count += 1
Andrew M. Kuchling978d8282006-11-09 21:16:46 +0000489 try:
490 return _create_carefully(path)
491 except OSError, e:
492 if e.errno != errno.EEXIST:
493 raise
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +0000494 else:
495 raise
Andrew M. Kuchling978d8282006-11-09 21:16:46 +0000496
497 # Fall through to here if stat succeeded or open raised EEXIST.
498 raise ExternalClashError('Name clash prevented file creation: %s' %
499 path)
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +0000500
501 def _refresh(self):
502 """Update table of contents mapping."""
R David Murray8b26c4b2011-05-06 21:56:22 -0400503 # If it has been less than two seconds since the last _refresh() call,
504 # we have to unconditionally re-read the mailbox just in case it has
505 # been modified, because os.path.mtime() has a 2 sec resolution in the
506 # most common worst case (FAT) and a 1 sec resolution typically. This
507 # results in a few unnecessary re-reads when _refresh() is called
508 # multiple times in that interval, but once the clock ticks over, we
509 # will only re-read as needed. Because the filesystem might be being
510 # served by an independent system with its own clock, we record and
511 # compare with the mtimes from the filesystem. Because the other
512 # system's clock might be skewing relative to our clock, we add an
513 # extra delta to our wait. The default is one tenth second, but is an
514 # instance variable and so can be adjusted if dealing with a
515 # particularly skewed or irregular system.
516 if time.time() - self._last_read > 2 + self._skewfactor:
517 refresh = False
518 for subdir in self._toc_mtimes:
519 mtime = os.path.getmtime(self._paths[subdir])
520 if mtime > self._toc_mtimes[subdir]:
521 refresh = True
522 self._toc_mtimes[subdir] = mtime
523 if not refresh:
Antoine Pitroud35b8c72009-11-01 00:30:13 +0000524 return
R David Murray8b26c4b2011-05-06 21:56:22 -0400525 # Refresh toc
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +0000526 self._toc = {}
R David Murray8b26c4b2011-05-06 21:56:22 -0400527 for subdir in self._toc_mtimes:
528 path = self._paths[subdir]
Andrew M. Kuchling420d4eb2009-05-02 19:17:28 +0000529 for entry in os.listdir(path):
530 p = os.path.join(path, entry)
Andrew M. Kuchling2b09ef02007-07-14 21:56:19 +0000531 if os.path.isdir(p):
532 continue
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +0000533 uniq = entry.split(self.colon)[0]
534 self._toc[uniq] = os.path.join(subdir, entry)
R David Murray8b26c4b2011-05-06 21:56:22 -0400535 self._last_read = time.time()
Andrew M. Kuchling420d4eb2009-05-02 19:17:28 +0000536
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +0000537 def _lookup(self, key):
538 """Use TOC to return subpath for given key, or raise a KeyError."""
539 try:
540 if os.path.exists(os.path.join(self._path, self._toc[key])):
541 return self._toc[key]
542 except KeyError:
543 pass
544 self._refresh()
545 try:
546 return self._toc[key]
547 except KeyError:
548 raise KeyError('No message with key: %s' % key)
549
550 # This method is for backward compatibility only.
551 def next(self):
552 """Return the next message in a one-time iteration."""
553 if not hasattr(self, '_onetime_keys'):
554 self._onetime_keys = self.iterkeys()
555 while True:
556 try:
557 return self[self._onetime_keys.next()]
558 except StopIteration:
559 return None
560 except KeyError:
561 continue
562
563
564class _singlefileMailbox(Mailbox):
565 """A single-file mailbox."""
566
567 def __init__(self, path, factory=None, create=True):
568 """Initialize a single-file mailbox."""
569 Mailbox.__init__(self, path, factory, create)
570 try:
Andrew M. Kuchling214db632006-05-02 21:44:33 +0000571 f = open(self._path, 'rb+')
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +0000572 except IOError, e:
573 if e.errno == errno.ENOENT:
574 if create:
Andrew M. Kuchling214db632006-05-02 21:44:33 +0000575 f = open(self._path, 'wb+')
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +0000576 else:
577 raise NoSuchMailboxError(self._path)
R. David Murray1a337902011-03-03 18:17:40 +0000578 elif e.errno in (errno.EACCES, errno.EROFS):
Andrew M. Kuchling214db632006-05-02 21:44:33 +0000579 f = open(self._path, 'rb')
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +0000580 else:
581 raise
582 self._file = f
583 self._toc = None
584 self._next_key = 0
Petri Lehtinen45f0d982012-06-28 13:48:17 +0300585 self._pending = False # No changes require rewriting the file.
586 self._pending_sync = False # No need to sync the file
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +0000587 self._locked = False
Petri Lehtinen45f0d982012-06-28 13:48:17 +0300588 self._file_length = None # Used to record mailbox size
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +0000589
590 def add(self, message):
591 """Add message and return assigned key."""
592 self._lookup()
593 self._toc[self._next_key] = self._append_message(message)
594 self._next_key += 1
Petri Lehtinen45f0d982012-06-28 13:48:17 +0300595 # _append_message appends the message to the mailbox file. We
596 # don't need a full rewrite + rename, sync is enough.
597 self._pending_sync = True
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +0000598 return self._next_key - 1
599
600 def remove(self, key):
601 """Remove the keyed message; raise KeyError if it doesn't exist."""
602 self._lookup(key)
603 del self._toc[key]
604 self._pending = True
605
606 def __setitem__(self, key, message):
607 """Replace the keyed message; raise KeyError if it doesn't exist."""
608 self._lookup(key)
609 self._toc[key] = self._append_message(message)
610 self._pending = True
611
612 def iterkeys(self):
613 """Return an iterator over keys."""
614 self._lookup()
615 for key in self._toc.keys():
616 yield key
617
618 def has_key(self, key):
619 """Return True if the keyed message exists, False otherwise."""
620 self._lookup()
621 return key in self._toc
622
623 def __len__(self):
624 """Return a count of messages in the mailbox."""
625 self._lookup()
626 return len(self._toc)
627
628 def lock(self):
629 """Lock the mailbox."""
630 if not self._locked:
631 _lock_file(self._file)
632 self._locked = True
633
634 def unlock(self):
635 """Unlock the mailbox if it is locked."""
636 if self._locked:
637 _unlock_file(self._file)
638 self._locked = False
639
640 def flush(self):
641 """Write any pending changes to disk."""
642 if not self._pending:
Petri Lehtinen45f0d982012-06-28 13:48:17 +0300643 if self._pending_sync:
644 # Messages have only been added, so syncing the file
645 # is enough.
646 _sync_flush(self._file)
647 self._pending_sync = False
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +0000648 return
Andrew M. Kuchlingeca4c312006-12-20 19:48:20 +0000649
650 # In order to be writing anything out at all, self._toc must
651 # already have been generated (and presumably has been modified
652 # by adding or deleting an item).
653 assert self._toc is not None
Tim Petersf733abb2007-01-30 03:03:46 +0000654
Andrew M. Kuchlingeca4c312006-12-20 19:48:20 +0000655 # Check length of self._file; if it's changed, some other process
656 # has modified the mailbox since we scanned it.
657 self._file.seek(0, 2)
658 cur_len = self._file.tell()
659 if cur_len != self._file_length:
660 raise ExternalClashError('Size of mailbox file changed '
661 '(expected %i, found %i)' %
662 (self._file_length, cur_len))
Tim Petersf733abb2007-01-30 03:03:46 +0000663
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +0000664 new_file = _create_temporary(self._path)
665 try:
666 new_toc = {}
667 self._pre_mailbox_hook(new_file)
668 for key in sorted(self._toc.keys()):
669 start, stop = self._toc[key]
670 self._file.seek(start)
671 self._pre_message_hook(new_file)
672 new_start = new_file.tell()
673 while True:
674 buffer = self._file.read(min(4096,
675 stop - self._file.tell()))
676 if buffer == '':
677 break
678 new_file.write(buffer)
679 new_toc[key] = (new_start, new_file.tell())
680 self._post_message_hook(new_file)
Petri Lehtinen7cf66992012-06-15 20:50:51 +0300681 self._file_length = new_file.tell()
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +0000682 except:
683 new_file.close()
684 os.remove(new_file.name)
685 raise
Andrew M. Kuchlingb5686da2006-11-09 13:51:14 +0000686 _sync_close(new_file)
687 # self._file is about to get replaced, so no need to sync.
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +0000688 self._file.close()
Petri Lehtinend07de402012-06-29 15:09:12 +0300689 # Make sure the new file's mode is the same as the old file's
690 mode = os.stat(self._path).st_mode
691 os.chmod(new_file.name, mode)
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +0000692 try:
693 os.rename(new_file.name, self._path)
694 except OSError, e:
Andrew MacIntyreafa358f2006-07-23 13:04:00 +0000695 if e.errno == errno.EEXIST or \
696 (os.name == 'os2' and e.errno == errno.EACCES):
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +0000697 os.remove(self._path)
698 os.rename(new_file.name, self._path)
699 else:
700 raise
Andrew M. Kuchling214db632006-05-02 21:44:33 +0000701 self._file = open(self._path, 'rb+')
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +0000702 self._toc = new_toc
703 self._pending = False
Petri Lehtinen45f0d982012-06-28 13:48:17 +0300704 self._pending_sync = False
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +0000705 if self._locked:
Andrew M. Kuchling0f871832006-10-27 16:55:34 +0000706 _lock_file(self._file, dotlock=False)
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +0000707
708 def _pre_mailbox_hook(self, f):
709 """Called before writing the mailbox to file f."""
710 return
711
712 def _pre_message_hook(self, f):
713 """Called before writing each message to file f."""
714 return
715
716 def _post_message_hook(self, f):
717 """Called after writing each message to file f."""
718 return
719
720 def close(self):
721 """Flush and close the mailbox."""
722 self.flush()
723 if self._locked:
724 self.unlock()
Andrew M. Kuchlingb5686da2006-11-09 13:51:14 +0000725 self._file.close() # Sync has been done by self.flush() above.
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +0000726
727 def _lookup(self, key=None):
728 """Return (start, stop) or raise KeyError."""
729 if self._toc is None:
730 self._generate_toc()
731 if key is not None:
732 try:
733 return self._toc[key]
734 except KeyError:
735 raise KeyError('No message with key: %s' % key)
736
737 def _append_message(self, message):
738 """Append message to mailbox and return (start, stop) offsets."""
739 self._file.seek(0, 2)
R. David Murray008c0442011-02-11 23:03:13 +0000740 before = self._file.tell()
Petri Lehtinen4e6e5a02012-06-29 13:43:37 +0300741 if len(self._toc) == 0 and not self._pending:
742 # This is the first message, and the _pre_mailbox_hook
743 # hasn't yet been called. If self._pending is True,
744 # messages have been removed, so _pre_mailbox_hook must
745 # have been called already.
Petri Lehtinen45f0d982012-06-28 13:48:17 +0300746 self._pre_mailbox_hook(self._file)
R. David Murray008c0442011-02-11 23:03:13 +0000747 try:
748 self._pre_message_hook(self._file)
749 offsets = self._install_message(message)
750 self._post_message_hook(self._file)
751 except BaseException:
752 self._file.truncate(before)
753 raise
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +0000754 self._file.flush()
Andrew M. Kuchlingeca4c312006-12-20 19:48:20 +0000755 self._file_length = self._file.tell() # Record current length of mailbox
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +0000756 return offsets
757
758
759
760class _mboxMMDF(_singlefileMailbox):
761 """An mbox or MMDF mailbox."""
762
763 _mangle_from_ = True
764
765 def get_message(self, key):
766 """Return a Message representation or raise a KeyError."""
767 start, stop = self._lookup(key)
768 self._file.seek(start)
769 from_line = self._file.readline().replace(os.linesep, '')
770 string = self._file.read(stop - self._file.tell())
771 msg = self._message_factory(string.replace(os.linesep, '\n'))
772 msg.set_from(from_line[5:])
773 return msg
774
775 def get_string(self, key, from_=False):
776 """Return a string representation or raise a KeyError."""
777 start, stop = self._lookup(key)
778 self._file.seek(start)
779 if not from_:
780 self._file.readline()
781 string = self._file.read(stop - self._file.tell())
782 return string.replace(os.linesep, '\n')
783
784 def get_file(self, key, from_=False):
785 """Return a file-like representation or raise a KeyError."""
786 start, stop = self._lookup(key)
787 self._file.seek(start)
788 if not from_:
789 self._file.readline()
790 return _PartialFile(self._file, self._file.tell(), stop)
791
792 def _install_message(self, message):
793 """Format a message and blindly write to self._file."""
794 from_line = None
795 if isinstance(message, str) and message.startswith('From '):
796 newline = message.find('\n')
797 if newline != -1:
798 from_line = message[:newline]
799 message = message[newline + 1:]
800 else:
801 from_line = message
802 message = ''
803 elif isinstance(message, _mboxMMDFMessage):
804 from_line = 'From ' + message.get_from()
Georg Brandl5a096e12007-01-22 19:40:21 +0000805 elif isinstance(message, email.message.Message):
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +0000806 from_line = message.get_unixfrom() # May be None.
807 if from_line is None:
808 from_line = 'From MAILER-DAEMON %s' % time.asctime(time.gmtime())
809 start = self._file.tell()
810 self._file.write(from_line + os.linesep)
811 self._dump_message(message, self._file, self._mangle_from_)
812 stop = self._file.tell()
813 return (start, stop)
814
815
816class mbox(_mboxMMDF):
817 """A classic mbox mailbox."""
818
819 _mangle_from_ = True
820
Petri Lehtinena4fd0dc2012-09-25 21:57:59 +0300821 # All messages must end in a newline character, and
822 # _post_message_hooks outputs an empty line between messages.
823 _append_newline = True
824
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +0000825 def __init__(self, path, factory=None, create=True):
826 """Initialize an mbox mailbox."""
827 self._message_factory = mboxMessage
828 _mboxMMDF.__init__(self, path, factory, create)
829
Petri Lehtinena4fd0dc2012-09-25 21:57:59 +0300830 def _post_message_hook(self, f):
831 """Called after writing each message to file f."""
832 f.write(os.linesep)
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +0000833
834 def _generate_toc(self):
835 """Generate key-to-(start, stop) table of contents."""
836 starts, stops = [], []
Petri Lehtinena4fd0dc2012-09-25 21:57:59 +0300837 last_was_empty = False
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +0000838 self._file.seek(0)
839 while True:
840 line_pos = self._file.tell()
841 line = self._file.readline()
842 if line.startswith('From '):
843 if len(stops) < len(starts):
Petri Lehtinena4fd0dc2012-09-25 21:57:59 +0300844 if last_was_empty:
845 stops.append(line_pos - len(os.linesep))
846 else:
847 # The last line before the "From " line wasn't
848 # blank, but we consider it a start of a
849 # message anyway.
850 stops.append(line_pos)
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +0000851 starts.append(line_pos)
Petri Lehtinena4fd0dc2012-09-25 21:57:59 +0300852 last_was_empty = False
853 elif not line:
854 if last_was_empty:
855 stops.append(line_pos - len(os.linesep))
856 else:
857 stops.append(line_pos)
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +0000858 break
Petri Lehtinena4fd0dc2012-09-25 21:57:59 +0300859 elif line == os.linesep:
860 last_was_empty = True
861 else:
862 last_was_empty = False
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +0000863 self._toc = dict(enumerate(zip(starts, stops)))
864 self._next_key = len(self._toc)
Andrew M. Kuchlingeca4c312006-12-20 19:48:20 +0000865 self._file_length = self._file.tell()
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +0000866
867
868class MMDF(_mboxMMDF):
869 """An MMDF mailbox."""
870
871 def __init__(self, path, factory=None, create=True):
872 """Initialize an MMDF mailbox."""
873 self._message_factory = MMDFMessage
874 _mboxMMDF.__init__(self, path, factory, create)
875
876 def _pre_message_hook(self, f):
877 """Called before writing each message to file f."""
878 f.write('\001\001\001\001' + os.linesep)
879
880 def _post_message_hook(self, f):
881 """Called after writing each message to file f."""
882 f.write(os.linesep + '\001\001\001\001' + os.linesep)
883
884 def _generate_toc(self):
885 """Generate key-to-(start, stop) table of contents."""
886 starts, stops = [], []
887 self._file.seek(0)
888 next_pos = 0
889 while True:
890 line_pos = next_pos
891 line = self._file.readline()
892 next_pos = self._file.tell()
893 if line.startswith('\001\001\001\001' + os.linesep):
894 starts.append(next_pos)
895 while True:
896 line_pos = next_pos
897 line = self._file.readline()
898 next_pos = self._file.tell()
899 if line == '\001\001\001\001' + os.linesep:
900 stops.append(line_pos - len(os.linesep))
901 break
902 elif line == '':
903 stops.append(line_pos)
904 break
905 elif line == '':
906 break
907 self._toc = dict(enumerate(zip(starts, stops)))
908 self._next_key = len(self._toc)
Andrew M. Kuchlingeca4c312006-12-20 19:48:20 +0000909 self._file.seek(0, 2)
910 self._file_length = self._file.tell()
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +0000911
912
913class MH(Mailbox):
914 """An MH mailbox."""
915
916 def __init__(self, path, factory=None, create=True):
917 """Initialize an MH instance."""
918 Mailbox.__init__(self, path, factory, create)
919 if not os.path.exists(self._path):
920 if create:
921 os.mkdir(self._path, 0700)
922 os.close(os.open(os.path.join(self._path, '.mh_sequences'),
923 os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0600))
924 else:
925 raise NoSuchMailboxError(self._path)
926 self._locked = False
927
928 def add(self, message):
929 """Add message and return assigned key."""
930 keys = self.keys()
931 if len(keys) == 0:
932 new_key = 1
933 else:
934 new_key = max(keys) + 1
935 new_path = os.path.join(self._path, str(new_key))
936 f = _create_carefully(new_path)
R. David Murrayf9e34232011-02-12 02:03:56 +0000937 closed = False
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +0000938 try:
939 if self._locked:
940 _lock_file(f)
941 try:
R. David Murray008c0442011-02-11 23:03:13 +0000942 try:
943 self._dump_message(message, f)
944 except BaseException:
R. David Murrayf9e34232011-02-12 02:03:56 +0000945 # Unlock and close so it can be deleted on Windows
946 if self._locked:
947 _unlock_file(f)
948 _sync_close(f)
949 closed = True
R. David Murray008c0442011-02-11 23:03:13 +0000950 os.remove(new_path)
951 raise
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +0000952 if isinstance(message, MHMessage):
953 self._dump_sequences(message, new_key)
954 finally:
955 if self._locked:
956 _unlock_file(f)
957 finally:
R. David Murrayf9e34232011-02-12 02:03:56 +0000958 if not closed:
959 _sync_close(f)
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +0000960 return new_key
961
962 def remove(self, key):
963 """Remove the keyed message; raise KeyError if it doesn't exist."""
964 path = os.path.join(self._path, str(key))
965 try:
Andrew M. Kuchling214db632006-05-02 21:44:33 +0000966 f = open(path, 'rb+')
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +0000967 except IOError, e:
968 if e.errno == errno.ENOENT:
969 raise KeyError('No message with key: %s' % key)
970 else:
971 raise
Andrew M. Kuchlingb72b0eb2010-02-22 18:42:07 +0000972 else:
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +0000973 f.close()
Andrew M. Kuchlingb72b0eb2010-02-22 18:42:07 +0000974 os.remove(path)
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +0000975
976 def __setitem__(self, key, message):
977 """Replace the keyed message; raise KeyError if it doesn't exist."""
978 path = os.path.join(self._path, str(key))
979 try:
Andrew M. Kuchling214db632006-05-02 21:44:33 +0000980 f = open(path, 'rb+')
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +0000981 except IOError, e:
982 if e.errno == errno.ENOENT:
983 raise KeyError('No message with key: %s' % key)
984 else:
985 raise
986 try:
987 if self._locked:
988 _lock_file(f)
989 try:
990 os.close(os.open(path, os.O_WRONLY | os.O_TRUNC))
991 self._dump_message(message, f)
992 if isinstance(message, MHMessage):
993 self._dump_sequences(message, key)
994 finally:
995 if self._locked:
996 _unlock_file(f)
997 finally:
Andrew M. Kuchlingb5686da2006-11-09 13:51:14 +0000998 _sync_close(f)
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +0000999
1000 def get_message(self, key):
1001 """Return a Message representation or raise a KeyError."""
1002 try:
1003 if self._locked:
Andrew M. Kuchling214db632006-05-02 21:44:33 +00001004 f = open(os.path.join(self._path, str(key)), 'r+')
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +00001005 else:
Andrew M. Kuchling214db632006-05-02 21:44:33 +00001006 f = open(os.path.join(self._path, str(key)), 'r')
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +00001007 except IOError, e:
1008 if e.errno == errno.ENOENT:
1009 raise KeyError('No message with key: %s' % key)
1010 else:
1011 raise
1012 try:
1013 if self._locked:
1014 _lock_file(f)
1015 try:
1016 msg = MHMessage(f)
1017 finally:
1018 if self._locked:
1019 _unlock_file(f)
1020 finally:
1021 f.close()
R. David Murray52720c52009-04-02 14:05:35 +00001022 for name, key_list in self.get_sequences().iteritems():
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +00001023 if key in key_list:
1024 msg.add_sequence(name)
1025 return msg
1026
1027 def get_string(self, key):
1028 """Return a string representation or raise a KeyError."""
1029 try:
1030 if self._locked:
Andrew M. Kuchling214db632006-05-02 21:44:33 +00001031 f = open(os.path.join(self._path, str(key)), 'r+')
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +00001032 else:
Andrew M. Kuchling214db632006-05-02 21:44:33 +00001033 f = open(os.path.join(self._path, str(key)), 'r')
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +00001034 except IOError, e:
1035 if e.errno == errno.ENOENT:
1036 raise KeyError('No message with key: %s' % key)
1037 else:
1038 raise
1039 try:
1040 if self._locked:
1041 _lock_file(f)
1042 try:
1043 return f.read()
1044 finally:
1045 if self._locked:
1046 _unlock_file(f)
1047 finally:
1048 f.close()
1049
1050 def get_file(self, key):
1051 """Return a file-like representation or raise a KeyError."""
1052 try:
Andrew M. Kuchling214db632006-05-02 21:44:33 +00001053 f = open(os.path.join(self._path, str(key)), 'rb')
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +00001054 except IOError, e:
1055 if e.errno == errno.ENOENT:
1056 raise KeyError('No message with key: %s' % key)
1057 else:
1058 raise
1059 return _ProxyFile(f)
1060
1061 def iterkeys(self):
1062 """Return an iterator over keys."""
1063 return iter(sorted(int(entry) for entry in os.listdir(self._path)
1064 if entry.isdigit()))
1065
1066 def has_key(self, key):
1067 """Return True if the keyed message exists, False otherwise."""
1068 return os.path.exists(os.path.join(self._path, str(key)))
1069
1070 def __len__(self):
1071 """Return a count of messages in the mailbox."""
1072 return len(list(self.iterkeys()))
1073
1074 def lock(self):
1075 """Lock the mailbox."""
1076 if not self._locked:
Andrew M. Kuchling214db632006-05-02 21:44:33 +00001077 self._file = open(os.path.join(self._path, '.mh_sequences'), 'rb+')
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +00001078 _lock_file(self._file)
1079 self._locked = True
1080
1081 def unlock(self):
1082 """Unlock the mailbox if it is locked."""
1083 if self._locked:
1084 _unlock_file(self._file)
Andrew M. Kuchlingb5686da2006-11-09 13:51:14 +00001085 _sync_close(self._file)
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +00001086 del self._file
1087 self._locked = False
1088
1089 def flush(self):
1090 """Write any pending changes to the disk."""
1091 return
1092
1093 def close(self):
1094 """Flush and close the mailbox."""
1095 if self._locked:
1096 self.unlock()
1097
1098 def list_folders(self):
1099 """Return a list of folder names."""
1100 result = []
1101 for entry in os.listdir(self._path):
1102 if os.path.isdir(os.path.join(self._path, entry)):
1103 result.append(entry)
1104 return result
1105
1106 def get_folder(self, folder):
1107 """Return an MH instance for the named folder."""
Andrew M. Kuchlinga3e5d372006-11-09 13:27:07 +00001108 return MH(os.path.join(self._path, folder),
1109 factory=self._factory, create=False)
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +00001110
1111 def add_folder(self, folder):
1112 """Create a folder and return an MH instance representing it."""
Andrew M. Kuchlinga3e5d372006-11-09 13:27:07 +00001113 return MH(os.path.join(self._path, folder),
1114 factory=self._factory)
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +00001115
1116 def remove_folder(self, folder):
1117 """Delete the named folder, which must be empty."""
1118 path = os.path.join(self._path, folder)
1119 entries = os.listdir(path)
1120 if entries == ['.mh_sequences']:
1121 os.remove(os.path.join(path, '.mh_sequences'))
1122 elif entries == []:
1123 pass
1124 else:
1125 raise NotEmptyError('Folder not empty: %s' % self._path)
1126 os.rmdir(path)
1127
1128 def get_sequences(self):
1129 """Return a name-to-key-list dictionary to define each sequence."""
1130 results = {}
Andrew M. Kuchling214db632006-05-02 21:44:33 +00001131 f = open(os.path.join(self._path, '.mh_sequences'), 'r')
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +00001132 try:
1133 all_keys = set(self.keys())
1134 for line in f:
1135 try:
1136 name, contents = line.split(':')
1137 keys = set()
1138 for spec in contents.split():
1139 if spec.isdigit():
1140 keys.add(int(spec))
1141 else:
1142 start, stop = (int(x) for x in spec.split('-'))
1143 keys.update(range(start, stop + 1))
1144 results[name] = [key for key in sorted(keys) \
1145 if key in all_keys]
1146 if len(results[name]) == 0:
1147 del results[name]
1148 except ValueError:
1149 raise FormatError('Invalid sequence specification: %s' %
1150 line.rstrip())
1151 finally:
1152 f.close()
1153 return results
1154
1155 def set_sequences(self, sequences):
1156 """Set sequences using the given name-to-key-list dictionary."""
Andrew M. Kuchling214db632006-05-02 21:44:33 +00001157 f = open(os.path.join(self._path, '.mh_sequences'), 'r+')
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +00001158 try:
1159 os.close(os.open(f.name, os.O_WRONLY | os.O_TRUNC))
1160 for name, keys in sequences.iteritems():
1161 if len(keys) == 0:
1162 continue
1163 f.write('%s:' % name)
1164 prev = None
1165 completing = False
1166 for key in sorted(set(keys)):
1167 if key - 1 == prev:
1168 if not completing:
1169 completing = True
1170 f.write('-')
1171 elif completing:
1172 completing = False
1173 f.write('%s %s' % (prev, key))
1174 else:
1175 f.write(' %s' % key)
1176 prev = key
1177 if completing:
1178 f.write(str(prev) + '\n')
1179 else:
1180 f.write('\n')
1181 finally:
Andrew M. Kuchlingb5686da2006-11-09 13:51:14 +00001182 _sync_close(f)
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +00001183
1184 def pack(self):
1185 """Re-name messages to eliminate numbering gaps. Invalidates keys."""
1186 sequences = self.get_sequences()
1187 prev = 0
1188 changes = []
1189 for key in self.iterkeys():
1190 if key - 1 != prev:
1191 changes.append((key, prev + 1))
Andrew M. Kuchling8c456f32006-11-17 13:30:25 +00001192 if hasattr(os, 'link'):
1193 os.link(os.path.join(self._path, str(key)),
1194 os.path.join(self._path, str(prev + 1)))
1195 os.unlink(os.path.join(self._path, str(key)))
1196 else:
1197 os.rename(os.path.join(self._path, str(key)),
1198 os.path.join(self._path, str(prev + 1)))
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +00001199 prev += 1
1200 self._next_key = prev + 1
1201 if len(changes) == 0:
1202 return
1203 for name, key_list in sequences.items():
1204 for old, new in changes:
1205 if old in key_list:
1206 key_list[key_list.index(old)] = new
1207 self.set_sequences(sequences)
1208
1209 def _dump_sequences(self, message, key):
1210 """Inspect a new MHMessage and update sequences appropriately."""
1211 pending_sequences = message.get_sequences()
1212 all_sequences = self.get_sequences()
1213 for name, key_list in all_sequences.iteritems():
1214 if name in pending_sequences:
1215 key_list.append(key)
1216 elif key in key_list:
1217 del key_list[key_list.index(key)]
1218 for sequence in pending_sequences:
1219 if sequence not in all_sequences:
1220 all_sequences[sequence] = [key]
1221 self.set_sequences(all_sequences)
1222
1223
1224class Babyl(_singlefileMailbox):
1225 """An Rmail-style Babyl mailbox."""
1226
1227 _special_labels = frozenset(('unseen', 'deleted', 'filed', 'answered',
1228 'forwarded', 'edited', 'resent'))
1229
1230 def __init__(self, path, factory=None, create=True):
1231 """Initialize a Babyl mailbox."""
1232 _singlefileMailbox.__init__(self, path, factory, create)
1233 self._labels = {}
1234
1235 def add(self, message):
1236 """Add message and return assigned key."""
1237 key = _singlefileMailbox.add(self, message)
1238 if isinstance(message, BabylMessage):
1239 self._labels[key] = message.get_labels()
1240 return key
1241
1242 def remove(self, key):
1243 """Remove the keyed message; raise KeyError if it doesn't exist."""
1244 _singlefileMailbox.remove(self, key)
1245 if key in self._labels:
1246 del self._labels[key]
1247
1248 def __setitem__(self, key, message):
1249 """Replace the keyed message; raise KeyError if it doesn't exist."""
1250 _singlefileMailbox.__setitem__(self, key, message)
1251 if isinstance(message, BabylMessage):
1252 self._labels[key] = message.get_labels()
1253
1254 def get_message(self, key):
1255 """Return a Message representation or raise a KeyError."""
1256 start, stop = self._lookup(key)
1257 self._file.seek(start)
1258 self._file.readline() # Skip '1,' line specifying labels.
1259 original_headers = StringIO.StringIO()
1260 while True:
1261 line = self._file.readline()
1262 if line == '*** EOOH ***' + os.linesep or line == '':
1263 break
1264 original_headers.write(line.replace(os.linesep, '\n'))
1265 visible_headers = StringIO.StringIO()
1266 while True:
1267 line = self._file.readline()
1268 if line == os.linesep or line == '':
1269 break
1270 visible_headers.write(line.replace(os.linesep, '\n'))
1271 body = self._file.read(stop - self._file.tell()).replace(os.linesep,
1272 '\n')
1273 msg = BabylMessage(original_headers.getvalue() + body)
1274 msg.set_visible(visible_headers.getvalue())
1275 if key in self._labels:
1276 msg.set_labels(self._labels[key])
1277 return msg
1278
1279 def get_string(self, key):
1280 """Return a string representation or raise a KeyError."""
1281 start, stop = self._lookup(key)
1282 self._file.seek(start)
1283 self._file.readline() # Skip '1,' line specifying labels.
1284 original_headers = StringIO.StringIO()
1285 while True:
1286 line = self._file.readline()
1287 if line == '*** EOOH ***' + os.linesep or line == '':
1288 break
1289 original_headers.write(line.replace(os.linesep, '\n'))
1290 while True:
1291 line = self._file.readline()
1292 if line == os.linesep or line == '':
1293 break
1294 return original_headers.getvalue() + \
1295 self._file.read(stop - self._file.tell()).replace(os.linesep,
1296 '\n')
1297
1298 def get_file(self, key):
1299 """Return a file-like representation or raise a KeyError."""
1300 return StringIO.StringIO(self.get_string(key).replace('\n',
1301 os.linesep))
1302
1303 def get_labels(self):
1304 """Return a list of user-defined labels in the mailbox."""
1305 self._lookup()
1306 labels = set()
1307 for label_list in self._labels.values():
1308 labels.update(label_list)
1309 labels.difference_update(self._special_labels)
1310 return list(labels)
1311
1312 def _generate_toc(self):
1313 """Generate key-to-(start, stop) table of contents."""
1314 starts, stops = [], []
1315 self._file.seek(0)
1316 next_pos = 0
1317 label_lists = []
1318 while True:
1319 line_pos = next_pos
1320 line = self._file.readline()
1321 next_pos = self._file.tell()
1322 if line == '\037\014' + os.linesep:
1323 if len(stops) < len(starts):
1324 stops.append(line_pos - len(os.linesep))
1325 starts.append(next_pos)
1326 labels = [label.strip() for label
1327 in self._file.readline()[1:].split(',')
1328 if label.strip() != '']
1329 label_lists.append(labels)
1330 elif line == '\037' or line == '\037' + os.linesep:
1331 if len(stops) < len(starts):
1332 stops.append(line_pos - len(os.linesep))
1333 elif line == '':
1334 stops.append(line_pos - len(os.linesep))
1335 break
1336 self._toc = dict(enumerate(zip(starts, stops)))
1337 self._labels = dict(enumerate(label_lists))
1338 self._next_key = len(self._toc)
Andrew M. Kuchlingeca4c312006-12-20 19:48:20 +00001339 self._file.seek(0, 2)
1340 self._file_length = self._file.tell()
Tim Petersf733abb2007-01-30 03:03:46 +00001341
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +00001342 def _pre_mailbox_hook(self, f):
1343 """Called before writing the mailbox to file f."""
1344 f.write('BABYL OPTIONS:%sVersion: 5%sLabels:%s%s\037' %
1345 (os.linesep, os.linesep, ','.join(self.get_labels()),
1346 os.linesep))
1347
1348 def _pre_message_hook(self, f):
1349 """Called before writing each message to file f."""
1350 f.write('\014' + os.linesep)
1351
1352 def _post_message_hook(self, f):
1353 """Called after writing each message to file f."""
1354 f.write(os.linesep + '\037')
1355
1356 def _install_message(self, message):
1357 """Write message contents and return (start, stop)."""
1358 start = self._file.tell()
1359 if isinstance(message, BabylMessage):
1360 special_labels = []
1361 labels = []
1362 for label in message.get_labels():
1363 if label in self._special_labels:
1364 special_labels.append(label)
1365 else:
1366 labels.append(label)
1367 self._file.write('1')
1368 for label in special_labels:
1369 self._file.write(', ' + label)
1370 self._file.write(',,')
1371 for label in labels:
1372 self._file.write(' ' + label + ',')
1373 self._file.write(os.linesep)
1374 else:
1375 self._file.write('1,,' + os.linesep)
Georg Brandl5a096e12007-01-22 19:40:21 +00001376 if isinstance(message, email.message.Message):
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +00001377 orig_buffer = StringIO.StringIO()
Georg Brandl5a096e12007-01-22 19:40:21 +00001378 orig_generator = email.generator.Generator(orig_buffer, False, 0)
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +00001379 orig_generator.flatten(message)
1380 orig_buffer.seek(0)
1381 while True:
1382 line = orig_buffer.readline()
1383 self._file.write(line.replace('\n', os.linesep))
1384 if line == '\n' or line == '':
1385 break
1386 self._file.write('*** EOOH ***' + os.linesep)
1387 if isinstance(message, BabylMessage):
1388 vis_buffer = StringIO.StringIO()
Georg Brandl5a096e12007-01-22 19:40:21 +00001389 vis_generator = email.generator.Generator(vis_buffer, False, 0)
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +00001390 vis_generator.flatten(message.get_visible())
1391 while True:
1392 line = vis_buffer.readline()
1393 self._file.write(line.replace('\n', os.linesep))
1394 if line == '\n' or line == '':
1395 break
1396 else:
1397 orig_buffer.seek(0)
1398 while True:
1399 line = orig_buffer.readline()
1400 self._file.write(line.replace('\n', os.linesep))
1401 if line == '\n' or line == '':
1402 break
1403 while True:
1404 buffer = orig_buffer.read(4096) # Buffer size is arbitrary.
1405 if buffer == '':
1406 break
1407 self._file.write(buffer.replace('\n', os.linesep))
1408 elif isinstance(message, str):
1409 body_start = message.find('\n\n') + 2
1410 if body_start - 2 != -1:
1411 self._file.write(message[:body_start].replace('\n',
1412 os.linesep))
1413 self._file.write('*** EOOH ***' + os.linesep)
1414 self._file.write(message[:body_start].replace('\n',
1415 os.linesep))
1416 self._file.write(message[body_start:].replace('\n',
1417 os.linesep))
1418 else:
1419 self._file.write('*** EOOH ***' + os.linesep + os.linesep)
1420 self._file.write(message.replace('\n', os.linesep))
1421 elif hasattr(message, 'readline'):
1422 original_pos = message.tell()
1423 first_pass = True
1424 while True:
1425 line = message.readline()
1426 self._file.write(line.replace('\n', os.linesep))
1427 if line == '\n' or line == '':
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +00001428 if first_pass:
1429 first_pass = False
Petri Lehtinen2d44cee2012-08-15 14:22:46 +03001430 self._file.write('*** EOOH ***' + os.linesep)
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +00001431 message.seek(original_pos)
1432 else:
1433 break
1434 while True:
1435 buffer = message.read(4096) # Buffer size is arbitrary.
1436 if buffer == '':
1437 break
1438 self._file.write(buffer.replace('\n', os.linesep))
1439 else:
1440 raise TypeError('Invalid message type: %s' % type(message))
1441 stop = self._file.tell()
1442 return (start, stop)
1443
1444
Georg Brandl5a096e12007-01-22 19:40:21 +00001445class Message(email.message.Message):
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +00001446 """Message with mailbox-format-specific properties."""
1447
1448 def __init__(self, message=None):
1449 """Initialize a Message instance."""
Georg Brandl5a096e12007-01-22 19:40:21 +00001450 if isinstance(message, email.message.Message):
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +00001451 self._become_message(copy.deepcopy(message))
1452 if isinstance(message, Message):
1453 message._explain_to(self)
1454 elif isinstance(message, str):
1455 self._become_message(email.message_from_string(message))
1456 elif hasattr(message, "read"):
1457 self._become_message(email.message_from_file(message))
1458 elif message is None:
Georg Brandl5a096e12007-01-22 19:40:21 +00001459 email.message.Message.__init__(self)
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +00001460 else:
1461 raise TypeError('Invalid message type: %s' % type(message))
1462
1463 def _become_message(self, message):
1464 """Assume the non-format-specific state of message."""
1465 for name in ('_headers', '_unixfrom', '_payload', '_charset',
1466 'preamble', 'epilogue', 'defects', '_default_type'):
1467 self.__dict__[name] = message.__dict__[name]
1468
1469 def _explain_to(self, message):
1470 """Copy format-specific state to message insofar as possible."""
1471 if isinstance(message, Message):
1472 return # There's nothing format-specific to explain.
1473 else:
1474 raise TypeError('Cannot convert to specified type')
1475
1476
1477class MaildirMessage(Message):
1478 """Message with Maildir-specific properties."""
1479
1480 def __init__(self, message=None):
1481 """Initialize a MaildirMessage instance."""
1482 self._subdir = 'new'
1483 self._info = ''
1484 self._date = time.time()
1485 Message.__init__(self, message)
1486
1487 def get_subdir(self):
1488 """Return 'new' or 'cur'."""
1489 return self._subdir
1490
1491 def set_subdir(self, subdir):
1492 """Set subdir to 'new' or 'cur'."""
1493 if subdir == 'new' or subdir == 'cur':
1494 self._subdir = subdir
1495 else:
1496 raise ValueError("subdir must be 'new' or 'cur': %s" % subdir)
1497
1498 def get_flags(self):
1499 """Return as a string the flags that are set."""
1500 if self._info.startswith('2,'):
1501 return self._info[2:]
1502 else:
1503 return ''
1504
1505 def set_flags(self, flags):
1506 """Set the given flags and unset all others."""
1507 self._info = '2,' + ''.join(sorted(flags))
1508
1509 def add_flag(self, flag):
1510 """Set the given flag(s) without changing others."""
1511 self.set_flags(''.join(set(self.get_flags()) | set(flag)))
1512
1513 def remove_flag(self, flag):
1514 """Unset the given string flag(s) without changing others."""
1515 if self.get_flags() != '':
1516 self.set_flags(''.join(set(self.get_flags()) - set(flag)))
1517
1518 def get_date(self):
1519 """Return delivery date of message, in seconds since the epoch."""
1520 return self._date
1521
1522 def set_date(self, date):
1523 """Set delivery date of message, in seconds since the epoch."""
1524 try:
1525 self._date = float(date)
1526 except ValueError:
1527 raise TypeError("can't convert to float: %s" % date)
1528
1529 def get_info(self):
1530 """Get the message's "info" as a string."""
1531 return self._info
1532
1533 def set_info(self, info):
1534 """Set the message's "info" string."""
1535 if isinstance(info, str):
1536 self._info = info
1537 else:
1538 raise TypeError('info must be a string: %s' % type(info))
1539
1540 def _explain_to(self, message):
1541 """Copy Maildir-specific state to message insofar as possible."""
1542 if isinstance(message, MaildirMessage):
1543 message.set_flags(self.get_flags())
1544 message.set_subdir(self.get_subdir())
1545 message.set_date(self.get_date())
1546 elif isinstance(message, _mboxMMDFMessage):
1547 flags = set(self.get_flags())
1548 if 'S' in flags:
1549 message.add_flag('R')
1550 if self.get_subdir() == 'cur':
1551 message.add_flag('O')
1552 if 'T' in flags:
1553 message.add_flag('D')
1554 if 'F' in flags:
1555 message.add_flag('F')
1556 if 'R' in flags:
1557 message.add_flag('A')
1558 message.set_from('MAILER-DAEMON', time.gmtime(self.get_date()))
1559 elif isinstance(message, MHMessage):
1560 flags = set(self.get_flags())
1561 if 'S' not in flags:
1562 message.add_sequence('unseen')
1563 if 'R' in flags:
1564 message.add_sequence('replied')
1565 if 'F' in flags:
1566 message.add_sequence('flagged')
1567 elif isinstance(message, BabylMessage):
1568 flags = set(self.get_flags())
1569 if 'S' not in flags:
1570 message.add_label('unseen')
1571 if 'T' in flags:
1572 message.add_label('deleted')
1573 if 'R' in flags:
1574 message.add_label('answered')
1575 if 'P' in flags:
1576 message.add_label('forwarded')
1577 elif isinstance(message, Message):
1578 pass
1579 else:
1580 raise TypeError('Cannot convert to specified type: %s' %
1581 type(message))
1582
1583
1584class _mboxMMDFMessage(Message):
1585 """Message with mbox- or MMDF-specific properties."""
1586
1587 def __init__(self, message=None):
1588 """Initialize an mboxMMDFMessage instance."""
1589 self.set_from('MAILER-DAEMON', True)
Georg Brandl5a096e12007-01-22 19:40:21 +00001590 if isinstance(message, email.message.Message):
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +00001591 unixfrom = message.get_unixfrom()
1592 if unixfrom is not None and unixfrom.startswith('From '):
1593 self.set_from(unixfrom[5:])
1594 Message.__init__(self, message)
1595
1596 def get_from(self):
1597 """Return contents of "From " line."""
1598 return self._from
1599
1600 def set_from(self, from_, time_=None):
1601 """Set "From " line, formatting and appending time_ if specified."""
1602 if time_ is not None:
1603 if time_ is True:
1604 time_ = time.gmtime()
1605 from_ += ' ' + time.asctime(time_)
1606 self._from = from_
1607
1608 def get_flags(self):
1609 """Return as a string the flags that are set."""
1610 return self.get('Status', '') + self.get('X-Status', '')
1611
1612 def set_flags(self, flags):
1613 """Set the given flags and unset all others."""
1614 flags = set(flags)
1615 status_flags, xstatus_flags = '', ''
1616 for flag in ('R', 'O'):
1617 if flag in flags:
1618 status_flags += flag
1619 flags.remove(flag)
1620 for flag in ('D', 'F', 'A'):
1621 if flag in flags:
1622 xstatus_flags += flag
1623 flags.remove(flag)
1624 xstatus_flags += ''.join(sorted(flags))
1625 try:
1626 self.replace_header('Status', status_flags)
1627 except KeyError:
1628 self.add_header('Status', status_flags)
1629 try:
1630 self.replace_header('X-Status', xstatus_flags)
1631 except KeyError:
1632 self.add_header('X-Status', xstatus_flags)
1633
1634 def add_flag(self, flag):
1635 """Set the given flag(s) without changing others."""
1636 self.set_flags(''.join(set(self.get_flags()) | set(flag)))
1637
1638 def remove_flag(self, flag):
1639 """Unset the given string flag(s) without changing others."""
1640 if 'Status' in self or 'X-Status' in self:
1641 self.set_flags(''.join(set(self.get_flags()) - set(flag)))
1642
1643 def _explain_to(self, message):
1644 """Copy mbox- or MMDF-specific state to message insofar as possible."""
1645 if isinstance(message, MaildirMessage):
1646 flags = set(self.get_flags())
1647 if 'O' in flags:
1648 message.set_subdir('cur')
1649 if 'F' in flags:
1650 message.add_flag('F')
1651 if 'A' in flags:
1652 message.add_flag('R')
1653 if 'R' in flags:
1654 message.add_flag('S')
1655 if 'D' in flags:
1656 message.add_flag('T')
1657 del message['status']
1658 del message['x-status']
1659 maybe_date = ' '.join(self.get_from().split()[-5:])
1660 try:
1661 message.set_date(calendar.timegm(time.strptime(maybe_date,
1662 '%a %b %d %H:%M:%S %Y')))
1663 except (ValueError, OverflowError):
1664 pass
1665 elif isinstance(message, _mboxMMDFMessage):
1666 message.set_flags(self.get_flags())
1667 message.set_from(self.get_from())
1668 elif isinstance(message, MHMessage):
1669 flags = set(self.get_flags())
1670 if 'R' not in flags:
1671 message.add_sequence('unseen')
1672 if 'A' in flags:
1673 message.add_sequence('replied')
1674 if 'F' in flags:
1675 message.add_sequence('flagged')
1676 del message['status']
1677 del message['x-status']
1678 elif isinstance(message, BabylMessage):
1679 flags = set(self.get_flags())
1680 if 'R' not in flags:
1681 message.add_label('unseen')
1682 if 'D' in flags:
1683 message.add_label('deleted')
1684 if 'A' in flags:
1685 message.add_label('answered')
1686 del message['status']
1687 del message['x-status']
1688 elif isinstance(message, Message):
1689 pass
1690 else:
1691 raise TypeError('Cannot convert to specified type: %s' %
1692 type(message))
1693
1694
1695class mboxMessage(_mboxMMDFMessage):
1696 """Message with mbox-specific properties."""
1697
1698
1699class MHMessage(Message):
1700 """Message with MH-specific properties."""
1701
1702 def __init__(self, message=None):
1703 """Initialize an MHMessage instance."""
1704 self._sequences = []
1705 Message.__init__(self, message)
1706
1707 def get_sequences(self):
1708 """Return a list of sequences that include the message."""
1709 return self._sequences[:]
1710
1711 def set_sequences(self, sequences):
1712 """Set the list of sequences that include the message."""
1713 self._sequences = list(sequences)
1714
1715 def add_sequence(self, sequence):
1716 """Add sequence to list of sequences including the message."""
1717 if isinstance(sequence, str):
1718 if not sequence in self._sequences:
1719 self._sequences.append(sequence)
1720 else:
1721 raise TypeError('sequence must be a string: %s' % type(sequence))
1722
1723 def remove_sequence(self, sequence):
1724 """Remove sequence from the list of sequences including the message."""
1725 try:
1726 self._sequences.remove(sequence)
1727 except ValueError:
1728 pass
1729
1730 def _explain_to(self, message):
1731 """Copy MH-specific state to message insofar as possible."""
1732 if isinstance(message, MaildirMessage):
1733 sequences = set(self.get_sequences())
1734 if 'unseen' in sequences:
1735 message.set_subdir('cur')
1736 else:
1737 message.set_subdir('cur')
1738 message.add_flag('S')
1739 if 'flagged' in sequences:
1740 message.add_flag('F')
1741 if 'replied' in sequences:
1742 message.add_flag('R')
1743 elif isinstance(message, _mboxMMDFMessage):
1744 sequences = set(self.get_sequences())
1745 if 'unseen' not in sequences:
1746 message.add_flag('RO')
1747 else:
1748 message.add_flag('O')
1749 if 'flagged' in sequences:
1750 message.add_flag('F')
1751 if 'replied' in sequences:
1752 message.add_flag('A')
1753 elif isinstance(message, MHMessage):
1754 for sequence in self.get_sequences():
1755 message.add_sequence(sequence)
1756 elif isinstance(message, BabylMessage):
1757 sequences = set(self.get_sequences())
1758 if 'unseen' in sequences:
1759 message.add_label('unseen')
1760 if 'replied' in sequences:
1761 message.add_label('answered')
1762 elif isinstance(message, Message):
1763 pass
1764 else:
1765 raise TypeError('Cannot convert to specified type: %s' %
1766 type(message))
1767
1768
1769class BabylMessage(Message):
1770 """Message with Babyl-specific properties."""
1771
1772 def __init__(self, message=None):
1773 """Initialize an BabylMessage instance."""
1774 self._labels = []
1775 self._visible = Message()
1776 Message.__init__(self, message)
1777
1778 def get_labels(self):
1779 """Return a list of labels on the message."""
1780 return self._labels[:]
1781
1782 def set_labels(self, labels):
1783 """Set the list of labels on the message."""
1784 self._labels = list(labels)
1785
1786 def add_label(self, label):
1787 """Add label to list of labels on the message."""
1788 if isinstance(label, str):
1789 if label not in self._labels:
1790 self._labels.append(label)
1791 else:
1792 raise TypeError('label must be a string: %s' % type(label))
1793
1794 def remove_label(self, label):
1795 """Remove label from the list of labels on the message."""
1796 try:
1797 self._labels.remove(label)
1798 except ValueError:
1799 pass
Tim Peters6d7cd7d2006-04-22 05:52:59 +00001800
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +00001801 def get_visible(self):
1802 """Return a Message representation of visible headers."""
1803 return Message(self._visible)
1804
1805 def set_visible(self, visible):
1806 """Set the Message representation of visible headers."""
1807 self._visible = Message(visible)
1808
1809 def update_visible(self):
1810 """Update and/or sensibly generate a set of visible headers."""
1811 for header in self._visible.keys():
1812 if header in self:
1813 self._visible.replace_header(header, self[header])
1814 else:
1815 del self._visible[header]
1816 for header in ('Date', 'From', 'Reply-To', 'To', 'CC', 'Subject'):
1817 if header in self and header not in self._visible:
1818 self._visible[header] = self[header]
1819
1820 def _explain_to(self, message):
1821 """Copy Babyl-specific state to message insofar as possible."""
1822 if isinstance(message, MaildirMessage):
1823 labels = set(self.get_labels())
1824 if 'unseen' in labels:
1825 message.set_subdir('cur')
1826 else:
1827 message.set_subdir('cur')
1828 message.add_flag('S')
1829 if 'forwarded' in labels or 'resent' in labels:
1830 message.add_flag('P')
1831 if 'answered' in labels:
1832 message.add_flag('R')
1833 if 'deleted' in labels:
1834 message.add_flag('T')
1835 elif isinstance(message, _mboxMMDFMessage):
1836 labels = set(self.get_labels())
1837 if 'unseen' not in labels:
1838 message.add_flag('RO')
1839 else:
1840 message.add_flag('O')
1841 if 'deleted' in labels:
1842 message.add_flag('D')
1843 if 'answered' in labels:
1844 message.add_flag('A')
1845 elif isinstance(message, MHMessage):
1846 labels = set(self.get_labels())
1847 if 'unseen' in labels:
1848 message.add_sequence('unseen')
1849 if 'answered' in labels:
1850 message.add_sequence('replied')
1851 elif isinstance(message, BabylMessage):
1852 message.set_visible(self.get_visible())
1853 for label in self.get_labels():
1854 message.add_label(label)
1855 elif isinstance(message, Message):
1856 pass
1857 else:
1858 raise TypeError('Cannot convert to specified type: %s' %
1859 type(message))
1860
1861
1862class MMDFMessage(_mboxMMDFMessage):
1863 """Message with MMDF-specific properties."""
1864
1865
1866class _ProxyFile:
1867 """A read-only wrapper of a file."""
1868
1869 def __init__(self, f, pos=None):
1870 """Initialize a _ProxyFile."""
1871 self._file = f
1872 if pos is None:
1873 self._pos = f.tell()
1874 else:
1875 self._pos = pos
1876
1877 def read(self, size=None):
1878 """Read bytes."""
1879 return self._read(size, self._file.read)
1880
1881 def readline(self, size=None):
1882 """Read a line."""
1883 return self._read(size, self._file.readline)
1884
1885 def readlines(self, sizehint=None):
1886 """Read multiple lines."""
1887 result = []
1888 for line in self:
1889 result.append(line)
1890 if sizehint is not None:
1891 sizehint -= len(line)
1892 if sizehint <= 0:
1893 break
1894 return result
1895
1896 def __iter__(self):
1897 """Iterate over lines."""
1898 return iter(self.readline, "")
1899
1900 def tell(self):
1901 """Return the position."""
1902 return self._pos
1903
1904 def seek(self, offset, whence=0):
1905 """Change position."""
1906 if whence == 1:
1907 self._file.seek(self._pos)
1908 self._file.seek(offset, whence)
1909 self._pos = self._file.tell()
1910
1911 def close(self):
1912 """Close the file."""
R David Murrayf1138bb2011-06-17 22:23:04 -04001913 if hasattr(self, '_file'):
1914 if hasattr(self._file, 'close'):
1915 self._file.close()
1916 del self._file
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +00001917
1918 def _read(self, size, read_method):
1919 """Read size bytes using read_method."""
1920 if size is None:
1921 size = -1
1922 self._file.seek(self._pos)
1923 result = read_method(size)
1924 self._pos = self._file.tell()
1925 return result
1926
1927
1928class _PartialFile(_ProxyFile):
1929 """A read-only wrapper of part of a file."""
1930
1931 def __init__(self, f, start=None, stop=None):
1932 """Initialize a _PartialFile."""
1933 _ProxyFile.__init__(self, f, start)
1934 self._start = start
1935 self._stop = stop
1936
1937 def tell(self):
1938 """Return the position with respect to start."""
1939 return _ProxyFile.tell(self) - self._start
1940
1941 def seek(self, offset, whence=0):
1942 """Change position, possibly with respect to start or stop."""
1943 if whence == 0:
1944 self._pos = self._start
1945 whence = 1
1946 elif whence == 2:
1947 self._pos = self._stop
1948 whence = 1
1949 _ProxyFile.seek(self, offset, whence)
1950
1951 def _read(self, size, read_method):
1952 """Read size bytes using read_method, honoring start and stop."""
1953 remaining = self._stop - self._pos
1954 if remaining <= 0:
1955 return ''
1956 if size is None or size < 0 or size > remaining:
1957 size = remaining
1958 return _ProxyFile._read(self, size, read_method)
1959
R David Murrayf1138bb2011-06-17 22:23:04 -04001960 def close(self):
1961 # do *not* close the underlying file object for partial files,
1962 # since it's global to the mailbox object
1963 if hasattr(self, '_file'):
1964 del self._file
1965
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +00001966
1967def _lock_file(f, dotlock=True):
Andrew M. Kuchling55732592006-06-26 13:12:16 +00001968 """Lock file f using lockf and dot locking."""
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +00001969 dotlock_done = False
1970 try:
1971 if fcntl:
1972 try:
1973 fcntl.lockf(f, fcntl.LOCK_EX | fcntl.LOCK_NB)
1974 except IOError, e:
R. David Murray1a337902011-03-03 18:17:40 +00001975 if e.errno in (errno.EAGAIN, errno.EACCES, errno.EROFS):
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +00001976 raise ExternalClashError('lockf: lock unavailable: %s' %
1977 f.name)
1978 else:
1979 raise
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +00001980 if dotlock:
1981 try:
1982 pre_lock = _create_temporary(f.name + '.lock')
1983 pre_lock.close()
1984 except IOError, e:
R. David Murray1a337902011-03-03 18:17:40 +00001985 if e.errno in (errno.EACCES, errno.EROFS):
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +00001986 return # Without write access, just skip dotlocking.
1987 else:
1988 raise
1989 try:
1990 if hasattr(os, 'link'):
1991 os.link(pre_lock.name, f.name + '.lock')
1992 dotlock_done = True
1993 os.unlink(pre_lock.name)
1994 else:
1995 os.rename(pre_lock.name, f.name + '.lock')
1996 dotlock_done = True
1997 except OSError, e:
Andrew MacIntyreafa358f2006-07-23 13:04:00 +00001998 if e.errno == errno.EEXIST or \
1999 (os.name == 'os2' and e.errno == errno.EACCES):
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +00002000 os.remove(pre_lock.name)
Tim Peters6d7cd7d2006-04-22 05:52:59 +00002001 raise ExternalClashError('dot lock unavailable: %s' %
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +00002002 f.name)
2003 else:
2004 raise
2005 except:
2006 if fcntl:
2007 fcntl.lockf(f, fcntl.LOCK_UN)
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +00002008 if dotlock_done:
2009 os.remove(f.name + '.lock')
2010 raise
2011
2012def _unlock_file(f):
Andrew M. Kuchling55732592006-06-26 13:12:16 +00002013 """Unlock file f using lockf and dot locking."""
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +00002014 if fcntl:
2015 fcntl.lockf(f, fcntl.LOCK_UN)
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +00002016 if os.path.exists(f.name + '.lock'):
2017 os.remove(f.name + '.lock')
2018
2019def _create_carefully(path):
2020 """Create a file if it doesn't exist and open for reading and writing."""
Andrew M. Kuchling70a6dbd2008-08-04 01:43:43 +00002021 fd = os.open(path, os.O_CREAT | os.O_EXCL | os.O_RDWR, 0666)
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +00002022 try:
Andrew M. Kuchling214db632006-05-02 21:44:33 +00002023 return open(path, 'rb+')
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +00002024 finally:
2025 os.close(fd)
2026
2027def _create_temporary(path):
2028 """Create a temp file based on path and open for reading and writing."""
2029 return _create_carefully('%s.%s.%s.%s' % (path, int(time.time()),
2030 socket.gethostname(),
2031 os.getpid()))
2032
Andrew M. Kuchlingb5686da2006-11-09 13:51:14 +00002033def _sync_flush(f):
2034 """Ensure changes to file f are physically on disk."""
2035 f.flush()
Andrew M. Kuchling16465682006-12-14 18:57:53 +00002036 if hasattr(os, 'fsync'):
2037 os.fsync(f.fileno())
Andrew M. Kuchlingb5686da2006-11-09 13:51:14 +00002038
2039def _sync_close(f):
2040 """Close file f, ensuring all changes are physically on disk."""
2041 _sync_flush(f)
2042 f.close()
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +00002043
2044## Start: classes from the original module (for backward compatibility).
2045
2046# Note that the Maildir class, whose name is unchanged, itself offers a next()
2047# method for backward compatibility.
Skip Montanaro17ab1232001-01-24 06:27:27 +00002048
Guido van Rossumc7b68821994-04-28 09:53:33 +00002049class _Mailbox:
Guido van Rossum4bf12542002-09-12 05:08:00 +00002050
Barry Warsaw81ad67c2001-01-31 22:13:15 +00002051 def __init__(self, fp, factory=rfc822.Message):
Fred Drakedbbf76b2000-07-09 16:44:26 +00002052 self.fp = fp
2053 self.seekp = 0
Barry Warsaw81ad67c2001-01-31 22:13:15 +00002054 self.factory = factory
Guido van Rossum8ca84201998-03-26 20:56:10 +00002055
Fred Drake72987a42001-05-02 20:20:53 +00002056 def __iter__(self):
Guido van Rossum93a696f2001-09-13 01:29:13 +00002057 return iter(self.next, None)
Fred Drake72987a42001-05-02 20:20:53 +00002058
Fred Drakedbbf76b2000-07-09 16:44:26 +00002059 def next(self):
2060 while 1:
2061 self.fp.seek(self.seekp)
2062 try:
2063 self._search_start()
2064 except EOFError:
2065 self.seekp = self.fp.tell()
2066 return None
2067 start = self.fp.tell()
2068 self._search_end()
2069 self.seekp = stop = self.fp.tell()
Fred Drake8152d322000-12-12 23:20:45 +00002070 if start != stop:
Fred Drakedbbf76b2000-07-09 16:44:26 +00002071 break
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +00002072 return self.factory(_PartialFile(self.fp, start, stop))
Guido van Rossumc7b68821994-04-28 09:53:33 +00002073
Barry Warsawffd05ee2002-03-01 22:39:14 +00002074# Recommended to use PortableUnixMailbox instead!
Guido van Rossumc7b68821994-04-28 09:53:33 +00002075class UnixMailbox(_Mailbox):
Guido van Rossum4bf12542002-09-12 05:08:00 +00002076
Fred Drakedbbf76b2000-07-09 16:44:26 +00002077 def _search_start(self):
2078 while 1:
2079 pos = self.fp.tell()
2080 line = self.fp.readline()
2081 if not line:
2082 raise EOFError
2083 if line[:5] == 'From ' and self._isrealfromline(line):
2084 self.fp.seek(pos)
2085 return
Guido van Rossum8ca84201998-03-26 20:56:10 +00002086
Fred Drakedbbf76b2000-07-09 16:44:26 +00002087 def _search_end(self):
2088 self.fp.readline() # Throw away header line
2089 while 1:
2090 pos = self.fp.tell()
2091 line = self.fp.readline()
2092 if not line:
2093 return
2094 if line[:5] == 'From ' and self._isrealfromline(line):
2095 self.fp.seek(pos)
2096 return
Guido van Rossumc7b68821994-04-28 09:53:33 +00002097
Barry Warsaw81ad67c2001-01-31 22:13:15 +00002098 # An overridable mechanism to test for From-line-ness. You can either
2099 # specify a different regular expression or define a whole new
2100 # _isrealfromline() method. Note that this only gets called for lines
2101 # starting with the 5 characters "From ".
2102 #
2103 # BAW: According to
2104 #http://home.netscape.com/eng/mozilla/2.0/relnotes/demo/content-length.html
2105 # the only portable, reliable way to find message delimiters in a BSD (i.e
2106 # Unix mailbox) style folder is to search for "\n\nFrom .*\n", or at the
2107 # beginning of the file, "^From .*\n". While _fromlinepattern below seems
2108 # like a good idea, in practice, there are too many variations for more
2109 # strict parsing of the line to be completely accurate.
2110 #
2111 # _strict_isrealfromline() is the old version which tries to do stricter
2112 # parsing of the From_ line. _portable_isrealfromline() simply returns
2113 # true, since it's never called if the line doesn't already start with
2114 # "From ".
2115 #
2116 # This algorithm, and the way it interacts with _search_start() and
2117 # _search_end() may not be completely correct, because it doesn't check
2118 # that the two characters preceding "From " are \n\n or the beginning of
2119 # the file. Fixing this would require a more extensive rewrite than is
Barry Warsawda5628f2002-08-26 16:44:56 +00002120 # necessary. For convenience, we've added a PortableUnixMailbox class
Andrew M. Kuchlingb94c0c32007-01-22 20:27:50 +00002121 # which does no checking of the format of the 'From' line.
Guido van Rossumc7b68821994-04-28 09:53:33 +00002122
Andrew M. Kuchlingb78bb742007-01-22 20:26:40 +00002123 _fromlinepattern = (r"From \s*[^\s]+\s+\w\w\w\s+\w\w\w\s+\d?\d\s+"
2124 r"\d?\d:\d\d(:\d\d)?(\s+[^\s]+)?\s+\d\d\d\d\s*"
2125 r"[^\s]*\s*"
2126 "$")
Fred Drakedbbf76b2000-07-09 16:44:26 +00002127 _regexp = None
Guido van Rossumfbe63de1998-04-03 16:04:05 +00002128
Barry Warsaw81ad67c2001-01-31 22:13:15 +00002129 def _strict_isrealfromline(self, line):
Fred Drakedbbf76b2000-07-09 16:44:26 +00002130 if not self._regexp:
2131 import re
2132 self._regexp = re.compile(self._fromlinepattern)
2133 return self._regexp.match(line)
Guido van Rossumfbe63de1998-04-03 16:04:05 +00002134
Barry Warsaw81ad67c2001-01-31 22:13:15 +00002135 def _portable_isrealfromline(self, line):
Tim Petersbc0e9102002-04-04 22:55:58 +00002136 return True
Barry Warsaw81ad67c2001-01-31 22:13:15 +00002137
2138 _isrealfromline = _strict_isrealfromline
2139
2140
2141class PortableUnixMailbox(UnixMailbox):
2142 _isrealfromline = UnixMailbox._portable_isrealfromline
2143
Guido van Rossumfbe63de1998-04-03 16:04:05 +00002144
Guido van Rossumc7b68821994-04-28 09:53:33 +00002145class MmdfMailbox(_Mailbox):
Guido van Rossum4bf12542002-09-12 05:08:00 +00002146
Fred Drakedbbf76b2000-07-09 16:44:26 +00002147 def _search_start(self):
2148 while 1:
2149 line = self.fp.readline()
2150 if not line:
2151 raise EOFError
2152 if line[:5] == '\001\001\001\001\n':
2153 return
Guido van Rossum8ca84201998-03-26 20:56:10 +00002154
Fred Drakedbbf76b2000-07-09 16:44:26 +00002155 def _search_end(self):
2156 while 1:
2157 pos = self.fp.tell()
2158 line = self.fp.readline()
2159 if not line:
2160 return
2161 if line == '\001\001\001\001\n':
2162 self.fp.seek(pos)
2163 return
Guido van Rossumc7b68821994-04-28 09:53:33 +00002164
Guido van Rossumc7b68821994-04-28 09:53:33 +00002165
Jack Jansen97157791995-10-23 13:59:53 +00002166class MHMailbox:
Guido van Rossum4bf12542002-09-12 05:08:00 +00002167
Barry Warsaw81ad67c2001-01-31 22:13:15 +00002168 def __init__(self, dirname, factory=rfc822.Message):
Fred Drakedbbf76b2000-07-09 16:44:26 +00002169 import re
Guido van Rossum0707fea2000-08-10 03:05:26 +00002170 pat = re.compile('^[1-9][0-9]*$')
Fred Drakedbbf76b2000-07-09 16:44:26 +00002171 self.dirname = dirname
Sjoerd Mullenderd2653a92000-08-11 07:48:36 +00002172 # the three following lines could be combined into:
2173 # list = map(long, filter(pat.match, os.listdir(self.dirname)))
2174 list = os.listdir(self.dirname)
2175 list = filter(pat.match, list)
Guido van Rossum0707fea2000-08-10 03:05:26 +00002176 list = map(long, list)
2177 list.sort()
2178 # This only works in Python 1.6 or later;
2179 # before that str() added 'L':
2180 self.boxes = map(str, list)
Raymond Hettingerb5ba8d72004-02-07 02:16:24 +00002181 self.boxes.reverse()
Barry Warsaw81ad67c2001-01-31 22:13:15 +00002182 self.factory = factory
Jack Jansen97157791995-10-23 13:59:53 +00002183
Fred Drake72987a42001-05-02 20:20:53 +00002184 def __iter__(self):
Guido van Rossum93a696f2001-09-13 01:29:13 +00002185 return iter(self.next, None)
Fred Drake72987a42001-05-02 20:20:53 +00002186
Fred Drakedbbf76b2000-07-09 16:44:26 +00002187 def next(self):
2188 if not self.boxes:
2189 return None
Raymond Hettingerb5ba8d72004-02-07 02:16:24 +00002190 fn = self.boxes.pop()
Fred Drakedbbf76b2000-07-09 16:44:26 +00002191 fp = open(os.path.join(self.dirname, fn))
Guido van Rossum4bf12542002-09-12 05:08:00 +00002192 msg = self.factory(fp)
2193 try:
2194 msg._mh_msgno = fn
2195 except (AttributeError, TypeError):
2196 pass
2197 return msg
Guido van Rossum8ca84201998-03-26 20:56:10 +00002198
Guido van Rossum9a4d6371998-12-23 22:05:42 +00002199
Guido van Rossumfdf58fe1997-05-15 14:33:09 +00002200class BabylMailbox(_Mailbox):
Guido van Rossum4bf12542002-09-12 05:08:00 +00002201
Fred Drakedbbf76b2000-07-09 16:44:26 +00002202 def _search_start(self):
2203 while 1:
2204 line = self.fp.readline()
2205 if not line:
2206 raise EOFError
2207 if line == '*** EOOH ***\n':
2208 return
Guido van Rossumfdf58fe1997-05-15 14:33:09 +00002209
Fred Drakedbbf76b2000-07-09 16:44:26 +00002210 def _search_end(self):
2211 while 1:
2212 pos = self.fp.tell()
2213 line = self.fp.readline()
2214 if not line:
2215 return
Johannes Gijsbers6abc6852004-08-21 12:30:26 +00002216 if line == '\037\014\n' or line == '\037':
Fred Drakedbbf76b2000-07-09 16:44:26 +00002217 self.fp.seek(pos)
2218 return
Guido van Rossumfdf58fe1997-05-15 14:33:09 +00002219
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +00002220## End: classes from the original module (for backward compatibility).
Guido van Rossum62448671996-09-17 21:33:15 +00002221
2222
Andrew M. Kuchling1da4a942006-04-22 02:32:43 +00002223class Error(Exception):
2224 """Raised for module-specific errors."""
2225
2226class NoSuchMailboxError(Error):
2227 """The specified mailbox does not exist and won't be created."""
2228
2229class NotEmptyError(Error):
2230 """The specified mailbox is not empty and deletion was requested."""
2231
2232class ExternalClashError(Error):
2233 """Another process caused an action to fail."""
2234
2235class FormatError(Error):
2236 """A file appears to have an invalid format."""