~didrocks/unity/altf10

« back to all changes in this revision

Viewing changes to grackle/client.py

  • Committer: Curtis Hovey
  • Date: 2012-03-17 21:21:37 UTC
  • Revision ID: curtis.hovey@canonical.com-20120317212137-r7zonl5ksenpa5ci
Save the scheme.

Show diffs side-by-side

added added

removed removed

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