Ruby real time google analytics API - ruby

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.

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 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?

Authorization to google drive api using 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

How to use google-api-ruby-client with the Google Calendar API?

I've been reading the docs for the Google Calendar API and the google-api-ruby-client library, but I'm having a lot of trouble understanding them.
I have a Rails application that has a front end that lets users create objects called Events, and it saves them in a database on my server. What I would like is, after these Events are saved in the database, I want to call the Google Calendar API to create an event on a Google Calendar (that the server created, and only the server has access to modify that calendar).
I'm having lots of issues figuring out how to authenticate with the API using the ruby library. It doesn't make sense for me to use OAuth2 because I don't need to authorize anything with the user because I'm not interested in their data. I looked into Service Accounts (http://code.google.com/p/google-api-ruby-client/wiki/ServiceAccounts), but it looks like Google Calendars is not supported by Service Accounts.
Anyone have any ideas? This is the code I was experimenting with (using Service Accounts):
#client = Google::APIClient.new(:key => 'my_api_key')
path_to_key_file = '/somepath/aaaaaa-privatekey.p12'
passphrase = 'my_pass_phrase'
key = Google::APIClient::PKCS12.load_key(path_to_key_file, passphrase)
asserter = Google::APIClient::JWTAsserter.new(
'blah_blah#developer.gserviceaccount.com',
'https://www.googleapis.com/auth/calendar',
key)
# To request an access token, call authorize:
#client.authorization = asserter.authorize()
calendar = #client.discovered_api('calendar', 'v3')
event = {
'summary' => 'Appointment',
'location' => 'Somewhere',
'start' => {
'dateTime' => '2012-06-03T10:00:00.000-07:00'
},
'end' => {
'dateTime' => '2012-06-03T10:25:00.000-07:00'
},
'attendees' => [
{
'email' => 'attendeeEmail'
},
#...
]
}
result = #client.execute!(:api_method => calendar.events.insert,
:parameters => {'calendarId' => 'primary'},
:body => JSON.dump(event),
:headers => {'Content-Type' => 'application/json'})
Then of course I get this error message: Google::APIClient::ClientError (The user must be signed up for Google Calendar.) because the Service Account does not support Google Calendars.
I think you'll still need a real google user to host the calendar instance. But once you've got the calendar created under your identity, you can share it with the service account. In the sharing settings for the calendar, just use the email address of the service account (my service account ends with #developer.gserviceaccount.com). With the right sharing permissions, your service account can create/alter the event info, and not mess with your specific identity. From there, you can share the calendar with more people (or public) for their consumption of the mirrored events.
The other hitch I've run into is that it seems you can only authorize() the service account once per expiration period. You'll have to save the token you get and reuse it for the next hour, and then fetch a new one.
I don't know anything about Ruby. But it seems like understanding the underlying REST queries would help debug your problem. I've documented them here: http://www.tqis.com/eloquency/googlecalendar.htm
I was having trouble with this too and finally got a handle on it. The bottom line is that Google Calendar API v3 requires OAuth and you need to setup an App/Project through the Google Developer Console and then request OAuth permission on the target Google account. Once authorization is granted, you'll want to save the refresh token and use it on subsequent calls to get new access tokens (which expire!). I wrote a detailed blog post about this here: http://www.geekytidbits.com/google-calendar-api-from-ruby/ and this is my example script that should hopefully help you understand the flow:
#gem install 'google-api-client'
require 'google/api_client'
#Setup auth client
client_secrets = Google::APIClient::ClientSecrets.load #client_secrets.json must be present in current directory!
auth_client = client_secrets.to_authorization
auth_client.update!(
:scope => 'https://www.googleapis.com/auth/calendar',
:access_type => "offline", #will make refresh_token available
:approval_prompt =>'force',
:redirect_uri => 'http://www.myauthorizedredirecturl.com'
)
refresh_token_available = File.exist?('refresh_token.txt')
if !refresh_token_available
#OAuth URL - this is the url that will prompt a Google Account owner to give access to this app.
puts "Navigate browser to: '#{auth_client.authorization_uri.to_s}' and copy/paste auth code after redirect."
#Once the authorization_uri (above) is followed and authorization is given, a redirect will be made
#to http://www.myauthorizedredirecturl.com (defined above) and include the auth code in the request url.
print "Auth code: "
auth_client.code = gets
else
#If authorization has already been given and refresh token saved previously, simply set the refresh code here.
auth_client.refresh_token = File.read('refresh_token.txt')
end
#Now, get our access token which is what we will need to work with the API.
auth_client.fetch_access_token!
if !refresh_token_available
#Save refresh_token for next time
#Note: auth_client.refresh_token is only available the first time after OAuth permission is granted.
#If you need it again, the Google Account owner would have deauthorize your app and you would have to request access again.
#Therefore, it is important that the refresh token is saved after authenticating the first time!
File.open('refresh_token.txt', 'w') { |file| file.write(auth_client.refresh_token) }
refresh_token_available = true
end
api_client = Google::APIClient.new
cal = api_client.discovered_api('calendar', 'v3')
#Get Event List
puts "Getting list of events..."
list = api_client.execute(:api_method => cal.events.list,
:authorization => auth_client,
:parameters => {
'maxResults' => 20,
'timeMin' => '2014-06-18T03:12:24-00:00',
'q' => 'Meeting',
'calendarId' => 'primary'})
puts "Fetched #{list.data.items.count} events..."
#Update Event
puts "Updating first event from list..."
update_event = list.data.items[0]
update_event.description = "Updated Description here"
result = api_client.execute(:api_method => cal.events.update,
:authorization => auth_client,
:parameters => { 'calendarId' => 'primary', 'eventId' => update_event.id},
:headers => {'Content-Type' => 'application/json'},
:body_object => update_event)
puts "Done with update."
#Add New Event
puts "Inserting new event..."
new_event = cal.events.insert.request_schema.new
new_event.start = { 'date' => '2015-01-01' } #All day event
new_event.end = { 'date' => '2015-01-01' }
new_event.description = "Description here"
new_event.summary = "Summary here"
result = api_client.execute(:api_method => cal.events.insert,
:authorization => auth_client,
:parameters => { 'calendarId' => 'primary'},
:headers => {'Content-Type' => 'application/json'},
:body_object => new_event)
puts "Done with insert."

Resources