forked from googleapis/google-api-ruby-client
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgoogle-api
executable file
·390 lines (358 loc) · 11.8 KB
/
google-api
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
#!/usr/bin/env ruby
bin_dir = File.expand_path("..", __FILE__)
lib_dir = File.expand_path("../lib", bin_dir)
$LOAD_PATH.unshift(lib_dir)
$LOAD_PATH.uniq!
OAUTH_SERVER_PORT = 12736
require 'rubygems'
require 'optparse'
require 'faraday'
require 'webrick'
require 'google/api_client/version'
require 'google/api_client'
require 'google/api_client/auth/installed_app'
require 'irb'
ARGV.unshift('--help') if ARGV.empty?
module Google
class APIClient
class CLI
# Initialize with default parameter values
def initialize(argv)
@options = {
:command => 'execute',
:rpcname => nil,
:verbose => false
}
@argv = argv.clone
if @argv.first =~ /^[a-z0-9][a-z0-9_-]*$/i
self.options[:command] = @argv.shift
end
if @argv.first =~ /^[a-z0-9_-]+\.[a-z0-9_\.-]+$/i
self.options[:rpcname] = @argv.shift
end
end
attr_reader :options
attr_reader :argv
def command
return self.options[:command]
end
def rpcname
return self.options[:rpcname]
end
def parser
@parser ||= OptionParser.new do |opts|
opts.banner = "Usage: google-api " +
"(execute <rpcname> | [command]) [options] [-- <parameters>]"
opts.separator "\nAvailable options:"
opts.on(
"--scope <scope>", String, "Set the OAuth scope") do |s|
options[:scope] = s
end
opts.on(
"--client-id <key>", String,
"Set the OAuth client id or key") do |k|
options[:client_credential_key] = k
end
opts.on(
"--client-secret <secret>", String,
"Set the OAuth client secret") do |s|
options[:client_credential_secret] = s
end
opts.on(
"--api <name>", String,
"Perform discovery on API") do |s|
options[:api] = s
end
opts.on(
"--api-version <id>", String,
"Select api version") do |id|
options[:version] = id
end
opts.on(
"--content-type <format>", String,
"Content-Type for request") do |f|
# Resolve content type shortcuts
case f
when 'json'
f = 'application/json'
when 'xml'
f = 'application/xml'
when 'atom'
f = 'application/atom+xml'
when 'rss'
f = 'application/rss+xml'
end
options[:content_type] = f
end
opts.on(
"-u", "--uri <uri>", String,
"Sets the URI to perform a request against") do |u|
options[:uri] = u
end
opts.on(
"--discovery-uri <uri>", String,
"Sets the URI to perform discovery") do |u|
options[:discovery_uri] = u
end
opts.on(
"-m", "--method <method>", String,
"Sets the HTTP method to use for the request") do |m|
options[:http_method] = m
end
opts.on(
"--requestor-id <email>", String,
"Sets the email address of the requestor") do |e|
options[:requestor_id] = e
end
opts.on("-v", "--verbose", "Run verbosely") do |v|
options[:verbose] = v
end
opts.on("-h", "--help", "Show this message") do
puts opts
exit
end
opts.on("--version", "Show version") do
puts "google-api-client (#{Google::APIClient::VERSION::STRING})"
exit
end
opts.separator(
"\nAvailable commands:\n" +
" oauth-2-login Log a user into an API with OAuth 2.0\n" +
" list List the methods available for an API\n" +
" execute Execute a method on the API\n" +
" irb Start an interactive client session"
)
end
end
def parse!
self.parser.parse!(self.argv)
symbol = self.command.gsub(/-/, "_").to_sym
if !COMMANDS.include?(symbol)
STDERR.puts("Invalid command: #{self.command}")
exit(1)
end
self.send(symbol)
end
def client
require 'yaml'
config_file = File.expand_path('~/.google-api.yaml')
authorization = nil
if File.exist?(config_file)
config = open(config_file, 'r') { |file| YAML.load(file.read) }
else
config = {}
end
if config["mechanism"]
authorization = config["mechanism"].to_sym
end
client = Google::APIClient.new(
:application_name => 'Ruby CLI',
:application_version => Google::APIClient::VERSION::STRING,
:authorization => authorization)
case authorization
when :oauth_1
STDERR.puts('OAuth 1 is deprecated. Please reauthorize with OAuth 2.')
client.authorization.client_credential_key =
config["client_credential_key"]
client.authorization.client_credential_secret =
config["client_credential_secret"]
client.authorization.token_credential_key =
config["token_credential_key"]
client.authorization.token_credential_secret =
config["token_credential_secret"]
when :oauth_2
client.authorization.scope = options[:scope]
client.authorization.client_id = config["client_id"]
client.authorization.client_secret = config["client_secret"]
client.authorization.access_token = config["access_token"]
client.authorization.refresh_token = config["refresh_token"]
else
# Dunno?
end
if options[:discovery_uri]
if options[:api] && options[:version]
client.register_discovery_uri(
options[:api], options[:version], options[:discovery_uri]
)
else
STDERR.puts(
'Cannot register a discovery URI without ' +
'specifying an API and version.'
)
exit(1)
end
end
return client
end
def api_version(api_name, version)
v = version
if !version
if client.preferred_version(api_name)
v = client.preferred_version(api_name).version
else
v = 'v1'
end
end
return v
end
COMMANDS = [
:oauth_2_login,
:list,
:execute,
:irb,
]
def oauth_2_login
require 'signet/oauth_2/client'
require 'yaml'
if !options[:client_credential_key] ||
!options[:client_credential_secret]
STDERR.puts('No client ID and secret supplied.')
exit(1)
end
if options[:access_token]
config = {
"mechanism" => "oauth_2",
"scope" => options[:scope],
"client_id" => options[:client_credential_key],
"client_secret" => options[:client_credential_secret],
"access_token" => options[:access_token],
"refresh_token" => options[:refresh_token]
}
config_file = File.expand_path('~/.google-api.yaml')
open(config_file, 'w') { |file| file.write(YAML.dump(config)) }
exit(0)
else
flow = Google::APIClient::InstalledAppFlow.new(
:port => OAUTH_SERVER_PORT,
:client_id => options[:client_credential_key],
:client_secret => options[:client_credential_secret],
:scope => options[:scope]
)
oauth_client = flow.authorize
if oauth_client
config = {
"mechanism" => "oauth_2",
"scope" => options[:scope],
"client_id" => oauth_client.client_id,
"client_secret" => oauth_client.client_secret,
"access_token" => oauth_client.access_token,
"refresh_token" => oauth_client.refresh_token
}
config_file = File.expand_path('~/.google-api.yaml')
open(config_file, 'w') { |file| file.write(YAML.dump(config)) }
end
exit(0)
end
end
def list
api_name = options[:api]
unless api_name
STDERR.puts('No API name supplied.')
exit(1)
end
#client = Google::APIClient.new(:authorization => nil)
if options[:discovery_uri]
if options[:api] && options[:version]
client.register_discovery_uri(
options[:api], options[:version], options[:discovery_uri]
)
else
STDERR.puts(
'Cannot register a discovery URI without ' +
'specifying an API and version.'
)
exit(1)
end
end
version = api_version(api_name, options[:version])
api = client.discovered_api(api_name, version)
rpcnames = api.to_h.keys
puts rpcnames.sort.join("\n")
exit(0)
end
def execute
client = self.client
# Setup HTTP request data
request_body = ''
input_streams, _, _ = IO.select([STDIN], [], [], 0)
request_body = STDIN.read || '' if input_streams
headers = []
if options[:content_type]
headers << ['Content-Type', options[:content_type]]
elsif request_body
# Default to JSON
headers << ['Content-Type', 'application/json']
end
if options[:uri]
# Make request with URI manually specified
uri = Addressable::URI.parse(options[:uri])
if uri.relative?
STDERR.puts('URI may not be relative.')
exit(1)
end
if options[:requestor_id]
uri.query_values = uri.query_values.merge(
'xoauth_requestor_id' => options[:requestor_id]
)
end
method = options[:http_method]
method ||= request_body == '' ? 'GET' : 'POST'
method.upcase!
response = client.execute(:http_method => method, :uri => uri.to_str,
:headers => headers, :body => request_body)
puts response.body
exit(0)
else
# Make request with URI generated from template and parameters
if !self.rpcname
STDERR.puts('No rpcname supplied.')
exit(1)
end
api_name = options[:api] || self.rpcname[/^([^\.]+)\./, 1]
version = api_version(api_name, options[:version])
api = client.discovered_api(api_name, version)
method = api.to_h[self.rpcname]
if !method
STDERR.puts(
"Method #{self.rpcname} does not exist for " +
"#{api_name}-#{version}."
)
exit(1)
end
parameters = self.argv.inject({}) do |accu, pair|
name, value = pair.split('=', 2)
accu[name] = value
accu
end
if options[:requestor_id]
parameters['xoauth_requestor_id'] = options[:requestor_id]
end
begin
result = client.execute(
:api_method => method,
:parameters => parameters,
:merged_body => request_body,
:headers => headers
)
puts result.response.body
exit(0)
rescue ArgumentError => e
puts e.message
exit(1)
end
end
end
def irb
$client = self.client
# Otherwise IRB will misinterpret command-line options
ARGV.clear
IRB.start(__FILE__)
end
def help
puts self.parser
exit(0)
end
end
end
end
Google::APIClient::CLI.new(ARGV).parse!