Twitter + Grackle, determining the logged in user - ruby

This is crazy, but I'm stumped! Once my user has logged into twitter via OAuth how do I determine their username using grackle?
#twitter = Grackle::Client.new(:auth => {
:type => :oauth,
:consumer_key => consumer_key,
:consumer_secret => consumer_secret,
:token => #access_token.token,
:token_secret => #access_token.secret
})
username = #twitter.something_here?

Try looking on here:
http://apiwiki.twitter.com/Twitter-REST-API-Method:-account%C2%A0verify_credentials
It tells you how via the main api how to get the current user information. You could look into hooking this up through Grackle.
Joe

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",

Soundcloud - Ruby creating a Playlist getting 422 (#soundcloud-ruby)

I suspect something at Soundcloud has changed because my code has not been altered and worked fine last year.
I see:
Error: HTTP status: 422 Unprocessable Entity, Status Code: 422, playlist_struct:{:title=>"Y11 - REVO - Sop", :description=>"Y11 - REVO - Sop newchoir", :tag_list=>"Sop", :tracks=>"219269586", :format=>"json", :oauth_token=>"..."}
My oauth_token works fine.
I call:
new_playlist = #client.post('/playlists', playlist_struct)
Where #client is defined using https://github.com/soundcloud/soundcloud-ruby as:
#client = SoundCloud.new({
:client_id => clientId,
:client_secret => clientSecret,
:username => email,
:password => password
})
And playlist_struct is per the error message.
Thoughts appreciated!
Regards, M.
Full code:
require 'rubygems'
require 'soundcloud'
require 'pp'
require 'logger'
def login
# http://soundcloud.com/you/apps
clientId = '...'
clientSecret = '...'
email = '...'
password = '...'
# register a new client, which will exchange the username, password for an access_token
# NOTE: the SoundCloud API Docs advise not to use the user credentials flow in a web app.
# In any case, never store the password of a user.
#client = SoundCloud.new({
:client_id => clientId,
:client_secret => clientSecret,
:username => email,
:password => password
})
# print logged in username
puts"h1. Logged in as " + #client.get('/me').username
# updating the users profile description
end
login()
playlist_struct = {
:title => "Hello"
}
new_playlist = #client.post('/playlists', playlist_struct)
#log.info ' OK: '+new_playlist.permalink_url
Looks like the playlist_struct now needs to include
playlist: {
...
}
Around the content.
As the code worked for a couple of years before hand I'd venture this is a silent change to the API.

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.

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