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