First pass at CLI for Ruby client.
[arvados.git] / bin / google-api
1 #!/usr/bin/env ruby
2
3 bin_dir = File.expand_path("..", __FILE__)
4 lib_dir = File.expand_path("../lib", bin_dir)
5
6 $LOAD_PATH.unshift(lib_dir)
7 $LOAD_PATH.uniq!
8
9 OAUTH_SERVER_PORT = 12736
10
11 require 'rubygems'
12 require 'optparse'
13 require 'google/api_client/version'
14 require 'google/api_client'
15
16 ARGV.unshift('--help') if ARGV.empty?
17
18 command = 'execute'
19 options = {}
20 OptionParser.new do |opts|
21   opts.banner =
22     "Usage: google-api <rpcname> [options] -- <parameters>\n" +
23     "   or: google-api --oauth-login=<scope> [options]\n" +
24     "   or: google-api --fuzz [options]"
25
26   opts.separator ""
27
28   opts.on(
29       "--oauth-login <scope>", String, "Authorize for the scope") do |s|
30     command = 'oauth-login'
31     options[:scope] = s
32   end
33   opts.on(
34       "-s", "--service <name>", String, "Perform discovery on service") do |s|
35     options[:service_name] = s
36   end
37   opts.on(
38       "--service-version <id>", String, "Select service version") do |id|
39     options[:service_version] = id
40   end
41   opts.on("--fuzz [rpcname]", String, "Fuzz an API or endpoint") do |rpcname|
42     command = 'fuzz'
43     options[:fuzz] = rpcname
44   end
45
46   opts.on_tail("-v", "--verbose", "Run verbosely") do |v|
47     options[:verbose] = v
48   end
49   opts.on_tail("-h", "--help", "Show this message") do
50     puts opts
51     exit
52   end
53   opts.on_tail("--version", "Show version") do
54     puts "google-api-client (#{Google::APIClient::VERSION::STRING})"
55     exit
56   end
57 end.parse!
58
59 if command == 'oauth-login' # Guard to keep start-up time short
60   require 'webrick'
61   # Used for oauth login
62   class OAuthVerifierServlet < WEBrick::HTTPServlet::AbstractServlet
63     def do_GET(request, response)
64       $verifier ||= Addressable::URI.unencode_component(
65         request.request_uri.to_s[/\?.*oauth_verifier=([^&$]+)(&|$)/, 1]
66       )
67       response.status = WEBrick::HTTPStatus::RC_ACCEPTED
68       # This javascript will auto-close the tab after the verifier is obtained.
69       response.body = <<-HTML
70 <html>
71   <head>
72     <script>
73       function closeWindow() { 
74         window.open('', '_self', '');
75         window.close();
76       }
77       setTimeout(closeWindow, 10);
78     </script>
79   </head>
80   <body>
81     You may close this window.
82   </body>
83 </html>
84 HTML
85       self.instance_variable_get('@server').stop
86     end
87   end
88 end
89
90 def oauth_login(options={})
91   require 'signet/oauth_1/client'
92   require 'launchy'
93   require 'yaml'
94   $verifier = nil
95   logger = WEBrick::Log.new('/dev/null') # TODO(bobaman): Cross-platform?
96   server = WEBrick::HTTPServer.new(
97     :Port => OAUTH_SERVER_PORT,
98     :Logger => logger,
99     :AccessLog => logger
100   )
101   trap("INT") { server.shutdown }
102
103   server.mount("/", OAuthVerifierServlet)
104
105   oauth_client = Signet::OAuth1::Client.new(
106     :temporary_credential_uri =>
107       'https://www.google.com/accounts/OAuthGetRequestToken',
108     :authorization_uri =>
109       'https://www.google.com/accounts/OAuthAuthorizeToken',
110     :token_credential_uri =>
111       'https://www.google.com/accounts/OAuthGetAccessToken',
112     :client_credential_key => 'anonymous',
113     :client_credential_secret => 'anonymous',
114     :callback => "http://localhost:#{OAUTH_SERVER_PORT}/"
115   )
116   scope = options[:scope]
117   # Special cases
118   case scope
119   when "https://www.googleapis.com/auth/buzz",
120       "https://www.googleapis.com/auth/buzz.readonly"
121     oauth_client.authorization_uri =
122       'https://www.google.com/buzz/api/auth/OAuthAuthorizeToken?' +
123       "domain=#{oauth_client.client_credential_key}&" +
124       "scope=#{scope}&" +
125       "xoauth_displayname=Google%20API%20Client"
126   end
127   oauth_client.fetch_temporary_credential!(:additional_parameters => {
128     :scope => scope,
129     :xoauth_displayname => 'Google API Client'
130   })
131
132   # Launch browser
133   Launchy::Browser.run(oauth_client.authorization_uri.to_s)
134
135   server.start
136   oauth_client.fetch_token_credential!(:verifier => $verifier)
137   config = {
138     "client_credential_key" => oauth_client.client_credential_key,
139     "client_credential_secret" => oauth_client.client_credential_secret,
140     "token_credential_key" => oauth_client.token_credential_key,
141     "token_credential_secret" => oauth_client.token_credential_secret
142   }
143   config_file = File.expand_path('~/.google-api.yaml')
144   open(config_file, 'w') { |file| file.write(YAML.dump(config)) }
145   exit(0)
146 end
147
148 def execute(options={})
149   config_file = File.expand_path('~/.google-api.yaml')
150   signed = File.exist?(config_file)
151   rpcname = ARGV.detect { |p| p =~ /^[a-z0-9_-]+\.[a-z0-9_\.-]+$/i }
152   if rpcname
153     ARGV.delete(rpcname)
154   else
155     STDERR.puts('Could not find rpcname.')
156     exit(1)
157   end
158   service_name = options[:service_name] || rpcname[/^([^\.]+)\./, 1]
159   client = Google::APIClient.new(:service => service_name)
160   if signed
161     if !client.authorization.kind_of?(Signet::OAuth1::Client)
162       STDERR.puts(
163         "Unexpected authorization mechanism: #{client.authorization.class}"
164       )
165       exit(1)
166     end
167     config = open(config_file, 'r') { |file| YAML.load(file.read) }
168     client.authorization.client_credential_key =
169       config["client_credential_key"]
170     client.authorization.client_credential_secret =
171       config["client_credential_secret"]
172     client.authorization.token_credential_key =
173       config["token_credential_key"]
174     client.authorization.token_credential_secret =
175       config["token_credential_secret"]
176   end
177   service_version =
178     options[:service_version] || client.latest_service(service_name).version
179   service = client.discovered_service(service_name, service_version)
180   method = service.to_h[rpcname]
181   if !method
182     STDERR.puts(
183       "Method #{rpcname} does not exist for " +
184       "#{service_name}-#{service_version}."
185     )
186     exit(1)
187   end
188   parameters = ARGV.inject({}) do |accu, pair|
189     name, value = pair.split('=', 2)
190     accu[name] = value
191     accu
192   end
193   request_body = ''
194   input_streams, _, _ = IO.select([STDIN], [], [], 0)
195   request_body = STDIN.read || '' if input_streams
196   response = client.execute(
197     method, parameters, request_body, [], {:signed => signed}
198   )
199   status, headers, body = response
200   puts body
201   exit(0)
202 end
203
204 def fuzz(options={})
205   STDERR.puts('API fuzzing not yet supported.')
206   if rpcname
207     # Fuzz just one method
208   else
209     # Fuzz the entire API
210   end
211   exit(1)
212 end
213
214 self.send(command.gsub(/-/, "_").to_sym, options)