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