~didrocks/unity/altf10

6 by Aaron Bentley
Use constants.
1
import httplib
11 by Aaron Bentley
Start working on GET.
2
import simplejson
3
from urlparse import urlunparse
4
from urllib import (
5
    quote,
6
    urlencode,
7
)
8
44 by Curtis Hovey
Move errors to their own module.
9
from grackle.error import (
52 by Curtis Hovey
Added support for hide_message.
10
    MessageIdNotFound,
44 by Curtis Hovey
Move errors to their own module.
11
    UnparsableDateRange,
12
    UnsupportedDisplayType,
13
    UnsupportedOrder,
35.1.4 by Curtis Hovey
Added SUPPORTED_DISPLAY_TYPES.
14
    )
15
16
7 by Aaron Bentley
Fix URLs etc.
17
class GrackleClient:
34 by Aaron Bentley
Cleanup
18
    """Class for accessing Grackle web service."""
7 by Aaron Bentley
Fix URLs etc.
19
20
    def __init__(self, host, port):
34 by Aaron Bentley
Cleanup
21
        """Constructor.
22
23
        :param host: The name of the server.
24
        :param port: The port providing Grackle service.
25
        """
7 by Aaron Bentley
Fix URLs etc.
26
        self.host = host
27
        self.port = port
11 by Aaron Bentley
Start working on GET.
28
        self.netloc = '%s:%d' % (host, port)
29
18 by Aaron Bentley
archive_name -> archive_id
30
    def archive_url(self, archive_id, query):
34 by Aaron Bentley
Cleanup
31
        """Return the URL for an archive
32
33
        :param archive_id: The id of the archive to generate the URL for.
34
        :param query: The query to use in the URL, as a dict.
35
        """
26 by Aaron Bentley
Implement an archive namespace.
36
        path = '/archive/%s' % quote(archive_id)
15 by Aaron Bentley
Test filtering by message-id.
37
        query_string = urlencode(query)
38
        return urlunparse(('http', self.netloc, path, '', query_string, ''))
11 by Aaron Bentley
Start working on GET.
39
40
    def _get_connection(self):
41
        return httplib.HTTPConnection(self.host, self.port)
42
34 by Aaron Bentley
Cleanup
43
    def _method_archive(self, method, archive_id, query, body=None):
44
        """Perform an HTTP method on an archive's URL."""
18 by Aaron Bentley
archive_name -> archive_id
45
        url = self.archive_url(archive_id, query)
11 by Aaron Bentley
Start working on GET.
46
        connection = self._get_connection()
34 by Aaron Bentley
Cleanup
47
        connection.request(method, url, body)
11 by Aaron Bentley
Start working on GET.
48
        return connection.getresponse()
49
52 by Curtis Hovey
Added support for hide_message.
50
    def message_url(self, archive_id, message_id, query):
51
        """Return the URL for a message
52
53
        :param archive_id: The id of the archive to generate the URL for.
54
        :param query: The query to use in the URL, as a dict.
55
        """
56
        path = '/archive/%s/%s' % (quote(archive_id), quote(message_id))
57
        query_string = urlencode(query)
58
        return urlunparse(('http', self.netloc, path, '', query_string, ''))
59
60
    def _method_message(self, method, archive_id, message_id,
61
                        query, body=None):
62
        """Perform an HTTP method on a message's URL."""
63
        url = self.message_url(archive_id, message_id, query)
64
        connection = self._get_connection()
65
        connection.request(method, url, body)
66
        return connection.getresponse()
67
46 by Curtis Hovey
Implemented a partial put into the MemoryStore.
68
    def put_archive(self, archive_id, mbox=None):
69
        """Create an archive.
70
71
        :param archive_id: The archive id.
72
        :param mbox: An optional mbox with messages to add to the new archive.
73
        """
74
        response = self._method_archive(
75
            'POST', '', {'archive_id': archive_id}, None)
76
        response.read()
77
        if response.status == httplib.BAD_REQUEST:
78
            raise Exception('wtf')
79
        elif response.status == httplib.CREATED:
80
            return
81
        else:
82
            raise Exception('!!')
83
18 by Aaron Bentley
archive_name -> archive_id
84
    def put_message(self, archive_id, key, file_obj):
34 by Aaron Bentley
Cleanup
85
        """Put a message into an archive.
86
87
        :param archive_id: The archive to put the message into.
88
        :param key: An arbitrary identifier that can later be used to retrieve
89
            the message.
90
        :param file_obj: The raw text of the message, as a file.
91
        """
46 by Curtis Hovey
Implemented a partial put into the MemoryStore.
92
        path = '%s/%s' % (archive_id, key)
34 by Aaron Bentley
Cleanup
93
        response = self._method_archive(
46 by Curtis Hovey
Implemented a partial put into the MemoryStore.
94
            'POST', path, {}, file_obj.read())
35.1.1 by Curtis Hovey
Hush lint.
95
        response.read()
7 by Aaron Bentley
Fix URLs etc.
96
        if response.status == httplib.BAD_REQUEST:
97
            raise Exception('wtf')
98
        elif response.status == httplib.CREATED:
99
            return
100
        else:
101
            raise Exception('!!')
11 by Aaron Bentley
Start working on GET.
102
38 by Curtis Hovey
Added basic handling of date_range.
103
    def get_messages(self, archive_id, message_ids=None, date_range=None,
104
                     limit=None, memo=None, order=None, headers=None,
105
                     include_hidden=False, max_body_length=None,
35.1.5 by Curtis Hovey
Moved the display_type arg.
106
                     display_type='all'):
34 by Aaron Bentley
Cleanup
107
        """Retrieve specified messages.
108
109
        :param archive_id: The archive to retrieve messages from.
110
        :param message_ids: (optional) Retrieve only messages with these ids.
38 by Curtis Hovey
Added basic handling of date_range.
111
        :param date_range: Retrieve the messages from or between a range of
112
            dates. Example: 2012-01-01..2012-01-31 retrieve all the messages
113
            between the 01 and 31 of January, including message from 01
114
            and 31.
34 by Aaron Bentley
Cleanup
115
        :param limit: The maximum number of messages to return.  The server
116
            may, at its discretion, return fewer.
117
        :param memo: (optional) Opaque identifier describing the position in
118
            the list of messages to return.  The combination of a memo and a
119
            limit describes a batch of results.  If not specified, the start
120
            is used.
121
        :param order: The order to return results in.  Supported orders are
122
            determined by the server.  See test_client.SUPPORTED_ORDERS for an
123
            example.
124
        :param headers: The headers to include in the message.  Only headers
125
            actually present in the message will be provided.  If unspecified,
126
            most headers will be included.
127
        :param max_body_length: The maximum length for a message's body.  When
128
            multiple messages are nested (as with a thread), this applies to
129
            each message's body, not the aggregate length of all messages'
130
            bodies.
131
        :param include_hidden: If true, include messages that have been
132
            flagged "hidden" in the results.
35.1.5 by Curtis Hovey
Moved the display_type arg.
133
        :param display_type: Adjust the message content to meet the needs of
134
            the intended display. Valid values are:
135
            all: (the default) include all message content.
136
            text-only: include only plain/text parts; exclude all other parts.
137
            headers-only: include only the message headers.
34 by Aaron Bentley
Cleanup
138
        """
11 by Aaron Bentley
Start working on GET.
139
        parameters = {}
140
        if message_ids is not None:
13 by Aaron Bentley
Retrieve messages.
141
            parameters['message_ids'] = message_ids
38 by Curtis Hovey
Added basic handling of date_range.
142
        if date_range is not None:
143
            parameters['date_range'] = date_range
19 by Aaron Bentley
Implement memo/limit support.
144
        if limit is not None:
145
            parameters['limit'] = limit
146
        if memo is not None:
147
            parameters['memo'] = memo
20 by Aaron Bentley
Support order by date
148
        if order is not None:
149
            parameters['order'] = order
27 by Aaron Bentley
get_messages supports header parameter.
150
        if headers is not None:
151
            parameters['headers'] = headers
35.1.5 by Curtis Hovey
Moved the display_type arg.
152
        if max_body_length is not None:
153
            parameters['max_body_length'] = max_body_length
154
        parameters['display_type'] = display_type
29 by Aaron Bentley
implement include_hidden.
155
        parameters['include_hidden'] = include_hidden
11 by Aaron Bentley
Start working on GET.
156
        query = {'parameters': simplejson.dumps(parameters)}
34 by Aaron Bentley
Cleanup
157
        response = self._method_archive('GET', archive_id, query)
21 by Aaron Bentley
Test unsupported orders.
158
        if response.status == httplib.BAD_REQUEST:
35.1.8 by Curtis Hovey
Use the exception __doc__ to ensure client and server can match exceptions.
159
            if response.reason == UnsupportedOrder.__doc__:
35.1.7 by Curtis Hovey
Moved the handling of unsupported display_type to server.
160
                raise UnsupportedOrder
35.1.8 by Curtis Hovey
Use the exception __doc__ to ensure client and server can match exceptions.
161
            elif response.reason == UnsupportedDisplayType.__doc__:
35.1.7 by Curtis Hovey
Moved the handling of unsupported display_type to server.
162
                raise UnsupportedDisplayType
39 by Curtis Hovey
Raise UnparsableDateRange when the date cannot be parsed.
163
            elif response.reason == UnparsableDateRange.__doc__:
164
                raise UnparsableDateRange
35.1.7 by Curtis Hovey
Moved the handling of unsupported display_type to server.
165
            else:
166
                raise ValueError('Bad request')
13 by Aaron Bentley
Retrieve messages.
167
        data = response.read()
168
        return simplejson.loads(data)
52 by Curtis Hovey
Added support for hide_message.
169
170
    def hide_message(self, archive_id, message_id, hidden):
171
        parameters = {
172
            'hidden': hidden,
173
            }
174
        query = {'parameters': simplejson.dumps(parameters)}
175
        response = self._method_message('POST', archive_id, message_id, query)
176
        if response.status == httplib.BAD_REQUEST:
177
            if response.reason == MessageIdNotFound.__doc__:
178
                raise MessageIdNotFound
179
        data = response.read()
180
        return simplejson.loads(data)