Authorization to google drive api using Ruby - ruby

I want to make a simple application (like a Service account -in google api console) which send a file to an google drive.
I have got code like this:
require 'rubygems'
require 'google/api_client'
require 'launchy'
#extra
gem 'oauth2'
gem 'omniauth'
client = Google::APIClient.new({:application_name => "testdevelop",:application_version => "1.0"})
drive = client.discovered_api('drive', 'v2')
####################################################################################
# Initialize OAuth 2.0 client
# client.authorization.client_id = '111062272758.apps.googleusercontent.com'
# client.authorization.client_secret = 's8j3VQwCvlyz2Hcpr06xrVfr'
# client.authorization.redirect_uri = 'urn:ietf:wg:oauth:2.0:oob'
# client.authorization.scope = 'https://www.googleapis.com/auth/drive'
# uri = client.authorization.authorization_uri
# Launchy.open(uri)
# $stdout.write "Enter authorization code: "
# client.authorization.code = gets.chomp
# client.authorization.fetch_access_token!
####################################################################################
key = Google::APIClient::KeyUtils.load_from_pkcs12('12355eaee706eb725ff5dd890b5c2bc39d536a53-privatekey.p12', 'notasecret')
client.authorization = Signet::OAuth2::Client.new(
:token_credential_uri => 'https://accounts.google.com/o/oauth2/token',
:audience => 'https://accounts.google.com/o/oauth2/token',
:scope => 'https://www.googleapis.com/auth/prediction',
:issuer => '312062272758-bg7s7ts9f3m11hjetboodre6hfg4qp8q#developer.gserviceaccount.com',
:signing_key => key)
client.authorization.fetch_access_token!
#####################################################################################
# Make an API call
# Insert a file
file = drive.files.insert.request_schema.new({
'title' => 'My document',
'description' => 'A test document',
'mimeType' => 'text/plain'
})
media = Google::APIClient::UploadIO.new('document.txt', 'text/plain')
result = client.execute(
:api_method => drive.files.insert,
:body_object => file,
:media => media,
:parameters => {
'uploadType' => 'multipart',
'alt' => 'json'})
# Pretty print the API result
jj result.data.to_hash
When I run it i got an error
`rescue in rbuf_fill': Timeout::Error (Faraday::Error::TimeoutError)
When I uncomment commented code and comment code between line of ############## It is possible to send a file into gDrive but I must enter the authorization code from web browser.
I want to do it automaticly thats i decided to use gDrive like a Service account
I have tried to increase connection time out by adding lines:
conn = Faraday.default_connection
conn.options[:timeout] = 500
and ofcourse with connection: conn after parametrs in request but i have got another error
`sysread_nonblock': end of file reached
(Faraday::Error::ConnectionFailed)

the (ssl)-certificate is missing.
how to fix: https://gist.github.com/fnichol/867550

Related

ruby: how to get count vistor a page with google analytics

i want to count visitor by page
opts = YAML.load_file("ga_config.yml")
## Update these to match your own apps credentials in the ga_config.yml file
service_account_email = opts['service_account_email'] # Email of service account
key_file = opts['key_file'] # File containing your private key
key_secret = opts['key_secret'] # Password to unlock private key
profile_id = opts['profileID'].to_s # Analytics profile ID.
client = Google::APIClient.new(
:application_name => opts['application_name'],
:application_version => opts['application_version'])
## Load our credentials for the service account
key = Google::APIClient::KeyUtils.load_from_pkcs12(key_file, key_secret)
visitors = []
client.authorization = Signet::OAuth2::Client.new(
:token_credential_uri => 'https://accounts.google.com/o/oauth2/token',
:audience => 'https://accounts.google.com/o/oauth2/token',
:scope => 'https://www.googleapis.com/auth/analytics.readonly',
:issuer => service_account_email,
:signing_key => key)
# Start the scheduler
# Request a token for our service account
client.authorization.fetch_access_token!
# Get the analytics API
analytics = client.discovered_api('analytics','v3')
# Execute the query
response = client.execute(:api_method => analytics.data.realtime.get, :parameters => {
'ids' => "ga:" + profile_id,
'metrics' => "ga:activeVisitors",
})
puts response.data.rows.count
when in run code.
response.data.row.count = 0.
but i go to https://analytics.google.com/analytics/web/#realtime/rt-content
in content
Right Now : 2
apparently there are any mistakes in my code?
how to fix this?
and I want to display get visitor by page
example:
ActivePage activeUser
/page1 1
/page2 3
How to get above data ?
thanks
you are requesting data from the Real-time api but you are not using valid real-time api metric. You will also need to add a dimension
try this
'metrics' => "rt:activeVisitors", 'dimensions' => "rt:pagePath",

google-api-ruby-client The current user has insufficient permissions to perform the requested operation

I am using the google-api-ruby-clientgoogle-api-ruby-client for my backend server to validate the android inapppurchase code (see below):
require 'google/api_client'
require 'google/api_client/client_secrets'
require 'google/api_client/auth/installed_app'
API_VERSION = 'v1.1'
service_account_email = 'xxx#developer.gserviceaccount.com' # Email of service account
key_file = 'xxx.p12' # File containing your private key
key_secret = 'notasecret' # Password to unlock private key
scope_url = 'https://www.googleapis.com/auth/androidpublisher'
client = Google::APIClient.new(
:application_name => 'Ruby Inapppurchases validate',
:application_version => '1.0.0')
key = Google::APIClient::KeyUtils.load_from_pkcs12(key_file, key_secret)
client.authorization = Signet::OAuth2::Client.new(
:token_credential_uri => 'https://accounts.google.com/o/oauth2/token',
:audience => 'https://accounts.google.com/o/oauth2/token',
:scope => scope_url,
:issuer => service_account_email,
:signing_key => key)
client.authorization.fetch_access_token!
publisher = client.discovered_api('androidpublisher', 'v1.1')
p client.execute(
api_method: publisher.inapppurchases.get,
parameters: {
packageName: 'com.examble',
productId: 'android.test.purchased',
token: "inapp:com.examble:android.test.purchased"
}).data
I follow the instruction for the api, but my error is as followed:
#<Google::APIClient::Schema::Androidpublisher::V1_1::InappPurchase:0x3fd021a64240
DATA:{"error"=>{"errors"=>[{"domain"=>"androidpublisher", "reason"=>"permissionDenied",
"message"=>"The current user has insufficient permissions to perform the requested operation."}],
"code"=>401, "message"=>"The current user has insufficient permissions to
perform the requested operation."}}>
This troubles me long time. Can anyone help me?

Google Apps Groups Settings API :: 500 Backend Error

Whenever I attempt to access the groups from our Google Apps instance, I get the following response:
{
"error": {
"errors": [
{
"domain": "global",
"reason": "backendError",
"message": "Backend Error"
}
],
"code": 500,
"message": "Backend Error"
}
}
The code I am using is below:
begin
require 'google/api_client'
rescue LoadError
puts "You need the google-api-ruby-client gem..."
puts "$ gem install google-api-client"
exit 1
end
client = Google::APIClient.new(application_name: "Group Modifier")
## Use key to authenticate and generate token
key = Google::APIClient::PKCS12.load_key("#{File.dirname(__FILE__)}/mykey.p12", 'notasecret')
service_account = Google::APIClient::JWTAsserter.new(
'mydeveloperid#developer.gserviceaccount.com',
'https://www.googleapis.com/auth/apps.groups.settings',
key)
client.authorization = service_account.authorize
groupssettings = client.discovered_api('groupssettings', 'v1')
result = client.execute(
:api_method => groupssettings.groups.get,
:parameters => { 'groupUniqueId' => 'mygroup#mydomain.com', 'alt' => 'json' }
)
puts result.body
I've added the correct permissions and all of that in both the "Manage API client access" within the Google Apps Admin Console and within the https://cloud.google.com/console.
I even noticed that when I use the "https://developers.google.com/admin-sdk/groups-settings/v1/reference/groups/get#try-it" it doesn't return anything.
Please help me out
I finally resolved my problem with using some example code from the git repo homepage. This is what I came up with:
begin
require 'google/api_client'
rescue LoadError
puts "You need the google-api-ruby-client gem..."
puts "$ gem install google-api-client"
exit 1
end
client = Google::APIClient.new
key = Google::APIClient::KeyUtils.load_from_pkcs12("#{File.dirname(__FILE__)}/mykey.p12", 'notasecret')
client.authorization = Signet::OAuth2::Client.new(
:token_credential_uri => 'https://accounts.google.com/o/oauth2/token',
:audience => 'https://accounts.google.com/o/oauth2/token',
:scope => 'https://www.googleapis.com/auth/apps.groups.settings',
:issuer => 'mydeveloperid#developer.gserviceaccount.com',
:person => 'myemail#mydomain.com',
:signing_key => key)
client.authorization.fetch_access_token!
groupssettings = client.discovered_api('groupssettings', 'v1')
result = client.execute(
:api_method => groupssettings.groups.get,
:parameters => { :groupUniqueId => 'mygroup#mydomain.com', :alt => 'json' }
)
puts result.body

Google realtime analytics API with Ruby

I am trying to use Google analytics realtime functionality but it doesn't seem to be working. I saw a similar post and implemented the solution but it does not seem to work. Here is my code
require 'google/api_client'
require 'date'
# Update these to match your own apps credentials
service_account_email = 'xxxxxxxxxxxxx#developer.gserviceaccount.com' # Email of service account
key_file = '/path/to/key/privatekey.p12' # File containing your private key
key_secret = 'notasecret' # Password to unlock private key
profileID = '111111111' # Analytics profile ID.
# Get the Google API client
client = Google::APIClient.new(:application_name => '[YOUR APPLICATION NAME]',
:application_version => '0.01')
# Load your credentials for the service account
key = Google::APIClient::KeyUtils.load_from_pkcs12(key_file, key_secret)
client.authorization = Signet::OAuth2::Client.new(
:token_credential_uri => 'https://accounts.google.com/o/oauth2/token',
:audience => 'https://accounts.google.com/o/oauth2/token',
:scope => 'https://www.googleapis.com/auth/analytics.readonly',
:issuer => service_account_email,
:signing_key => key)
# Start the scheduler
SCHEDULER.every '1m', :first_in => 0 do
# Request a token for our service account
client.authorization.fetch_access_token!
# Get the analytics API
analytics = client.discovered_api('analytics','v3')
# Execute the query
visitCount = client.execute(:api_method => analytics.data.realtime.get, :parameters => {
'ids' => "ga:" + profileID,
'metrics' => "ga:activeVisitors",
})
# Update the dashboard
send_event('cur_visitors', { current: visitCount.data.rows[0][0] })
end
However I get the error
undefined method '[]' for nil:NilClass
for the second last line. I know that the API does work for non-realtime functionality so I do not think there is any problem with authorization. Can anyone suggest why this could be happening?

Ruby real time google analytics API

I am trying to get activeVisitors with the google-api-ruby-client. The client is listed in the real time google analytics API docs here however I see nothing in the docs about using it for real time api.
I see the function discovered_api however I see no list for posisble parameters for the API name.
Example for Regular Analytics API:
# Get the analytics API
analytics = client.discovered_api('analytics','v3')
Does anyone know how to use this client to get real time active visitors?
Here is the code I am trying to use:
require 'google/api_client'
require 'date'
# Update these to match your own apps credentials
service_account_email = 'xxxxxxxxxxxxx#developer.gserviceaccount.com' # Email of service account
key_file = '/path/to/key/privatekey.p12' # File containing your private key
key_secret = 'notasecret' # Password to unlock private key
profileID = '111111111' # Analytics profile ID.
# Get the Google API client
client = Google::APIClient.new(:application_name => '[YOUR APPLICATION NAME]',
:application_version => '0.01')
# Load your credentials for the service account
key = Google::APIClient::KeyUtils.load_from_pkcs12(key_file, key_secret)
client.authorization = Signet::OAuth2::Client.new(
:token_credential_uri => 'https://accounts.google.com/o/oauth2/token',
:audience => 'https://accounts.google.com/o/oauth2/token',
:scope => 'https://www.googleapis.com/auth/analytics.readonly',
:issuer => service_account_email,
:signing_key => key)
# Start the scheduler
SCHEDULER.every '1m', :first_in => 0 do
# Request a token for our service account
client.authorization.fetch_access_token!
# Get the analytics API
analytics = client.discovered_api('analytics','v3')
# Execute the query
visitCount = client.execute(:api_method => analytics.data.ga.get, :parameters => {
'ids' => "ga:" + profileID,
'metrics' => "ga:activeVisitors",
})
# Update the dashboard
send_event('current_visitors', { current: visitCount.data.rows[0][0] })
end
Error returned:
Missing required parameters: end-date, start-date.
Assuming that the ruby client lib uses the discovery service and the method is actually available, instead of:
visitCount = client.execute(:api_method => analytics.data.ga.get, :parameters => {
'ids' => "ga:" + profileID,
'metrics' => "ga:activeVisitors",
try this (change ga to realtime in the api_method):
visitCount = client.execute(:api_method => analytics.data.realtime.get, :parameters => {
'ids' => "ga:" + profileID,
'metrics' => "ga:activeVisitors",
If you're a member of the Real-time reporting product forum, this post may be helpful - https://groups.google.com/forum/m/#!topic/google-analytics-realtime-api/zgAsKFBenV8
You might try...
analytics = client.discovered_api('realtime','v3')
Or real-time, or w/o v3.
If that works update your get method too.
Wish I could be more help but there is absolutely no documentation on this.

Resources