blob: 4fc9411eadafe6bb2d02b83d2d85c0ebcc41e449 [file] [log] [blame]
leadpipe@wpgntav-ubiq70.hot.corp.google.comdbcaba42011-11-02 16:26:42 -05001#!/usr/bin/python2.4
2# -*- coding: utf-8 -*-
3#
4# Copyright (C) 2011 Google Inc.
5
6"""Sample for retrieving advertiser information from GAN."""
7
8__author__ = 'leadpipe@google.com (Luke Blanshard)'
9
10import apiclient
11import gflags
12import httplib2
13import json
14import logging
15import os
16import stat
17import sys
18
19from django.conf import settings
20from django.template import Template, Context
21from django.template.loader import get_template
22
23from apiclient.discovery import build
24from oauth2client.file import Storage
25from oauth2client.client import AccessTokenRefreshError
26from oauth2client.client import flow_from_clientsecrets
27from oauth2client.tools import run
28
29settings.configure(DEBUG=True, TEMPLATE_DEBUG=True,
30 TEMPLATE_DIRS=('.'))
31
32
33FLAGS = gflags.FLAGS
34
35# CLIENT_SECRETS, name of a file containing the OAuth 2.0 information for this
36# application, including client_id and client_secret, which are found
37# on the API Access tab on the Google APIs
38# Console <http://code.google.com/apis/console>
39CLIENT_SECRETS = '../client_secrets.json'
40
41# Helpful message to display in the browser if the CLIENT_SECRETS file
42# is missing.
43MISSING_CLIENT_SECRETS_MESSAGE = """
44WARNING: Please configure OAuth 2.0
45
46To make this sample run you will need to populate the client_secrets.json file
47found at:
48
49 %s
50
51with information from the APIs Console <https://code.google.com/apis/console>.
52
53""" % os.path.join(os.path.dirname(__file__), CLIENT_SECRETS)
54
55# Set up a Flow object to be used if we need to authenticate.
56FLOW = flow_from_clientsecrets(CLIENT_SECRETS,
57 scope='https://www.googleapis.com/auth/gan.readonly',
58 message=MISSING_CLIENT_SECRETS_MESSAGE)
59
60
61# The gflags module makes defining command-line options easy for
62# applications. Run this program with the '--help' argument to see
63# all the flags that it understands.
64gflags.DEFINE_enum('logging_level', 'DEBUG',
65 ['DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL'],
66 'Set the level of logging detail.')
67
68gflags.DEFINE_enum("request_type", 'LIST', ['GET', 'LIST'],
69 'Type of request to be made')
70
71gflags.DEFINE_enum("output_type", 'STDOUT', ['BOTH', 'HTML', 'STDOUT'],
72 'Set how to output the results received from the API')
73
74gflags.DEFINE_string('credentials_filename', '../credentials.dat',
75 'File to store credentials in', short_name='cf')
76
77API_FLAGS = {'relationshipStatus':None, 'advertiserId':None, 'role':None,
78 'roleId':None, 'category':None, 'minSevenDayEpc':None,
79 'minNinetyDayEpc':None, 'minPayoutRank':None}
80
81gflags.DEFINE_enum(
82 'relationshipStatus', None,
83 ['APPROVED', 'AVAILABLE', 'PENDING', 'DECLINED', 'DEACTIVATED'],
84 'Status of the relationship')
85
86gflags.DEFINE_string(
87 'advertiserId', None,
88 'Advertiser ID to lookup (get requests only).')
89
90gflags.DEFINE_string('category', None,
91 'Caret delimited set of advertiser categories to include'
92 + ' (list requests only).')
93
94gflags.DEFINE_string('minSevenDayEpc', None,
95 'Minimum value for the advertiser\'s seven day EPC'
96 + ' (list requests only).')
97
98gflags.DEFINE_string('minNinetyDayEpc', None,
99 'Minimum value for the advertiser\'s ninety day EPC'
100 + ' (list requests only).')
101
102gflags.DEFINE_enum('minPayoutRank', None, ['1', '2', '3', '4'],
103 'Minimum value for the advertiser\'s payout rank'
104 + ' (list requests only)')
105
106def usage(argv):
107 print 'Usage: %s <role> <role-id>\n%s' % (argv[0], FLAGS)
108 sys.exit(1)
109
110
111def main(argv):
112 # Let the gflags module process the command-line arguments
113 try:
114 argv = FLAGS(argv)
115 except gflags.FlagsError, e:
116 print e
117 usage(argv)
118
119 if len(argv) != 3:
120 usage(argv)
121 params = {
122 'role': argv[1],
123 'roleId': argv[2]
124 }
125
126 # Set the logging according to the command-line flag
127 logging.getLogger().setLevel(getattr(logging, FLAGS.logging_level))
128
129 # If the Credentials don't exist or are invalid run through the native client
130 # flow. The Storage object will ensure that if successful the good
131 # Credentials will get written back to a file.
132 storage = Storage(FLAGS.credentials_filename)
133 credentials = storage.get()
134 if credentials is None or credentials.invalid:
135 credentials = run(FLOW, storage)
136
137 # Create an httplib2.Http object to handle our HTTP requests and authorize it
138 # with our good Credentials.
139 http = httplib2.Http()
140 http = credentials.authorize(http)
141
142 service = build('gan', 'v1beta1', http=http)
143
144 advertisers = service.advertisers()
145
146 # Filter out all params that aren't set.
147 for key in FLAGS:
148 if key in API_FLAGS and FLAGS[key].value != None:
149 params[key] = FLAGS[key].value
150
151 # Retrieve the relevant advertisers.
152 stdout = {}
153 html = {}
154 try:
155 if FLAGS.request_type == "GET":
156 get_call = advertisers.get(**params)
157
158 stdout = get_call.execute()
159 html['items'] = [stdout['item']]
160 else:
161 all_items = []
162 request = advertisers.list(**params)
163 while request:
164 response = request.execute()
165 if 'items' in response:
166 all_items.extend(response['items'])
167 request = advertisers.list_next(request, response)
168
169 html['items'] = all_items
170 stdout = html
171 except apiclient.errors.HttpError, e:
172 print json.dumps(e.__dict__, sort_keys=True, indent=4)
173
174 if FLAGS.output_type in ["BOTH", "HTML"]:
175 template = get_template('advertisers_template.html')
176 context = Context(html)
177
178 out = open("output.html", 'w')
179 out.write(template.render(context).encode('UTF-8'))
180 os.fchmod(out.fileno(), stat.S_IROTH|stat.S_IRGRP|stat.S_IRUSR|stat.S_IWUSR)
181 out.close()
182
183 print 'Wrote output.html'
184
185 if FLAGS.output_type in ["BOTH", "STDOUT"]:
186 print json.dumps(stdout, sort_keys=True, indent=4)
187
188if __name__ == '__main__':
189 main(sys.argv)