Created
March 31, 2014 08:46
-
-
Save benbonnet/9888084 to your computer and use it in GitHub Desktop.
shares.rake
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'csv' | |
namespace :count do | |
task :shares => :environment do | |
CSV.open("#{Rails.root}/shares.csv", "wb") do |csv| | |
csv << ["title", "lang", "url", "twitter","facebook","google+"] | |
Post.published.reverse.each do |p| | |
["fr","en"].each do |lang| | |
begin | |
puts title = p["title_#{lang}"] | |
lang = lang | |
url = "http://discov-her.com/#{lang}/article/#{p["slug_#{lang}"].parameterize}" | |
puts twitter = twitter_shared(url) | |
puts facebook = facebook_shares(url) | |
puts gplus = get_googleplus(url) | |
csv << [title,lang,url,twitter,facebook,gplus] | |
puts "......." | |
rescue | |
puts "error" | |
end | |
end | |
sleep 1 | |
end | |
end | |
end | |
end | |
def get_googleplus(url) | |
require 'curb' | |
require 'json' | |
hash = { | |
method: "pos.plusones.get", | |
id: "p", | |
params: { | |
nolog: true, | |
id: url, | |
source: "widget", | |
userId: "@viewer", | |
groupId: "@self" | |
}, | |
jsonrpc: "2.0", | |
key: "p", | |
apiVersion: "v1" | |
} | |
result = ( | |
Curl::Easy.http_post("https://clients6.google.com/rpc?key=AIzaSyCKSbrvQasunBoV16zDH9R33D88CeLr9gQ", hash.to_json) do |curl| | |
curl.headers['Accept']='application/json' | |
curl.headers['Content-Type']='application/json' | |
curl.headers['Api-Version']='2.2' | |
end) | |
result=JSON.parse(result.body_str) | |
count = result && result['result'] && result['result']['metadata'] && result['result']['metadata']['globalCounts'] && result['result']['metadata']['globalCounts']['count'] ? result['result']['metadata']['globalCounts']['count'].to_i : 0 | |
end | |
def facebook_shares(url) | |
data = Net::HTTP.get(URI.parse("http://graph.facebook.com/?ids=#{URI.escape(url)}")) | |
data = JSON.parse(data) | |
return data[url]['shares'] | |
end | |
def twitter_shared(url) | |
data = Net::HTTP.get(URI.parse("http://urls.api.twitter.com/1/urls/count.json?url=#{URI.escape(url)}")) | |
data = JSON.parse(data) | |
return data["count"] | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment