blob: bc45167cbe8eac2c170315bf680fe7ca7e4bd881 [file] [log] [blame]
Joe Gregorio093d9bf2011-09-08 16:09:55 -04001#!/usr/bin/python2.4
2# -*- coding: utf-8 -*-
3#
4# Copyright (C) 2011 Google Inc.
5
leadpipe@wpgntav-ubiq70.hot.corp.google.combba48982011-11-02 16:27:24 -05006"""Sample for retrieving event information from GAN."""
Joe Gregorio093d9bf2011-09-08 16:09:55 -04007
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
leadpipe@wpgntav-ubiq70.hot.corp.google.combba48982011-11-02 16:27:24 -050025from oauth2client.client import AccessTokenRefreshError
26from oauth2client.client import flow_from_clientsecrets
Joe Gregorio093d9bf2011-09-08 16:09:55 -040027from oauth2client.tools import run
28
29settings.configure(DEBUG=True, TEMPLATE_DEBUG=True,
30 TEMPLATE_DIRS=('.'))
31
32
33FLAGS = gflags.FLAGS
34
leadpipe@wpgntav-ubiq70.hot.corp.google.combba48982011-11-02 16:27:24 -050035# 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,
Joe Gregorio093d9bf2011-09-08 16:09:55 -040057 scope='https://www.googleapis.com/auth/gan.readonly',
leadpipe@wpgntav-ubiq70.hot.corp.google.combba48982011-11-02 16:27:24 -050058 message=MISSING_CLIENT_SECRETS_MESSAGE)
Joe Gregorio093d9bf2011-09-08 16:09:55 -040059
60# The gflags module makes defining command-line options easy for
61# applications. Run this program with the '--help' argument to see
62# all the flags that it understands.
63gflags.DEFINE_enum('logging_level', 'DEBUG',
64 ['DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL'],
65 'Set the level of logging detail.')
66
67gflags.DEFINE_enum("output_type", 'STDOUT', ['BOTH', 'HTML', 'STDOUT'],
68 'Set how to output the results received from the API')
69
leadpipe@wpgntav-ubiq70.hot.corp.google.combba48982011-11-02 16:27:24 -050070gflags.DEFINE_string('credentials_filename', '../credentials.dat',
Joe Gregorio093d9bf2011-09-08 16:09:55 -040071 'File to store credentials in', short_name='cf')
72
73API_FLAGS = {'eventDateMin':None, 'eventDateMax':None, 'advertiserId':None,
74 'publisherId':None, 'orderId':None, 'sku':None,
75 'productCategory':None, 'linkId':None, 'memberId':None,
76 'status':None, 'type':None, 'role':None, 'roleId':None}
77
78gflags.DEFINE_string(
79 'eventDateMin', None,
80 'RFC 3339 formatted min date. Ex: 2005-08-09-T10:57:00-08:00')
81
82gflags.DEFINE_string(
83 'eventDateMax', None,
84 'RFC 3339 formatted max date. Ex: 2005-08-09-T10:57:00-08:00')
85
86gflags.DEFINE_string('advertiserId', None,
87 'caret delimited advertiser IDs')
88
89gflags.DEFINE_string('publisherId', None,
90 'caret delimited publisher IDs')
91
92gflags.DEFINE_string('orderId', None,
93 'caret delimited order IDs')
94
95gflags.DEFINE_string('sku', None,
96 'caret delimited SKUs')
97
98gflags.DEFINE_string('productCategory', None,
99 'caret delimited product categories')
100
101gflags.DEFINE_string('linkId', None,
102 'caret delimited link IDs')
103
104gflags.DEFINE_string('memberId', None,
105 'caret delimited member IDs')
106
107gflags.DEFINE_string('status', None,
108 'status of events - valid values "active" or "cancelled"')
109
110gflags.DEFINE_string('type', None,
111 'type of events - valid values "action" or "transaction"')
112
113
114def usage(argv):
115 print 'Usage: %s <role> <role-id>\n%s' % (argv[0], FLAGS)
116 sys.exit(1)
117
118
119def main(argv):
120 # Let the gflags module process the command-line arguments
121 try:
122 argv = FLAGS(argv)
123 except gflags.FlagsError, e:
124 print e
125 usage(argv)
126
127 if len(argv) != 3:
128 usage(argv)
129 params = {
130 'role': argv[1],
131 'roleId': argv[2]
132 }
133
134 # Set the logging according to the command-line flag
135 logging.getLogger().setLevel(getattr(logging, FLAGS.logging_level))
136
137 # If the Credentials don't exist or are invalid run through the native client
138 # flow. The Storage object will ensure that if successful the good
139 # Credentials will get written back to a file.
140 storage = Storage(FLAGS.credentials_filename)
141 credentials = storage.get()
142 if credentials is None or credentials.invalid:
143 credentials = run(FLOW, storage)
144
145 # Create an httplib2.Http object to handle our HTTP requests and authorize it
146 # with our good Credentials.
147 http = httplib2.Http()
148 http = credentials.authorize(http)
149
150 service = build('gan', 'v1beta1', http=http)
151
152 events = service.events()
153
154 # Filter out all params that aren't set.
155 for key in FLAGS:
156 if key in API_FLAGS and FLAGS[key].value != None:
157 params[key] = FLAGS[key].value
158
159 # Retrieve the relevant events.
leadpipe@wpgntav-ubiq70.hot.corp.google.combba48982011-11-02 16:27:24 -0500160 all_items = []
Joe Gregorio093d9bf2011-09-08 16:09:55 -0400161 try:
leadpipe@wpgntav-ubiq70.hot.corp.google.combba48982011-11-02 16:27:24 -0500162 request = events.list(**params)
163 while request:
164 response = request.execute()
165 if FLAGS.output_type in ["BOTH", "STDOUT"]:
166 print json.dumps(response, sort_keys=True, indent=4)
167 all_items.extend(response['items'])
168 request = events.list_next(request, response)
169
Joe Gregorio093d9bf2011-09-08 16:09:55 -0400170 except apiclient.errors.HttpError, e:
171 print json.dumps(e.__dict__, sort_keys=True, indent=4)
172
173 if FLAGS.output_type in ["BOTH", "HTML"]:
174 template = get_template('events_template.html')
leadpipe@wpgntav-ubiq70.hot.corp.google.combba48982011-11-02 16:27:24 -0500175 context = Context({'items':items})
Joe Gregorio093d9bf2011-09-08 16:09:55 -0400176
177 out = open("output.html", 'w')
178 out.write(template.render(context).encode('UTF-8'))
179 os.fchmod(out.fileno(), stat.S_IROTH|stat.S_IRGRP|stat.S_IRUSR|stat.S_IWUSR)
180 out.close()
181
182 print 'Wrote output.html'
183
Joe Gregorio093d9bf2011-09-08 16:09:55 -0400184if __name__ == '__main__':
185 main(sys.argv)