Tracking JSON calls with Google Analytics in a Ruby/Rails app - ruby-on-rails

I searched a lot about this issue but I can't find anything good. I think that this is a common problem: you have a web app and build JSON APIs on top of your platform, so you can develop some widgets, mobile apps or third party applications.
I know that there a are a lot of specific analytics services via API (like Mixpanel, Kissmetrics and many others) but I want to track all the JSON calls also via Google Analytics.
I found that the best method is to use the __utm.gif image but strangely I cannot find any plugin or gem to use this image.
So I tried to build my own method without success (see the code below)...
Someone can help?
def google_analytics_call(page_title)
today = Time.now.to_i
utma = cookies[:__utma].to_s
utmb = cookies[:__utmb].to_s
utmc = cookies[:__utmc].to_s
utmz = cookies[:__utmz].to_s
utma = (rand(8).to_s + "." + rand(10).to_s + "." + today.to_s + "." + today.to_s+ "." + today.to_s) unless cookies[:__utma]
utmb = rand(8).to_s unless cookies[:__utmb]
utmc = rand(8).to_s unless cookies[:__utmc]
utmz = rand(8).to_s+ "." + today + ".2.2.utmccn%3D(direct)%7Cutmcsr%3D(direct)%7Cutmcmd%3D(none)" unless cookies[:__utmz]
Thread.new do
params = {
:utmac => GOOGLE_ANALYTICS,
:utmcc => "__utma%3D"+utma+"%3B%2B"+"__utmb%3D"+utmb+"%3B%2B"+"__utmc%3D"+utmc+"%3B%2B"+"__utmz%3D"+utmz+"%3B%2B",
:utmcn => "1",
:utmcs => "-",
:utmdt => page_title, #page title
:utmhn => BASE_URL,
:utmwv => 1,
:utmt => "page",
:utmr => request.referer
}
puts params
http_get("www.google-analytics.com", "/__utm.gif", params)
end
end

i think you want to use the async tracker, which is part of google analytics. Here is an example of how I track clicks that fire an async AJAX event:
$('.trackable').bind('click', function(event){
var action = $(this).attr('action');
var category = $(this).attr('category');
_gaq.push(['_trackEvent', action, category]);
});
The "_gaq" is the google asynchronous queue and can be added to any JS function you want to track metrics within. The function above allows you to add a class called "trackable" and track events when the user clicks on it. An example looks like this:
<a category='FEATURED' action='Like This' class='trackable' href="http://MYSSERVER.com/foo.json" target='_blank'>track asynchronously.</a>

Not quick answer, but I think you should try Gabba gem

Related

Editing Google Calendar Event Meets URI With External Link via API

I've had code that has been working for the last year or so, that adds a new Google Meets Entry Point with my own custom URI to the Google Calendar Event via the Google Calendar API.
For example if I click on "Join with Google Meet" below it does not go to a meets.google.com link like usual, because I replaced it with my own custom link.
Unfortunately for some reason in the past couple weeks this stopped working. Now when my code tries to edit the URI for the meet, it returns this error: Google::Apis::ClientError (invalid: Invalid Value). I haven't changed the code in months and this only started happening recently.
Here is what the code looks like:
def update_event_meet_url(service, event, send_updates = "all")
entry_points = [
Google::Apis::CalendarV3::EntryPoint.new(
entry_point_type: "video",
label: meeting_url,
uri: meeting_url,
),
]
if original_phone_info.present?
entry_points << Google::Apis::CalendarV3::EntryPoint.new(
entry_point_type: original_phone_info["entry_point_type"],
label: original_phone_info["label"],
uri: original_phone_info["uri"],
pin: original_phone_info["pin"],
region_code: original_phone_info["region_code"],
)
end
event_changes = {
conference_data: Google::Apis::CalendarV3::ConferenceData.new(entry_points: entry_points),
}
updated_event = Google::Apis::CalendarV3::Event.new(event_changes)
service.patch_event(
gcalendar_id,
event.id,
updated_event,
conference_data_version: 1,
send_updates: send_updates,
)
end
I know the problem is with the video entry point because I replaced the meeting_url with a working https://meets.google.com link and it worked. But if I try anything else that is not meets.google.com it errors.
I'm using this Ruby gem https://github.com/googleapis/google-api-ruby-client.
Any help would be appreciated! Thanks!
Contacted google support and looks like there was a recent release that changed the behavior of conferenceData.conferenceSolution.key.type. More info here: https://developers.google.com/calendar/releases#january_11_2021)we
Basically I needed to change my conference solution key type to addOn instead of hangoutsMeet. The subsequent problem I had was that I still needed a hangoutsMeet link, since the third party url I'm using would eventually redirect to the meets.google.com link. And the only way to get a hangoutsMeet link is to create the initial event with conferenceData.conferenceSolution.key.type = hangoutsMeet.
So what I did was create the google event with conferenceData.conferenceSolution.key.type = 'hangoutsMeet' and then I did a subsequent patch_event call that set the initial hangoutsMeet conference solution to null and created a new conferenceSolution of type addOn. That way I could store the original meets.google.com link and then use that link for the redirect from my third party link.
def update_event_meet_url(service, event, send_updates = "all")
entry_points = [
Google::Apis::CalendarV3::EntryPoint.new(
entry_point_type: "video",
label: meeting_url,
uri: meeting_url,
),
]
conference_solution_key = Google::Apis::CalendarV3::ConferenceSolutionKey.new(type: "addOn")
conference_solution =
Google::Apis::CalendarV3::ConferenceSolution.new(key: conference_solution_key)
event_changes = {
conference_data: Google::Apis::CalendarV3::ConferenceData.new(
conference_solution: conference_solution,
entry_points: entry_points,
create_request: nil,
),
}
updated_event = Google::Apis::CalendarV3::Event.new(event_changes)
service.patch_event(
gcalendar_id,
event.id,
updated_event,
conference_data_version: 1,
send_updates: send_updates,
)
end

Scraperwiki Twitter Query

Please forgive me, as I have limited knowledge of scraperwiki and twitter mining.
I have the following code to scrape twitter data. However, I want to edit the code to only give me results that are geotagged for New York on a particular date (let's say, April 1, 2013). Do you know how I should do this?
###############################################################################
# Twitter srcaper for the term 'hello'.
###############################################################################
import scraperwiki
import simplejson
# retrieve a page
base_url = 'http://search.twitter.com/search.json?q='
q = 'hello'
options = '&rpp=10&page='
page = 1
while 1:
try:
url = base_url + q + options + str(page)
html = scraperwiki.scrape(url)
#print html
soup = simplejson.loads(html)
for result in soup['results']:
data = {}
data['id'] = result['id']
data['text'] = result['text']
data['from_user'] = result['from_user']
data['created_at'] = result['created_at']
# save records to the datastore
scraperwiki.datastore.save(["id"], data)
page = page + 1
except:
print str(page) + ' pages scraped'
break
In addition to q, use the query parameters geocode and until. See this page of the Twitter API documentation. Please note that you cannot use the Search API to find Tweets older than about a week.
Besides, it's easier to use urllib.urlencode() to construct your query, like for example
query_dict = {'q':'search term(s)', 'geocode':'37.781157,-122.398720,25mi', 'until':'2013-05-10'}
query = urllib.urlencode(query_dict)
response = urllib.urlopen(basic_url + query).read()
Update: Please see this example scraper that you can copy and adapt to your needs.

Get online users XMPP4r + Rails

I'm trying get online friends by user in XMPP server (Ejabberd). I'm using Ruby on Rails 3.2.
The idea is to add in array all online users to use this on view page.
I found asynchronous code (below), but it use Thread and it's difficult to work on controller method.
jid = Jabber::JID.new('user#localhost')
cl = Jabber::Client.new(jid)
cl.connect
cl.auth('123456')
#online_users = [] #online users queue
roster = Jabber::Roster::Helper.new(cl)
mainthread = Thread.current
roster.add_presence_callback { |item,oldpres,pres|
if item.online?
#online_users.push item
else
#online_users.delete_if {|x| x.jid == item.jid }
end
puts #online_users.inspect
puts "#{item.jid} - online: #{item.online?}"
}
cl.send(Jabber::Presence.new.set_show(:dnd))
t = Thread.new { sleep XMPP_REQUEST_TIMEOUT; mainthread.wakeup;}
Thread.stop
cl.close
So I need some synchronous code, or some way to execute this kind of code in controller method.
Thanks.
For this found another solution that help me:
I installed a mod_rest in ejabberd server. This module allow that you do HTTP request of terminal commands of ejabberdctl.
So it has "ejabberdctl connected_users", that return users online.
So in your model app using gem rest-client you can do something like it:
def online_users
response = RestClient.post('http://localhost:5280/rest', "connected_users")
response
end
You will be much happier in the long run if you use a library like Strophe.js to do this in the browser, talking to an XMPP server that has BOSH enabled. Snapshots of presence are never anywhere as interesting as you expect them to be, and you're going to have really bad authentication/authorization problems on the path down which you're heading.

Rails 3: How to tell if a user has visited a page before?

I have a Rails app (using Authlogic for authentication) with a simple jquery animation that I only want to run once upon first page load. I know that the key is to check cookies or something to see if the user has visited the page before. Please forgive my n00bness, I know little to nothing about HTTP cookies or sessions.
So, what's the best way to see if a visiting user (even if they haven't logged in) is viewing a page for the first time?
EDIT: Ok, so I realize I wasn't being entirely clear.
I've spent hours looking at similar questions and reading the Rails API Docs for cookies and sessions and I still can't visualize how to implement a visited? function for each page in my site that will only be set to "true" after the user has visited the page the first time. I looked at the supposed "duplicate" question Rails Detect If User's Very First Visit and the respective answers and still can't figure it out.
Here's my "Pages" controller:
def home
#title = "Home"
end
def contact
#title = "Contact Us"
end
dd
And my jquery javascript that does a simple animation:
$(document).ready(function()
{
if (!$.cookie('visited')) {
$('.title .flying-text').css({opacity:0});
$('.title .active-text').animate({
opacity:1,
marginTop: "-150px",
}, 5000);
}
});
I only want it to show if the user HAS NOT visited the page before. I have no idea how to properly set a cookie in Rails, nor where to put it, nor how to make sure that the animation script can access that exact same cookie value. Can someone give me a hand?
~Dan
You can set a cookie like this:
cookies[:welcomed] = {:value => true, :expires => Time.now + 6.months}
and from jquery make a wee function
function readCookie(name) {
var nameEQ = name + "=", ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i += 1) {
var c = ca[i];
while (c.charAt(0) === ' ') {
c = c.substring(1, c.length);
}
if (c.indexOf(nameEQ) === 0) {
return c.substring(nameEQ.length, c.length);
}
}
return null;
}
and call it #in js
if (readCookie('welcomed') == null){}
Ignore the cookie from Javascript.
Using the question referenced as a duplicate, use a permanent cooke and on the first run, set a class on your body from Rails (let's say first-run). Then, have your javascript check and see if body has class first-run. At that point, you can have javascript execute it's first run code.

Is there a way to get the twitter share count for a specific URL?

I looked through the API documentation but couldn't find it. It would be nice to grab that number to see how popular a url is. Engadget uses the twitter share button on articles if you're looking for an example. I'm attempting to do this through javascript. Any help is appreciated.
You can use the following API endpoint,
http://cdn.api.twitter.com/1/urls/count.json?url=http://stackoverflow.com
Note that the http://urls.api.twitter.com/ endpoint is not public.)
The endpoint will return a JSON string similar to,
{"count":27438,"url":"http:\/\/stackoverflow.com\/"}
On the client, if you are making a request to get the URL share count for your own domain (the one the script is running from), then an AJAX request will work (e.g. jQuery.getJSON). Otherwise, issue a JSONP request by appending callback=?:
jQuery.getJSON('https://cdn.api.twitter.com/1/urls/count.json?url=http://stackoverflow.com/&callback=?', function (data) {
jQuery('#so-url-shares').text(data.count);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="so-url-shares">Calculating...</div>
Update:
As of 21st November 2015, this way of getting twitter share count, does not work anymore. Read more at: https://blog.twitter.com/2015/hard-decisions-for-a-sustainable-platform
This is not possible anymore as from today, you can read more here:
https://twitter.com/twitterdev/status/667836799897591808
And no plans to implement it back, unfortunately.
Up vote so users do not lose time trying out.
Update:
It is however possible via http://opensharecount.com, they provide a drop-in replacement for the old private JSON URL based on searches made via the API (so you don't need to do all that work).
It's based on the REST API Search endpoints. Its still new system, so we should see how it goes. In the future we can expect more of similar systems, because there is huge demand.
this is for url with https (for Brodie)
https://cdn.api.twitter.com/1/urls/count.json?url=YOUR_URL
No.
How do I access the count API to find out how many Tweets my URL has had?
In this early stage of the Tweet Button the count API is private. This means you need to use either our javascript or iframe Tweet Button to be able to render the count. As our systems scale we will look to make the count API public for developers to use.
http://dev.twitter.com/pages/tweet_button_faq#custom-shortener-count
Yes,
https://share.yandex.ru/gpp.xml?url=http://www.web-technology-experts-notes.in
Replace "http://www.web-technology-experts-notes.in" with "your full web page URL".
Check the Sharing count of Facebook, Twitter, LinkedIn and Pinterest
http://www.web-technology-experts-notes.in/2015/04/share-count-and-share-url-of-facebook-twitter-linkedin-and-pininterest.html
Update:
As of 21st November 2015, Twitter has removed the "Tweet count endpoint" API.
Read More: https://twitter.com/twitterdev/status/667836799897591808
The approved reply is the right one. There are other versions of the same endpoint, used internally by Twitter.
For example, the official share button with count uses this one:
https://cdn.syndication.twitter.com/widgets/tweetbutton/count.json?url=[URL]
JSONP support is there adding &callback=func.
I know that is an old question but for me the url http://cdn.api.twitter.com/1/urls/count.json?url=http://stackoverflow.com did not work in ajax calls due to Cross-origin issues.
I solved using PHP CURL, I made a custom route and called it through ajax.
/* Other Code */
$options = array(
CURLOPT_RETURNTRANSFER => true, // return web page
CURLOPT_HEADER => false, // don't return headers
CURLOPT_FOLLOWLOCATION => true, // follow redirects
CURLOPT_MAXREDIRS => 10, // stop after 10 redirects
CURLOPT_ENCODING => "", // handle compressed
CURLOPT_USERAGENT => "test", // name of client
CURLOPT_AUTOREFERER => true, // set referrer on redirect
CURLOPT_CONNECTTIMEOUT => 120, // time-out on connect
CURLOPT_TIMEOUT => 120, // time-out on response
);
$url = $_POST["url"]; //whatever you need
if($url !== ""){
$curl = curl_init("http://urls.api.twitter.com/1/urls/count.json?url=".$url);
curl_setopt_array($curl, $options);
$result = curl_exec($curl);
curl_close($curl);
echo json_encode(json_decode($result)); //whatever response you need
}
It is important to use a POST because passsing url in GET request cause issues.
Hope it helped.
This comment https://stackoverflow.com/a/8641185/1118419 proposes to use Topsy API. I am not sure that API is correct:
Twitter response for www.e-conomic.dk:
http://urls.api.twitter.com/1/urls/count.json?url=http://www.e-conomic.dk
shows 10 count
Topsy response fro www.e-conomic.dk:
http://otter.topsy.com/stats.json?url=http://www.e-conomic.dk
18 count
This way you can get it with jquery. The div id="twitterCount" will be populated automatic when the page is loaded.
function getTwitterCount(url){
var tweets;
$.getJSON('http://urls.api.twitter.com/1/urls/count.json?url=' + url + '&callback=?', function(data){
tweets = data.count;
$('#twitterCount').html(tweets);
});
}
var urlBase='http://http://stackoverflow.com';
getTwitterCount(urlBase);
Cheers!
Yes, there is. As long as you do the following:
Issue a JSONP request to one of the urls:
http://cdn.api.twitter.com/1/urls/count.json?url=[URL_IN_REQUEST]&callback=[YOUR_CALLBACK]
http://urls.api.twitter.com/1/urls/count.json?url=[URL_IN_REQUEST]&callback=[YOUR_CALLBACK]
Make sure that the request you are making is from the same domain as the [URL_IN_REQUEST]. Otherwise, it will not work.
Example:
Making requests from example.com to request the count of example.com/page/1. Should work.
Making requests from another-example.com to request the count of example.com/page/1. Will NOT work.
I just read the contents into a json object via php, then parse it out..
<script>
<?php
$tweet_count_url = 'http://urls.api.twitter.com/1/urls/count.json?url='.$post_link;
$tweet_count_open = fopen($tweet_count_url,"r");
$tweet_count_read = fread($tweet_count_open,2048);
fclose($tweet_count_open);
?>
var obj = jQuery.parseJSON('<?=$tweet_count_read;?>');
jQuery("#tweet-count").html("("+obj.count+") ");
</script>
Simple enough, and it serves my purposes perfectly.
This Javascript class will let you fetch share information from Facebook, Twitter and LinkedIn.
Example of usage
<p>Facebook count: <span id="facebook_count"></span>.</p>
<p>Twitter count: <span id="twitter_count"></span>.</p>
<p>LinkedIn count: <span id="linkedin_count"></span>.</p>
<script type="text/javascript">
var smStats=new SocialMediaStats('https://google.com/'); // Replace with your desired URL
smStats.facebookCount('facebook_count'); // 'facebook_count' refers to the ID of the HTML tag where the result will be placed.
smStats.twitterCount('twitter_count');
smStats.linkedinCount('linkedin_count');
</script>
Download
https://404it.no/js/blog/SocialMediaStats.js
More examples and documentation
Javascript Class For Getting URL Shares On Facebook, Twitter And LinkedIn

Resources