From b2e83b85fc833159163198a2e83f621001571ac8 Mon Sep 17 00:00:00 2001 From: Mathieu Agopian Date: Fri, 22 Mar 2013 22:56:33 +0100 Subject: [PATCH] All live tests but test_idle (and skipped) are now passing --- imapclient/imap_utf7.py | 90 +++++++++++------- imapclient/imapclient.py | 168 +++++++++++++++++++--------------- imapclient/livetest.py | 28 +++--- imapclient/response_lexer.py | 39 ++++---- imapclient/response_parser.py | 11 ++- 5 files changed, 193 insertions(+), 143 deletions(-) diff --git a/imapclient/imap_utf7.py b/imapclient/imap_utf7.py index ed19de5..a6fb529 100644 --- a/imapclient/imap_utf7.py +++ b/imapclient/imap_utf7.py @@ -24,8 +24,7 @@ from __future__ import unicode_literals -from .six import text_type, PY3, int2byte -from .pycompat import iter_as_bytes +from .six import text_type, binary_type, iteritems class FolderNameError(ValueError): pass @@ -33,73 +32,100 @@ class FolderNameError(ValueError): PRINTABLE = set(range(0x20, 0x26)) | set(range(0x27, 0x7f)) def encode(s): - """Encode a folder name using IMAP modified UTF-7 encoding + """Encode a folder name using IMAP modified UTF-7 encoding. + + Even though we're using "encode" here the output is still a unicode string. - Input and output types: - Python 2 - str/unicode to str - Python 3 - str to bytes """ - # This is for Python 2 only. Under Python 3 the input will always be unicode. - if (not PY3 and isinstance(s, str) and - sum(n for n in (ord(c) for c in s) if n > 127)): - raise FolderNameError("%r contains characters not valid in a str " - "folder name. Convert to unicode first?" % s) + if not isinstance(s, text_type): + return s r = [] _in = [] def extend_result_if_chars_buffered(): if _in: - r.extend([b'&', modified_base64(''.join(_in)), b'-']) + r.extend(['&', modified_base64(''.join(_in)), '-']) del _in[:] for c in s: if ord(c) in PRINTABLE: extend_result_if_chars_buffered() - r.append(int2byte(ord(c))) + r.append(c) elif c == '&': extend_result_if_chars_buffered() - r.append(b'&-') + r.append('&-') else: _in.append(c) extend_result_if_chars_buffered() - return b''.join(r[:]) + return ''.join(r) def decode(s): - """Decode a folder name from IMAP modified UTF-7 encoding to unicode + """Decode a folder name from IMAP modified UTF-7 encoding to unicode. + + Even though we're using "decode" here the input may still be a unicode + string. + + If the input is bytes, it's first decoded to unicode. - Input and output types: - Python 2 - str to unicode - Python 3 - bytes to str """ + if isinstance(s, binary_type): + s = s.decode('latin-1') + if not isinstance(s, text_type): + return s + r = [] _in = [] - for c in iter_as_bytes(s): - if c == b'&' and not _in: - _in.append(b'&') - elif c == b'-' and _in: + for c in s: + if c == '&' and not _in: + _in.append('&') + elif c == '-' and _in: if len(_in) == 1: r.append('&') else: - r.append(modified_unbase64(b''.join(_in[1:]))) + r.append(modified_unbase64(''.join(_in[1:]))) _in = [] elif _in: _in.append(c) else: r.append(c) if _in: - r.append(modified_unbase64(b''.join(_in[1:]))) + r.append(modified_unbase64(''.join(_in[1:]))) - return ''.join( - x.decode('latin-1') if not isinstance(x, text_type) else x - for x in r[:]) + return ''.join(r) def modified_base64(s): - s_utf7 = s.encode('utf-7') - return s_utf7[1:-1].replace(b'/', b',') + # encode to utf-7: '\xff' => b'+AP8-', decode from latin-1 => '+AP8-' + s_utf7 = s.encode('utf-7').decode('latin-1') + return s_utf7[1:-1].replace('/', ',') def modified_unbase64(s): - s_utf7 = b'+' + s.replace(b',', b'/') + b'-' - return s_utf7.decode('utf-7') + s_utf7 = '+' + s.replace(',', '/') + '-' + # encode to latin-1: '+AP8-' => b'+AP8-', decode from utf-7 => '\xff' + return s_utf7.encode('latin-1').decode('utf-7') + + +def from_bytes(data, folder_encode=True): + """Convert bytes to string in lists, tuples and dicts. + + Decode by decoding from latin-1 or modified utf7. + + """ + if isinstance(data, dict): + decoded = {} + for key, value in iteritems(data): + key = from_bytes(key, folder_encode) + value = from_bytes(value, folder_encode) + decoded[key] = value + return decoded + if isinstance(data, list): + return [from_bytes(item, folder_encode) for item in data] + if isinstance(data, tuple): + return tuple([from_bytes(item, folder_encode) for item in data]) + if folder_encode: + return decode(data) + if isinstance(data, binary_type): + return data.decode('latin-1') + return data diff --git a/imapclient/imapclient.py b/imapclient/imapclient.py index 17f083b..27f2573 100644 --- a/imapclient/imapclient.py +++ b/imapclient/imapclient.py @@ -19,11 +19,14 @@ try: except ImportError: oauth2 = None -from . import imap_utf7 +from .imap_utf7 import encode as encode_utf7, from_bytes from .fixed_offset import FixedOffset -from .six import moves, string_types, iteritems +from .six import moves, iteritems, text_type, integer_types, PY3 xrange = moves.xrange +if PY3: + long = int # long is just int in python3 + __all__ = ['IMAPClient', 'DELETED', 'SEEN', 'ANSWERED', 'FLAGGED', 'DRAFT', 'RECENT'] @@ -136,13 +139,15 @@ class IMAPClient(object): """Logout, returning the server response. """ typ, data = self._imap.logout() + data = from_bytes(data, self.folder_encode) self._check_resp('BYE', 'logout', typ, data) return data[0] def capabilities(self): """Returns the server capability list. """ - return self._imap.capabilities + capabilities = from_bytes(self._imap.capabilities, self.folder_encode) + return capabilities def has_capability(self, capability): """Return ``True`` if the IMAP server has the given *capability*. @@ -152,7 +157,7 @@ class IMAPClient(object): # capabilities may in the future be named SORT2 which is # still compatible with the current standard and will not # be detected by this method. - if capability.upper() in self._imap.capabilities: + if capability.upper() in self.capabilities(): return True else: return False @@ -249,9 +254,14 @@ class IMAPClient(object): return self._do_list('LSUB', directory, pattern) def _do_list(self, cmd, directory, pattern): + if self.folder_encode: + directory = encode_utf7(directory) + pattern = encode_utf7(pattern) typ, dat = self._imap._simple_command(cmd, directory, pattern) + dat = from_bytes(dat, self.folder_encode) self._checkok(cmd, typ, dat) typ, dat = self._imap._untagged_response(typ, dat, cmd) + dat = from_bytes(dat, self.folder_encode) return self._proc_folder_list(dat) def _proc_folder_list(self, folder_data): @@ -263,10 +273,9 @@ class IMAPClient(object): ret = [] parsed = parse_response(folder_data) while parsed: - raw_flags, delim, raw_name = parsed[:3] + flags, delim, name = parsed[:3] parsed = parsed[3:] - flags = [imap_utf7.decode(flag) for flag in raw_flags] - ret.append((flags, delim, self._decode_folder_name(raw_name))) + ret.append((flags, delim, self._parse_folder_name(name))) return ret def select_folder(self, folder, readonly=False): @@ -287,8 +296,10 @@ class IMAPClient(object): 'UIDNEXT': 11, 'UIDVALIDITY': 1239278212} """ - self._command_and_check('select', self._encode_folder_name(folder), readonly) - return self._process_select_response(self._imap.untagged_responses) + self._command_and_check('select', self._imap._quote(folder), readonly) + untagged = self._imap.untagged_responses + untagged = from_bytes(untagged, self.folder_encode) + return self._process_select_response(untagged) def _process_select_response(self, resp): out = {} @@ -340,8 +351,8 @@ class IMAPClient(object): See `RFC 2177 `_ for more information about the IDLE extension. """ - self._idle_tag = self._imap._command('IDLE') - resp = self._imap._get_response() + self._idle_tag = from_bytes(self._imap._command('IDLE'), self.folder_encode) + resp = from_bytes(self._imap._get_response(), self.folder_encode) if resp is not None: raise self.Error('Unexpected IDLE response: %s' % resp) @@ -365,10 +376,11 @@ class IMAPClient(object): """ # make the socket non-blocking so the timeout can be # implemented for this call - if self.ssl: - sock = self._imap.sslobj - else: - sock = self._imap.sock + + # in py2, imaplib has sslobj (for ssl connexions), and sock for non-sll + # in the py3 version it's just sock + sock = getattr(self._imap, 'sslobj', self._imap.sock) + sock.setblocking(0) try: resps = [] @@ -376,7 +388,7 @@ class IMAPClient(object): if rs: while True: try: - line = self._imap._get_line() + line = from_bytes(self._imap._get_line(), self.folder_encode) except (socket.timeout, socket.error): break else: @@ -414,11 +426,11 @@ class IMAPClient(object): """ if what is None: what = ('MESSAGES', 'RECENT', 'UIDNEXT', 'UIDVALIDITY', 'UNSEEN') - elif isinstance(what, string_types): + elif isinstance(what, text_type): what = (what,) what_ = '(%s)' % (' '.join(what)) - data = self._command_and_check('status', self._encode_folder_name(folder), what_, unpack=True) + data = self._command_and_check('status', self._imap._quote(folder), what_, unpack=True) _, status_items = parse_response([data]) return dict(as_pairs(status_items)) @@ -431,37 +443,37 @@ class IMAPClient(object): def create_folder(self, folder): """Create *folder* on the server returning the server response string. """ - return self._command_and_check('create', self._encode_folder_name(folder), unpack=True) + return self._command_and_check('create', self._imap._quote(folder), unpack=True) def rename_folder(self, old_name, new_name): """Change the name of a folder on the server. """ return self._command_and_check('rename', - self._encode_folder_name(old_name), - self._encode_folder_name(new_name), + self._imap._quote(old_name), + self._imap._quote(new_name), unpack=True) def delete_folder(self, folder): """Delete *folder* on the server returning the server response string. """ - return self._command_and_check('delete', self._encode_folder_name(folder), unpack=True) + return self._command_and_check('delete', self._imap._quote(folder), unpack=True) def folder_exists(self, folder): """Return ``True`` if *folder* exists on the server. """ - data = self._command_and_check('list', '', self._encode_folder_name(folder)) + data = self._command_and_check('list', '', self._imap._quote(folder)) data = [x for x in data if x] return len(data) == 1 and data[0] != None def subscribe_folder(self, folder): """Subscribe to *folder*, returning the server response string. """ - return self._command_and_check('subscribe', self._encode_folder_name(folder)) + return self._command_and_check('subscribe', self._imap._quote(folder)) def unsubscribe_folder(self, folder): """Unsubscribe to *folder*, returning the server response string. """ - return self._command_and_check('unsubscribe', self._encode_folder_name(folder)) + return self._command_and_check('unsubscribe', self._imap._quote(folder)) def search(self, criteria='ALL', charset=None): """Return a list of messages ids matching *criteria*. @@ -483,7 +495,7 @@ class IMAPClient(object): if not criteria: raise ValueError('no criteria specified') - if isinstance(criteria, string_types): + if isinstance(criteria, text_type): criteria = (criteria,) crit_list = ['(%s)' % c for c in criteria] @@ -497,6 +509,8 @@ class IMAPClient(object): else: typ, data = self._imap.search(charset, *crit_list) + data = from_bytes(data, self.folder_encode) + self._checkok('search', typ, data) data = data[0] if data is None: # no untagged responses... @@ -525,11 +539,11 @@ class IMAPClient(object): if not self.has_capability('SORT'): raise self.Error('The server does not support the SORT extension') - if isinstance(sort_criteria, string_types): + if isinstance(sort_criteria, text_type): sort_criteria = (sort_criteria,) sort_criteria = seq_to_parenlist([s.upper() for s in sort_criteria]) - if isinstance(criteria, string_types): + if isinstance(criteria, text_type): criteria = (criteria,) crit_list = ['(%s)' % c for c in criteria] @@ -683,8 +697,10 @@ class IMAPClient(object): args.insert(0, 'UID') tag = self._imap._command(*args) typ, data = self._imap._command_complete('FETCH', tag) + data = from_bytes(data, self.folder_encode) self._checkok('fetch', typ, data) typ, data = self._imap._untagged_response(typ, data, 'FETCH') + data = from_bytes(data, self.folder_encode) return parse_fetch_response(data, self.normalise_times, self.use_uid) def append(self, folder, msg, flags=(), msg_time=None): @@ -708,10 +724,11 @@ class IMAPClient(object): time_val = '"%s"' % datetime_to_imap(msg_time) else: time_val = None + flags = self.quote_encode_flags(flags) return self._command_and_check('append', - self._encode_folder_name(folder), + self._imap._quote(folder), seq_to_parenlist(flags), - time_val, msg, + time_val, msg.encode('ascii'), unpack=True) def copy(self, messages, folder): @@ -721,7 +738,7 @@ class IMAPClient(object): """ return self._command_and_check('copy', messages_to_str(messages), - self._encode_folder_name(folder), + self._imap._quote(folder), uid=True, unpack=True) def expunge(self): @@ -753,7 +770,7 @@ class IMAPClient(object): """Returns a list of ``(who, acl)`` tuples describing the access controls for *folder*. """ - data = self._command_and_check('getacl', self._encode_folder_name(folder)) + data = self._command_and_check('getacl', self._imap._quote(folder)) parts = list(response_lexer.TokenSource(data)) parts = parts[1:] # First item is folder name return [(parts[i], parts[i+1]) for i in xrange(0, len(parts), 2)] @@ -765,7 +782,7 @@ class IMAPClient(object): server response string. """ return self._command_and_check('setacl', - self._encode_folder_name(folder), + self._imap._quote(folder), who, what, unpack=True) @@ -784,8 +801,9 @@ class IMAPClient(object): line = self._imap._get_response() if tagged_commands[tag]: break - resps.append(_parse_untagged_response(line)) + resps.append(_parse_untagged_response(from_bytes(line, self.folder_encode))) typ, data = tagged_commands.pop(tag) + data = from_bytes(data, self.folder_encode) self._checkok(command, typ, data) return data[0], resps @@ -794,11 +812,17 @@ class IMAPClient(object): uid = pop_with_default(kwargs, 'uid', False) assert not kwargs, "unexpected keyword args: " + ', '.join(kwargs) + if self.folder_encode: + # "encode" all args to modified UTF-7 just in case there's folder + # names or flags + args = [encode_utf7(arg) for arg in args] + if uid and self.use_uid: typ, data = self._imap.uid(command, *args) else: meth = getattr(self._imap, command) typ, data = meth(*args) + data = from_bytes(data, self.folder_encode) self._checkok(command, typ, data) if unpack: return data[0] @@ -814,43 +838,39 @@ class IMAPClient(object): """ if not messages: return {} + flags = self.quote_encode_flags(flags) data = self._command_and_check('store', messages_to_str(messages), cmd, seq_to_parenlist(flags), uid=True) - return self._flatten_dict(parse_fetch_response((data))) + return self._flatten_dict(parse_fetch_response(data)) def _flatten_dict(self, fetch_dict): - return dict([ - (msgid, data.values()[0]) + """Return the msg id with the value of the key which isn't 'SEQ'. + + eg: flatten_dict({1: {'SEQ': 1, 'FLAGS': ('abc', 'def')}, + 2: {'SEQ': 2, 'FLAGS': ('ghi', 'jkl')}) + >>> {1: ('abc', 'def'), 2: ('ghi', 'jkl')} + + """ + # remove all SEQ keys + for msgid, data in iteritems(fetch_dict): del data['SEQ'] + + # there should now be only one key left per data dict, use its value + return dict( + (msgid, tuple(data.values())[0]) for msgid, data in iteritems(fetch_dict) - ]) + ) - def _decode_folder_name(self, name): + def _parse_folder_name(self, name): if isinstance(name, int): # Some IMAP implementations return integer folder names # with quotes. These get parsed to ints so convert them # back to strings. - return str(name) - if self.folder_encode: - return imap_utf7.decode(name) + return text_type(name) return name - def _encode_folder_name(self, name): - if self.folder_encode: - name = imap_utf7.encode(name) - # imaplib assumes that if a command argument (in this case a - # folder name) has double quotes around it, then it doesn't - # need quoting. This "feature" prevents creation of folders - # with names that start and end with double quotes. - # - # To work around this IMAPClient performs the quoting - # itself. This adds start and end double quotes which also - # serves to fool IMAP4._checkquote into not attempting further - # quoting. A hack but it works. - return _quote_arg(name) - def __debug_get(self): return self._imap.debug @@ -867,26 +887,25 @@ class IMAPClient(object): self.log_file.write('%s %s\n' % (datetime.now().strftime('%M:%S.%f'), text)) self.log_file.flush() + def quote_encode_flags(self, flags): + """Encode to modified utf-7 if needed and quote.""" + if isinstance(flags, text_type): + flags = (flags,) + flags = [self._imap._quote(flag) for flag in flags] + if self.folder_encode: + flags = [encode_utf7(flag) for flag in flags] + return flags + def messages_to_str(messages): """Convert a sequence of messages ids or a single integer message id into an id list string for use with IMAP commands """ - if isinstance(messages, (str, int, long)): + if isinstance(messages, (text_type, integer_types)): messages = (messages,) elif not isinstance(messages, (tuple, list)): raise ValueError('invalid message list: %r' % messages) - return ','.join([str(m) for m in messages]) - -def seq_to_parenlist(flags): - """Convert a sequence of strings into parenthised list string for - use with IMAP commands. - """ - if isinstance(flags, str): - flags = (flags,) - elif not isinstance(flags, (tuple, list)): - raise ValueError('invalid flags list: %r' % flags) - return '(%s)' % ' '.join(flags) + return ','.join([text_type(m) for m in messages]) def datetime_to_imap(dt): """Convert a datetime instance to a IMAP datetime string. @@ -898,10 +917,15 @@ def datetime_to_imap(dt): dt = dt.replace(tzinfo=FixedOffset.for_system()) return dt.strftime("%d-%b-%Y %H:%M:%S %z") -def _quote_arg(arg): - arg = arg.replace('\\', '\\\\') - arg = arg.replace('"', '\\"') - return '"%s"' % arg +def seq_to_parenlist(flags): + """Convert a sequence of strings into parenthised list string for + use with IMAP commands. + """ + if isinstance(flags, text_type): + flags = (flags,) + elif not isinstance(flags, (tuple, list)): + raise ValueError('invalid flags list: %r' % flags) + return '(%s)' % ' '.join(flags) def _parse_untagged_response(text): assert text.startswith('* ') diff --git a/imapclient/livetest.py b/imapclient/livetest.py index 19f53ce..c44f428 100644 --- a/imapclient/livetest.py +++ b/imapclient/livetest.py @@ -14,7 +14,7 @@ from datetime import datetime from email.utils import make_msgid import imapclient -from imapclient.six import string_types +from imapclient.six import text_type from imapclient.test.util import unittest from imapclient.config import parse_config_file, create_client_from_config @@ -272,7 +272,7 @@ def createLiveTestClass(conf, use_uid): new_folder = folder + 'x' resp = self.client.rename_folder(folder, new_folder) - self.assertIsInstance(resp, str) + self.assertIsInstance(resp, text_type) self.assertTrue(len(resp) > 0) self.assertFalse(self.client.folder_exists(folder)) @@ -308,7 +308,7 @@ def createLiveTestClass(conf, use_uid): # Append message resp = self.client.append(self.base_folder, SIMPLE_MESSAGE, ('abc', 'def'), msg_time) - self.assertIsInstance(resp, str) + self.assertIsInstance(resp, text_type) # Retrieve the just added message and check that all looks well self.assertEqual(self.client.select_folder(self.base_folder)['EXISTS'], 1) @@ -316,7 +316,7 @@ def createLiveTestClass(conf, use_uid): resp = self.client.fetch(self.client.search()[0], ('RFC822', 'FLAGS', 'INTERNALDATE')) self.assertEqual(len(resp), 1) - msginfo = resp.values()[0] + msginfo = tuple(resp.values())[0] # Time should match the time we specified returned_msg_time = msginfo['INTERNALDATE'] @@ -336,7 +336,7 @@ def createLiveTestClass(conf, use_uid): def _flagtest(func, args, expected_flags): answer = func(msg_id, *args) - self.assertTrue(answer.has_key(msg_id)) + self.assertTrue(msg_id in answer) answer_flags = set(answer[msg_id]) answer_flags.discard(r'\Recent') # Might be present but don't care self.assertSetEqual(answer_flags, set(expected_flags)) @@ -355,7 +355,7 @@ def createLiveTestClass(conf, use_uid): def _labeltest(func, args, expected_labels): answer = func(msg_id, *args) - self.assertEquals(answer.keys(), [msg_id]) + self.assertEqual(list(answer.keys()), [msg_id]) actual_labels = set(answer[msg_id]) self.assertSetEqual(actual_labels, set(expected_labels)) @@ -566,7 +566,7 @@ def createLiveTestClass(conf, use_uid): responses = self.client.idle_check(timeout=5) text, more_responses = self.client.idle_done() self.assertIn((1, 'EXISTS'), responses) - self.assertTrue(isinstance(text, str)) + self.assertTrue(isinstance(text, text_type)) self.assertGreater(len(text), 0) self.assertTrue(isinstance(more_responses, list)) @@ -578,7 +578,7 @@ def createLiveTestClass(conf, use_uid): text, responses = self.client.idle_done() self.assertIn((2, 'EXISTS'), responses) - self.assertTrue(isinstance(text, str)) + self.assertTrue(isinstance(text, text_type)) self.assertGreater(len(text), 0) def test_noop(self): @@ -586,9 +586,9 @@ def createLiveTestClass(conf, use_uid): # Initially there should be no responses text, resps = self.client.noop() - self.assertTrue(isinstance(text, str)) + self.assertTrue(isinstance(text, text_type)) self.assertGreater(len(text), 0) - self.assertEquals(resps, []) + self.assertEqual(resps, []) # Start a new connection and upload a new message client2 = create_client_from_config(conf) @@ -597,7 +597,7 @@ def createLiveTestClass(conf, use_uid): # Check for this addition in the NOOP data msg, resps = self.client.noop() - self.assertTrue(isinstance(text, str)) + self.assertTrue(isinstance(text, text_type)) self.assertGreater(len(text), 0) self.assertTrue(isinstance(resps, list)) self.assertIn((1, 'EXISTS'), resps) @@ -607,7 +607,7 @@ def createLiveTestClass(conf, use_uid): # Test empty mailbox text, resps = self.client.expunge() - self.assertTrue(isinstance(text, str)) + self.assertTrue(isinstance(text, text_type)) self.assertGreater(len(text), 0) # Some servers return nothing while others (e.g. Exchange) return (0, 'EXISTS') self.assertIn(resps, ([], [(0, 'EXISTS')])) @@ -617,7 +617,7 @@ def createLiveTestClass(conf, use_uid): msg, resps = self.client.expunge() - self.assertTrue(isinstance(text, str)) + self.assertTrue(isinstance(text, text_type)) self.assertGreater(len(text), 0) self.assertTrue(isinstance(resps, list)) if not self.is_gmail(): @@ -639,7 +639,7 @@ def createLiveTestClass(conf, use_uid): def lower_if_str(val): - if isinstance(val, string_types): + if isinstance(val, text_type): return val.lower() return val diff --git a/imapclient/response_lexer.py b/imapclient/response_lexer.py index 85073f1..bb05e92 100644 --- a/imapclient/response_lexer.py +++ b/imapclient/response_lexer.py @@ -19,7 +19,6 @@ from __future__ import unicode_literals __all__ = ["Lexer"] from . import six -from .pycompat import iter_as_bytes, to_native_str class TokenSource(object): """ @@ -40,11 +39,11 @@ class TokenSource(object): def __iter__(self): return self.src -CTRL_CHARS = b''.join([bytes(chr(ch), 'latin-1') for ch in range(32)]) -SPECIALS = b' ()%"[' + CTRL_CHARS -ALL_CHARS = [bytes(chr(ch), 'latin-1') for ch in range(256)] +CTRL_CHARS = ''.join([chr(ch) for ch in range(32)]) +SPECIALS = ' ()%"[' + CTRL_CHARS +ALL_CHARS = [chr(ch) for ch in range(256)] NON_SPECIALS = frozenset([ch for ch in ALL_CHARS if ch not in SPECIALS]) -WHITESPACE = frozenset(iter_as_bytes(b' \t\r\n')) +WHITESPACE = frozenset(' \t\r\n') class Lexer(object): "A lexical analyzer class for IMAP" @@ -60,19 +59,19 @@ class Lexer(object): token = '' try: for nextchar in stream_i: - if escape and nextchar == b"\\": + if escape and nextchar == "\\": escaper = nextchar nextchar = six.next(stream_i) if nextchar != escaper and nextchar != end_char: - token += to_native_str(escaper.decode) + token += escaper.decode elif nextchar == end_char: break - token += to_native_str(nextchar) + token += nextchar else: - raise ValueError("No closing '%s'" % to_native_str(end_char)) + raise ValueError("No closing '%s'" % end_char) except StopIteration: - raise ValueError("No closing '%s'" % to_native_str(end_char)) - return token + to_native_str(end_char) + raise ValueError("No closing '%s'" % end_char) + return token + end_char def read_token_stream(self, stream_i): whitespace = WHITESPACE @@ -90,20 +89,20 @@ class Lexer(object): token = '' for nextchar in stream_i: if nextchar in wordchars: - token += to_native_str(nextchar) - elif nextchar == b'[': - token += to_native_str(nextchar) + read_until(stream_i, b']', escape=False) + token += nextchar + elif nextchar == '[': + token += nextchar + read_until(stream_i, ']', escape=False) else: if nextchar in whitespace: yield token - elif nextchar == b'"': + elif nextchar == '"': assert not token - yield to_native_str(nextchar) + read_until(stream_i, nextchar) + yield nextchar + read_until(stream_i, nextchar) else: # Other punctuation, eg. "(". This ends the current token. if token: yield token - yield to_native_str(nextchar) + yield nextchar break else: if token: @@ -136,15 +135,15 @@ class LiteralHandlingIter: # A 'record' with a string which includes a literal marker, and # the literal itself. self.src_text = resp_record[0] - assert self.src_text.endswith(b"}"), self.src_text - self.literal = to_native_str(resp_record[1]) + assert self.src_text.endswith("}"), self.src_text + self.literal = resp_record[1] else: # just a line with no literals. self.src_text = resp_record self.literal = None def __iter__(self): - return PushableIterator(iter_as_bytes(self.src_text)) + return PushableIterator(self.src_text) class PushableIterator(object): diff --git a/imapclient/response_parser.py b/imapclient/response_parser.py index aec73ca..dd298fb 100644 --- a/imapclient/response_parser.py +++ b/imapclient/response_parser.py @@ -35,12 +35,12 @@ class ParseError(ValueError): pass -def parse_response(text): +def parse_response(data): """Pull apart IMAP command responses. Returns nested tuples of appropriately typed objects. """ - return tuple(gen_parsed_response(text)) + return tuple(gen_parsed_response(data)) def gen_parsed_response(text): @@ -59,7 +59,8 @@ def gen_parsed_response(text): raise ParseError("%s: %s" % (str(err), token)) -def parse_fetch_response(text, normalise_times=True, uid_is_key=True): +def parse_fetch_response(text, normalise_times=True, uid_is_key=True, + folder_encode=True): """Pull apart IMAP FETCH responses as returned by imaplib. Returns a dictionary, keyed by message ID. Each value a dictionary @@ -142,13 +143,13 @@ class BodyData(tuple): def _convert_INTERNALDATE(date_string, normalise_times=True): - mo = imaplib.InternalDate.match(b'INTERNALDATE "' + date_string + '"') + mo = imaplib.InternalDate.match(bytes('INTERNALDATE "%s"' % date_string, 'latin-1')) if not mo: raise ValueError("couldn't parse date %r" % date_string) zoneh = int(mo.group('zoneh')) zonem = (zoneh * 60) + int(mo.group('zonem')) - if mo.group('zonen') == '-': + if mo.group('zonen') == b'-': zonem = -zonem tz = FixedOffset(zonem) -- 2.43.0