blob: 64493b5cfedcb80c92afccc23213e0d91f28def6 [file] [log] [blame]
ade@google.comc7da92b2010-10-25 20:03:48 -04001# Copyright (C) 2010 Google Inc.
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.
ade@google.com46aad172011-01-04 00:14:17 +000014from apiclient.discovery import build
15from apiclient.oauth import FlowThreeLegged
16
17import datetime
ade@google.comc7da92b2010-10-25 20:03:48 -040018import httplib2
19import logging
20import oauth_wrap
ade@google.com46aad172011-01-04 00:14:17 +000021import optparse
ade@google.comc7da92b2010-10-25 20:03:48 -040022import os
23import sys
24
ade@google.com46aad172011-01-04 00:14:17 +000025
ade@google.comc7da92b2010-10-25 20:03:48 -040026def load_properties_file(path):
27 properties = {}
28 for line in open(path):
29 line = line.strip()
30 if line.startswith('#'):
31 continue
32
33 key,value = line.split('=')
34 properties[key.strip()] = value.strip()
35 return properties
36
ade@google.com46aad172011-01-04 00:14:17 +000037
38def save_properties(consumer_key, consumer_secret, token_key, token_secret, path):
39 file = open(path, 'w')
40
41 # File format and order is based on oacurl.java's defaults
42 now = datetime.datetime.today()
43 now_string = now.strftime('%a %b %d %H:%m:%S %Z %Y')
44 file.write('#%s\n' % now_string)
45 file.write('consumerSecret=%s\n' % consumer_secret)
46 file.write('accessToken=%s\n' % token_key)
47 file.write('consumerKey=%s\n' % consumer_key)
48 file.write('accessTokenSecret=%s\n' % token_secret)
49 file.close()
50
ade@google.comc7da92b2010-10-25 20:03:48 -040051def fetch(url):
52 logging.debug('Now fetching: %s' % url)
53
54 path = os.path.expanduser('~/.oacurl.properties')
55 if not os.path.exists(path):
56 logging.debug('User is not logged in.')
57
58 print 'You are not logged in'
59 sys.exit(1)
ade@google.com46aad172011-01-04 00:14:17 +000060
ade@google.comc7da92b2010-10-25 20:03:48 -040061 properties = load_properties_file(path)
62 oauth_parameters = {
63 'consumer_key': properties['consumerKey'],
64 'consumer_secret' : properties['consumerSecret'],
65 'oauth_token' : properties['accessToken'],
66 'oauth_token_secret':properties['accessTokenSecret']}
67
68 http = oauth_wrap.get_authorised_http(oauth_parameters)
69 response, content = http.request(url)
70 logging.debug(response)
71 logging.debug(content)
72
73 return response,content
74
ade@google.com46aad172011-01-04 00:14:17 +000075
76def buzz_login():
77 buzz_discovery = build("buzz", "v1").auth_discovery()
78
79 flow = FlowThreeLegged(buzz_discovery,
80 consumer_key='anonymous',
81 consumer_secret='anonymous',
82 user_agent='google-api-client-python-buzz-cmdline/1.0',
83 domain='anonymous',
84 scope='https://www.googleapis.com/auth/buzz',
85 xoauth_displayname='oacurl.py')
86
87 authorize_url = flow.step1_get_authorize_url()
88
89 print 'Go to the following link in your browser:'
90 print authorize_url
91 print
92
93 accepted = 'n'
94 while accepted.lower() == 'n':
95 accepted = raw_input('Have you authorized me? (y/n) ')
96 verification = raw_input('What is the verification code? ').strip()
97
98 credentials = flow.step2_exchange(verification)
99 path = os.path.expanduser('~/.oacurl.properties')
100 save_properties('anonymous', 'anonymous', credentials.token.key, credentials.token.secret,path)
101
102
103def generic_login():
104 #TODO(ade) Implement support for other services
105 print 'Support for services other than Buzz is not implemented yet. Sorry.'
106
107def login(options):
108 if options.buzz:
109 buzz_login()
110 else:
111 generic_login()
112
113
ade@google.comc7da92b2010-10-25 20:03:48 -0400114def get_command(args):
ade@google.com46aad172011-01-04 00:14:17 +0000115 if args[0] == 'login':
116 return 'login'
ade@google.comc7da92b2010-10-25 20:03:48 -0400117 if args[0] == 'fetch':
118 return 'fetch'
119 return None
120
121def configure_logging(options):
122 if options.verbose:
123 logging.basicConfig(level=logging.DEBUG)
124
125def main():
126 usage = '''Usage: %prog [options] fetch <url>
127 Example: %prog -v fetch "https://www.googleapis.com/buzz/v1/people/@me/@self?alt=json&pp=1"
128 '''
129 parser = optparse.OptionParser(usage=usage)
130 parser.set_defaults(verbose=False)
131 parser.add_option('-v', '--verbose', action='store_true', dest='verbose')
132 parser.add_option('-q', '--quiet', action='store_false', dest='verbose')
ade@google.com46aad172011-01-04 00:14:17 +0000133 parser.add_option('--buzz', action='store_true', dest='buzz')
ade@google.comc7da92b2010-10-25 20:03:48 -0400134
135 (options, args) = parser.parse_args()
136
137 configure_logging(options)
138 logging.debug('Options: %s and Args: %s' % (str(options), str(args)))
139
140 command = get_command(args)
141
142 if not command:
143 parser.error('Invalid arguments')
144 return
145
146 if command == 'fetch':
147 response, content = fetch(args[1])
148 print response
149 print content
ade@google.com46aad172011-01-04 00:14:17 +0000150 return
151
152 if command == 'login':
153 login(options)
ade@google.comc7da92b2010-10-25 20:03:48 -0400154
155if __name__ == '__main__':
156 main()