gam7 7.3.4__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of gam7 might be problematic. Click here for more details.

Files changed (72) hide show
  1. gam/__init__.py +77555 -0
  2. gam/__main__.py +40 -0
  3. gam/atom/__init__.py +1460 -0
  4. gam/atom/auth.py +41 -0
  5. gam/atom/client.py +214 -0
  6. gam/atom/core.py +535 -0
  7. gam/atom/data.py +327 -0
  8. gam/atom/http.py +354 -0
  9. gam/atom/http_core.py +599 -0
  10. gam/atom/http_interface.py +144 -0
  11. gam/atom/mock_http.py +123 -0
  12. gam/atom/mock_http_core.py +313 -0
  13. gam/atom/mock_service.py +235 -0
  14. gam/atom/service.py +723 -0
  15. gam/atom/token_store.py +105 -0
  16. gam/atom/url.py +130 -0
  17. gam/cacerts.pem +1130 -0
  18. gam/cbcm-v1.1beta1.json +593 -0
  19. gam/contactdelegation-v1.json +249 -0
  20. gam/datastudio-v1.json +486 -0
  21. gam/gamlib/__init__.py +17 -0
  22. gam/gamlib/glaction.py +308 -0
  23. gam/gamlib/glapi.py +837 -0
  24. gam/gamlib/glcfg.py +616 -0
  25. gam/gamlib/glclargs.py +1184 -0
  26. gam/gamlib/glentity.py +831 -0
  27. gam/gamlib/glgapi.py +817 -0
  28. gam/gamlib/glgdata.py +98 -0
  29. gam/gamlib/glglobals.py +307 -0
  30. gam/gamlib/glindent.py +46 -0
  31. gam/gamlib/glmsgs.py +547 -0
  32. gam/gamlib/glskus.py +246 -0
  33. gam/gamlib/gluprop.py +279 -0
  34. gam/gamlib/glverlibs.py +33 -0
  35. gam/gamlib/yubikey.py +202 -0
  36. gam/gdata/__init__.py +825 -0
  37. gam/gdata/alt/__init__.py +20 -0
  38. gam/gdata/alt/app_engine.py +101 -0
  39. gam/gdata/alt/appengine.py +321 -0
  40. gam/gdata/apps/__init__.py +526 -0
  41. gam/gdata/apps/audit/__init__.py +1 -0
  42. gam/gdata/apps/audit/service.py +278 -0
  43. gam/gdata/apps/contacts/__init__.py +874 -0
  44. gam/gdata/apps/contacts/service.py +355 -0
  45. gam/gdata/apps/service.py +544 -0
  46. gam/gdata/apps/sites/__init__.py +283 -0
  47. gam/gdata/apps/sites/service.py +246 -0
  48. gam/gdata/service.py +1714 -0
  49. gam/gdata/urlfetch.py +247 -0
  50. gam/googleapiclient/__init__.py +27 -0
  51. gam/googleapiclient/_auth.py +167 -0
  52. gam/googleapiclient/_helpers.py +207 -0
  53. gam/googleapiclient/channel.py +315 -0
  54. gam/googleapiclient/discovery.py +1662 -0
  55. gam/googleapiclient/discovery_cache/__init__.py +78 -0
  56. gam/googleapiclient/discovery_cache/appengine_memcache.py +55 -0
  57. gam/googleapiclient/discovery_cache/base.py +46 -0
  58. gam/googleapiclient/discovery_cache/file_cache.py +145 -0
  59. gam/googleapiclient/errors.py +197 -0
  60. gam/googleapiclient/http.py +1962 -0
  61. gam/googleapiclient/mimeparse.py +183 -0
  62. gam/googleapiclient/model.py +429 -0
  63. gam/googleapiclient/schema.py +317 -0
  64. gam/googleapiclient/version.py +15 -0
  65. gam/iso8601/__init__.py +28 -0
  66. gam/iso8601/iso8601.py +160 -0
  67. gam/serviceaccountlookup-v1.json +141 -0
  68. gam/six.py +982 -0
  69. gam7-7.3.4.dist-info/METADATA +69 -0
  70. gam7-7.3.4.dist-info/RECORD +72 -0
  71. gam7-7.3.4.dist-info/WHEEL +4 -0
  72. gam7-7.3.4.dist-info/licenses/LICENSE +201 -0
gam/gdata/service.py ADDED
@@ -0,0 +1,1714 @@
1
+ #!/usr/bin/python
2
+ #
3
+ # Copyright (C) 2006,2008 Google Inc.
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+
17
+
18
+ """GDataService provides CRUD ops. and programmatic login for GData services.
19
+
20
+ Error: A base exception class for all exceptions in the gdata_client
21
+ module.
22
+
23
+ CaptchaRequired: This exception is thrown when a login attempt results in a
24
+ captcha challenge from the ClientLogin service. When this
25
+ exception is thrown, the captcha_token and captcha_url are
26
+ set to the values provided in the server's response.
27
+
28
+ BadAuthentication: Raised when a login attempt is made with an incorrect
29
+ username or password.
30
+
31
+ NotAuthenticated: Raised if an operation requiring authentication is called
32
+ before a user has authenticated.
33
+
34
+ NonAuthSubToken: Raised if a method to modify an AuthSub token is used when
35
+ the user is either not authenticated or is authenticated
36
+ through another authentication mechanism.
37
+
38
+ NonOAuthToken: Raised if a method to modify an OAuth token is used when the
39
+ user is either not authenticated or is authenticated through
40
+ another authentication mechanism.
41
+
42
+ RequestError: Raised if a CRUD request returned a non-success code.
43
+
44
+ UnexpectedReturnType: Raised if the response from the server was not of the
45
+ desired type. For example, this would be raised if the
46
+ server sent a feed when the client requested an entry.
47
+
48
+ GDataService: Encapsulates user credentials needed to perform insert, update
49
+ and delete operations with the GData API. An instance can
50
+ perform user authentication, query, insertion, deletion, and
51
+ update.
52
+
53
+ Query: Eases query URI creation by allowing URI parameters to be set as
54
+ dictionary attributes. For example a query with a feed of
55
+ '/base/feeds/snippets' and ['bq'] set to 'digital camera' will
56
+ produce '/base/feeds/snippets?bq=digital+camera' when .ToUri() is
57
+ called on it.
58
+ """
59
+
60
+
61
+ __author__ = 'api.jscudder (Jeffrey Scudder)'
62
+
63
+ import re
64
+ import urllib.request, urllib.parse, urllib.error
65
+ import urllib.parse
66
+ import lxml.etree as ElementTree
67
+ import atom.service
68
+ import gdata
69
+ import atom
70
+ import atom.http_interface
71
+ import atom.token_store
72
+
73
+
74
+ AUTH_SERVER_HOST = 'https://www.google.com'
75
+
76
+
77
+ # When requesting an AuthSub token, it is often helpful to track the scope
78
+ # which is being requested. One way to accomplish this is to add a URL
79
+ # parameter to the 'next' URL which contains the requested scope. This
80
+ # constant is the default name (AKA key) for the URL parameter.
81
+ SCOPE_URL_PARAM_NAME = 'authsub_token_scope'
82
+ # When requesting an OAuth access token or authorization of an existing OAuth
83
+ # request token, it is often helpful to track the scope(s) which is/are being
84
+ # requested. One way to accomplish this is to add a URL parameter to the
85
+ # 'callback' URL which contains the requested scope. This constant is the
86
+ # default name (AKA key) for the URL parameter.
87
+ OAUTH_SCOPE_URL_PARAM_NAME = 'oauth_token_scope'
88
+ # Default parameters for GDataService.GetWithRetries method
89
+ DEFAULT_NUM_RETRIES = 3
90
+ DEFAULT_DELAY = 1
91
+ DEFAULT_BACKOFF = 2
92
+
93
+
94
+ def lookup_scopes(service_name):
95
+ """Finds the scope URLs for the desired service.
96
+
97
+ In some cases, an unknown service may be used, and in those cases this
98
+ function will return None.
99
+ """
100
+ if service_name in CLIENT_LOGIN_SCOPES:
101
+ return CLIENT_LOGIN_SCOPES[service_name]
102
+ return None
103
+
104
+
105
+ # Module level variable specifies which module should be used by GDataService
106
+ # objects to make HttpRequests. This setting can be overridden on each
107
+ # instance of GDataService.
108
+ # This module level variable is deprecated. Reassign the http_client member
109
+ # of a GDataService object instead.
110
+ http_request_handler = atom.service
111
+
112
+
113
+ class Error(Exception):
114
+ pass
115
+
116
+
117
+ class CaptchaRequired(Error):
118
+ pass
119
+
120
+
121
+ class BadAuthentication(Error):
122
+ pass
123
+
124
+
125
+ class NotAuthenticated(Error):
126
+ pass
127
+
128
+
129
+ class NonAuthSubToken(Error):
130
+ pass
131
+
132
+
133
+ class NonOAuthToken(Error):
134
+ pass
135
+
136
+
137
+ class RequestError(Error):
138
+ pass
139
+
140
+
141
+ class UnexpectedReturnType(Error):
142
+ pass
143
+
144
+
145
+ class BadAuthenticationServiceURL(Error):
146
+ pass
147
+
148
+
149
+ class FetchingOAuthRequestTokenFailed(RequestError):
150
+ pass
151
+
152
+
153
+ class TokenUpgradeFailed(RequestError):
154
+ pass
155
+
156
+
157
+ class RevokingOAuthTokenFailed(RequestError):
158
+ pass
159
+
160
+
161
+ class AuthorizationRequired(Error):
162
+ pass
163
+
164
+
165
+ class TokenHadNoScope(Error):
166
+ pass
167
+
168
+
169
+ class RanOutOfTries(Error):
170
+ pass
171
+
172
+
173
+ class GDataService(atom.service.AtomService):
174
+ """Contains elements needed for GData login and CRUD request headers.
175
+
176
+ Maintains additional headers (tokens for example) needed for the GData
177
+ services to allow a user to perform inserts, updates, and deletes.
178
+ """
179
+ # The hander member is deprecated, use http_client instead.
180
+ handler = None
181
+ # The auth_token member is deprecated, use the token_store instead.
182
+ auth_token = None
183
+ # The tokens dict is deprecated in favor of the token_store.
184
+ tokens = None
185
+
186
+ def __init__(self, email=None, password=None, account_type='HOSTED_OR_GOOGLE',
187
+ service=None, auth_service_url=None, source=None, server=None,
188
+ additional_headers=None, handler=None, tokens=None,
189
+ http_client=None, token_store=None):
190
+ """Creates an object of type GDataService.
191
+
192
+ Args:
193
+ email: string (optional) The user's email address, used for
194
+ authentication.
195
+ password: string (optional) The user's password.
196
+ account_type: string (optional) The type of account to use. Use
197
+ 'GOOGLE' for regular Google accounts or 'HOSTED' for Google
198
+ Apps accounts, or 'HOSTED_OR_GOOGLE' to try finding a HOSTED
199
+ account first and, if it doesn't exist, try finding a regular
200
+ GOOGLE account. Default value: 'HOSTED_OR_GOOGLE'.
201
+ service: string (optional) The desired service for which credentials
202
+ will be obtained.
203
+ auth_service_url: string (optional) User-defined auth token request URL
204
+ allows users to explicitly specify where to send auth token requests.
205
+ source: string (optional) The name of the user's application.
206
+ server: string (optional) The name of the server to which a connection
207
+ will be opened. Default value: 'base.google.com'.
208
+ additional_headers: dictionary (optional) Any additional headers which
209
+ should be included with CRUD operations.
210
+ handler: module (optional) This parameter is deprecated and has been
211
+ replaced by http_client.
212
+ tokens: This parameter is deprecated, calls should be made to
213
+ token_store instead.
214
+ http_client: An object responsible for making HTTP requests using a
215
+ request method. If none is provided, a new instance of
216
+ atom.http.ProxiedHttpClient will be used.
217
+ token_store: Keeps a collection of authorization tokens which can be
218
+ applied to requests for a specific URLs. Critical methods are
219
+ find_token based on a URL (atom.url.Url or a string), add_token,
220
+ and remove_token.
221
+ """
222
+ atom.service.AtomService.__init__(self, http_client=http_client,
223
+ token_store=token_store)
224
+ self.email = email
225
+ self.password = password
226
+ self.account_type = account_type
227
+ self.service = service
228
+ self.auth_service_url = auth_service_url
229
+ self.server = server
230
+ self.additional_headers = additional_headers or {}
231
+ self._oauth_input_params = None
232
+ self.__SetSource(source)
233
+ self.__captcha_token = None
234
+ self.__captcha_url = None
235
+ self.__gsessionid = None
236
+
237
+ if http_request_handler.__name__ == 'gdata.urlfetch':
238
+ import gdata.alt.appengine
239
+ self.http_client = gdata.alt.appengine.AppEngineHttpClient()
240
+
241
+ def _SetSessionId(self, session_id):
242
+ """Used in unit tests to simulate a 302 which sets a gsessionid."""
243
+ self.__gsessionid = session_id
244
+
245
+ # Define properties for GDataService
246
+ def _SetAuthSubToken(self, auth_token, scopes=None):
247
+ """Deprecated, use SetAuthSubToken instead."""
248
+ self.SetAuthSubToken(auth_token, scopes=scopes)
249
+
250
+ def __SetAuthSubToken(self, auth_token, scopes=None):
251
+ """Deprecated, use SetAuthSubToken instead."""
252
+ self._SetAuthSubToken(auth_token, scopes=scopes)
253
+
254
+ def _GetAuthToken(self):
255
+ """Returns the auth token used for authenticating requests.
256
+
257
+ Returns:
258
+ string
259
+ """
260
+ current_scopes = lookup_scopes(self.service)
261
+ if current_scopes:
262
+ token = self.token_store.find_token(current_scopes[0])
263
+ if hasattr(token, 'auth_header'):
264
+ return token.auth_header
265
+ return None
266
+
267
+ def _GetCaptchaToken(self):
268
+ """Returns a captcha token if the most recent login attempt generated one.
269
+
270
+ The captcha token is only set if the Programmatic Login attempt failed
271
+ because the Google service issued a captcha challenge.
272
+
273
+ Returns:
274
+ string
275
+ """
276
+ return self.__captcha_token
277
+
278
+ def __GetCaptchaToken(self):
279
+ return self._GetCaptchaToken()
280
+
281
+ captcha_token = property(__GetCaptchaToken,
282
+ doc="""Get the captcha token for a login request.""")
283
+
284
+ def _GetCaptchaURL(self):
285
+ """Returns the URL of the captcha image if a login attempt generated one.
286
+
287
+ The captcha URL is only set if the Programmatic Login attempt failed
288
+ because the Google service issued a captcha challenge.
289
+
290
+ Returns:
291
+ string
292
+ """
293
+ return self.__captcha_url
294
+
295
+ def __GetCaptchaURL(self):
296
+ return self._GetCaptchaURL()
297
+
298
+ captcha_url = property(__GetCaptchaURL,
299
+ doc="""Get the captcha URL for a login request.""")
300
+
301
+ def GetGeneratorFromLinkFinder(self, link_finder, func,
302
+ num_retries=DEFAULT_NUM_RETRIES,
303
+ delay=DEFAULT_DELAY,
304
+ backoff=DEFAULT_BACKOFF):
305
+ """returns a generator for pagination"""
306
+ yield link_finder
307
+ next = link_finder.GetNextLink()
308
+ while next is not None:
309
+ next_feed = func(str(self.GetWithRetries(
310
+ next.href, num_retries=num_retries, delay=delay, backoff=backoff)))
311
+ yield next_feed
312
+ next = next_feed.GetNextLink()
313
+
314
+ def _GetElementGeneratorFromLinkFinder(self, link_finder, func,
315
+ num_retries=DEFAULT_NUM_RETRIES,
316
+ delay=DEFAULT_DELAY,
317
+ backoff=DEFAULT_BACKOFF):
318
+ for element in self.GetGeneratorFromLinkFinder(link_finder, func,
319
+ num_retries=num_retries,
320
+ delay=delay,
321
+ backoff=backoff).entry:
322
+ yield element
323
+
324
+ def GetOAuthInputParameters(self):
325
+ return self._oauth_input_params
326
+
327
+ def SetOAuthInputParameters(self, signature_method, consumer_key,
328
+ consumer_secret=None, rsa_key=None,
329
+ two_legged_oauth=False, requestor_id=None):
330
+ """Sets parameters required for using OAuth authentication mechanism.
331
+
332
+ NOTE: Though consumer_secret and rsa_key are optional, either of the two
333
+ is required depending on the value of the signature_method.
334
+
335
+ Args:
336
+ signature_method: class which provides implementation for strategy class
337
+ oauth.oauth.OAuthSignatureMethod. Signature method to be used for
338
+ signing each request. Valid implementations are provided as the
339
+ constants defined by gdata.auth.OAuthSignatureMethod. Currently
340
+ they are gdata.auth.OAuthSignatureMethod.RSA_SHA1 and
341
+ gdata.auth.OAuthSignatureMethod.HMAC_SHA1
342
+ consumer_key: string Domain identifying third_party web application.
343
+ consumer_secret: string (optional) Secret generated during registration.
344
+ Required only for HMAC_SHA1 signature method.
345
+ rsa_key: string (optional) Private key required for RSA_SHA1 signature
346
+ method.
347
+ two_legged_oauth: boolean (optional) Enables two-legged OAuth process.
348
+ requestor_id: string (optional) User email adress to make requests on
349
+ their behalf. This parameter should only be set when two_legged_oauth
350
+ is True.
351
+ """
352
+ self._oauth_input_params = gdata.auth.OAuthInputParams(
353
+ signature_method, consumer_key, consumer_secret=consumer_secret,
354
+ rsa_key=rsa_key, requestor_id=requestor_id)
355
+ if two_legged_oauth:
356
+ oauth_token = gdata.auth.OAuthToken(
357
+ oauth_input_params=self._oauth_input_params)
358
+ self.SetOAuthToken(oauth_token)
359
+
360
+ def FetchOAuthRequestToken(self, scopes=None, extra_parameters=None,
361
+ request_url='%s/accounts/OAuthGetRequestToken' % \
362
+ AUTH_SERVER_HOST, oauth_callback=None):
363
+ """Fetches and sets the OAuth request token and returns it.
364
+
365
+ Args:
366
+ scopes: string or list of string base URL(s) of the service(s) to be
367
+ accessed. If None, then this method tries to determine the
368
+ scope(s) from the current service.
369
+ extra_parameters: dict (optional) key-value pairs as any additional
370
+ parameters to be included in the URL and signature while making a
371
+ request for fetching an OAuth request token. All the OAuth parameters
372
+ are added by default. But if provided through this argument, any
373
+ default parameters will be overwritten. For e.g. a default parameter
374
+ oauth_version 1.0 can be overwritten if
375
+ extra_parameters = {'oauth_version': '2.0'}
376
+ request_url: Request token URL. The default is
377
+ 'https://www.google.com/accounts/OAuthGetRequestToken'.
378
+ oauth_callback: str (optional) If set, it is assume the client is using
379
+ the OAuth v1.0a protocol where the callback url is sent in the
380
+ request token step. If the oauth_callback is also set in
381
+ extra_params, this value will override that one.
382
+
383
+ Returns:
384
+ The fetched request token as a gdata.auth.OAuthToken object.
385
+
386
+ Raises:
387
+ FetchingOAuthRequestTokenFailed if the server responded to the request
388
+ with an error.
389
+ """
390
+ if scopes is None:
391
+ scopes = lookup_scopes(self.service)
392
+ if not isinstance(scopes, (list, tuple)):
393
+ scopes = [scopes,]
394
+ if oauth_callback:
395
+ if extra_parameters is not None:
396
+ extra_parameters['oauth_callback'] = oauth_callback
397
+ else:
398
+ extra_parameters = {'oauth_callback': oauth_callback}
399
+ request_token_url = gdata.auth.GenerateOAuthRequestTokenUrl(
400
+ self._oauth_input_params, scopes,
401
+ request_token_url=request_url,
402
+ extra_parameters=extra_parameters)
403
+ response = self.http_client.request('GET', str(request_token_url))
404
+ if response.status == 200:
405
+ token = gdata.auth.OAuthToken()
406
+ token.set_token_string(response.read())
407
+ token.scopes = scopes
408
+ token.oauth_input_params = self._oauth_input_params
409
+ self.SetOAuthToken(token)
410
+ return token
411
+ error = {
412
+ 'status': response.status,
413
+ 'reason': 'Non 200 response on fetch request token',
414
+ 'body': response.read()
415
+ }
416
+ raise FetchingOAuthRequestTokenFailed(error)
417
+
418
+ def SetOAuthToken(self, oauth_token):
419
+ """Attempts to set the current token and add it to the token store.
420
+
421
+ The oauth_token can be any OAuth token i.e. unauthorized request token,
422
+ authorized request token or access token.
423
+ This method also attempts to add the token to the token store.
424
+ Use this method any time you want the current token to point to the
425
+ oauth_token passed. For e.g. call this method with the request token
426
+ you receive from FetchOAuthRequestToken.
427
+
428
+ Args:
429
+ request_token: gdata.auth.OAuthToken OAuth request token.
430
+ """
431
+ if self.auto_set_current_token:
432
+ self.current_token = oauth_token
433
+ if self.auto_store_tokens:
434
+ self.token_store.add_token(oauth_token)
435
+
436
+ def GenerateOAuthAuthorizationURL(
437
+ self, request_token=None, callback_url=None, extra_params=None,
438
+ include_scopes_in_callback=False,
439
+ scopes_param_prefix=OAUTH_SCOPE_URL_PARAM_NAME,
440
+ request_url='%s/accounts/OAuthAuthorizeToken' % AUTH_SERVER_HOST):
441
+ """Generates URL at which user will login to authorize the request token.
442
+
443
+ Args:
444
+ request_token: gdata.auth.OAuthToken (optional) OAuth request token.
445
+ If not specified, then the current token will be used if it is of
446
+ type <gdata.auth.OAuthToken>, else it is found by looking in the
447
+ token_store by looking for a token for the current scope.
448
+ callback_url: string (optional) The URL user will be sent to after
449
+ logging in and granting access.
450
+ extra_params: dict (optional) Additional parameters to be sent.
451
+ include_scopes_in_callback: Boolean (default=False) if set to True, and
452
+ if 'callback_url' is present, the 'callback_url' will be modified to
453
+ include the scope(s) from the request token as a URL parameter. The
454
+ key for the 'callback' URL's scope parameter will be
455
+ OAUTH_SCOPE_URL_PARAM_NAME. The benefit of including the scope URL as
456
+ a parameter to the 'callback' URL, is that the page which receives
457
+ the OAuth token will be able to tell which URLs the token grants
458
+ access to.
459
+ scopes_param_prefix: string (default='oauth_token_scope') The URL
460
+ parameter key which maps to the list of valid scopes for the token.
461
+ This URL parameter will be included in the callback URL along with
462
+ the scopes of the token as value if include_scopes_in_callback=True.
463
+ request_url: Authorization URL. The default is
464
+ 'https://www.google.com/accounts/OAuthAuthorizeToken'.
465
+ Returns:
466
+ A string URL at which the user is required to login.
467
+
468
+ Raises:
469
+ NonOAuthToken if the user's request token is not an OAuth token or if a
470
+ request token was not available.
471
+ """
472
+ if request_token and not isinstance(request_token, gdata.auth.OAuthToken):
473
+ raise NonOAuthToken
474
+ if not request_token:
475
+ if isinstance(self.current_token, gdata.auth.OAuthToken):
476
+ request_token = self.current_token
477
+ else:
478
+ current_scopes = lookup_scopes(self.service)
479
+ if current_scopes:
480
+ token = self.token_store.find_token(current_scopes[0])
481
+ if isinstance(token, gdata.auth.OAuthToken):
482
+ request_token = token
483
+ if not request_token:
484
+ raise NonOAuthToken
485
+ return str(gdata.auth.GenerateOAuthAuthorizationUrl(
486
+ request_token,
487
+ authorization_url=request_url,
488
+ callback_url=callback_url, extra_params=extra_params,
489
+ include_scopes_in_callback=include_scopes_in_callback,
490
+ scopes_param_prefix=scopes_param_prefix))
491
+
492
+ def UpgradeToOAuthAccessToken(self, authorized_request_token=None,
493
+ request_url='%s/accounts/OAuthGetAccessToken' \
494
+ % AUTH_SERVER_HOST, oauth_version='1.0',
495
+ oauth_verifier=None):
496
+ """Upgrades the authorized request token to an access token and returns it
497
+
498
+ Args:
499
+ authorized_request_token: gdata.auth.OAuthToken (optional) OAuth request
500
+ token. If not specified, then the current token will be used if it is
501
+ of type <gdata.auth.OAuthToken>, else it is found by looking in the
502
+ token_store by looking for a token for the current scope.
503
+ request_url: Access token URL. The default is
504
+ 'https://www.google.com/accounts/OAuthGetAccessToken'.
505
+ oauth_version: str (default='1.0') oauth_version parameter. All other
506
+ 'oauth_' parameters are added by default. This parameter too, is
507
+ added by default but here you can override it's value.
508
+ oauth_verifier: str (optional) If present, it is assumed that the client
509
+ will use the OAuth v1.0a protocol which includes passing the
510
+ oauth_verifier (as returned by the SP) in the access token step.
511
+
512
+ Returns:
513
+ Access token
514
+
515
+ Raises:
516
+ NonOAuthToken if the user's authorized request token is not an OAuth
517
+ token or if an authorized request token was not available.
518
+ TokenUpgradeFailed if the server responded to the request with an
519
+ error.
520
+ """
521
+ if (authorized_request_token and
522
+ not isinstance(authorized_request_token, gdata.auth.OAuthToken)):
523
+ raise NonOAuthToken
524
+ if not authorized_request_token:
525
+ if isinstance(self.current_token, gdata.auth.OAuthToken):
526
+ authorized_request_token = self.current_token
527
+ else:
528
+ current_scopes = lookup_scopes(self.service)
529
+ if current_scopes:
530
+ token = self.token_store.find_token(current_scopes[0])
531
+ if isinstance(token, gdata.auth.OAuthToken):
532
+ authorized_request_token = token
533
+ if not authorized_request_token:
534
+ raise NonOAuthToken
535
+ access_token_url = gdata.auth.GenerateOAuthAccessTokenUrl(
536
+ authorized_request_token,
537
+ self._oauth_input_params,
538
+ access_token_url=request_url,
539
+ oauth_version=oauth_version,
540
+ oauth_verifier=oauth_verifier)
541
+ response = self.http_client.request('GET', str(access_token_url))
542
+ if response.status == 200:
543
+ token = gdata.auth.OAuthTokenFromHttpBody(response.read())
544
+ token.scopes = authorized_request_token.scopes
545
+ token.oauth_input_params = authorized_request_token.oauth_input_params
546
+ self.SetOAuthToken(token)
547
+ return token
548
+ else:
549
+ raise TokenUpgradeFailed({'status': response.status,
550
+ 'reason': 'Non 200 response on upgrade',
551
+ 'body': response.read()})
552
+
553
+ def RevokeOAuthToken(self, request_url='%s/accounts/AuthSubRevokeToken' % \
554
+ AUTH_SERVER_HOST):
555
+ """Revokes an existing OAuth token.
556
+
557
+ request_url: Token revoke URL. The default is
558
+ 'https://www.google.com/accounts/AuthSubRevokeToken'.
559
+ Raises:
560
+ NonOAuthToken if the user's auth token is not an OAuth token.
561
+ RevokingOAuthTokenFailed if request for revoking an OAuth token failed.
562
+ """
563
+ scopes = lookup_scopes(self.service)
564
+ token = self.token_store.find_token(scopes[0])
565
+ if not isinstance(token, gdata.auth.OAuthToken):
566
+ raise NonOAuthToken
567
+
568
+ response = token.perform_request(self.http_client, 'GET', request_url,
569
+ headers={'Content-Type':'application/x-www-form-urlencoded'})
570
+ if response.status == 200:
571
+ self.token_store.remove_token(token)
572
+ else:
573
+ raise RevokingOAuthTokenFailed
574
+
575
+ def GetAuthSubToken(self):
576
+ """Returns the AuthSub token as a string.
577
+
578
+ If the token is an gdta.auth.AuthSubToken, the Authorization Label
579
+ ("AuthSub token") is removed.
580
+
581
+ This method examines the current_token to see if it is an AuthSubToken
582
+ or SecureAuthSubToken. If not, it searches the token_store for a token
583
+ which matches the current scope.
584
+
585
+ The current scope is determined by the service name string member.
586
+
587
+ Returns:
588
+ If the current_token is set to an AuthSubToken/SecureAuthSubToken,
589
+ return the token string. If there is no current_token, a token string
590
+ for a token which matches the service object's default scope is returned.
591
+ If there are no tokens valid for the scope, returns None.
592
+ """
593
+ if isinstance(self.current_token, gdata.auth.AuthSubToken):
594
+ return self.current_token.get_token_string()
595
+ current_scopes = lookup_scopes(self.service)
596
+ if current_scopes:
597
+ token = self.token_store.find_token(current_scopes[0])
598
+ if isinstance(token, gdata.auth.AuthSubToken):
599
+ return token.get_token_string()
600
+ else:
601
+ token = self.token_store.find_token(atom.token_store.SCOPE_ALL)
602
+ if isinstance(token, gdata.auth.ClientLoginToken):
603
+ return token.get_token_string()
604
+ return None
605
+
606
+ def SetAuthSubToken(self, token, scopes=None, rsa_key=None):
607
+ """Sets the token sent in requests to an AuthSub token.
608
+
609
+ Sets the current_token and attempts to add the token to the token_store.
610
+
611
+ Only use this method if you have received a token from the AuthSub
612
+ service. The auth token is set automatically when UpgradeToSessionToken()
613
+ is used. See documentation for Google AuthSub here:
614
+ http://code.google.com/apis/accounts/AuthForWebApps.html
615
+
616
+ Args:
617
+ token: gdata.auth.AuthSubToken or gdata.auth.SecureAuthSubToken or string
618
+ The token returned by the AuthSub service. If the token is an
619
+ AuthSubToken or SecureAuthSubToken, the scope information stored in
620
+ the token is used. If the token is a string, the scopes parameter is
621
+ used to determine the valid scopes.
622
+ scopes: list of URLs for which the token is valid. This is only used
623
+ if the token parameter is a string.
624
+ rsa_key: string (optional) Private key required for RSA_SHA1 signature
625
+ method. This parameter is necessary if the token is a string
626
+ representing a secure token.
627
+ """
628
+ if not isinstance(token, gdata.auth.AuthSubToken):
629
+ token_string = token
630
+ if rsa_key:
631
+ token = gdata.auth.SecureAuthSubToken(rsa_key)
632
+ else:
633
+ token = gdata.auth.AuthSubToken()
634
+
635
+ token.set_token_string(token_string)
636
+
637
+ # If no scopes were set for the token, use the scopes passed in, or
638
+ # try to determine the scopes based on the current service name. If
639
+ # all else fails, set the token to match all requests.
640
+ if not token.scopes:
641
+ if scopes is None:
642
+ scopes = lookup_scopes(self.service)
643
+ if scopes is None:
644
+ scopes = [atom.token_store.SCOPE_ALL]
645
+ token.scopes = scopes
646
+ if self.auto_set_current_token:
647
+ self.current_token = token
648
+ if self.auto_store_tokens:
649
+ self.token_store.add_token(token)
650
+
651
+ def GetClientLoginToken(self):
652
+ """Returns the token string for the current token or a token matching the
653
+ service scope.
654
+
655
+ If the current_token is a ClientLoginToken, the token string for
656
+ the current token is returned. If the current_token is not set, this method
657
+ searches for a token in the token_store which is valid for the service
658
+ object's current scope.
659
+
660
+ The current scope is determined by the service name string member.
661
+ The token string is the end of the Authorization header, it doesn not
662
+ include the ClientLogin label.
663
+ """
664
+ if isinstance(self.current_token, gdata.auth.ClientLoginToken):
665
+ return self.current_token.get_token_string()
666
+ current_scopes = lookup_scopes(self.service)
667
+ if current_scopes:
668
+ token = self.token_store.find_token(current_scopes[0])
669
+ if isinstance(token, gdata.auth.ClientLoginToken):
670
+ return token.get_token_string()
671
+ else:
672
+ token = self.token_store.find_token(atom.token_store.SCOPE_ALL)
673
+ if isinstance(token, gdata.auth.ClientLoginToken):
674
+ return token.get_token_string()
675
+ return None
676
+
677
+ def SetClientLoginToken(self, token, scopes=None):
678
+ """Sets the token sent in requests to a ClientLogin token.
679
+
680
+ This method sets the current_token to a new ClientLoginToken and it
681
+ also attempts to add the ClientLoginToken to the token_store.
682
+
683
+ Only use this method if you have received a token from the ClientLogin
684
+ service. The auth_token is set automatically when ProgrammaticLogin()
685
+ is used. See documentation for Google ClientLogin here:
686
+ http://code.google.com/apis/accounts/docs/AuthForInstalledApps.html
687
+
688
+ Args:
689
+ token: string or instance of a ClientLoginToken.
690
+ """
691
+ if not isinstance(token, gdata.auth.ClientLoginToken):
692
+ token_string = token
693
+ token = gdata.auth.ClientLoginToken()
694
+ token.set_token_string(token_string)
695
+
696
+ if not token.scopes:
697
+ if scopes is None:
698
+ scopes = lookup_scopes(self.service)
699
+ if scopes is None:
700
+ scopes = [atom.token_store.SCOPE_ALL]
701
+ token.scopes = scopes
702
+ if self.auto_set_current_token:
703
+ self.current_token = token
704
+ if self.auto_store_tokens:
705
+ self.token_store.add_token(token)
706
+
707
+ # Private methods to create the source property.
708
+ def __GetSource(self):
709
+ return self.__source
710
+
711
+ def __SetSource(self, new_source):
712
+ self.__source = new_source
713
+ # Update the UserAgent header to include the new application name.
714
+ self.additional_headers['User-Agent'] = atom.http_interface.USER_AGENT % (
715
+ self.__source,)
716
+
717
+ source = property(__GetSource, __SetSource,
718
+ doc="""The source is the name of the application making the request.
719
+ It should be in the form company_id-app_name-app_version""")
720
+
721
+ # Authentication operations
722
+
723
+ def ProgrammaticLogin(self, captcha_token=None, captcha_response=None):
724
+ """Authenticates the user and sets the GData Auth token.
725
+
726
+ Login retreives a temporary auth token which must be used with all
727
+ requests to GData services. The auth token is stored in the GData client
728
+ object.
729
+
730
+ Login is also used to respond to a captcha challenge. If the user's login
731
+ attempt failed with a CaptchaRequired error, the user can respond by
732
+ calling Login with the captcha token and the answer to the challenge.
733
+
734
+ Args:
735
+ captcha_token: string (optional) The identifier for the captcha challenge
736
+ which was presented to the user.
737
+ captcha_response: string (optional) The user's answer to the captch
738
+ challenge.
739
+
740
+ Raises:
741
+ CaptchaRequired if the login service will require a captcha response
742
+ BadAuthentication if the login service rejected the username or password
743
+ Error if the login service responded with a 403 different from the above
744
+ """
745
+ request_body = gdata.auth.generate_client_login_request_body(self.email,
746
+ self.password, self.service, self.source, self.account_type,
747
+ captcha_token, captcha_response)
748
+
749
+ # If the user has defined their own authentication service URL,
750
+ # send the ClientLogin requests to this URL:
751
+ if not self.auth_service_url:
752
+ auth_request_url = AUTH_SERVER_HOST + '/accounts/ClientLogin'
753
+ else:
754
+ auth_request_url = self.auth_service_url
755
+
756
+ auth_response = self.http_client.request('POST', auth_request_url,
757
+ data=request_body,
758
+ headers={'Content-Type':'application/x-www-form-urlencoded'})
759
+ response_body = auth_response.read()
760
+
761
+ if auth_response.status == 200:
762
+ # TODO: insert the token into the token_store directly.
763
+ self.SetClientLoginToken(
764
+ gdata.auth.get_client_login_token(response_body))
765
+ self.__captcha_token = None
766
+ self.__captcha_url = None
767
+
768
+ elif auth_response.status == 403:
769
+ # Examine each line to find the error type and the captcha token and
770
+ # captch URL if they are present.
771
+ captcha_parameters = gdata.auth.get_captcha_challenge(response_body,
772
+ captcha_base_url='%s/accounts/' % AUTH_SERVER_HOST)
773
+ if captcha_parameters:
774
+ self.__captcha_token = captcha_parameters['token']
775
+ self.__captcha_url = captcha_parameters['url']
776
+ raise CaptchaRequired('Captcha Required')
777
+ elif response_body.splitlines()[0] == 'Error=BadAuthentication':
778
+ self.__captcha_token = None
779
+ self.__captcha_url = None
780
+ raise BadAuthentication('Incorrect username or password')
781
+ else:
782
+ self.__captcha_token = None
783
+ self.__captcha_url = None
784
+ raise Error('Server responded with a 403 code')
785
+ elif auth_response.status == 302:
786
+ self.__captcha_token = None
787
+ self.__captcha_url = None
788
+ # Google tries to redirect all bad URLs back to
789
+ # http://www.google.<locale>. If a redirect
790
+ # attempt is made, assume the user has supplied an incorrect authentication URL
791
+ raise BadAuthenticationServiceURL('Server responded with a 302 code.')
792
+
793
+ def ClientLogin(self, username, password, account_type=None, service=None,
794
+ auth_service_url=None, source=None, captcha_token=None,
795
+ captcha_response=None):
796
+ """Convenience method for authenticating using ProgrammaticLogin.
797
+
798
+ Sets values for email, password, and other optional members.
799
+
800
+ Args:
801
+ username:
802
+ password:
803
+ account_type: string (optional)
804
+ service: string (optional)
805
+ auth_service_url: string (optional)
806
+ captcha_token: string (optional)
807
+ captcha_response: string (optional)
808
+ """
809
+ self.email = username
810
+ self.password = password
811
+
812
+ if account_type:
813
+ self.account_type = account_type
814
+ if service:
815
+ self.service = service
816
+ if source:
817
+ self.source = source
818
+ if auth_service_url:
819
+ self.auth_service_url = auth_service_url
820
+
821
+ self.ProgrammaticLogin(captcha_token, captcha_response)
822
+
823
+ def GenerateAuthSubURL(self, next, scope, secure=False, session=True,
824
+ domain='default'):
825
+ """Generate a URL at which the user will login and be redirected back.
826
+
827
+ Users enter their credentials on a Google login page and a token is sent
828
+ to the URL specified in next. See documentation for AuthSub login at:
829
+ http://code.google.com/apis/accounts/docs/AuthSub.html
830
+
831
+ Args:
832
+ next: string The URL user will be sent to after logging in.
833
+ scope: string or list of strings. The URLs of the services to be
834
+ accessed.
835
+ secure: boolean (optional) Determines whether or not the issued token
836
+ is a secure token.
837
+ session: boolean (optional) Determines whether or not the issued token
838
+ can be upgraded to a session token.
839
+ """
840
+ if not isinstance(scope, (list, tuple)):
841
+ scope = (scope,)
842
+ return gdata.auth.generate_auth_sub_url(next, scope, secure=secure,
843
+ session=session,
844
+ request_url='%s/accounts/AuthSubRequest' % AUTH_SERVER_HOST,
845
+ domain=domain)
846
+
847
+ def UpgradeToSessionToken(self, token=None):
848
+ """Upgrades a single use AuthSub token to a session token.
849
+
850
+ Args:
851
+ token: A gdata.auth.AuthSubToken or gdata.auth.SecureAuthSubToken
852
+ (optional) which is good for a single use but can be upgraded
853
+ to a session token. If no token is passed in, the token
854
+ is found by looking in the token_store by looking for a token
855
+ for the current scope.
856
+
857
+ Raises:
858
+ NonAuthSubToken if the user's auth token is not an AuthSub token
859
+ TokenUpgradeFailed if the server responded to the request with an
860
+ error.
861
+ """
862
+ if token is None:
863
+ scopes = lookup_scopes(self.service)
864
+ if scopes:
865
+ token = self.token_store.find_token(scopes[0])
866
+ else:
867
+ token = self.token_store.find_token(atom.token_store.SCOPE_ALL)
868
+ if not isinstance(token, gdata.auth.AuthSubToken):
869
+ raise NonAuthSubToken
870
+
871
+ self.SetAuthSubToken(self.upgrade_to_session_token(token))
872
+
873
+ def upgrade_to_session_token(self, token):
874
+ """Upgrades a single use AuthSub token to a session token.
875
+
876
+ Args:
877
+ token: A gdata.auth.AuthSubToken or gdata.auth.SecureAuthSubToken
878
+ which is good for a single use but can be upgraded to a
879
+ session token.
880
+
881
+ Returns:
882
+ The upgraded token as a gdata.auth.AuthSubToken object.
883
+
884
+ Raises:
885
+ TokenUpgradeFailed if the server responded to the request with an
886
+ error.
887
+ """
888
+ response = token.perform_request(self.http_client, 'GET',
889
+ AUTH_SERVER_HOST + '/accounts/AuthSubSessionToken',
890
+ headers={'Content-Type':'application/x-www-form-urlencoded'})
891
+ response_body = response.read()
892
+ if response.status == 200:
893
+ token.set_token_string(
894
+ gdata.auth.token_from_http_body(response_body))
895
+ return token
896
+ else:
897
+ raise TokenUpgradeFailed({'status': response.status,
898
+ 'reason': 'Non 200 response on upgrade',
899
+ 'body': response_body})
900
+
901
+ def RevokeAuthSubToken(self):
902
+ """Revokes an existing AuthSub token.
903
+
904
+ Raises:
905
+ NonAuthSubToken if the user's auth token is not an AuthSub token
906
+ """
907
+ scopes = lookup_scopes(self.service)
908
+ token = self.token_store.find_token(scopes[0])
909
+ if not isinstance(token, gdata.auth.AuthSubToken):
910
+ raise NonAuthSubToken
911
+
912
+ response = token.perform_request(self.http_client, 'GET',
913
+ AUTH_SERVER_HOST + '/accounts/AuthSubRevokeToken',
914
+ headers={'Content-Type':'application/x-www-form-urlencoded'})
915
+ if response.status == 200:
916
+ self.token_store.remove_token(token)
917
+
918
+ def AuthSubTokenInfo(self):
919
+ """Fetches the AuthSub token's metadata from the server.
920
+
921
+ Raises:
922
+ NonAuthSubToken if the user's auth token is not an AuthSub token
923
+ """
924
+ scopes = lookup_scopes(self.service)
925
+ token = self.token_store.find_token(scopes[0])
926
+ if not isinstance(token, gdata.auth.AuthSubToken):
927
+ raise NonAuthSubToken
928
+
929
+ response = token.perform_request(self.http_client, 'GET',
930
+ AUTH_SERVER_HOST + '/accounts/AuthSubTokenInfo',
931
+ headers={'Content-Type':'application/x-www-form-urlencoded'})
932
+ result_body = response.read()
933
+ if response.status == 200:
934
+ return result_body
935
+ else:
936
+ raise RequestError({'status': response.status,
937
+ 'body': result_body})
938
+
939
+ def GetWithRetries(self, uri, extra_headers=None, redirects_remaining=4,
940
+ encoding='UTF-8', converter=None, num_retries=DEFAULT_NUM_RETRIES,
941
+ delay=DEFAULT_DELAY, backoff=DEFAULT_BACKOFF, logger=None):
942
+ """This is a wrapper method for Get with retrying capability.
943
+
944
+ To avoid various errors while retrieving bulk entities by retrying
945
+ specified times.
946
+
947
+ Note this method relies on the time module and so may not be usable
948
+ by default in Python2.2.
949
+
950
+ Args:
951
+ num_retries: Integer; the retry count.
952
+ delay: Integer; the initial delay for retrying.
953
+ backoff: Integer; how much the delay should lengthen after each failure.
954
+ logger: An object which has a debug(str) method to receive logging
955
+ messages. Recommended that you pass in the logging module.
956
+ Raises:
957
+ ValueError if any of the parameters has an invalid value.
958
+ RanOutOfTries on failure after number of retries.
959
+ """
960
+ # Moved import for time module inside this method since time is not a
961
+ # default module in Python2.2. This method will not be usable in
962
+ # Python2.2.
963
+ import time
964
+ if backoff <= 1:
965
+ raise ValueError("backoff must be greater than 1")
966
+ num_retries = int(num_retries)
967
+
968
+ if num_retries < 0:
969
+ raise ValueError("num_retries must be 0 or greater")
970
+
971
+ if delay <= 0:
972
+ raise ValueError("delay must be greater than 0")
973
+
974
+ # Let's start
975
+ mtries, mdelay = num_retries, delay
976
+ while mtries > 0:
977
+ if mtries != num_retries:
978
+ if logger:
979
+ logger.debug("Retrying: %s" % uri)
980
+ try:
981
+ rv = self.Get(uri, extra_headers=extra_headers,
982
+ redirects_remaining=redirects_remaining,
983
+ encoding=encoding, converter=converter)
984
+ except SystemExit:
985
+ # Allow this error
986
+ raise
987
+ except RequestError as e:
988
+ # Error 500 is 'internal server error' and warrants a retry
989
+ # Error 503 is 'service unavailable' and warrants a retry
990
+ if e[0]['status'] not in [500, 503]:
991
+ raise e
992
+ # Else, fall through to the retry code...
993
+ except Exception as e:
994
+ if logger:
995
+ logger.debug(e)
996
+ # Fall through to the retry code...
997
+ else:
998
+ # This is the right path.
999
+ return rv
1000
+ mtries -= 1
1001
+ time.sleep(mdelay)
1002
+ mdelay *= backoff
1003
+ raise RanOutOfTries('Ran out of tries.')
1004
+
1005
+ # CRUD operations
1006
+ def Get(self, uri, extra_headers=None, url_params=None,
1007
+ escape_params=True, redirects_remaining=4,
1008
+ encoding='UTF-8', converter=None):
1009
+ """Query the GData API with the given URI
1010
+
1011
+ The uri is the portion of the URI after the server value
1012
+ (ex: www.google.com).
1013
+
1014
+ To perform a query against Google Base, set the server to
1015
+ 'base.google.com' and set the uri to '/base/feeds/...', where ... is
1016
+ your query. For example, to find snippets for all digital cameras uri
1017
+ should be set to: '/base/feeds/snippets?bq=digital+camera'
1018
+
1019
+ Args:
1020
+ uri: string The query in the form of a URI. Example:
1021
+ '/base/feeds/snippets?bq=digital+camera'.
1022
+ extra_headers: dictionary (optional) Extra HTTP headers to be included
1023
+ in the GET request. These headers are in addition to
1024
+ those stored in the client's additional_headers property.
1025
+ The client automatically sets the Content-Type and
1026
+ Authorization headers.
1027
+ url_params: dict (optional) Additional URL parameters to be included
1028
+ in the URI. These are translated into query arguments
1029
+ in the form '&dict_key=value&...'.
1030
+ Example: {'max-results': '250'} becomes &max-results=250
1031
+ escape_params: boolean (optional) If false, the calling code has already
1032
+ ensured that the query will form a valid URL (all
1033
+ reserved characters have been escaped). If true, this
1034
+ method will escape the query and any URL parameters
1035
+ provided.
1036
+ redirects_remaining: int (optional) Tracks the number of additional
1037
+ redirects this method will allow. If the service object receives
1038
+ a redirect and remaining is 0, it will not follow the redirect.
1039
+ This was added to avoid infinite redirect loops.
1040
+ encoding: string (optional) The character encoding for the server's
1041
+ response. Default is UTF-8
1042
+ converter: func (optional) A function which will transform
1043
+ the server's results before it is returned. Example: use
1044
+ GDataFeedFromString to parse the server response as if it
1045
+ were a GDataFeed.
1046
+
1047
+ Returns:
1048
+ If there is no ResultsTransformer specified in the call, a GDataFeed
1049
+ or GDataEntry depending on which is sent from the server. If the
1050
+ response is niether a feed or entry and there is no ResultsTransformer,
1051
+ return a string. If there is a ResultsTransformer, the returned value
1052
+ will be that of the ResultsTransformer function.
1053
+ """
1054
+
1055
+ if extra_headers is None:
1056
+ extra_headers = {}
1057
+
1058
+ if self.__gsessionid is not None:
1059
+ if uri.find('gsessionid=') < 0:
1060
+ if uri.find('?') > -1:
1061
+ uri += '&gsessionid=%s' % (self.__gsessionid,)
1062
+ else:
1063
+ uri += '?gsessionid=%s' % (self.__gsessionid,)
1064
+
1065
+ server_response = self.request('GET', uri,
1066
+ headers=extra_headers, url_params=url_params)
1067
+ result_body = server_response.read()
1068
+
1069
+ if server_response.status == 200:
1070
+ if converter:
1071
+ return converter(result_body)
1072
+ # There was no ResultsTransformer specified, so try to convert the
1073
+ # server's response into a GDataFeed.
1074
+ feed = gdata.GDataFeedFromString(result_body)
1075
+ if not feed:
1076
+ # If conversion to a GDataFeed failed, try to convert the server's
1077
+ # response to a GDataEntry.
1078
+ entry = gdata.GDataEntryFromString(result_body)
1079
+ if not entry:
1080
+ # The server's response wasn't a feed, or an entry, so return the
1081
+ # response body as a string.
1082
+ return result_body
1083
+ return entry
1084
+ return feed
1085
+ elif server_response.status == 302:
1086
+ if redirects_remaining > 0:
1087
+ location = (server_response.getheader('Location')
1088
+ or server_response.getheader('location'))
1089
+ if location is not None:
1090
+ m = re.compile(r'[?&]gsessionid=(\w*)').search(location)
1091
+ if m is not None:
1092
+ self.__gsessionid = m.group(1)
1093
+ return GDataService.Get(self, location, extra_headers, redirects_remaining - 1,
1094
+ encoding=encoding, converter=converter)
1095
+ else:
1096
+ raise RequestError({'status': server_response.status,
1097
+ 'reason': '302 received without Location header',
1098
+ 'body': result_body})
1099
+ else:
1100
+ raise RequestError({'status': server_response.status,
1101
+ 'reason': 'Redirect received, but redirects_remaining <= 0',
1102
+ 'body': result_body})
1103
+ else:
1104
+ raise RequestError({'status': server_response.status,
1105
+ 'reason': server_response.reason, 'body': result_body})
1106
+
1107
+ def GetMedia(self, uri, extra_headers=None):
1108
+ """Returns a MediaSource containing media and its metadata from the given
1109
+ URI string.
1110
+ """
1111
+ response_handle = self.request('GET', uri,
1112
+ headers=extra_headers, url_params=url_params)
1113
+ return gdata.MediaSource(response_handle, response_handle.getheader(
1114
+ 'Content-Type'),
1115
+ response_handle.getheader('Content-Length'))
1116
+
1117
+ def GetEntry(self, uri, extra_headers=None):
1118
+ """Query the GData API with the given URI and receive an Entry.
1119
+
1120
+ See also documentation for gdata.service.Get
1121
+
1122
+ Args:
1123
+ uri: string The query in the form of a URI. Example:
1124
+ '/base/feeds/snippets?bq=digital+camera'.
1125
+ extra_headers: dictionary (optional) Extra HTTP headers to be included
1126
+ in the GET request. These headers are in addition to
1127
+ those stored in the client's additional_headers property.
1128
+ The client automatically sets the Content-Type and
1129
+ Authorization headers.
1130
+
1131
+ Returns:
1132
+ A GDataEntry built from the XML in the server's response.
1133
+ """
1134
+
1135
+ result = GDataService.Get(self, uri, extra_headers,
1136
+ converter=atom.EntryFromString)
1137
+ if isinstance(result, atom.Entry):
1138
+ return result
1139
+ else:
1140
+ raise UnexpectedReturnType('Server did not send an entry')
1141
+
1142
+ def GetFeed(self, uri, extra_headers=None,
1143
+ converter=gdata.GDataFeedFromString):
1144
+ """Query the GData API with the given URI and receive a Feed.
1145
+
1146
+ See also documentation for gdata.service.Get
1147
+
1148
+ Args:
1149
+ uri: string The query in the form of a URI. Example:
1150
+ '/base/feeds/snippets?bq=digital+camera'.
1151
+ extra_headers: dictionary (optional) Extra HTTP headers to be included
1152
+ in the GET request. These headers are in addition to
1153
+ those stored in the client's additional_headers property.
1154
+ The client automatically sets the Content-Type and
1155
+ Authorization headers.
1156
+
1157
+ Returns:
1158
+ A GDataFeed built from the XML in the server's response.
1159
+ """
1160
+
1161
+ result = GDataService.Get(self, uri, extra_headers, converter=converter)
1162
+ if isinstance(result, atom.Feed):
1163
+ return result
1164
+ else:
1165
+ raise UnexpectedReturnType('Server did not send a feed')
1166
+
1167
+ def GetNext(self, feed):
1168
+ """Requests the next 'page' of results in the feed.
1169
+
1170
+ This method uses the feed's next link to request an additional feed
1171
+ and uses the class of the feed to convert the results of the GET request.
1172
+
1173
+ Args:
1174
+ feed: atom.Feed or a subclass. The feed should contain a next link and
1175
+ the type of the feed will be applied to the results from the
1176
+ server. The new feed which is returned will be of the same class
1177
+ as this feed which was passed in.
1178
+
1179
+ Returns:
1180
+ A new feed representing the next set of results in the server's feed.
1181
+ The type of this feed will match that of the feed argument.
1182
+ """
1183
+ next_link = feed.GetNextLink()
1184
+ # Create a closure which will convert an XML string to the class of
1185
+ # the feed object passed in.
1186
+ def ConvertToFeedClass(xml_string):
1187
+ return atom.CreateClassFromXMLString(feed.__class__, xml_string)
1188
+ # Make a GET request on the next link and use the above closure for the
1189
+ # converted which processes the XML string from the server.
1190
+ if next_link and next_link.href:
1191
+ return GDataService.Get(self, next_link.href,
1192
+ converter=ConvertToFeedClass)
1193
+ else:
1194
+ return None
1195
+
1196
+ def Post(self, data, uri, extra_headers=None, url_params=None,
1197
+ escape_params=True, redirects_remaining=4, media_source=None,
1198
+ converter=None):
1199
+ """Insert or update data into a GData service at the given URI.
1200
+
1201
+ Args:
1202
+ data: string, ElementTree._Element, atom.Entry, or gdata.GDataEntry The
1203
+ XML to be sent to the uri.
1204
+ uri: string The location (feed) to which the data should be inserted.
1205
+ Example: '/base/feeds/items'.
1206
+ extra_headers: dict (optional) HTTP headers which are to be included.
1207
+ The client automatically sets the Content-Type,
1208
+ Authorization, and Content-Length headers.
1209
+ url_params: dict (optional) Additional URL parameters to be included
1210
+ in the URI. These are translated into query arguments
1211
+ in the form '&dict_key=value&...'.
1212
+ Example: {'max-results': '250'} becomes &max-results=250
1213
+ escape_params: boolean (optional) If false, the calling code has already
1214
+ ensured that the query will form a valid URL (all
1215
+ reserved characters have been escaped). If true, this
1216
+ method will escape the query and any URL parameters
1217
+ provided.
1218
+ media_source: MediaSource (optional) Container for the media to be sent
1219
+ along with the entry, if provided.
1220
+ converter: func (optional) A function which will be executed on the
1221
+ server's response. Often this is a function like
1222
+ GDataEntryFromString which will parse the body of the server's
1223
+ response and return a GDataEntry.
1224
+
1225
+ Returns:
1226
+ If the post succeeded, this method will return a GDataFeed, GDataEntry,
1227
+ or the results of running converter on the server's result body (if
1228
+ converter was specified).
1229
+ """
1230
+ return GDataService.PostOrPut(self, 'POST', data, uri,
1231
+ extra_headers=extra_headers, url_params=url_params,
1232
+ escape_params=escape_params, redirects_remaining=redirects_remaining,
1233
+ media_source=media_source, converter=converter)
1234
+
1235
+ def PostOrPut(self, verb, data, uri, extra_headers=None, url_params=None,
1236
+ escape_params=True, redirects_remaining=4, media_source=None,
1237
+ converter=None):
1238
+ """Insert data into a GData service at the given URI.
1239
+
1240
+ Args:
1241
+ verb: string, either 'POST' or 'PUT'
1242
+ data: string, ElementTree._Element, atom.Entry, or gdata.GDataEntry The
1243
+ XML to be sent to the uri.
1244
+ uri: string The location (feed) to which the data should be inserted.
1245
+ Example: '/base/feeds/items'.
1246
+ extra_headers: dict (optional) HTTP headers which are to be included.
1247
+ The client automatically sets the Content-Type,
1248
+ Authorization, and Content-Length headers.
1249
+ url_params: dict (optional) Additional URL parameters to be included
1250
+ in the URI. These are translated into query arguments
1251
+ in the form '&dict_key=value&...'.
1252
+ Example: {'max-results': '250'} becomes &max-results=250
1253
+ escape_params: boolean (optional) If false, the calling code has already
1254
+ ensured that the query will form a valid URL (all
1255
+ reserved characters have been escaped). If true, this
1256
+ method will escape the query and any URL parameters
1257
+ provided.
1258
+ media_source: MediaSource (optional) Container for the media to be sent
1259
+ along with the entry, if provided.
1260
+ converter: func (optional) A function which will be executed on the
1261
+ server's response. Often this is a function like
1262
+ GDataEntryFromString which will parse the body of the server's
1263
+ response and return a GDataEntry.
1264
+
1265
+ Returns:
1266
+ If the post succeeded, this method will return a GDataFeed, GDataEntry,
1267
+ or the results of running converter on the server's result body (if
1268
+ converter was specified).
1269
+ """
1270
+ if extra_headers is None:
1271
+ extra_headers = {}
1272
+
1273
+ if self.__gsessionid is not None:
1274
+ if uri.find('gsessionid=') < 0:
1275
+ if url_params is None:
1276
+ url_params = {}
1277
+ url_params['gsessionid'] = self.__gsessionid
1278
+
1279
+ if data and media_source:
1280
+ if ElementTree.iselement(data):
1281
+ data_str = ElementTree.tostring(data)
1282
+ else:
1283
+ data_str = str(data)
1284
+
1285
+ multipart = []
1286
+ multipart.append('Media multipart posting\r\n--END_OF_PART\r\n' + \
1287
+ 'Content-Type: application/atom+xml; charset=UTF-8\r\n\r\n')
1288
+ multipart.append('\r\n--END_OF_PART\r\nContent-Type: ' + \
1289
+ media_source.content_type+'\r\n\r\n')
1290
+ multipart.append('\r\n--END_OF_PART--\r\n')
1291
+
1292
+ extra_headers['MIME-version'] = '1.0'
1293
+ extra_headers['Content-Length'] = str(len(multipart[0]) +
1294
+ len(multipart[1]) + len(multipart[2]) +
1295
+ len(data_str) + media_source.content_length)
1296
+
1297
+ extra_headers['Content-Type'] = 'multipart/related; boundary=END_OF_PART'
1298
+ server_response = self.request(verb, uri,
1299
+ data=[multipart[0], data_str, multipart[1], media_source.file_handle,
1300
+ multipart[2]], headers=extra_headers, url_params=url_params)
1301
+ result_body = server_response.read()
1302
+
1303
+ elif media_source or isinstance(data, gdata.MediaSource):
1304
+ if isinstance(data, gdata.MediaSource):
1305
+ media_source = data
1306
+ extra_headers['Content-Length'] = str(media_source.content_length)
1307
+ extra_headers['Content-Type'] = media_source.content_type
1308
+ server_response = self.request(verb, uri,
1309
+ data=media_source.file_handle, headers=extra_headers,
1310
+ url_params=url_params)
1311
+ result_body = server_response.read()
1312
+
1313
+ else:
1314
+ http_data = data
1315
+ #content_type = 'application/atom+xml; charset=UTF-8'
1316
+ #extra_headers['Content-Type'] = content_type
1317
+ server_response = self.request(verb, uri, data=http_data,
1318
+ headers=extra_headers, url_params=url_params)
1319
+ result_body = server_response.read()
1320
+
1321
+ # Server returns 201 for most post requests, but when performing a batch
1322
+ # request the server responds with a 200 on success.
1323
+ if server_response.status == 201 or server_response.status == 200:
1324
+ if converter:
1325
+ return converter(result_body)
1326
+ feed = gdata.GDataFeedFromString(result_body)
1327
+ if not feed:
1328
+ entry = gdata.GDataEntryFromString(result_body)
1329
+ if not entry:
1330
+ return result_body
1331
+ return entry
1332
+ return feed
1333
+ elif server_response.status == 302:
1334
+ if redirects_remaining > 0:
1335
+ location = (server_response.getheader('Location')
1336
+ or server_response.getheader('location'))
1337
+ if location is not None:
1338
+ m = re.compile(r'[?&]gsessionid=(\w*)').search(location)
1339
+ if m is not None:
1340
+ self.__gsessionid = m.group(1)
1341
+ return GDataService.PostOrPut(self, verb, data, location,
1342
+ extra_headers, url_params, escape_params,
1343
+ redirects_remaining - 1, media_source, converter=converter)
1344
+ else:
1345
+ raise RequestError({'status': server_response.status,
1346
+ 'reason': '302 received without Location header',
1347
+ 'body': result_body})
1348
+ else:
1349
+ raise RequestError({'status': server_response.status,
1350
+ 'reason': 'Redirect received, but redirects_remaining <= 0',
1351
+ 'body': result_body})
1352
+ else:
1353
+ raise RequestError({'status': server_response.status,
1354
+ 'reason': server_response.reason, 'body': result_body})
1355
+
1356
+ def Put(self, data, uri, extra_headers=None, url_params=None,
1357
+ escape_params=True, redirects_remaining=3, media_source=None,
1358
+ converter=None):
1359
+ """Updates an entry at the given URI.
1360
+
1361
+ Args:
1362
+ data: string, ElementTree._Element, or xml_wrapper.ElementWrapper The
1363
+ XML containing the updated data.
1364
+ uri: string A URI indicating entry to which the update will be applied.
1365
+ Example: '/base/feeds/items/ITEM-ID'
1366
+ extra_headers: dict (optional) HTTP headers which are to be included.
1367
+ The client automatically sets the Content-Type,
1368
+ Authorization, and Content-Length headers.
1369
+ url_params: dict (optional) Additional URL parameters to be included
1370
+ in the URI. These are translated into query arguments
1371
+ in the form '&dict_key=value&...'.
1372
+ Example: {'max-results': '250'} becomes &max-results=250
1373
+ escape_params: boolean (optional) If false, the calling code has already
1374
+ ensured that the query will form a valid URL (all
1375
+ reserved characters have been escaped). If true, this
1376
+ method will escape the query and any URL parameters
1377
+ provided.
1378
+ converter: func (optional) A function which will be executed on the
1379
+ server's response. Often this is a function like
1380
+ GDataEntryFromString which will parse the body of the server's
1381
+ response and return a GDataEntry.
1382
+
1383
+ Returns:
1384
+ If the put succeeded, this method will return a GDataFeed, GDataEntry,
1385
+ or the results of running converter on the server's result body (if
1386
+ converter was specified).
1387
+ """
1388
+ return GDataService.PostOrPut(self, 'PUT', data, uri,
1389
+ extra_headers=extra_headers, url_params=url_params,
1390
+ escape_params=escape_params, redirects_remaining=redirects_remaining,
1391
+ media_source=media_source, converter=converter)
1392
+
1393
+ def Delete(self, uri, extra_headers=None, url_params=None,
1394
+ escape_params=True, redirects_remaining=4):
1395
+ """Deletes the entry at the given URI.
1396
+
1397
+ Args:
1398
+ uri: string The URI of the entry to be deleted. Example:
1399
+ '/base/feeds/items/ITEM-ID'
1400
+ extra_headers: dict (optional) HTTP headers which are to be included.
1401
+ The client automatically sets the Content-Type and
1402
+ Authorization headers.
1403
+ url_params: dict (optional) Additional URL parameters to be included
1404
+ in the URI. These are translated into query arguments
1405
+ in the form '&dict_key=value&...'.
1406
+ Example: {'max-results': '250'} becomes &max-results=250
1407
+ escape_params: boolean (optional) If false, the calling code has already
1408
+ ensured that the query will form a valid URL (all
1409
+ reserved characters have been escaped). If true, this
1410
+ method will escape the query and any URL parameters
1411
+ provided.
1412
+
1413
+ Returns:
1414
+ True if the entry was deleted.
1415
+ """
1416
+ if extra_headers is None:
1417
+ extra_headers = {}
1418
+
1419
+ if self.__gsessionid is not None:
1420
+ if uri.find('gsessionid=') < 0:
1421
+ if url_params is None:
1422
+ url_params = {}
1423
+ url_params['gsessionid'] = self.__gsessionid
1424
+
1425
+ server_response = self.request('DELETE', uri,
1426
+ headers=extra_headers, url_params=url_params)
1427
+ result_body = server_response.read()
1428
+
1429
+ if server_response.status == 200:
1430
+ return True
1431
+ elif server_response.status == 302:
1432
+ if redirects_remaining > 0:
1433
+ location = (server_response.getheader('Location')
1434
+ or server_response.getheader('location'))
1435
+ if location is not None:
1436
+ m = re.compile(r'[?&]gsessionid=(\w*)').search(location)
1437
+ if m is not None:
1438
+ self.__gsessionid = m.group(1)
1439
+ return GDataService.Delete(self, location, extra_headers,
1440
+ url_params, escape_params, redirects_remaining - 1)
1441
+ else:
1442
+ raise RequestError({'status': server_response.status,
1443
+ 'reason': '302 received without Location header',
1444
+ 'body': result_body})
1445
+ else:
1446
+ raise RequestError({'status': server_response.status,
1447
+ 'reason': 'Redirect received, but redirects_remaining <= 0',
1448
+ 'body': result_body})
1449
+ else:
1450
+ raise RequestError({'status': server_response.status,
1451
+ 'reason': server_response.reason, 'body': result_body})
1452
+
1453
+
1454
+ def ExtractToken(url, scopes_included_in_next=True):
1455
+ """Gets the AuthSub token from the current page's URL.
1456
+
1457
+ Designed to be used on the URL that the browser is sent to after the user
1458
+ authorizes this application at the page given by GenerateAuthSubRequestUrl.
1459
+
1460
+ Args:
1461
+ url: The current page's URL. It should contain the token as a URL
1462
+ parameter. Example: 'http://example.com/?...&token=abcd435'
1463
+ scopes_included_in_next: If True, this function looks for a scope value
1464
+ associated with the token. The scope is a URL parameter with the
1465
+ key set to SCOPE_URL_PARAM_NAME. This parameter should be present
1466
+ if the AuthSub request URL was generated using
1467
+ GenerateAuthSubRequestUrl with include_scope_in_next set to True.
1468
+
1469
+ Returns:
1470
+ A tuple containing the token string and a list of scope strings for which
1471
+ this token should be valid. If the scope was not included in the URL, the
1472
+ tuple will contain (token, None).
1473
+ """
1474
+ parsed = urllib.parse.urlparse(url)
1475
+ token = gdata.auth.AuthSubTokenFromUrl(parsed[4])
1476
+ scopes = ''
1477
+ if scopes_included_in_next:
1478
+ for pair in parsed[4].split('&'):
1479
+ if pair.startswith('%s=' % SCOPE_URL_PARAM_NAME):
1480
+ scopes = urllib.parse.unquote_plus(pair.split('=')[1])
1481
+ return (token, scopes.split(' '))
1482
+
1483
+
1484
+ def GenerateAuthSubRequestUrl(next, scopes, hd='default', secure=False,
1485
+ session=True, request_url='https://www.google.com/accounts/AuthSubRequest',
1486
+ include_scopes_in_next=True):
1487
+ """Creates a URL to request an AuthSub token to access Google services.
1488
+
1489
+ For more details on AuthSub, see the documentation here:
1490
+ http://code.google.com/apis/accounts/docs/AuthSub.html
1491
+
1492
+ Args:
1493
+ next: The URL where the browser should be sent after the user authorizes
1494
+ the application. This page is responsible for receiving the token
1495
+ which is embeded in the URL as a parameter.
1496
+ scopes: The base URL to which access will be granted. Example:
1497
+ 'http://www.google.com/calendar/feeds' will grant access to all
1498
+ URLs in the Google Calendar data API. If you would like a token for
1499
+ multiple scopes, pass in a list of URL strings.
1500
+ hd: The domain to which the user's account belongs. This is set to the
1501
+ domain name if you are using Google Apps. Example: 'example.org'
1502
+ Defaults to 'default'
1503
+ secure: If set to True, all requests should be signed. The default is
1504
+ False.
1505
+ session: If set to True, the token received by the 'next' URL can be
1506
+ upgraded to a multiuse session token. If session is set to False, the
1507
+ token may only be used once and cannot be upgraded. Default is True.
1508
+ request_url: The base of the URL to which the user will be sent to
1509
+ authorize this application to access their data. The default is
1510
+ 'https://www.google.com/accounts/AuthSubRequest'.
1511
+ include_scopes_in_next: Boolean if set to true, the 'next' parameter will
1512
+ be modified to include the requested scope as a URL parameter. The
1513
+ key for the next's scope parameter will be SCOPE_URL_PARAM_NAME. The
1514
+ benefit of including the scope URL as a parameter to the next URL, is
1515
+ that the page which receives the AuthSub token will be able to tell
1516
+ which URLs the token grants access to.
1517
+
1518
+ Returns:
1519
+ A URL string to which the browser should be sent.
1520
+ """
1521
+ if isinstance(scopes, list):
1522
+ scope = ' '.join(scopes)
1523
+ else:
1524
+ scope = scopes
1525
+ if include_scopes_in_next:
1526
+ if next.find('?') > -1:
1527
+ next += '&%s' % urllib.parse.urlencode({SCOPE_URL_PARAM_NAME:scope})
1528
+ else:
1529
+ next += '?%s' % urllib.parse.urlencode({SCOPE_URL_PARAM_NAME:scope})
1530
+ return gdata.auth.GenerateAuthSubUrl(next=next, scope=scope, secure=secure,
1531
+ session=session, request_url=request_url, domain=hd)
1532
+
1533
+
1534
+ class Query(dict):
1535
+ """Constructs a query URL to be used in GET requests
1536
+
1537
+ Url parameters are created by adding key-value pairs to this object as a
1538
+ dict. For example, to add &max-results=25 to the URL do
1539
+ my_query['max-results'] = 25
1540
+
1541
+ Category queries are created by adding category strings to the categories
1542
+ member. All items in the categories list will be concatenated with the /
1543
+ symbol (symbolizing a category x AND y restriction). If you would like to OR
1544
+ 2 categories, append them as one string with a | between the categories.
1545
+ For example, do query.categories.append('Fritz|Laurie') to create a query
1546
+ like this feed/-/Fritz%7CLaurie . This query will look for results in both
1547
+ categories.
1548
+ """
1549
+
1550
+ def __init__(self, feed=None, text_query=None, params=None,
1551
+ categories=None):
1552
+ """Constructor for Query
1553
+
1554
+ Args:
1555
+ feed: str (optional) The path for the feed (Examples:
1556
+ '/base/feeds/snippets' or 'calendar/feeds/jo@gmail.com/private/full'
1557
+ text_query: str (optional) The contents of the q query parameter. The
1558
+ contents of the text_query are URL escaped upon conversion to a URI.
1559
+ params: dict (optional) Parameter value string pairs which become URL
1560
+ params when translated to a URI. These parameters are added to the
1561
+ query's items (key-value pairs).
1562
+ categories: list (optional) List of category strings which should be
1563
+ included as query categories. See
1564
+ http://code.google.com/apis/gdata/reference.html#Queries for
1565
+ details. If you want to get results from category A or B (both
1566
+ categories), specify a single list item 'A|B'.
1567
+ """
1568
+
1569
+ self.feed = feed
1570
+ self.categories = []
1571
+ if text_query:
1572
+ self.text_query = text_query
1573
+ if isinstance(params, dict):
1574
+ for param in params:
1575
+ self[param] = params[param]
1576
+ if isinstance(categories, list):
1577
+ for category in categories:
1578
+ self.categories.append(category)
1579
+
1580
+ def _GetTextQuery(self):
1581
+ if 'q' in list(self.keys()):
1582
+ return self['q']
1583
+ else:
1584
+ return None
1585
+
1586
+ def _SetTextQuery(self, query):
1587
+ self['q'] = query
1588
+
1589
+ text_query = property(_GetTextQuery, _SetTextQuery,
1590
+ doc="""The feed query's q parameter""")
1591
+
1592
+ def _GetAuthor(self):
1593
+ if 'author' in list(self.keys()):
1594
+ return self['author']
1595
+ else:
1596
+ return None
1597
+
1598
+ def _SetAuthor(self, query):
1599
+ self['author'] = query
1600
+
1601
+ author = property(_GetAuthor, _SetAuthor,
1602
+ doc="""The feed query's author parameter""")
1603
+
1604
+ def _GetAlt(self):
1605
+ if 'alt' in list(self.keys()):
1606
+ return self['alt']
1607
+ else:
1608
+ return None
1609
+
1610
+ def _SetAlt(self, query):
1611
+ self['alt'] = query
1612
+
1613
+ alt = property(_GetAlt, _SetAlt,
1614
+ doc="""The feed query's alt parameter""")
1615
+
1616
+ def _GetUpdatedMin(self):
1617
+ if 'updated-min' in list(self.keys()):
1618
+ return self['updated-min']
1619
+ else:
1620
+ return None
1621
+
1622
+ def _SetUpdatedMin(self, query):
1623
+ self['updated-min'] = query
1624
+
1625
+ updated_min = property(_GetUpdatedMin, _SetUpdatedMin,
1626
+ doc="""The feed query's updated-min parameter""")
1627
+
1628
+ def _GetUpdatedMax(self):
1629
+ if 'updated-max' in list(self.keys()):
1630
+ return self['updated-max']
1631
+ else:
1632
+ return None
1633
+
1634
+ def _SetUpdatedMax(self, query):
1635
+ self['updated-max'] = query
1636
+
1637
+ updated_max = property(_GetUpdatedMax, _SetUpdatedMax,
1638
+ doc="""The feed query's updated-max parameter""")
1639
+
1640
+ def _GetPublishedMin(self):
1641
+ if 'published-min' in list(self.keys()):
1642
+ return self['published-min']
1643
+ else:
1644
+ return None
1645
+
1646
+ def _SetPublishedMin(self, query):
1647
+ self['published-min'] = query
1648
+
1649
+ published_min = property(_GetPublishedMin, _SetPublishedMin,
1650
+ doc="""The feed query's published-min parameter""")
1651
+
1652
+ def _GetPublishedMax(self):
1653
+ if 'published-max' in list(self.keys()):
1654
+ return self['published-max']
1655
+ else:
1656
+ return None
1657
+
1658
+ def _SetPublishedMax(self, query):
1659
+ self['published-max'] = query
1660
+
1661
+ published_max = property(_GetPublishedMax, _SetPublishedMax,
1662
+ doc="""The feed query's published-max parameter""")
1663
+
1664
+ def _GetStartIndex(self):
1665
+ if 'start-index' in list(self.keys()):
1666
+ return self['start-index']
1667
+ else:
1668
+ return None
1669
+
1670
+ def _SetStartIndex(self, query):
1671
+ if not isinstance(query, str):
1672
+ query = str(query)
1673
+ self['start-index'] = query
1674
+
1675
+ start_index = property(_GetStartIndex, _SetStartIndex,
1676
+ doc="""The feed query's start-index parameter""")
1677
+
1678
+ def _GetMaxResults(self):
1679
+ if 'max-results' in list(self.keys()):
1680
+ return self['max-results']
1681
+ else:
1682
+ return None
1683
+
1684
+ def _SetMaxResults(self, query):
1685
+ if not isinstance(query, str):
1686
+ query = str(query)
1687
+ self['max-results'] = query
1688
+
1689
+ max_results = property(_GetMaxResults, _SetMaxResults,
1690
+ doc="""The feed query's max-results parameter""")
1691
+
1692
+ def _GetOrderBy(self):
1693
+ if 'orderby' in list(self.keys()):
1694
+ return self['orderby']
1695
+ else:
1696
+ return None
1697
+
1698
+ def _SetOrderBy(self, query):
1699
+ self['orderby'] = query
1700
+
1701
+ orderby = property(_GetOrderBy, _SetOrderBy,
1702
+ doc="""The feed query's orderby parameter""")
1703
+
1704
+ def ToUri(self):
1705
+ q_feed = self.feed or ''
1706
+ category_string = '/'.join(
1707
+ [urllib.parse.quote_plus(c) for c in self.categories])
1708
+ # Add categories to the feed if there are any.
1709
+ if len(self.categories) > 0:
1710
+ q_feed = q_feed + '/-/' + category_string
1711
+ return atom.service.BuildUri(q_feed, self)
1712
+
1713
+ def __str__(self):
1714
+ return self.ToUri()