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"""Utilities for making samples.
16
17Consolidates a lot of code commonly repeated in sample applications.
18"""
19from __future__ import absolute_import
20
21__author__ = 'jcgregorio@google.com (Joe Gregorio)'
22__all__ = ['init']
23
24
25import argparse
26import httplib2
27import os
28
29from googleapiclient import discovery
30from oauth2client import client
31from oauth2client import file
32from oauth2client import tools
33
34
35def init(argv, name, version, doc, filename, scope=None, parents=[], discovery_filename=None):
36  """A common initialization routine for samples.
37
38  Many of the sample applications do the same initialization, which has now
39  been consolidated into this function. This function uses common idioms found
40  in almost all the samples, i.e. for an API with name 'apiname', the
41  credentials are stored in a file named apiname.dat, and the
42  client_secrets.json file is stored in the same directory as the application
43  main file.
44
45  Args:
46    argv: list of string, the command-line parameters of the application.
47    name: string, name of the API.
48    version: string, version of the API.
49    doc: string, description of the application. Usually set to __doc__.
50    file: string, filename of the application. Usually set to __file__.
51    parents: list of argparse.ArgumentParser, additional command-line flags.
52    scope: string, The OAuth scope used.
53    discovery_filename: string, name of local discovery file (JSON). Use when discovery doc not available via URL.
54
55  Returns:
56    A tuple of (service, flags), where service is the service object and flags
57    is the parsed command-line flags.
58  """
59  if scope is None:
60    scope = 'https://www.googleapis.com/auth/' + name
61
62  # Parser command-line arguments.
63  parent_parsers = [tools.argparser]
64  parent_parsers.extend(parents)
65  parser = argparse.ArgumentParser(
66      description=doc,
67      formatter_class=argparse.RawDescriptionHelpFormatter,
68      parents=parent_parsers)
69  flags = parser.parse_args(argv[1:])
70
71  # Name of a file containing the OAuth 2.0 information for this
72  # application, including client_id and client_secret, which are found
73  # on the API Access tab on the Google APIs
74  # Console <http://code.google.com/apis/console>.
75  client_secrets = os.path.join(os.path.dirname(filename),
76                                'client_secrets.json')
77
78  # Set up a Flow object to be used if we need to authenticate.
79  flow = client.flow_from_clientsecrets(client_secrets,
80      scope=scope,
81      message=tools.message_if_missing(client_secrets))
82
83  # Prepare credentials, and authorize HTTP object with them.
84  # If the credentials don't exist or are invalid run through the native client
85  # flow. The Storage object will ensure that if successful the good
86  # credentials will get written back to a file.
87  storage = file.Storage(name + '.dat')
88  credentials = storage.get()
89  if credentials is None or credentials.invalid:
90    credentials = tools.run_flow(flow, storage, flags)
91  http = credentials.authorize(http = httplib2.Http())
92
93  if discovery_filename is None:
94    # Construct a service object via the discovery service.
95    service = discovery.build(name, version, http=http)
96  else:
97    # Construct a service object using a local discovery document file.
98    with open(discovery_filename) as discovery_file:
99      service = discovery.build_from_document(
100          discovery_file.read(),
101          base='https://www.googleapis.com/',
102          http=http)
103  return (service, flags)
104