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