Refresh samples + add new ones for YouTube, Analytics

This commit is contained in:
Steve Bazyl committed 2016-01-07 11:41:45 -08:00
1 parent 1715fc9945
commit fd4ff04266
15 files changed
+622 -165

No files matched your search

+94
View File
@@ -0,0 +1,94 @@
# Copyright 2016 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
require 'googleauth'
require 'googleauth/stores/file_token_store'
require 'fileutils'
require 'thor'
require 'os'
# Base command line module for samples. Provides authorization support,
# either using application default credentials or user authorization
# depending on the use case.
class BaseCli < Thor
include Thor::Actions
OOB_URI = 'urn:ietf:wg:oauth:2.0:oob'
class_option :user, :type => :string
class_option :api_key, :type => :string
no_commands do
# Returns the path to the client_secrets.json file.
def client_secrets_path
return ENV['GOOGLE_CLIENT_SECRETS'] if ENV.has_key?('GOOGLE_CLIENT_SECRETS')
return well_known_path_for('client_secrets.json')
end
# Returns the path to the token store.
def token_store_path
return ENV['GOOGLE_CREDENTIAL_STORE'] if ENV.has_key?('GOOGLE_CREDENTIAL_STORE')
return well_known_path_for('credentials.yaml')
end
# Builds a path to a file in $HOME/.config/google (or %APPDATA%/google,
# on Windows)
def well_known_path_for(file)
if OS.windows?
File.join(ENV['APPDATA'], 'google', file)
else
File.join(ENV['HOME'], '.config', 'google', file)
end
end
# Returns application credentials for the given scope.
def application_credentials_for(scope)
Google::Auth.get_application_default(scope)
end
# Returns user credentials for the given scope. Requests authorization
# if requrired.
def user_credentials_for(scope)
FileUtils.mkdir_p(File.dirname(token_store_path))
if ENV['GOOGLE_CLIENT_ID']
client_id = Google::Auth::ClientId.new(ENV['GOOGLE_CLIENT_ID'], ENV['GOOGLE_CLIENT_SECRET'])
else
client_id = Google::Auth::ClientId.from_file(client_secrets_path)
end
token_store = Google::Auth::Stores::FileTokenStore.new(:file => token_store_path)
authorizer = Google::Auth::UserAuthorizer.new(client_id, scope, token_store)
user_id = options[:user] || 'default'
credentials = authorizer.get_credentials(user_id)
if credentials.nil?
url = authorizer.get_authorization_url(base_url: OOB_URI)
say "Open the following URL in your browser and authorize the application."
say url
code = ask "Enter the authorization code:"
credentials = authorizer.get_and_store_credentials_from_code(
user_id: user_id, code: code, base_url: OOB_URI)
end
credentials
end
# Gets the API key of the client
def api_key
ENV['GOOGLE_API_KEY'] || options[:api_key]
end
end
end
+62
View File
@@ -0,0 +1,62 @@
# Copyright 2016 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
require 'google/apis/analytics_v3'
require 'base_cli'
module Samples
# Examples for the Google Analytics APIs
#
# Sample usage session:
#
# $ ./google-api-samples analytics show_visits 55622900 --start='2015-12-01' --end='2015-12-08'
# ga:date ga:sessions ga:users ga:newUsers ga:percentNewSessions ga:sessionDuration ga:avgSessionDuration
# 20151201 0 0 0 0.0 0.0 0.0
# 20151202 0 0 0 0.0 0.0 0.0
# 20151203 1 1 1 100.0 0.0 0.0
# 20151204 2 2 1 50.0 616.0 308.0
# 20151205 0 0 0 0.0 0.0 0.0
# 20151206 1 1 1 100.0 0.0 0.0
# 20151207 0 0 0 0.0 0.0 0.0
# 20151208 2 2 1 50.0 0.0 0.0
#
class Analytics < BaseCli
Analytics = Google::Apis::AnalyticsV3
desc 'show_visits PROFILE_ID', 'Show visists for the given analytics profile ID'
method_option :start, type: :string, required: true
method_option :end, type: :string, required: true
def show_visits(profile_id)
analytics = Analytics::AnalyticsService.new
analytics.authorization = user_credentials_for(Analytics::AUTH_ANALYTICS)
dimensions = %w(ga:date)
metrics = %w(ga:sessions ga:users ga:newUsers ga:percentNewSessions
ga:sessionDuration ga:avgSessionDuration)
sort = %w(ga:date)
result = analytics.get_ga_data("ga:#{profile_id}",
options[:start],
options[:end],
metrics.join(','),
dimensions: dimensions.join(','),
sort: sort.join(','))
data = []
data.push(result.column_headers.map { |h| h.name })
data.push(*result.rows)
print_table(data)
end
end
end
+83
View File
@@ -0,0 +1,83 @@
# Copyright 2016 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
require 'google/apis/calendar_v3'
require 'base_cli'
module Samples
# Examples for the Google Calendar API
#
# Sample usage:
#
# $ ./google-api-samples calendar list --limit 10
class Calendar < BaseCli
Calendar = Google::Apis::CalendarV3
desc 'schedule', 'Create an event'
method_option :summary, type: :string, required: true
method_option :start, type: :string, required: true
method_option :end , type: :string, required: true
method_option :attendees, type: :array
def schedule
calendar = Calendar::CalendarService.new
calendar.authorization = user_credentials_for(Calendar::AUTH_CALENDAR)
event = {
summary: options[:summary],
attendees: Array(options[:attenddes]).map { |email| { email: email } },
start: {
date_time: DateTime.parse(options[:start])
},
end: {
date_time: DateTime.parse(options[:end])
}
}
event = calendar.insert_event('primary', event, send_notifications: true)
say "Created event '#{event.summary}' (#{event.id})"
end
desc 'list', 'List upcoming events'
method_option :limit, type: :numeric
def list()
calendar = Calendar::CalendarService.new
calendar.authorization = user_credentials_for(Calendar::AUTH_CALENDAR)
page_token = nil
limit = options[:limit] || 1000
now = Time.now.iso8601
begin
result = calendar.list_events('primary',
max_results: [limit, 100].min,
single_events: true,
order_by: 'startTime',
time_min: now,
page_token: page_token,
fields: 'items(id,summary,start),next_page_token')
result.items.each do |event|
time = event.start.date_time || event.start.date
say "#{time}, #{event.summary}"
end
limit -= result.items.length
if result.next_page_token
page_token = result.next_page_token
else
page_token = nil
end
end while !page_token.nil? && limit > 0
end
end
end
+82
View File
@@ -0,0 +1,82 @@
# Copyright 2016 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
require 'google/apis/drive_v3'
require 'base_cli'
module Samples
# Examples for the Google Drive API
#
# Sample usage:
#
# $ ./google-api-samples drive upload ~/myvideo.mov
class Drive < BaseCli
Drive = Google::Apis::DriveV3
desc 'upload FILE', 'Upload a file to Google Drive'
method_option :name, type: :string
def upload(file)
drive = Drive::DriveService.new
drive.authorization = user_credentials_for(Drive::AUTH_DRIVE)
metadata = {
name: options[:name] || file
}
result = drive.create_file(metadata, upload_source: file)
say "Upload complete"
end
desc 'download FILE_ID', 'Download a file from Google Drive'
method_option :out, type: :string
def download(file_id)
drive = Drive::DriveService.new
drive.authorization = user_credentials_for(Drive::AUTH_DRIVE)
dest = options[:out] || StringIO.new
drive.get_file(file_id, download_dest: dest)
if dest.is_a?(StringIO)
dest.rewind
STDOUT.write(dest.read)
else
say "File downloaded to #{options[:out]}"
end
end
desc 'list QUERY', 'Search for files'
method_option :limit, type: :numeric
def list(query)
drive = Drive::DriveService.new
drive.authorization = user_credentials_for(Drive::AUTH_DRIVE)
page_token = nil
limit = options[:limit] || 1000
begin
result = drive.list_files(q: query,
page_size: [limit, 100].min,
page_token: page_token,
fields: 'files(id,name),next_page_token')
result.files.each { |file| puts "#{file.id}, #{file.name}" }
limit -= result.files.length
if result.next_page_token
page_token = result.next_page_token
else
page_token = nil
end
end while !page_token.nil? && limit > 0
end
end
end
+114
View File
@@ -0,0 +1,114 @@
# Copyright 2016 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
require 'google/apis/pubsub_v1'
require 'base_cli'
module Samples
# Examples for the Google Cloud Pub/Sub API.
#
# Sample usage session:
#
# $ ./google-api-samples pubsub create_topic mytopic --project=623040240964
# # ./google-api-samples pubsub subscribe mysub --topic=mytopic --project=623040240964
# $ ./google-api-samples pubsub publish 'Hello!' --topic=mytopic --project=623040240964
# $ ./google-api-samples pubsub pull mysub --project=623040240964
# Received: Hello!
# $ ./google-api-samples pubsub unsubscribe mysub --project=623040240964
# $ ./google-api-samples pubsub delete_topic mytopic --project=623040240964
#
class PubSub < BaseCli
Pubsub = Google::Apis::PubsubV1
desc 'create_topic TOPIC_NAME', 'Create a topic'
method_option :project, type: :string, required: true
def create_topic(name)
pubsub = Pubsub::PubsubService.new
pubsub.authorization = Google::Auth.get_application_default([Pubsub::AUTH_PUBSUB])
topic = "projects/#{options[:project]}/topics/#{name}"
pubsub.create_topic(topic)
end
desc 'delete_topic TOPIC_NAME', 'Delete a topic'
method_option :project, type: :string, required: true
def delete_topic(name)
pubsub = Pubsub::PubsubService.new
pubsub.authorization = Google::Auth.get_application_default([Pubsub::AUTH_PUBSUB])
topic = "projects/#{options[:project]}/topics/#{name}"
pubsub.delete_topic(topic)
end
desc 'subscribe SUBSCRIPTION_NAME', 'Subscribe to a topic'
method_option :project, type: :string, required: true
method_option :topic, type: :string, required: true
def subscribe(name)
pubsub = Pubsub::PubsubService.new
pubsub.authorization = Google::Auth.get_application_default([Pubsub::AUTH_PUBSUB])
topic = "projects/#{options[:project]}/topics/#{options[:topic]}"
subscription = "projects/#{options[:project]}/subscriptions/#{name}"
pubsub.create_subscription(subscription, Pubsub::Subscription.new(topic: topic))
end
desc 'unsubscribe subscription_name', 'Ububscribe from a topic'
method_option :project, type: :string, required: true
def unsubscribe(name)
pubsub = Pubsub::PubsubService.new
pubsub.authorization = Google::Auth.get_application_default([Pubsub::AUTH_PUBSUB])
subscription = "projects/#{options[:project]}/subscriptions/#{name}"
pubsub.delete_subscription(subscription)
end
desc 'publish MESSAGE', 'Publish a message to a topic'
method_option :project, type: :string, required: true
method_option :topic, type: :string, required: true
def publish(message)
pubsub = Pubsub::PubsubService.new
pubsub.authorization = Google::Auth.get_application_default([Pubsub::AUTH_PUBSUB])
topic = "projects/#{options[:project]}/topics/#{options[:topic]}"
request = Pubsub::PublishRequest.new(messages: [])
request.messages << Pubsub::Message.new(data: message)
pubsub.publish_topic(topic, request)
end
desc 'pull SUBSCRIPTION_NAME', 'Pull message(s) from the topic'
method_option :project, type: :string, required: true
method_option :max, type: :numeric, default: 5
def pull(name)
pubsub = Pubsub::PubsubService.new
pubsub.authorization = Google::Auth.get_application_default([Pubsub::AUTH_PUBSUB])
subscription = "projects/#{options[:project]}/subscriptions/#{name}"
# Pull messages
response = pubsub.pull_subscription(subscription, Pubsub::PullRequest.new(max_messages: options[:max]))
response.received_messages.each do |received_message|
data = received_message.message.data
puts "Received: #{data}"
end
# Acknowledge receipt
ack_ids = response.received_messages.map{ |msg| msg.ack_id }
pubsub.acknowledge_subscription(subscription, Pubsub::AcknowledgeRequest.new(ack_ids: ack_ids))
end
end
end
+44
View File
@@ -0,0 +1,44 @@
# Copyright 2016 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
require 'google/apis/translate_v2'
require 'base_cli'
module Samples
# Examples for the Google Translate API
#
# Sample usage:
#
# $ ./google-api-samples translate 'Hola!' --target='en'
# Hello
#
class Translate < BaseCli
Translate = Google::Apis::TranslateV2
desc 'translate PHRASE', 'Translate a phrase'
method_option :source, type: :string
method_option :target, type: :string, required: true
def translate(phrase)
translate = Translate::TranslateService.new
translate.key = api_key
result = translate.list_translations(phrase, options[:target], source: options[:source])
puts result.translations.first.translated_text
end
default_task :translate
end
end
+44
View File
@@ -0,0 +1,44 @@
# Copyright 2016 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
require 'google/apis/youtube_v3'
require 'base_cli'
module Samples
# Examples for the YouTube APIs
#
# Sample usage:
#
# $ ./google-api-samples youtube upload ~/myvideo.mov --title="So funny!"
#
class YouTube < BaseCli
YT = Google::Apis::YoutubeV3
desc 'upload FILE', 'Upload a video to YouTube'
method_option :title, type: :string
def upload(file)
youtube = YT::YouTubeService.new
youtube.authorization = user_credentials_for(YT::AUTH_YOUTUBE)
metadata = {
snippet: {
title: options[:title] || file
}
}
result = youtube.insert_video('snippet', metadata, upload_source: file)
say "Upload complete"
end
end
end