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