3 bin_dir = File.expand_path("..", __FILE__)
4 lib_dir = File.expand_path("../lib", bin_dir)
6 $LOAD_PATH.unshift(lib_dir)
9 OAUTH_SERVER_PORT = 12736
15 require 'google/api_client/version'
16 require 'google/api_client'
18 ARGV.unshift('--help') if ARGV.empty?
23 # Used for oauth login
24 class OAuthVerifierServlet < WEBrick::HTTPServlet::AbstractServlet
27 def do_GET(request, response)
28 $verifier ||= Addressable::URI.unencode_component(
29 request.request_uri.to_s[/\?.*oauth_verifier=([^&$]+)(&|$)/, 1] ||
30 request.request_uri.to_s[/\?.*code=([^&$]+)(&|$)/, 1]
32 response.status = WEBrick::HTTPStatus::RC_ACCEPTED
33 # This javascript will auto-close the tab after the
34 # verifier is obtained.
35 response.body = <<-HTML
39 function closeWindow() {
40 window.open('', '_self', '');
43 setTimeout(closeWindow, 10);
47 You may close this window.
52 server = self.instance_variable_get('@server')
57 # Initialize with default parameter values
60 :command => 'execute',
65 if @argv.first =~ /^[a-z0-9][a-z0-9_-]*$/i
66 self.options[:command] = @argv.shift
68 if @argv.first =~ /^[a-z0-9_-]+\.[a-z0-9_\.-]+$/i
69 self.options[:rpcname] = @argv.shift
77 return self.options[:command]
81 return self.options[:rpcname]
85 @parser ||= OptionParser.new do |opts|
86 opts.banner = "Usage: google-api " +
87 "(execute <rpcname> | [command]) [options] [-- <parameters>]"
89 opts.separator "\nAvailable options:"
92 "--scope <scope>", String, "Set the OAuth scope") do |s|
96 "--client-id <key>", String,
97 "Set the OAuth client id or key") do |k|
98 options[:client_credential_key] = k
101 "--client-secret <secret>", String,
102 "Set the OAuth client secret") do |s|
103 options[:client_credential_secret] = s
106 "--api <name>", String,
107 "Perform discovery on API") do |s|
111 "--service-version <id>", String,
112 "Select service version") do |id|
113 options[:version] = id
116 "--content-type <format>", String,
117 "Content-Type for request") do |f|
118 # Resolve content type shortcuts
121 f = 'application/json'
123 f = 'application/xml'
125 f = 'application/atom+xml'
127 f = 'application/rss+xml'
129 options[:content_type] = f
132 "-u", "--uri <uri>", String,
133 "Sets the URI to perform a request against") do |u|
137 "--discovery-uri <uri>", String,
138 "Sets the URI to perform discovery") do |u|
139 options[:discovery_uri] = u
142 "-m", "--method <method>", String,
143 "Sets the HTTP method to use for the request") do |m|
144 options[:http_method] = m
147 "--requestor-id <email>", String,
148 "Sets the email address of the requestor") do |e|
149 options[:requestor_id] = e
152 opts.on("-v", "--verbose", "Run verbosely") do |v|
153 options[:verbose] = v
155 opts.on("-h", "--help", "Show this message") do
159 opts.on("--version", "Show version") do
160 puts "google-api-client (#{Google::APIClient::VERSION::STRING})"
165 "\nAvailable commands:\n" +
166 " oauth-1-login Log a user into an API with OAuth 1.0a\n" +
167 " oauth-2-login Log a user into an API with OAuth 2.0 d10\n" +
168 " list List the methods available for a service\n" +
169 " execute Execute a method on the API\n" +
170 " irb Start an interactive client session"
176 self.parser.parse!(self.argv)
177 symbol = self.command.gsub(/-/, "_").to_sym
178 if !COMMANDS.include?(symbol)
179 STDERR.puts("Invalid command: #{self.command}")
186 require 'signet/oauth_1/client'
189 config_file = File.expand_path('~/.google-api.yaml')
191 if File.exist?(config_file)
192 config = open(config_file, 'r') { |file| YAML.load(file.read) }
196 if config["mechanism"]
197 authorization = config["mechanism"].to_sym
200 client = Google::APIClient.new(:authorization => authorization)
204 if client.authorization &&
205 !client.authorization.kind_of?(Signet::OAuth1::Client)
207 "Unexpected authorization mechanism: " +
208 "#{client.authorization.class}"
212 config = open(config_file, 'r') { |file| YAML.load(file.read) }
213 client.authorization.client_credential_key =
214 config["client_credential_key"]
215 client.authorization.client_credential_secret =
216 config["client_credential_secret"]
217 client.authorization.token_credential_key =
218 config["token_credential_key"]
219 client.authorization.token_credential_secret =
220 config["token_credential_secret"]
222 if client.authorization &&
223 !client.authorization.kind_of?(Signet::OAuth2::Client)
225 "Unexpected authorization mechanism: " +
226 "#{client.authorization.class}"
230 config = open(config_file, 'r') { |file| YAML.load(file.read) }
231 client.authorization.scope = options[:scope]
232 client.authorization.client_id = config["client_id"]
233 client.authorization.client_secret = config["client_secret"]
234 client.authorization.access_token = config["access_token"]
235 client.authorization.refresh_token = config["refresh_token"]
240 if options[:discovery_uri]
241 client.discovery_uri = options[:discovery_uri]
247 def api_version(api, version)
250 if client.preferred_version(api)
251 v = client.preferred_version(api).version
269 require 'signet/oauth_1/client'
272 if options[:client_credential_key] &&
273 options[:client_credential_secret]
275 "mechanism" => "oauth_1",
276 "scope" => options[:scope],
277 "client_credential_key" => options[:client_credential_key],
278 "client_credential_secret" => options[:client_credential_secret],
279 "token_credential_key" => nil,
280 "token_credential_secret" => nil
282 config_file = File.expand_path('~/.google-api.yaml')
283 open(config_file, 'w') { |file| file.write(YAML.dump(config)) }
287 # TODO(bobaman): Cross-platform?
288 logger = WEBrick::Log.new('/dev/null')
289 server = WEBrick::HTTPServer.new(
290 :Port => OAUTH_SERVER_PORT,
294 trap("INT") { server.shutdown }
296 server.mount("/", OAuthVerifierServlet)
298 oauth_client = Signet::OAuth1::Client.new(
299 :temporary_credential_uri =>
300 'https://www.google.com/accounts/OAuthGetRequestToken',
301 :authorization_uri =>
302 'https://www.google.com/accounts/OAuthAuthorizeToken',
303 :token_credential_uri =>
304 'https://www.google.com/accounts/OAuthGetAccessToken',
305 :client_credential_key => 'anonymous',
306 :client_credential_secret => 'anonymous',
307 :callback => "http://localhost:#{OAUTH_SERVER_PORT}/"
309 oauth_client.fetch_temporary_credential!(:additional_parameters => {
310 :scope => options[:scope],
311 :xoauth_displayname => 'Google API Client'
315 Launchy::Browser.run(oauth_client.authorization_uri.to_s)
318 oauth_client.fetch_token_credential!(:verifier => $verifier)
320 "scope" => options[:scope],
321 "client_credential_key" =>
322 oauth_client.client_credential_key,
323 "client_credential_secret" =>
324 oauth_client.client_credential_secret,
325 "token_credential_key" =>
326 oauth_client.token_credential_key,
327 "token_credential_secret" =>
328 oauth_client.token_credential_secret
330 config_file = File.expand_path('~/.google-api.yaml')
331 open(config_file, 'w') { |file| file.write(YAML.dump(config)) }
337 require 'signet/oauth_2/client'
340 if !options[:client_credential_key] ||
341 !options[:client_credential_secret]
342 STDERR.puts('No client ID and secret supplied.')
345 if options[:access_token]
347 "mechanism" => "oauth_2",
348 "scope" => options[:scope],
349 "client_id" => options[:client_credential_key],
350 "client_secret" => options[:client_credential_secret],
351 "access_token" => options[:access_token],
352 "refresh_token" => options[:refresh_token]
354 config_file = File.expand_path('~/.google-api.yaml')
355 open(config_file, 'w') { |file| file.write(YAML.dump(config)) }
359 # TODO(bobaman): Cross-platform?
360 logger = WEBrick::Log.new('/dev/null')
361 server = WEBrick::HTTPServer.new(
362 :Port => OAUTH_SERVER_PORT,
366 trap("INT") { server.shutdown }
368 server.mount("/", OAuthVerifierServlet)
370 oauth_client = Signet::OAuth2::Client.new(
371 :authorization_uri =>
372 'https://www.google.com/accounts/o8/oauth2/authorization',
373 :token_credential_uri =>
374 'https://www.google.com/accounts/o8/oauth2/token',
375 :client_id => options[:client_credential_key],
376 :client_secret => options[:client_credential_secret],
377 :redirect_uri => "http://localhost:#{OAUTH_SERVER_PORT}/",
378 :scope => options[:scope]
382 Launchy::Browser.run(oauth_client.authorization_uri.to_s)
385 oauth_client.code = $verifier
386 oauth_client.fetch_access_token!
388 "mechanism" => "oauth_2",
389 "scope" => options[:scope],
390 "client_id" => oauth_client.client_id,
391 "client_secret" => oauth_client.client_secret,
392 "access_token" => oauth_client.access_token,
393 "refresh_token" => oauth_client.refresh_token
395 config_file = File.expand_path('~/.google-api.yaml')
396 open(config_file, 'w') { |file| file.write(YAML.dump(config)) }
404 STDERR.puts('No API name supplied.')
407 client = Google::APIClient.new(:authorization => nil)
408 if options[:discovery_uri]
409 client.discovery_uri = options[:discovery_uri]
411 version = api_version(api, options[:version])
412 service = client.discovered_api(api, version)
413 rpcnames = service.to_h.keys
414 puts rpcnames.sort.join("\n")
421 # Setup HTTP request data
423 input_streams, _, _ = IO.select([STDIN], [], [], 0)
424 request_body = STDIN.read || '' if input_streams
426 if options[:content_type]
427 headers << ['Content-Type', options[:content_type]]
430 headers << ['Content-Type', 'application/json']
434 # Make request with URI manually specified
435 uri = Addressable::URI.parse(options[:uri])
437 STDERR.puts('URI may not be relative.')
440 if options[:requestor_id]
441 uri.query_values = uri.query_values.merge(
442 'xoauth_requestor_id' => options[:requestor_id]
445 method = options[:http_method]
446 method ||= request_body == '' ? 'GET' : 'POST'
448 request = [method, uri.to_str, headers, [request_body]]
449 request = client.generate_authenticated_request(:request => request)
450 response = client.transmit(request)
451 status, headers, body = response
455 # Make request with URI generated from template and parameters
457 STDERR.puts('No rpcname supplied.')
460 api = options[:api] || self.rpcname[/^([^\.]+)\./, 1]
461 version = api_version(api, options[:version])
462 service = client.discovered_api(api, version)
463 method = service.to_h[self.rpcname]
466 "Method #{self.rpcname} does not exist for " +
471 parameters = self.argv.inject({}) do |accu, pair|
472 name, value = pair.split('=', 2)
476 if options[:requestor_id]
477 parameters['xoauth_requestor_id'] = options[:requestor_id]
480 result = client.execute(
481 :api_method => method,
482 :parameters => parameters,
483 :merged_body => request_body,
486 status, headers, body = result.response
489 rescue ArgumentError => e
497 $client = self.client
498 # Otherwise IRB will misinterpret command-line options
504 STDERR.puts('API fuzzing not yet supported.')
506 # Fuzz just one method
508 # Fuzz the entire API
521 Google::APIClient::CLI.new(ARGV).parse!