Bluez support cleanup.
[wammu.git] / Wammu / IMAP.py
blobc5679ec5bf89a8c4e90f6843fe16a6e49609effe
1 # -*- coding: UTF-8 -*-
2 # vim: expandtab sw=4 ts=4 sts=4:
3 '''
4 Wammu - Phone manager
5 IMAP UTF-7 codec
6 '''
7 __author__ = 'Michal Čihař'
8 __email__ = 'michal@cihar.com'
9 __license__ = '''
10 Copyright (c) 2003 - 2007 Michal Čihař
12 This program is free software; you can redistribute it and/or modify it
13 under the terms of the GNU General Public License version 2 as published by
14 the Free Software Foundation.
16 This program is distributed in the hope that it will be useful, but WITHOUT
17 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
18 FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
19 more details.
21 You should have received a copy of the GNU General Public License along with
22 this program; if not, write to the Free Software Foundation, Inc.,
23 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
24 '''
26 import codecs
27 def modified_base64(s):
28 s_utf7 = s.encode('utf-7')
29 return s_utf7[1:-1].replace('/', ',')
31 def modified_unbase64(s):
32 s_utf7 = '+' + s.replace(',', '/') + '-'
33 return unicode(s_utf7, 'utf-7')
35 def encoder(s):
36 r = []
37 _in = []
38 for c in s:
39 if ord(c) in (range(0x20, 0x26) + range(0x27, 0x7f)):
40 if _in:
41 r.extend(['&', modified_base64(''.join(_in)), '-'])
42 del _in[:]
43 r.append(str(c))
44 elif c == '&':
45 if _in:
46 r.extend(['&', modified_base64(''.join(_in)), '-'])
47 del _in[:]
48 r.append('&-')
49 else:
50 _in.append(c)
51 if _in:
52 r.extend(['&', modified_base64(''.join(_in)), '-'])
53 return (''.join(r), len(s))
55 def decoder(s):
56 r = []
57 decode = []
58 for c in s:
59 if c == '&' and not decode:
60 decode.append('&')
61 elif c == '-' and decode:
62 if len(decode) == 1:
63 r.append('&')
64 else:
65 r.append(modified_unbase64(''.join(decode[1:])))
66 decode = []
67 elif decode:
68 decode.append(c)
69 else:
70 r.append(c)
71 if decode:
72 r.append(modified_unbase64(''.join(decode[1:])))
73 return (u''.join(r), len(s))
75 class StreamReader(codecs.StreamReader):
76 def decode(self, s, errors='strict'):
77 return decoder(s)
79 class StreamWriter(codecs.StreamWriter):
80 def decode(self, s, errors='strict'):
81 return encoder(s)
83 def imap4_utf_7(name):
84 if name == 'imap4-utf-7':
85 return (encoder, decoder, StreamReader, StreamWriter)
87 codecs.register(imap4_utf_7)