~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
46 by Curtis Hovey
Implemented a partial put into the MemoryStore.
50
    def put_archive(self, archive_id, mbox=None):
51
        """Create an archive.
52
53
        :param archive_id: The archive id.
54
        :param mbox: An optional mbox with messages to add to the new archive.
55
        """
56
        response = self._method_archive(
57
            'POST', '', {'archive_id': archive_id}, None)
58
        response.read()
59
        if response.status == httplib.BAD_REQUEST:
60
            raise Exception('wtf')
61
        elif response.status == httplib.CREATED:
62
            return
63
        else:
64
            raise Exception('!!')
65
18 by Aaron Bentley
archive_name -> archive_id
66
    def put_message(self, archive_id, key, file_obj):
34 by Aaron Bentley
Cleanup
67
        """Put a message into an archive.
68
69
        :param archive_id: The archive to put the message into.
70
        :param key: An arbitrary identifier that can later be used to retrieve
71
            the message.
72
        :param file_obj: The raw text of the message, as a file.
73
        """
46 by Curtis Hovey
Implemented a partial put into the MemoryStore.
74
        path = '%s/%s' % (archive_id, key)
34 by Aaron Bentley
Cleanup
75
        response = self._method_archive(
46 by Curtis Hovey
Implemented a partial put into the MemoryStore.
76
            'POST', path, {}, file_obj.read())
35.1.1 by Curtis Hovey
Hush lint.
77
        response.read()
7 by Aaron Bentley
Fix URLs etc.
78
        if response.status == httplib.BAD_REQUEST:
79
            raise Exception('wtf')
80
        elif response.status == httplib.CREATED:
81
            return
82
        else:
83
            raise Exception('!!')
11 by Aaron Bentley
Start working on GET.
84
38 by Curtis Hovey
Added basic handling of date_range.
85
    def get_messages(self, archive_id, message_ids=None, date_range=None,
86
                     limit=None, memo=None, order=None, headers=None,
87
                     include_hidden=False, max_body_length=None,
35.1.5 by Curtis Hovey
Moved the display_type arg.
88
                     display_type='all'):
34 by Aaron Bentley
Cleanup
89
        """Retrieve specified messages.
90
91
        :param archive_id: The archive to retrieve messages from.
92
        :param message_ids: (optional) Retrieve only messages with these ids.
38 by Curtis Hovey
Added basic handling of date_range.
93
        :param date_range: Retrieve the messages from or between a range of
94
            dates. Example: 2012-01-01..2012-01-31 retrieve all the messages
95
            between the 01 and 31 of January, including message from 01
96
            and 31.
34 by Aaron Bentley
Cleanup
97
        :param limit: The maximum number of messages to return.  The server
98
            may, at its discretion, return fewer.
99
        :param memo: (optional) Opaque identifier describing the position in
100
            the list of messages to return.  The combination of a memo and a
101
            limit describes a batch of results.  If not specified, the start
102
            is used.
103
        :param order: The order to return results in.  Supported orders are
104
            determined by the server.  See test_client.SUPPORTED_ORDERS for an
105
            example.
106
        :param headers: The headers to include in the message.  Only headers
107
            actually present in the message will be provided.  If unspecified,
108
            most headers will be included.
109
        :param max_body_length: The maximum length for a message's body.  When
110
            multiple messages are nested (as with a thread), this applies to
111
            each message's body, not the aggregate length of all messages'
112
            bodies.
113
        :param include_hidden: If true, include messages that have been
114
            flagged "hidden" in the results.
35.1.5 by Curtis Hovey
Moved the display_type arg.
115
        :param display_type: Adjust the message content to meet the needs of
116
            the intended display. Valid values are:
117
            all: (the default) include all message content.
118
            text-only: include only plain/text parts; exclude all other parts.
119
            headers-only: include only the message headers.
34 by Aaron Bentley
Cleanup
120
        """
11 by Aaron Bentley
Start working on GET.
121
        parameters = {}
122
        if message_ids is not None:
13 by Aaron Bentley
Retrieve messages.
123
            parameters['message_ids'] = message_ids
38 by Curtis Hovey
Added basic handling of date_range.
124
        if date_range is not None:
125
            parameters['date_range'] = date_range
19 by Aaron Bentley
Implement memo/limit support.
126
        if limit is not None:
127
            parameters['limit'] = limit
128
        if memo is not None:
129
            parameters['memo'] = memo
20 by Aaron Bentley
Support order by date
130
        if order is not None:
131
            parameters['order'] = order
27 by Aaron Bentley
get_messages supports header parameter.
132
        if headers is not None:
133
            parameters['headers'] = headers
35.1.5 by Curtis Hovey
Moved the display_type arg.
134
        if max_body_length is not None:
135
            parameters['max_body_length'] = max_body_length
136
        parameters['display_type'] = display_type
29 by Aaron Bentley
implement include_hidden.
137
        parameters['include_hidden'] = include_hidden
11 by Aaron Bentley
Start working on GET.
138
        query = {'parameters': simplejson.dumps(parameters)}
34 by Aaron Bentley
Cleanup
139
        response = self._method_archive('GET', archive_id, query)
21 by Aaron Bentley
Test unsupported orders.
140
        if response.status == httplib.BAD_REQUEST:
35.1.8 by Curtis Hovey
Use the exception __doc__ to ensure client and server can match exceptions.
141
            if response.reason == UnsupportedOrder.__doc__:
35.1.7 by Curtis Hovey
Moved the handling of unsupported display_type to server.
142
                raise UnsupportedOrder
35.1.8 by Curtis Hovey
Use the exception __doc__ to ensure client and server can match exceptions.
143
            elif response.reason == UnsupportedDisplayType.__doc__:
35.1.7 by Curtis Hovey
Moved the handling of unsupported display_type to server.
144
                raise UnsupportedDisplayType
39 by Curtis Hovey
Raise UnparsableDateRange when the date cannot be parsed.
145
            elif response.reason == UnparsableDateRange.__doc__:
146
                raise UnparsableDateRange
35.1.7 by Curtis Hovey
Moved the handling of unsupported display_type to server.
147
            else:
148
                raise ValueError('Bad request')
13 by Aaron Bentley
Retrieve messages.
149
        data = response.read()
150
        return simplejson.loads(data)
52 by Curtis Hovey
Added support for hide_message.
151
152
    def hide_message(self, archive_id, message_id, hidden):
153
        parameters = {
154
            'hidden': hidden,
155
            }
156
        query = {'parameters': simplejson.dumps(parameters)}
53 by Curtis Hovey
Factor-out message methods.
157
        path = '%s/%s' % (archive_id, message_id)
158
        response = self._method_archive('POST', path, query)
52 by Curtis Hovey
Added support for hide_message.
159
        if response.status == httplib.BAD_REQUEST:
160
            if response.reason == MessageIdNotFound.__doc__:
161
                raise MessageIdNotFound
162
        data = response.read()
163
        return simplejson.loads(data)