7
from urlparse import parse_qs
9
from grackle.error import (
14
UnsupportedDisplayType,
19
SUPPORTED_DISPLAY_TYPES = set(['all', 'text-only', 'headers-only'])
22
SUPPORTED_ORDERS = set(
23
['date', 'author', 'subject', 'thread_newest', 'thread_oldest',
27
def threaded_messages(messages):
31
for message in messages:
32
if message.get('replies') is None:
33
threads[message['message_id']] = [message]
36
pending.append(message)
37
for message in pending:
38
threads[message['replies']].append(message)
39
return threads.values()
42
def get_body_text(message):
43
"""Return the first plain/text messaage part."""
44
if not message.is_multipart():
45
return message.get_payload()
46
for part in email.iterators.typed_subpart_iterator(message, 'multipart'):
47
subparts = part.get_payload()
48
for subpart in subparts:
49
if subpart.get_content_type() == 'text/plain':
50
return subpart.get_payload().strip()
54
def make_json_message(message_id, raw_message, hidden=False):
55
message = email.message_from_string(raw_message)
56
headers = dict(message.items())
58
'message_id': message_id,
60
# This is broken because the in-reply-to must be encoded.
61
# X-Message-ID-Hash is calculated from the Base 32.
62
'thread_id': headers.get('in-reply-to', message_id),
63
'date': headers.get('date'),
64
'subject': headers.get('subject'),
65
'author': headers.get('from'),
68
'replies': headers.get('in-reply-to'),
69
'body': get_body_text(message),
75
"""A memory-backed message store."""
77
def __init__(self, message_archives):
79
self.message_archives = message_archives
82
def is_multipart(message):
83
return isinstance(message['body'], list)
85
def put_archive(self, archive_id, raw_archive=None):
86
# XXX sinzui 2012-02-29: this needs to raise an error
87
# if the th archive_id is invalid, or the raw archive is not mbox.
88
if archive_id in self.message_archives:
89
raise ArchiveIdExists()
90
self.message_archives[archive_id] = []
92
def put_message(self, archive_id, message_id, raw_message):
93
# XXX sinzui 2012-02-29: this needs to raise an error
94
# if the th archive_id is invalid, message_id is not base32
95
# or the raw message is not an email.
96
if archive_id not in self.message_archives:
97
raise ArchiveIdNotFound()
99
raise ValueError('raw_message is not a message.')
100
json_message = make_json_message(message_id, raw_message)
101
messages = self.message_archives[archive_id]
102
messages.append(json_message)
104
def get_messages(self, archive_id, query_string):
105
"""Return matching messages.
107
:param archive_id: The archive to retrieve from.
108
:param query_string: Contains 'parameters', which is a JSON-format
109
string describing parameters.
111
query = parse_qs(query_string)
112
parameters = simplejson.loads(query['parameters'][0])
113
order = parameters.get('order')
114
messages = self.message_archives[archive_id]
115
if order is not None:
116
if order not in SUPPORTED_ORDERS:
117
raise UnsupportedOrder
118
elif order.startswith('thread_'):
119
threaded = threaded_messages(messages)
121
if order == 'thread_subject':
122
threaded.sort(key=lambda t: t[0]['subject'])
123
if order == 'thread_oldest':
124
threaded.sort(key=lambda t: min(m['date'] for m in t))
125
if order == 'thread_newest':
126
threaded.sort(key=lambda t: max(m['date'] for m in t))
127
for thread in threaded:
128
messages.extend(thread)
130
messages.sort(key=lambda m: m[order])
131
display_type = parameters.get('display_type', 'all')
132
if display_type not in SUPPORTED_DISPLAY_TYPES:
133
raise UnsupportedDisplayType
134
if 'date_range' in parameters:
136
start_date, end_date = parameters['date_range'].split('..')
137
if not start_date or not end_date:
138
raise UnparsableDateRange
140
raise UnparsableDateRange
142
for message in messages:
143
if (not parameters['include_hidden'] and message['hidden']):
145
if ('message_ids' in parameters
146
and message['message_id'] not in parameters['message_ids']):
148
if ('date_range' in parameters
149
and (message['date'] < start_date
150
or message['date'] > end_date)):
152
message = dict(message)
153
if 'headers' in parameters:
155
(k, v) for k, v in message['headers'].iteritems()
156
if k in parameters['headers'])
157
message['headers'] = headers
158
if display_type == 'headers-only':
160
elif display_type == 'text-only' and self.is_multipart(message):
162
part.get_payload() for part in message['body']
163
if part.get_content_type() == 'text/plain']
164
message['body'] = '\n\n'.join(text_parts)
165
elif display_type == 'all' and self.is_multipart(message):
166
parts = [str(part.get_payload()) for part in message['body']]
167
message['body'] = '\n\n'.join(parts)
168
max_body = parameters.get('max_body_length')
169
if max_body is not None and display_type != 'headers-only':
170
message['body'] = message['body'][:max_body]
171
new_messages.append(message)
172
messages = new_messages
173
limit = parameters.get('limit', 100)
174
memo = parameters.get('memo')
175
message_id_indices = dict(
176
(m['message_id'], idx) for idx, m in enumerate(messages))
180
start = message_id_indices[memo.encode('rot13')]
182
previous_memo = messages[start - 1]['message_id'].encode('rot13')
185
end = min(start + limit, len(messages))
186
if end < len(messages):
187
next_memo = messages[end]['message_id'].encode('rot13')
190
messages = messages[start:end]
193
'messages': messages,
194
'next_memo': next_memo,
195
'previous_memo': previous_memo
199
def hide_message(self, archive_id, message_id, query_string):
200
"""Change the visbility of a message in an archive.
202
:param archive_id: The archive to retrieve from.
203
:param query_string: Contains 'parameters', which is a JSON-format
204
string describing parameters.
206
query = parse_qs(query_string)
207
parameters = simplejson.loads(query['parameters'][0])
208
hidden = parameters['hidden']
209
messages = self.message_archives[archive_id]
210
for message in messages:
211
if message['message_id'] == message_id:
212
message['hidden'] = hidden
214
'message_id': message_id,
218
raise MessageIdNotFound