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