I am using pengwynn linkedIn gem in my rails project. How do I follow a company given the company id.
I have written the following code, but it is not working.
client = LinkedIn::Client.new('consumer_key', 'consumer_secret')
rtoken = client.request_token.token
rsecret = client.request_token.secret
client.request_token.authorize_url
=> "https://api.linkedin.com/uas/oauth/authorize?oauth_token=<generated_token>"
client.authorize_from_request(rtoken, rsecret, pin)
client.company(:id => <company_id>).follow
Any idea why it is not working or any other solution?
If you're using linkedin gem 0.3.x, it doesn't have a method to follow a company.
It could be added in 2-0-stable branch.
Then I've same task, I just fork gem and add follow_company method to /lib/linked_in/api/update_methods.rb
def follow_company(company_id)
path = "/people/~/following/companies"
post(path, {id: company_id}.to_json ,"Content-Type" => "application/json")
end
Related
I need some help with Google integration.
I need to create google contacts through the Google Contacts API but all the gems I can find only gets the contents and it also seems like the Google Contacts API doesn't support JSON posts, only xml/atom.
This is what I have
Gemfile
gem 'google-api-client'
google_contacts_controller.rb
require 'google/apis/people_v1'
require 'google/api_client/client_secrets'
class GoogleContactsController < ApplicationController
def auth
client_secrets = Google::APIClient::ClientSecrets.load('app/controllers/google_contacts/client_secret.json')
auth_client = client_secrets.to_authorization
auth_client.update!(
:scope => 'https://www.google.com/m8/feeds/',
:redirect_uri => 'http://localhost:3000/google_contacts/auth')[]
if request['code'] == nil
auth_uri = auth_client.authorization_uri.to_s
redirect_to auth_uri
else
auth_client.code = request['code']
auth_client.fetch_access_token!
auth_client.client_secret = nil
_auth_client(auth_client)
redirect_to action: 'sync_contacts'
end
end
def sync_contacts
unless session.has_key?(:credentials)
_auth_client
unless session.has_key?(:credentials)
redirect action: 'auth'
end
end
client_opts = JSON.parse(session[:credentials])
auth_client = Signet::OAuth2::Client.new(client_opts)
people_service = Google::Apis::PeopleV1::PeopleServiceService.new
people_service.authorization = auth_client
response = people_service.list_person_connections('people/me', request_mask_include_field: %w'person.names', page_size: 10,)
remote_name_arry = response.connections.map{|person| person.names[0].display_name}
redirect_to action: 'done', message: 'Synced Contacts'
end
def done
#message = params[:message]
end
private
def _auth_client(auth_client=nil)
if auth_client
credentials = GoogleContactCredential.new
credentials.authorization_uri = auth_client.authorization_uri
credentials.token_credential_uri = auth_client.token_credential_uri
credentials.client_id = auth_client.client_id
credentials.scope = "[#{auth_client.scope.join(', ')}]"
credentials.redirect_uri = auth_client.redirect_uri
credentials.expiry = auth_client.expiry
credentials.expires_at = auth_client.expires_at
credentials.access_token = auth_client.access_token
if credentials.save
session[:credentials] = credentials.to_json
end
else
credentials = GoogleContactCredential.first
if credentials.present?
session[:credentials] = credentials.to_json
end
end
credentials
end
end
This all works fine and I am able to get all of my contacts but I can not find a way with this gem or another gem or JSON to create contacts.
Is there anybody that has had this issue and can please point me in the right direction.
UPDATE
I have also tried using the google_contacts_api gem to no success.
Here is what I have
Gemfile
gem 'google_contacts_api'
google_contacts_controller.rb
def sync_contacts
unless session.has_key?(:credentials)
_auth_client
unless session.has_key?(:credentials)
redirect action: 'auth'
end
end
client_opts = JSON.parse(session[:credentials])
auth = OAuth2::Client.new(client_opts['client_id'], client_opts['client_secret'], client_opts)
token = OAuth2::AccessToken.new(auth, client_opts['access_token'])
google_contacts_user = GoogleContactsApi::User.new(token)
contacts = google_contacts_user.contacts
contact = contacts.first
logger.info contact.title
new_group = google_contacts_user.create_group('New group')
redirect_to action: 'done', message: 'Synced Contacts'
end
Everything works fine until this line (which I got out of the example supplied for the gem):
new_group = google_contacts_user.create_group('New group')
Then I get this line exception:
undefined method `create_group' for #<GoogleContactsApi::User:0x007ff2da2291b8>
Can someone spot my mistake I made?
Also, how would I proceed to create contacts as I can not seem to find documentation or posts on actually creating and updating contacts, I thought maybe I would have to create a group and then I can add contacts to the group but as I can not manage to create a group I can not test that theory.
Please point me in the right direction
The Google People API is read-only and can't be used to update or add new contacts. For that, you need to use the Google Contacts API which is, unfortunately, not supported by the google-api-client gem.
To access the Google Client API, you can try using this gem:
google_contacts_api
If you run into trouble setting it up, check out this stackoverflow question:
access google contacts api
It has a helpful answer written by the same person who wrote the gem.
EDIT
It looks like development on the google_contacts_api gem stopped before functionality for creating contacts was added. I'm looking through the various gems on Github and they're all in states of disrepair / death.
As much as it pains me to say it, your best bet might be to access Google Contacts directly via their web API.
Best of luck and sorry for the disheartening answer.
Hi I am wondering how to get user posts insights from Facebook API Koala Gem.
I only found solutions that works for facebook page posts but not user posts.
I used the code below for user posts but it just returns empty array.
#graph.get_connections('me', 'insights', metric: 'page_impressions', period: 'now')
UPDATE
user = Authentication.where(user_id: current_user.id, provider: "facebook").first
oauth_access_token = user.token
#graph = Koala::Facebook::API.new(oauth_access_token)
#posts = #graph.get_connection('me', 'posts',{ fields: ['id', 'message', 'link', 'name', 'description', "likes.summary(true)", "shares", "comments.summary(true)"]})
The code above works fine, but when I try to get post insights, it returns empty array.
If your using omniauth-facebook gem you just have to make sure you have the right permissions in your scope and you can use the original query.
config/initializers/omniauth.rb
OmniAuth.config.logger = Rails.logger
Rails.application.config.middleware.use OmniAuth::Builder do
provider :facebook, {id}, {secret},
:scope => 'email,manage_pages,read_stream,read_insights'
end
Also, you can get post insights for a page via koala. This worked for me.
m = Koala::Facebook::API.new(User.find(5).oauth_token)
m = m.get_connections('me', 'accounts')
m = m.first['access_token']
#post_graph = Koala::Facebook::API.new(m)
#feed = #post_graph.get_connection('me', 'feed')
#postid = #feed.first['id']
#post_data = #post_graph.get_connections(#postid, 'likes', since: "2015-05-17", until: "2015-07-17")
https://github.com/arsduo/koala/wiki/Acting-as-a-Page
https://developers.facebook.com/docs/graph-api/reference/v2.3/post
If you check here at 'Edges' you can see that /insights are available only for Pages.
'/insights Insights for this post (only for Pages).'
I hope I am right and helped you.
Here you can see it is only for pages post
/{post-id}/insights (where this is a Page post)
Context:
I have a rails application. I have a form where users can enter their email list to be a part of the news letter.
I am using mail chimp and gibbon gem for rails.
I can successfully add new subscribers to a list using the gibbon api
I can successfully create a new campaign as shown in the code below.
In my gem file :
gem 'gibbon', git: 'git://github.com/amro/gibbon.git'
For testing out the functionality, I invoke the create action in CampaignsController(code below).
The campaign is created successfully and I get the result back from the api, but in the next step the app crashes with the following error message :
Problem:
TypeError in CampaignsController#create
["xyz"] is not a symbol where xyz is the campaign_id of the newly created campaign.
Code:
In CampaignsController
def create
mailchimp = Gibbon::API.new(Rails.application.secrets.mailchimp_api_key)
new_campaign = mailchimp.campaigns.create({:type=>"plaintext",
:options=>
{:list_id=>"abcdefgh",
:subject=>"Hello World",:from_email => "xyz#gmail.com",
:from_name => "abc",:to_name =>"Programmer"},
:content =>
{:text => "Hello remote programmers I hope you find this mail."}
})
cid = new_campaign["id"]
mailchimp.campaigns.send(cid)
end
It looks like mailchimp.campaigns.send is looking for a hash of options, not just an id.
From their specs:
expect(#gibbon.campaigns.send({"cid" => "1234567"})).to eq({"cid" => "1234567"})
I'm attempting a server-to-server connection between my Google Analytics account and my Rails app. For this, I'm using the Legato, omniauth-google-oauth2, and google-api-client gems. My intention is to have a rake task that sieves out pageview data from a particular site. However, I can't seem to get any user data out of it. Here's the code:
require 'google/api_client'
def service_account_user(scope="https://www.googleapis.com/auth/analytics.readonly")
client = Google::APIClient.new(
:application_name => "Listmaker",
:application_version => "2.0"
)
key = OpenSSL::PKey::RSA.new(Figaro.env.google_private_key, "notasecret")
service_account = Google::APIClient::JWTAsserter.new(Figaro.env.google_app_email_address, scope, key)
client.authorization = service_account.authorize
oauth_client = OAuth2::Client.new("", "", {
:authorize_url => 'https://accounts.google.com/o/oauth2/auth',
:token_url => 'https://accounts.google.com/o/oauth2/token'
})
token = OAuth2::AccessToken.new(oauth_client, client.authorization.access_token)
Legato::User.new(token)
end
class Pageviews
extend Legato::Model
metrics :pageviews
dimensions :page_path
filter :for_page_path, &lambda {|page_path| matches(:page_path, page_path)}
end
puts profile = service_account_user.profiles.first
I appear to be getting an empty array for the profile variable after running the task. I've definitely added the developer email address to the Google Analytics View I'm interested in. Not sure what's wrong.
For a service account to work with Google Analytics the Service account email must be added at the Account level. It wont work if it was only added at the view level.
I've been spending the last few days banging my head against the wall on supporting the ability to add a contact to the Google Contacts API in my Rails 3 application. Despite many false starts, I've finally made some progress by employing the Ruby OAuth gem, and following the tutorial here: http://everburning.com/news/google-analytics-oauth-and-ruby-oh-my/
When I follow this in the console, I get further than I do in my Rails app. I can create an access token, authenticate against Google's service with the specific scope of the Contacts API, and apply the oauth_verifier token to get an access token. But when it comes time to push the data, I get this error:
response = at.post("https://www.google.com/m8/feeds/contacts/default/full", gdata)
=> #<Net::HTTPUnauthorized 401 Unknown authorization header readbody=true>
Where does the "readbody=true" header come from, and how would I get rid of it?
But it's worse in the Rails app. I have one controller action ("googlecontacts") that creates the request token and leads the user to the authentication site with Google:
def googlecontacts
#card = Card.find_by_short_link(params[:id])
#consumer = OAuth::Consumer.new(
'anonymous',
'anonymous',
{
:site => 'https://www.google.com',
:request_token_path => '/accounts/OAuthGetRequestToken',
:access_token_path => '/accounts/OAuthGetAccessToken',
:authorize_path => '/accounts/OAuthAuthorizeToken',
:signature_method => 'HMAC-SHA1',
:oauth_version => '1.0'
})
#request_token = #consumer.get_request_token(
{:oauth_callback => 'http://monkey.dev/cards/google_auth?redir='+#card.short_link},
{:scope => "https://www.google.com/m8/feeds/"}
)
session[:request_token] = #request_token
redirect_to #request_token.authorize_url
end
This appears to work; I get a working request token object, and the user is forwarded to the Google service to authenticate. The callback URL ("google_auth") should take the oauth_verifier token to create an access token. Here's the beginning of the controller:
def google_auth
#access_token = session[:request_token].get_access_token(:oauth_verifier=>params[:oauth_verifier])
And here's where it craps out. The error on that last line is:
You have a nil object when you didn't expect it!
You might have expected an instance of Array.
The error occurred while evaluating nil.[]
But the values that are in there -- the session[:request_token] and the params[:oauth_verifier] -- are present and accounted for in that action! I can't figure out what is nil here.
So I guess I need to figure out this second problem first, but bonus points for answering the first problem as well. :-)
Thanks for reading.
Aaron.
Try setting/getting the session data with a string not symbol, i.e. session["request_token"], not session[:request_token]. I know I've had that issue before in the past.
Unknown authorization header typically means that your signature didn't match what you sent. I do not recommend the oauth gem. It's full of bugs and weird issues and it doesn't properly escape certain parameters.
The Signet gem is the officially supported gem for accessing Google APIs in Ruby.
Here's how you'd implement this with Signet:
require 'signet/oauth_1/client'
require 'addressable/uri'
card = Card.find_by_short_link(params[:id])
callback = Addressable::URI.parse('http://monkey.dev/cards/google_auth')
callback.query_values = {'redir' => card.short_link}
client = Signet::OAuth1::Client.new(
:temporary_credential_uri =>
'https://www.google.com/accounts/OAuthGetRequestToken',
:authorization_uri =>
'https://www.google.com/accounts/OAuthAuthorizeToken',
:token_credential_uri =>
'https://www.google.com/accounts/OAuthGetAccessToken',
:client_credential_key => 'anonymous',
:client_credential_secret => 'anonymous',
:callback => callback
)
session[:temporary_credential] = (
client.fetch_temporary_credential!(:additional_parameters => {
:scope => 'https://www.google.com/m8/feeds/'
})
)
redirect_to(client.authorization_uri)