Debian Codegraph @

googleapiclient/channel.py

raw
1 # Copyright 2014 Google Inc. All Rights Reserved.
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
6 #
7 # http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14
15 """Channel notifications support.
16
17 Classes and functions to support channel subscriptions and notifications
18 on those channels.
19
20 Notes:
21 - This code is based on experimental APIs and is subject to change.
22 - Notification does not do deduplication of notification ids, that's up to
23 the receiver.
24 - Storing the Channel between calls is up to the caller.
25
26
27 Example setting up a channel:
28
29 # Create a new channel that gets notifications via webhook.
30 channel = new_webhook_channel("https://example.com/my_web_hook")
31
32 # Store the channel, keyed by 'channel.id'. Store it before calling the
33 # watch method because notifications may start arriving before the watch
34 # method returns.
35 ...
36
37 resp = service.objects().watchAll(
38 bucket="some_bucket_id", body=channel.body()).execute()
39 channel.update(resp)
40
41 # Store the channel, keyed by 'channel.id'. Store it after being updated
42 # since the resource_id value will now be correct, and that's needed to
43 # stop a subscription.
44 ...
45
46
47 An example Webhook implementation using webapp2. Note that webapp2 puts
48 headers in a case insensitive dictionary, as headers aren't guaranteed to
49 always be upper case.
50
51 id = self.request.headers[X_GOOG_CHANNEL_ID]
52
53 # Retrieve the channel by id.
54 channel = ...
55
56 # Parse notification from the headers, including validating the id.
57 n = notification_from_headers(channel, self.request.headers)
58
59 # Do app specific stuff with the notification here.
60 if n.resource_state == 'sync':
61 # Code to handle sync state.
62 elif n.resource_state == 'exists':
63 # Code to handle the exists state.
64 elif n.resource_state == 'not_exists':
65 # Code to handle the not exists state.
66
67
68 Example of unsubscribing.
69
70 service.channels().stop(channel.body()).execute()
71 """
72 from __future__ import absolute_import
73
74 import datetime
75 import uuid
76
77 from googleapiclient import _helpers as util
78 from googleapiclient import errors
79
80 # The unix time epoch starts at midnight 1970.
81 EPOCH = datetime.datetime(1970, 1, 1)
82
83 # Map the names of the parameters in the JSON channel description to
84 # the parameter names we use in the Channel class.
85 CHANNEL_PARAMS = {
86 "address": "address",
87 "id": "id",
88 "expiration": "expiration",
89 "params": "params",
90 "resourceId": "resource_id",
91 "resourceUri": "resource_uri",
92 "type": "type",
93 "token": "token",
94 }
95
96 X_GOOG_CHANNEL_ID = "X-GOOG-CHANNEL-ID"
97 X_GOOG_MESSAGE_NUMBER = "X-GOOG-MESSAGE-NUMBER"
98 X_GOOG_RESOURCE_STATE = "X-GOOG-RESOURCE-STATE"
99 X_GOOG_RESOURCE_URI = "X-GOOG-RESOURCE-URI"
100 X_GOOG_RESOURCE_ID = "X-GOOG-RESOURCE-ID"
101
102
103 def _upper_header_keys(headers):
104 new_headers = {}
105 for k, v in headers.items():
106 new_headers[k.upper()] = v
107 return new_headers
108
109
110 class Notification(object):
111 """A Notification from a Channel.
112
113 Notifications are not usually constructed directly, but are returned
114 from functions like notification_from_headers().
115
116 Attributes:
117 message_number: int, The unique id number of this notification.
118 state: str, The state of the resource being monitored.
119 uri: str, The address of the resource being monitored.
120 resource_id: str, The unique identifier of the version of the resource at
121 this event.
122 """
123
124 @util.positional(5)
125 def __init__(self, message_number, state, resource_uri, resource_id):
126 """Notification constructor.
127
128 Args:
129 message_number: int, The unique id number of this notification.
130 state: str, The state of the resource being monitored. Can be one
131 of "exists", "not_exists", or "sync".
132 resource_uri: str, The address of the resource being monitored.
133 resource_id: str, The identifier of the watched resource.
134 """
135 self.message_number = message_number
136 self.state = state
137 self.resource_uri = resource_uri
138 self.resource_id = resource_id
139
140
141 class Channel(object):
142 """A Channel for notifications.
143
144 Usually not constructed directly, instead it is returned from helper
145 functions like new_webhook_channel().
146
147 Attributes:
148 type: str, The type of delivery mechanism used by this channel. For
149 example, 'web_hook'.
150 id: str, A UUID for the channel.
151 token: str, An arbitrary string associated with the channel that
152 is delivered to the target address with each event delivered
153 over this channel.
154 address: str, The address of the receiving entity where events are
155 delivered. Specific to the channel type.
156 expiration: int, The time, in milliseconds from the epoch, when this
157 channel will expire.
158 params: dict, A dictionary of string to string, with additional parameters
159 controlling delivery channel behavior.
160 resource_id: str, An opaque id that identifies the resource that is
161 being watched. Stable across different API versions.
162 resource_uri: str, The canonicalized ID of the watched resource.
163 """
164
165 @util.positional(5)
166 def __init__(
167 self,
168 type,
169 id,
170 token,
171 address,
172 expiration=None,
173 params=None,
174 resource_id="",
175 resource_uri="",
176 ):
177 """Create a new Channel.
178
179 In user code, this Channel constructor will not typically be called
180 manually since there are functions for creating channels for each specific
181 type with a more customized set of arguments to pass.
182
183 Args:
184 type: str, The type of delivery mechanism used by this channel. For
185 example, 'web_hook'.
186 id: str, A UUID for the channel.
187 token: str, An arbitrary string associated with the channel that
188 is delivered to the target address with each event delivered
189 over this channel.
190 address: str, The address of the receiving entity where events are
191 delivered. Specific to the channel type.
192 expiration: int, The time, in milliseconds from the epoch, when this
193 channel will expire.
194 params: dict, A dictionary of string to string, with additional parameters
195 controlling delivery channel behavior.
196 resource_id: str, An opaque id that identifies the resource that is
197 being watched. Stable across different API versions.
198 resource_uri: str, The canonicalized ID of the watched resource.
199 """
200 self.type = type
201 self.id = id
202 self.token = token
203 self.address = address
204 self.expiration = expiration
205 self.params = params
206 self.resource_id = resource_id
207 self.resource_uri = resource_uri
208
209 def body(self):
210 """Build a body from the Channel.
211
212 Constructs a dictionary that's appropriate for passing into watch()
213 methods as the value of body argument.
214
215 Returns:
216 A dictionary representation of the channel.
217 """
218 result = {
219 "id": self.id,
220 "token": self.token,
221 "type": self.type,
222 "address": self.address,
223 }
224 if self.params:
225 result["params"] = self.params
226 if self.resource_id:
227 result["resourceId"] = self.resource_id
228 if self.resource_uri:
229 result["resourceUri"] = self.resource_uri
230 if self.expiration:
231 result["expiration"] = self.expiration
232
233 return result
234
235 def update(self, resp):
236 """Update a channel with information from the response of watch().
237
238 When a request is sent to watch() a resource, the response returned
239 from the watch() request is a dictionary with updated channel information,
240 such as the resource_id, which is needed when stopping a subscription.
241
242 Args:
243 resp: dict, The response from a watch() method.
244 """
245 for json_name, param_name in CHANNEL_PARAMS.items():
246 value = resp.get(json_name)
247 if value is not None:
248 setattr(self, param_name, value)
249
250
251 def notification_from_headers(channel, headers):
252 """Parse a notification from the webhook request headers, validate
253 the notification, and return a Notification object.
254
255 Args:
256 channel: Channel, The channel that the notification is associated with.
257 headers: dict, A dictionary like object that contains the request headers
258 from the webhook HTTP request.
259
260 Returns:
261 A Notification object.
262
263 Raises:
264 errors.InvalidNotificationError if the notification is invalid.
265 ValueError if the X-GOOG-MESSAGE-NUMBER can't be converted to an int.
266 """
267 headers = _upper_header_keys(headers)
268 channel_id = headers[X_GOOG_CHANNEL_ID]
269 if channel.id != channel_id:
270 raise errors.InvalidNotificationError(
271 "Channel id mismatch: %s != %s" % (channel.id, channel_id)
272 )
273 else:
274 message_number = int(headers[X_GOOG_MESSAGE_NUMBER])
275 state = headers[X_GOOG_RESOURCE_STATE]
276 resource_uri = headers[X_GOOG_RESOURCE_URI]
277 resource_id = headers[X_GOOG_RESOURCE_ID]
278 return Notification(message_number, state, resource_uri, resource_id)
279
280
281 @util.positional(2)
282 def new_webhook_channel(url, token=None, expiration=None, params=None):
283 """Create a new webhook Channel.
284
285 Args:
286 url: str, URL to post notifications to.
287 token: str, An arbitrary string associated with the channel that
288 is delivered to the target address with each notification delivered
289 over this channel.
290 expiration: datetime.datetime, A time in the future when the channel
291 should expire. Can also be None if the subscription should use the
292 default expiration. Note that different services may have different
293 limits on how long a subscription lasts. Check the response from the
294 watch() method to see the value the service has set for an expiration
295 time.
296 params: dict, Extra parameters to pass on channel creation. Currently
297 not used for webhook channels.
298 """
299 expiration_ms = 0
300 if expiration:
301 delta = expiration - EPOCH
302 expiration_ms = (
303 delta.microseconds / 1000 + (delta.seconds + delta.days * 24 * 3600) * 1000
304 )
305 if expiration_ms < 0:
306 expiration_ms = 0
307
308 return Channel(
309 "web_hook",
310 str(uuid.uuid4()),
311 token,
312 url,
313 expiration=expiration_ms,
314 params=params,
315 )