desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Start tracking a new sub-task.'
def push_marks(self, subtask):
self.time_tracking.append((subtask, []))
'Sub-task ended!'
def pop_marks(self, name=None, quiet=True):
elapsed = self.report_marks(quiet=quiet) if (len(self.time_tracking) > 1): if ((not name) or (self.time_tracking[(-1)][0] == name)): self.time_tracking.pop((-1)) return elapsed
'Render command result objects to the user'
def display_result(self, result):
try: if (self.render_mode in ('json', 'as.json')): return self._display_result('json', result.as_('json')) if (self.render_mode in ('text', 'as.text')): return self._display_result('text', unicode(result)) if (self.render_mode in ('csv', 'as.csv')): return...
'Render data as JSON'
def render_json(self, data):
class NoFailEncoder(JSONEncoder, ): def default(self, obj): if isinstance(obj, (list, dict, str, unicode, int, float, bool, type(None))): return JSONEncoder.default(self, obj) else: return json_helper(obj) return json.dumps(data, indent=1, cls=NoFa...
'Render data as HTML'
def render_web(self, cfg, tpl_names, data):
alldata = default_dict(self.html_variables) alldata['config'] = cfg alldata.update(data) try: template = self._web_template(cfg, tpl_names) if template: return template.render(alldata) else: tpl_esc_names = [escape_html(tn) for tn in tpl_names] ...
'Add to the dict using an autoselected key'
def append(self, value):
if ('_any' in self.rules): k = b36((max(([int(k, 36) for k in self.keys()] + [(-1)])) + 1)).lower() self[k] = value return k else: raise UsageError(_('Cannot append to fixed dict'))
'Reimplement update, so it goes through our sanity checks.'
def update(self, *args, **kwargs):
for src in args: if hasattr(src, 'keys'): for key in src: self[key] = src[key] else: for (key, val) in src: self[key] = val for key in kwargs: self[key] = kwargs[key]
'Parse a config file fragment. Invalid data will be ignored, but will generate warnings in the session UI. Returns True on a clean parse, False if any of the settings were bogus. >>> cfg.parse_config(session, \'[config/sys]\nfd_cache_size = 123\n\') True >>> cfg.sys.fd_cache_size 123 >>> cfg.parse_config(session, \'[co...
def parse_config(self, session, data, source='internal'):
parser = CommentedEscapedConfigParser() parser.readfp(io.BytesIO(str(data))) def item_sorter(i): try: return (int(i[0], 36), i[1]) except (ValueError, IndexError, KeyError, TypeError): return i all_okay = True for section in parser.sections(): okay = T...
'We keep old master key files around for up to 5 days, so users can revert if they make some sort of horrible mistake. After that we delete the backups because they\'re technically a security risk.'
def _delete_old_master_keys(self, keyfile):
maxage = (time.time() - ((5 * 24) * 3600)) prefix = (os.path.basename(keyfile) + '.') dirname = os.path.dirname(keyfile) for f in os.listdir(dirname): fn = os.path.join(dirname, f) if (f.startswith(prefix) and (os.stat(fn).st_mtime < maxage)): safe_remove(fn)
'Safely remove a mailbox from the cache, saving any state changes to the encrypted pickles. If the mailbox is still in use somewhere in the app (as measured by the Python reference counter), we DON\'T remove from cache, to ensure each mailbox is represented by exactly one object at a time.'
def uncache_mailbox(self, session, entry, drop=True, force_save=False):
(pfn, mbx_id) = entry[:2] if pfn: def dropit(l): return [c for c in l if (c[0] != pfn)] else: def dropit(l): return [c for c in l if (c[1] != mbx_id)] with self._lock: mboxes = [c[2] for c in self._mbox_cache if ((c[0] == pfn) if pfn else (c[1] == mbx_id))...
'Add a mailbox to the cache, potentially evicting other entries if the cache has grown too large.'
def cache_mailbox(self, session, pfn, mbx_id, mbox):
with self._lock: if (pfn is not None): self._mbox_cache = [c for c in self._mbox_cache if (c[0] != pfn)] elif mbx_id: self._mbox_cache = [c for c in self._mbox_cache if (c[1] != mbx_id)] self._mbox_cache.append((pfn, mbx_id, mbox)) flush = self._mbox_cache[:(-...
'Get the gettext translation object, no matter where our CWD is'
@classmethod def getLocaleDirectory(self):
return os.path.join(self.DEFAULT_SHARED_DATADIR(), 'locale')
'Return the path to a data directory for a particular type of file data, optionally creating the directory if it is missing. >>> p = cfg.data_directory(\'html_theme\', mode=\'r\', mkdir=False) >>> p == os.path.abspath(\'shared-data/default-theme\') True'
def data_directory(self, ftype, mode='rb', mkdir=False):
bpath = self.sys.path.get(ftype) if (not bpath.startswith('/')): cpath = os.path.join(self.workdir, bpath) if (os.path.exists(cpath) or ('w' in mode)): bpath = cpath if (mkdir and (not os.path.exists(cpath))): os.mkdir(cpath) else: bpat...
'Returns a path where we need more disk space, None if all is ok.'
def need_more_disk_space(self, required=0, nodefault=False, ratio=1.0):
if (not (nodefault and required)): required = (ratio * max(required, ((self.sys.minfree_mb * 1024) * 1024))) for path in (self.workdir,): if (get_free_disk_bytes(path) < required): return path return None
'Get a search index by path (instead of the default), or None if no matching index is found.'
def get_path_index(self, session, path):
idx = None (mi, mbox) = self.open_mailbox_path(session, path, raw_open=True) if mbox: idx = mbox.get_index(self, mbx_mid=mi) if (idx is None): import mailpile.index.base idx = mailpile.index.base.BaseIndex(self) return idx
'Find and the closest matching posting list container file'
@classmethod def _GetFilenameAndSig(cls, config, sig):
sig = sig[:cls.MAX_HASH_LEN] while (len(sig) > 0): fn = cls._SaveFile(config, sig) try: if os.path.exists(fn): return (fn, sig) except (IOError, OSError): pass if (len(sig) > 1): sig = sig[:(-1)] else: return...
'Query the Mailpile secrets for a usable passphrase.'
def prepare_passphrase(self, keyid, signing=False, decrypting=False):
def _use(kid, sps_reader): self.passphrase = sps_reader GnuPG.LAST_KEY_USED = kid return True if self.config: message = [] if decrypting: message.append(_('Your PGP key is needed for decrypting.')) if signing: message.appe...
'Returns a string representing the GnuPG version number.'
def version(self):
self.event.running_gpg(_('Checking GnuPG version')) retvals = self.run(['--version'], novercheck=True) return retvals[1]['stdout'][0].split('\n')[0]
'Returns a tuple representing the GnuPG version number.'
def version_tuple(self, update=False):
global GPG_VERSIONS if (update or (not GPG_VERSIONS.get(self.gpgbinary))): vertext = self.version().strip().split()[(-1)] version = tuple((int(v) for v in vertext.split('.'))) GPG_VERSIONS[self.gpgbinary] = version return GPG_VERSIONS[self.gpgbinary]
'Returns the location of the GnuPG keyring'
def gnupghome(self):
self.event.running_gpg(_('Checking GnuPG home directory')) rv = self.run(['--version'], novercheck=True)[1]['stdout'][0] for l in rv.splitlines(): if l.startswith('Home: '): return os.path.expanduser(l[6:].strip()) return os.path.expanduser(os.getenv('GNUPGHOME', '~/.gnup...
'>>> g = GnuPG(None) >>> g.list_keys()[0] 0'
def list_keys(self, selectors=None):
list_keys = ['--fingerprint'] for sel in set((selectors or [])): list_keys += ['--list-keys', sel] if (not selectors): list_keys += ['--list-keys'] self.event.running_gpg((_('Fetching GnuPG public key list (selectors=%s)') % ', '.join((selectors or [])))) retvals = ...
'Imports gpg keys from a file object or string. >>> key_data = open("testing/pub.key").read() >>> g = GnuPG(None) >>> g.import_keys(key_data) {\'failed\': [], \'updated\': [{\'details_text\': \'unchanged\', \'details\': 0, \'fingerprint\': \'08A650B8E2CBC1B02297915DC65626EED13C70DA\'}], \'imported\': [], \'results\': {...
def import_keys(self, key_data=None):
self.event.running_gpg(_('Importing key to GnuPG key chain')) retvals = self.run(['--import'], gpg_input=key_data) return self._parse_import(retvals[1]['status'])
'Note that this test will fail if you don\'t replace the recipient with one whose key you control. >>> g = GnuPG(None) >>> ct = g.encrypt("Hello, World", to=["smari@mailpile.is"])[1] >>> g.decrypt(ct)["text"] \'Hello, World\''
def decrypt(self, data, outputfd=None, passphrase=None, as_lines=False):
if (passphrase is not None): self.passphrase = passphrase.get_reader() elif GnuPG.LAST_KEY_USED: self.prepare_passphrase(GnuPG.LAST_KEY_USED, decrypting=True) self.event.running_gpg((_('Decrypting %d bytes of data') % len(data))) for tries in (1, 2): retvals = self.ru...
'Given the start and end index of a desired segment of decoded data, this function finds smallest segment of an encoded base64 array that when decoded will include the desired decoded segment. It\'s assumed that the base64 data has a uniform line structure of line_len encoded characters including line_end eol character...
def base64_segment(self, dec_start, dec_end, skip, line_len, line_end=2):
enc_start = (4 * (dec_start / 3)) dec_skip = (dec_start - ((3 * enc_start) / 4)) enc_start += (line_end * (enc_start / (line_len - line_end))) enc_end = (4 * (dec_end / 3)) enc_end += (line_end * (enc_end / (line_len - line_end))) return (enc_start, enc_end, dec_skip)
'Parse the header of a PGP packet to get the packet type, header length, and data length. Extra trailing characters in header are ignored. prev_partial indicates that the previous packet was a partial packet. An illegal header returns type -1, lengths 0. Header format is defined in RFC4880 section 4.'
def pgp_packet_hdr_parse(self, header, prev_partial=False):
hdr = bytearray(header.ljust(6, chr(0))) if (not prev_partial): hdr_len = 1 else: hdr[1:] = hdr hdr[0] = 0 hdr_len = 0 is_partial = False if (prev_partial or ((hdr[0] & 192) == 192)): ptag = (hdr[0] & 63) body_len = hdr[1] lengthtype = 0 ...
'Checks arbitrary data to see if it is a PGP object and returns a set that indicates the kind(s) of object found. The names of the set elements are based on RFC3156 content types with \'pgp-\' stripped so they can be used in sniffers for other protocols, e.g. S/MIME. There are additional set elements \'armored\' and \'...
def sniff(self, data, encoding=None):
found = set() is_base64 = False is_quopri = False line_len = 0 line_end = 1 enc_start = 0 enc_end = 0 dec_start = 0 skip = 0 ptag = 0 hdr_len = 0 body_len = 0 partial = False offset_enc = 0 offset_dec = 0 offset_packet = 0 if (encoding and (encoding.lo...
'>>> g = GnuPG(None) >>> s = g.sign("Hello, World", _from="smari@mailpile.is", clearsign=True)[1] >>> g.verify(s)'
def verify(self, data, signature=None):
params = ['--verify'] if signature: sig = tempfile.NamedTemporaryFile() sig.write(signature) sig.flush() params.append(sig.name) params.append('-') self.event.running_gpg((_('Checking signature in %d bytes of data') % len(data))) (ret, retvals) =...
'>>> g = GnuPG(None) >>> g.encrypt("Hello, World", to=["smari@mailpile.is"])[0] 0'
def encrypt(self, data, tokeys=[], armor=True, sign=False, fromkey=None, throw_keyids=False):
if tokeys: action = ['--encrypt', '--yes', '--expert', '--trust-model', 'always'] for r in tokeys: action.append('--recipient') action.append(r) action.extend([]) self.event.running_gpg((_('Encrypting %d bytes of data to %s') % (len(data), ',...
'>>> g = GnuPG(None) >>> g.sign("Hello, World", fromkey="smari@mailpile.is")[0] 0'
def sign(self, data, fromkey=None, armor=True, detatch=True, clearsign=False, passphrase=None):
if (passphrase is not None): self.passphrase = passphrase.get_reader() if (fromkey and (passphrase is None)): self.prepare_passphrase(fromkey, signing=True) if (detatch and (not clearsign)): action = ['--detach-sign'] elif clearsign: action = ['--clearsign'] else: ...
'Prepends a 0x to hexadecimal key ids. For example, D13C70DA is converted to 0xD13C70DA. This is required by version 2.x of GnuPG (and is accepted by 1.x).'
def _escape_hex_keyid_term(self, term):
is_hex_keyid = False if ((len(term) == GPG_KEYID_LENGTH) or (len(term) == (2 * GPG_KEYID_LENGTH))): hex_digits = set(string.hexdigits) is_hex_keyid = all(((c in hex_digits) for c in term)) if is_hex_keyid: return ('0x%s' % term) else: return term
'This lets a callback have a chat with the GPG process...'
def chat(self, gpg_args, callback, *args, **kwargs):
gpg_args = ([self.gpgbinary, '--utf8-strings', '--personal-digest-preferences=SHA512', '--digest-algo=SHA512', '--cert-digest-algo=SHA512', '--no-tty', '--command-fd=0', '--status-fd=1'] + (gpg_args or [])) if self.homedir: gpg_args.insert(1, ('--homedir=%s' % self.homedir)) if (self.version_tuple()...
'This generates a mixed state for the message. The most exciting state is returned/explained, the status prefixed with "mixed-". How exciting states are, is determined by the order of the STATUSES attribute. This is lossy, but hopefully in a useful and non-harmful way.'
def _mix_in(self, ci):
status = self['status'] if (self.STATUSES.index(status) <= self.STATUSES.index(ci.part_status)): mix = copy.copy(ci) if (self.bubbly and (status != mix.part_status) and (not mix.part_status.startswith('mixed-'))): mix['status'] = ('mixed-%s' % mix.part_status) else: ...
'This creates one VCard per e-mail address found in UIDs'
@classmethod def vcards_one_per_uid(cls, keys, vcards, kindhint=None):
new_vcards = [] for (key_id, key) in keys.iteritems(): if cls.key_is_useless(key): continue for uid in key.get('uids', []): email = uid.get('email') if email: vcls = [cls.key_vcl(key_id, key)] if uid.get('name'): ...
'This creates on VCards per key'
@classmethod def vcards_per_key(cls, keys, vcards):
new_vcards = [] for (key_id, key) in keys.iteritems(): if cls.key_is_useless(key): continue vcls = [cls.key_vcl(key_id, key)] emails = [] for uid in key.get('uids', []): if uid.get('email'): vcls.append(VCardLine(name='email', value=uid['em...
'This creates merged VCards, grouping by uid/e-mail and key'
@classmethod def vcards_merged(cls, keys, vcards):
new_vcards = [] for (key_id, key) in keys.iteritems(): if cls.key_is_useless(key): continue vcls = [cls.key_vcl(key_id, key)] card = None emails = [] for uid in key.get('uids', []): if uid.get('email'): vcls.append(VCardLine(name='e...
'Scan the plugin directories for plugins we could load. This updates the global PluginManager state and returns the PluginManager itself (for chaining).'
def discover(self, paths, update=False):
plugins = self.BUILTIN[:] for pdir in paths: for subdir in self._listdir(pdir): pname = subdir.lower() if (pname in self.BUILTIN): print ('Cannot overwrite built-in plugin: %s' % pname) continue if ((pname in self.DISCOVERED...
'Pass one of processing the manifest data. This updates the global configuration and registers Python code with the URL map.'
def _process_manifest_pass_one(self, full_name, manifest=None, plugin_path=None):
if (not manifest): return manifest_path = (lambda *p: self._mf_path(manifest, *p)) manifest_iteritems = (lambda *p: self._mf_iteritems(manifest, *p)) for (section, rules) in manifest_iteritems('config', 'sections'): self.register_config_section(*(section.split('.') + [rules])) for (s...
'Pass two of processing the manifest data. This maps templates and data to API commands and links registers classes and methods as hooks here and there. As these things depend both on configuration and the URL map, this happens as a second phase.'
def _process_manifest_pass_two(self, full_name, manifest=None, plugin_path=None):
if (not manifest): return manifest_path = (lambda *p: self._mf_path(manifest, *p)) manifest_iteritems = (lambda *p: self._mf_iteritems(manifest, *p)) for fn in manifest.get('code', {}).get('javascript', []): class_name = fn.replace('/', '.').rsplit('.', 1)[0] if full_name.endswit...
'Avoids stacking several consecutive Fw: Re: Re: Re:'
@staticmethod def prefix_subject(subject, prefix, prefix_regex):
if (subject is None): return prefix elif prefix_regex.match(subject): return subject else: return ('%s %s' % (prefix, subject))
'>>> from mailpile.crypto.dnspka import * >>> d = DNSPKALookup() >>> res = d.lookup("smari@immi.is") >>> res["result"]["count"] == 1'
def _lookup(self, address, strict_email_match=True):
if (not DNS): return {} dom = address.replace('@', '._pka.') result = self.req.req(dom) for res in (result.answers if result else []): if (res['typename'] != 'TXT'): continue for entry in res['data']: return self._keyinfo(entry) return {}
'Request a key for address.'
def get_key(self, address, keytype='openpgp', server=None):
(result, signature) = self._nickserver_get_key(address, keytype, server) if self._verify_result(result, signature): return self._import_key(result, keytype) return False
'Refresh all known keys.'
def refresh_keys(self):
for (addr, keytype) in self._get_managed_keys(): (result, signature) = self._nickserver_get_key(addr, keytype) if self._verify_result(result, signature): self._import_key(result, keytype)
'Send a new key to the nickserver'
def send_key(self, address, public_key, type):
raise NotImplementedError()
'Parse the result into a JSON blob and a signature'
def _parse_result(self, result):
return (json.loads(result), '')
'Request a provider key for the appropriate domain. This is equivalent to get_key() with address=domain, except it should store the provider key in an appropriate key store'
def _get_providerkey(self, domain):
pass
''
def _verify_providerkey(self, domain):
pass
'Verify that the JSON result blob is correctly signed, and that the signature is from the correct provider key.'
def _verify_result(self, result, signature):
return True
'Automatically detect which nicknym server to query based on the address.'
def _discover_server(self, address):
addr = address.split('@') addr.reverse() domain = addr[0] return ('https://nicknym.%s:6425/' % domain)
'Ask an alternative server for a key to verify that the same result is being provided.'
def _audit_key(self, address, keytype, server):
(result, signature) = self._nickserver_get_key(address, keytype, server) if self._verify_result(result, signature): pass return True
'Reset to an untrained state'
def reset(self, at_config):
self.trainer.reset(self, at_config) self.trained = False
'Returns (result, evidence), result =True, False or None'
def should_tag(self, atagger, at_config, msg, keywords):
return (False, None)
'Learn that this message should (or should not) be tagged'
def learn(self, atagger, at_config, msg, keywords, should_tag):
pass
'Reset to an untrained state (called by AutoTagger.reset)'
def reset(self, atagger, at_config):
pass
'Retrain autotaggers'
def _retrain(self, tags=None):
(session, config, idx) = (self.session, self.session.config, self._idx()) tags = (tags or [asb.match_tag for asb in autotag_configs(config)]) tids = [config.get_tag(t)._key for t in tags if t] session.ui.mark(_('Retraining SpamBayes autotaggers')) if (not config.real_hasattr('autotag')): ...
'Retrains autotaggers Classmethod used for periodic automatic retraining'
@classmethod def interval_retrain(cls, session):
result = cls(session)._retrain() if result: return True else: return False
'Fetch a token and associated details from an authorization server. Returns something like this: \'access_token\': \'tsbk6pcSPSNffdzEkxVicwf...\', \'token_type\': \'Bearer\', \'expires_at\': 123456789, \'refresh_token\': \'1CtboygBSKA-Ut1e7...\''
@classmethod def GetToken(cls, session, oauth2_cfg, code, tok_id=None):
post_data = urlencode([('code', code), ('client_id', oauth2_cfg['client_id']), ('client_secret', oauth2_cfg['client_secret']), ('redirect_uri', cls.RedirectURI(session.config, oauth2_cfg, session.ui.html_variables.get('http_host'))), ('grant_type', 'authorization_code')]) data = json.loads(cls.URLGet(session, o...
'Return all the incomplete events, in order.'
def incomplete(self, **filters):
if ('event_id' in filters): ids = [filters['event_id']] else: ids = sorted(self._events.keys()) for ek in ids: e = self._events.get(ek, None) if ((e is not None) and (Event.COMPLETE not in e.flags) and self._match(e, filters)): (yield e)
'Return all events since a given time, in order.'
def since(self, ts, **filters):
if (ts < 0): ts += time.time() if (('event_id' in filters) and (filters['event_id'][:1] != '!')): ids = [filters['event_id']] else: ids = sorted(self._events.keys()) for ek in ids: e = self._events.get(ek, None) if ((e is not None) and (e.ts >= ts) and self._match...
'Log an Event object.'
def log_event(self, event):
with self._lock: self._save_events([event]) self._logged += 1 self._maybe_rotate_log() self._notify_waiters() for ui in self._watching_uis: ui.notify(event.as_text(compact=True)) return event
'Log a new event.'
def log(self, *args, **kwargs):
return self.log_event(Event(*args, **kwargs))
'Return the current server host, e.g. \'localhost\''
def http_host(self):
try: return self.headers.get('host', 'localhost').rsplit(':', 1)[0] except AttributeError: return 'unknown'
'Robustified cookie parser that silently drops invalid cookies.'
def _load_cookies(self):
cookies = Cookie.SimpleCookie() for fragment in self.headers.get('cookie', '').split('; '): if fragment: try: cookies.load(fragment) except Cookie.CookieError: pass return cookies
'Fetch the session ID from a cookie, or assign a new one'
def http_session(self):
session_id = self._load_cookies().get(self.server.session_cookie) if session_id: session_id = session_id.value self.assert_no_newline(session_id) else: session_id = self.server.make_session_id(self) return session_id
'Return the current server URL, e.g. \'http://localhost:33411/\''
def server_url(self):
try: surl = ('%s://%s' % (self.headers.get('x-forwarded-proto', 'http'), self.headers.get('host', 'localhost'))) self.server.server_url = surl except AttributeError: surl = self.server.server_url return surl
'Send the HTTP response header'
def send_http_response(self, code, msg):
msg = ('%s %s' % (code, msg)) self.assert_no_newline(msg) self.wfile.write(('HTTP/1.1 %s\r\n' % msg))
'Send common HTTP headers plus a list of custom headers: - Cache-Control - Content-Type This function does not send the HTTP/1.1 header, so ensure self.send_http_response() was called before Keyword arguments: header_list -- A list of custom headers to send, containing key-value tuples cachectrl -- The value of the...
def send_standard_headers(self, header_list=[], cachectrl='private', mimetype='text/html'):
if (mimetype.startswith('text/') and (';' not in mimetype)): mimetype += '; charset = utf-8' self.send_header('Cache-Control', cachectrl) self.send_header('Content-Security-Policy', security.http_content_security_policy(self.server)) self.send_header('Content-Type', mimetype) for he...
'Sends the HTTP header and a response list message -- The body of the response to send header_list -- A list of custom headers to send, containing key-value tuples code -- The HTTP response code to send mimetype -- The MIME type to send as \'Content-Type\' value suppress_body -- Set this to True t...
def send_full_response(self, message, code=200, msg='OK', mimetype='text/html', header_list=[], cachectrl=None, suppress_body=False):
message = unicode(message).encode('utf-8') self.log_request(code, ((message and len(message)) or '-')) self.send_http_response(code, msg) if (code == 401): self.send_header('WWW-Authenticate', ('Basic realm = MP%d' % (time.time() / 3600))) headers = [] if (not suppress_body): ...
'Generate an unguessable and unauthenticated new session ID.'
def make_session_id(self, request):
session_id = None while ((session_id in self.sessions) or (session_id is None)): session_id = okay_random(32, self.secret, ('%s' % (request and request.headers))) return session_id
'Get one (or all) indexed fields for this mail.'
def get(self, field, default=''):
field = field.lower() if (field == 'subject'): return self.get_msg_info(self.index.MSG_SUBJECT) elif (field == 'from'): return self.get_msg_info(self.index.MSG_FROM) else: raw = ' '.join(self.get_msg(pgpmime=False).get_all(field, default)) return (safe_decode_hdr(hdr=r...
'Remove the message or raise error if nonexistent.'
def remove(self, key):
safe_remove(os.path.join(self._mailroot, self._lookup(key))) try: del self._toc[key] except: pass
'If the message exists, remove it.'
def discard(self, key):
try: self.remove(key) except KeyError: pass except OSError as e: if (e.errno != errno.ENOENT): raise
'Replace a message'
def __setitem__(self, key, message):
raise NotImplemented('Mailpile is readonly, for now.')
'Initialize a Mailbox instance.'
def __init__(self, host, user=None, password=None, auth_type='password', use_ssl=True, port=None, debug=False, conn_cls=None, session=None):
Mailbox.__init__(self, '/') self.host = host self.user = user self.password = password self.auth_type = auth_type self.use_ssl = use_ssl self.port = port self.debug = debug self.conn_cls = conn_cls self.session = session self._lock = MboxRLock() self._pop3 = None self...
'Replace the keyed message; raise KeyError if it doesn\'t exist.'
def __setitem__(self, key, message):
raise NotImplementedError('Method must be implemented by subclass')
'Return a Message representation or raise a KeyError.'
def get_message(self, key):
return Message(self._get(key))
'Return a byte string representation or raise a KeyError.'
def get_bytes(self, key, *args):
return self._get(key, *args)
'Return a file-like representation or raise a KeyError.'
def get_file(self, key):
return StringIO.StringIO(self._get(key))
'Return an iterator over keys.'
def iterkeys(self):
with self._lock: if (self._keys is None): self._connect() try: (stat, key_list, octets) = self._pop3.uidl() except poplib.error_proto: raise UnsupportedProtocolError() self._keys = [tuple(k.split(' ', 1)) for k in key_list] ...
'Return True if the keyed message exists, False otherwise.'
def __contains__(self, key):
return (key in self.iterkeys())
'Return a count of messages in the mailbox.'
def __len__(self):
return len(self.iterkeys())
'Write any pending changes to the disk.'
def flush(self):
self.close()
'Flush and close the mailbox.'
def close(self):
try: if self._pop3: self._pop3.quit() finally: self._pop3 = None self._keys = None
'Return a file-like representation or raise a KeyError.'
def get_file(self, key):
fname = self._lookup(key) if fname.endswith('.gz'): f = gzip.open(os.path.join(self._path, fname), 'rb') else: f = open(os.path.join(self._path, fname), 'rb') return mailbox._ProxyFile(f)
'Update table of contents mapping.'
def _refresh(self):
self._toc = {} for path in self._paths: for (dirpath, dirnames, filenames) in os.walk(self._paths[path]): for filename in [f for f in filenames if (f.endswith('.eml.gz') or f.endswith('.eml'))]: self._toc[filename] = os.path.join(dirpath, filename)
'Return a Message representation or raise a KeyError.'
def get_message(self, key):
with self._lock: with self._get_fd(key) as fd: if self._factory: return self._factory(fd) else: return mailbox.MaildirMessage(fd)
'Add message and return assigned key.'
def add(self, message):
key = self._encryption_key_func() es = None try: tmpdir = os.path.join(self._path, 'tmp') if (not os.path.exists(tmpdir)): os.mkdir(tmpdir, 448) if key: es = EncryptingStreamer(key, dir=tmpdir, name='WERVD', delimited=False) else: es = Chec...
'Turns the /var/value prefix into a query-string argument. Returns a new path with the prefix stripped. >>> query_data = {} >>> path = urlmap._prefix_to_query(\'/var/val/stuff\', query_data, {}) >>> path, query_data (\'/stuff\', {\'var\': [\'val\']})'
def _prefix_to_query(self, path, query_data, post_data):
(which, value, path) = path[1:].split('/', 2) query_data[which] = [value] return ('/' + path)
'Return an instantiated mailpile.command object or raise a UsageError. >>> urlmap._command(\'output\', args=[\'html\'], method=False) <mailpile.plugins.core.Output...> >>> urlmap._command(\'bogus\') Traceback (most recent call last): UsageError: Unknown command: bogus >>> urlmap._command(\'message/update\', method=\'GE...
def _command(self, name, args=None, query_data=None, post_data=None, method='GET', async=False):
try: match = [c for c in self._api_commands(method, strict=False) if ((method and (name == c.SYNOPSIS[2])) or ((not method) and (name == c.SYNOPSIS[1])))] if (len(match) != 1): raise UsageError(('Unknown command: %s' % name)) except ValueError as e: raise UsageError(str...
'Return an output command based on the URL filename component. As a side-effect, the filename component will be removed from the path_parts list. >>> path_parts = \'/a/b/as.json\'.split(\'/\') >>> command = urlmap._choose_output(path_parts) >>> (path_parts, command) ([\'\', \'a\', \'b\'], <mailpile.plugins.core.Output....
def _choose_output(self, path_parts, fmt='html'):
if ((len(path_parts) > 1) and (not path_parts[(-1)])): path_parts.pop((-1)) else: om = path_parts.pop((-1)) if re.match('^[a-zA-Z0-9\\.!_-]+$', om): fn = om.split('!')[0] for suffix in self.OUTPUT_SUFFIXES: if (fn.endswith(suffix) or (suffix == ('....
'Redirects to /profiles/ for now. (FIXME)'
def _map_root(self, request, path_parts, query_data, post_data):
destination = ('%s/profiles/' % self.config.sys.http_path) return [UrlRedirect(self.session, 'redirect', arg=[destination])]
'Map /in/TAG_NAME/[@<pos>]/ to tag searches. >>> path = \'/in/inbox/@20/as.json\' >>> commands = urlmap._map_tag(request, path[1:].split(\'/\'), {}, {}) >>> commands [<mailpile.plugins.core.Output...>, <mailpile.plugins.search.Search...>] >>> commands[0].args (\'as.json\',) >>> commands[1].args (\'@20\', \'in:inbox\')'...
def _map_tag(self, request, path_parts, query_data, post_data):
output = self._choose_output(path_parts) pos = None while (path_parts and (path_parts[(-1)][0] in ('@',))): pos = (path_parts[(-1)].startswith('@') and path_parts.pop((-1))) tag_slug = '/'.join([p for p in path_parts[1:] if p]) tag = self.config.get_tag(tag_slug) tag_search = ([term for ...
'Map /thread/METADATA_ID/... to view or extract commands. >>> path = \'/thread/=123/\' >>> commands = urlmap._map_thread(request, path[1:].split(\'/\'), {}, {}) >>> commands [<mailpile.plugins.core.Output...>, <mailpile.plugins.search.View...>] >>> commands[1].args (\'=123\',)'
def _map_thread(self, request, path_parts, query_data, post_data):
(message_mids, i) = ([], 1) while path_parts[i].startswith('='): message_mids.append(path_parts[i]) i += 1 return [self._choose_output(path_parts), self._command('message', args=message_mids, query_data=query_data, post_data=post_data)]
'Map a path to a command list, prefering the longest match. >>> urlmap._map_api_command(\'GET\', [\'message\', \'draft\', \'\'], {}, {}) [<mailpile.plugins.core.Output...>, <...Draft...>] >>> urlmap._map_api_command(\'POST\', [\'message\', \'update\', \'\'], {}, {}) [<mailpile.plugins.core.Output...>, <...Update...>] >...
def _map_api_command(self, method, path_parts, query_data, post_data, fmt='html', async=False):
output = self._choose_output(path_parts, fmt=fmt) for bp in reversed(range(1, (len(path_parts) + 1))): try: return [output, self._command('/'.join(path_parts[:bp]), args=path_parts[bp:], query_data=query_data, post_data=post_data, method=method, async=async)] except UsageError: ...
'Convert an HTTP request to a list of mailpile.command objects. >>> urlmap.map(request, \'GET\', \'/in/inbox/\', {}, {}) [<mailpile.plugins.core.Output...>, <mailpile.plugins.search.Search...>] The /api/ URL space is versioned and provides access to all the built-in commands. Requesting the wrong version or a bogus com...
def map(self, request, method, path, query_data, post_data, authenticate=False):
if self.session: sid = self.session.ui.html_variables.get('http_session') user_session = (mailpile.auth.SESSION_CACHE.get(sid) if sid else None) else: sid = user_session = None is_async = path.startswith(('/%s/' % self.MAP_ASYNC_API)) is_api = path.startswith(('/%s/' % self.MAP_A...
'Map a message to it\'s short-hand thread URL.'
def url_thread(self, message_id, output=''):
return self._url(('/thread/=%s/' % message_id), output)
'Map a message to it\'s raw message source URL.'
def url_source(self, message_id, output=''):
return self._url(('/message/raw/=%s/as.text' % message_id), output)
'Map a message to it\'s short-hand editing URL.'
def url_edit(self, message_id, output=''):
return self._url(('/message/draft/=%s/' % message_id), output)
'Redirect to the /auth/ or a /setup/* endpoint'
def redirect_to_auth_or_setup(self, method, path, query_data, setup=True):
from mailpile.plugins.setup_magic import Setup if (method.lower() == 'get'): qd = [(k, v) for (k, vl) in query_data.iteritems() for v in vl] if ('_path' not in query_data): qd.append(('_path', path)) else: qd = [] if setup: nxt = Setup.Next(self.session.config...
'Map a tag to it\'s short-hand URL. >>> urlmap.url_tag(\'Inbox\') \'/in/inbox/\' >>> urlmap.url_tag(\'inbox\', output=\'json\') \'/in/inbox/as.json\' >>> urlmap.url_tag(\'1\') \'/in/inbox/\' Unknown tags raise an exception. >>> urlmap.url_tag(\'99\') Traceback (most recent call last): ValueError: Unknown tag: 99'
def url_tag(self, tag_id, output=''):
try: tag = self.config.tags[tag_id] if (tag is None): raise KeyError('oops') except (KeyError, IndexError): tag = [t for t in self.config.tags.values() if (t.slug == tag_id.lower())] tag = (tag and tag[0]) if tag: return self._url(('/in/%s/' % tag.slug), o...
'Return the URL of the Sent tag'
def url_sent(self, output=''):
return self.url_tag('Sent', output=output)