Facebook Share and Share on Twitter in Rails - ruby-on-rails

On my landing page I want users to be able to Share on Facebook and Share on Twitter that page with a particular message. I would like to be able to know when they have actually post it on Facebook and/or Twitter (any way to get the callback).
What is the correct way to add a Facebook Share link in Rails? I want to have my own button.
I have taken a look at Koala but I am wondering if it is too much because I just want to be able to Share that landing page. I don't want to provide any kind of authentication or anything more complex. The only tricky part is that I need to know when they have actually shared.
Thanks

You can use external service like sharethis,addthis with some option,
For facebook you can use own way of sharing for this by registering with facebook app
consider following example
<a href="#" onclick='postToFeed("<%= image_url%>","<%= somte text %>"); return false;'>
<%= image_tag("btn_fb.png" , :alt=>"Facebook") %>
</a>
<script type="text/javascript">
FB.init({appId: APP_ID", status: true, cookie: true});
function postToFeed(img,name) {
// calling the API ...
var obj = {
method: 'feed',
// redirect_uri: 'http://localhost:3000',
link: 'http://url/',
picture: img,
name: 'NAME',
caption: 'CAPTION',
description: DESCRIPTION
};
function callback(response) {
document.getElementById('msg').innerHTML = "Post ID: " + response['post_id'];
}
FB.ui(obj, callback);
}
</script>

Related

trying to customize Facebook posts within my rails app, like it does on Stackoverflow site

At the bottom of questions on stackoverflow it says:
'Know someone who can answer? Share a link to this question via email, Google+, Twitter, or Facebook.'
It's the Facebook part I'm interested in. When the user clicks 'Facebook' they get something like:
The cursor is in the 'Write Something' box, exactly where you want it to be, there's a banner underneath drawing attention to the stackoverflow site...perfect.
In my rails app I can link to Facebook with:
<div class ="centre_text">Maybe
you'd like to <%= link_to 'ask your friends on Facebook',
"http://www.facebook.com/mypage", :target => "_blank" %> for what
you're looking for? </div>
It goes to the user's page, where they can write a post. But how do I have it like Stackoverflow's, where the 'Write Something' takes up most of the screen, with a 'Share link' button, and how can I put in a banner/detail, like Stackoverflow does?
Any pointers in the right direction would be greatly appreciated.
I am giving you a simple html example, so that you can get idea and customize it according to your need:
Like I want to share a link on facebook, then what I will do is as following:
First create a link:
<img class="fShare" data-url="http://google.com/" data-title="luxury sedan" src="facebook.png" width="5" height="11" alt="facebook" />
add some javascript for this link:
$(document).ready(function() {
$(".fShare").click(function() {
window.open(
'https://www.facebook.com/sharer/sharer.php?u=' + $(this).attr("data-url") + '&t=' + $(this).attr("data-title"),
'facebook-share-dialog',
'width=626,height=436');
return false;
});
});

Facebook Authorization on Rails app: why do we need to do Both server and client side authorization?

In Ryan's Railscast on Facebook authorization, he adds some Facebook SDK javascript at the end to "degrade facebook client side authorization with server side authorization." However, I do not see the use of it. If we already set up the authorization from the server side using omniauth, why do we have to add the client-side authorization again? What difference does it make?
The referenced javascript code is (From the linked Railscast):
jQuery ->
$('body').prepend('<div id="fb-root"></div>')
$.ajax
url: "#{window.location.protocol}//connect.facebook.net/en_US/all.js"
dataType: 'script'
cache: true
window.fbAsyncInit = ->
FB.init(appId: '<%= ENV["FACEBOOK_APP_ID"] %>', cookie: true)
$('#sign_in').click (e) ->
e.preventDefault()
FB.login (response) ->
window.location = '/auth/facebook/callback' if response.authResponse
$('#sign_out').click (e) ->
FB.getLoginStatus (response) ->
FB.logout() if response.authResponse
true
UPDATE:
One of the reasons we need to integrate FB.login authorization with the server-side authorization might be that the Omniauth server-side authorization does NOT work if it's accessed within the Facebook iFrame. If the user accesses the application for the first time, the application must ask for permissions; however, oAuth permission dialog cannot be loaded within the iFrame to prevent clickjacking. Calling FB.login can avoid such problem, because it will show the permission box as a popup(Omniauth popup option will not work).
So now I have a genuine reason to integrate client-side authorization, but the code from Railscasts does not work with my current settings. I've chosen to do it the following way.
Right now, I have the following script in my application.html.erb:
<script>
// Additional JS functions here
window.fbAsyncInit = function() {
FB.init({
appId : <%= ENV['FACEBOOK_KEY'] %>, // App ID
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true // parse XFBML
});
};
// Load the SDK Asynchronously
(function(d){
var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
if (d.getElementById(id)) {return;}
js = d.createElement('script'); js.id = id; js.async = true;
js.src = "//connect.facebook.net/en_US/all.js";
ref.parentNode.insertBefore(js, ref);
}(document));
</script>
And in my view, I have the following link invoking the Facebook log in action:
<%= link_to 'log in with facebook', '/auth/facebook', id: 'fb_log_in_link' %>
I add the following script to the view page where I have the login link.
function login() {
FB.login(function(response) {
if (response.authResponse) {
window.location = '/auth/facebook/callback'
}
});
}
Also, I need to change the link to call the function instead of directing to /auth/facebook/
<%= link_to_function 'log in with facebook', 'login()' %>
Done! The server-side and client-side authorization are fully integrated. Since I was still confused after watching Ryan's Railscast, I want to add a little bit of explanation for those who might be also confused.
The way this works:
Facebook SDK is initailized when the while the page is loaded.
The user clicks the "log in with Facebook" link.
FB.login function is called by the link, and the user goes through all the permissions process (e.g. permission dialog showing up asking for the user's permissions).
Then, the user is directed to /auth/facebook/callback. From routes.rb we have the line match 'auth/:provider/callback', to: 'sessions#create'. Therefore, now the server will either create a new user or simply create a session if the user has already registered before.
Done! The user is logged in.
Merging server-side and client-side authorization has two major advantages:
1. If the user is logged into the application either inside Facebook(via appcenter) he will be logged into the application outside Facebook as well. Vice versa, if the user logs in outside Facebook, he will be logged in automatically if he accesses it within Facebook after.
2. Logging in with /auth/facebook does not work if the user logs in within Facebook iFrame. To prevent clickjacking Facebook prohibits prompting users to auth permissions dialog within Facebook iFrame. The only way to avoid this is to open the dialog in a separate popup, and logging in with FB.login solves the problem.
the short answer is - you don't.
you can choose between client side login (via javascript SDK) and server side login using omniauth.
the disadventage of server-side login is overloading the server for a call you can do from the client.
the advantage is that usually the token is longer (3 months token and not 1-2 hours like client side).
i suggest combine the two. use the client side for initial login, once you do that have an async call from the server side for extended token (only if you have to).
It just says,
Facebook provides a JavaScript SDK that we can use to authenticate a user on the client-side so that it doesn’t look to them like they’ve left our application then returned.
It means that this is for the client side understanding that when user returned from the application, it doesn't look like that they have indeed left it.

Embed youtube comments and like

I was wondering if it's possible to embed youtube videos' comments and like button with the video?
If there is such thing, how can I do that or where can I get more info? Thanks
Here you can see an example of how to get and display the video comments
Getting Youtube Video Information using javascript/jquery
and in the Topic Explorer project you can see how to add a 'like' or add the video to your favorites:
https://code.google.com/p/yt-topic-explorer/source/browse/app/views/main.html
<button ng-click="addToList($event.target, 'likes', videoResult.id)">{{'LIKE'|i18n}}</button>
<button ng-click="addToList($event.target, 'favorites', videoResult.id)">{{'FAVORITE'|i18n}}</button>
and in:
https://code.google.com/p/yt-topic-explorer/source/browse/app/scripts/controllers/main.js
$scope.addToList = function(target, listName, videoId) {
var listId = $rootScope.relatedPlaylists[listName];
target.textContent = topicExplorerApp.filter.i18n('ADDING');
target.disabled = true;
youtube({
method: 'POST',
service: 'playlistItems',
params: {
part: 'snippet'
},
body: {
snippet: {
playlistId: listId,
resourceId: {
kind: constants.VIDEO_KIND,
videoId: videoId
}
}
},
callback: function(results) {
if ('error' in results) {
target.textContent = 'Error';
} else {
target.textContent = topicExplorerApp.filter.i18n('ADDED');
}
}
});
};
YouTube does not have any embed code that you can use to embed comments. So basically there are 2 options to embed comments -
1. Use the YouTube API to embed and post comments. This will need a good coding knowledge.
To get comments use this endpoint
GET https://www.googleapis.com/youtube/v3/commentThreads
To add comments use this endpoint
POST https://www.googleapis.com/youtube/v3/playlistItems
2. Or you can use a ready-made plugin that allows this functionality. Here is a small demo of the Youmax plugin that will list comments as well as allow you to add comments.
EDITED: On Feb,2016 YT has stopped the solution bellow from working :-( I'll keep it here just for reference
FOR THE COMMENTS:
As YT has deprecated the gdata for the comments url, you can scrape 'em also from here; its a workaround though :D
https://www.youtube.com/all_comments?v=cOIKAnF3mjs
...no authentication needed! :) and if you want to work the client side only (in this example by cross-domain), go through JS
<textarea style="width:100%;height:100%" id=cu></textarea>
<script>
var r='';
function c(d)
{
for(i=0;i<=d.query.count-1;i++)
r=r+d.results[i];
document.getElementById('cu').innerHTML=r;
}
</script>
<script src="http://query.yahooapis.com/v1/public/yql?q=%20SELECT%20*%20FROM%20html%20WHERE%20url%3D%22https://www.youtube.com/all_comments?v=cOIKAnF3mjs%22&callback=c"></script>
You can Access YouTube Comments by processing this URL
http://gdata.youtube.com/feeds/api/videos/{$videoID}/comments
The YouTube like functionality requires the user to be logged-in to his/hers Google account

Facebook login in a Ruby on Rails application

I'm developing a Ruby on Rails application using the Facebook flogin button with JavaScript.
My code:*
<fb:login-button perms="email" onlogin="createFbSession();"></fb:login-button>
<div id="fb-root"></div>
<script src="http://connect.facebook.net/en_US/all.js">
</script>
<script>
FB.init({
appId:"xxxxxxx", cookie:true,
status:true, xfbml:true
});
function createFbSession() {
FB.getLoginStatus(function(response) {
if (response.session) {
window.location = "<%= fb_login_path %>";
}
});
}
</script>
When I click on the flogin button, sometimes I receive the following error in the popup window:
An error occurred. Please try again later.
What does it mean?
You could use omniauth which lets you use facebook/twitter/openid etc... in ruby without having to use a js library linked in from facebook.
Railscasts have a great episode on a simple onmiauth setup which is well worth a watch and because omniauth returns similar data for all providers just change twitter to facebook and you should be fine.
Omniauth also allows for multiple providers in the same login system, as some people (myself included) prefer to use twitter so enforced facebook login would put me off.
When using the fb:login-button, for some reason, if you don't create it using the content_tag helper it breaks when rendered as html. In rails seems to work when rendered like this: <%= content_tag("fb:login-button", "Log in", {:scope=>"email"}) %>
Note: I'm using rails 3.1, I haven't tried that solution with previous versions.

Twitter Tweet or ReTweet Callbacks

Hope you are having a good time.
I am creating a website where when users Tweet a wordpress blog entry then they get points on the websites.
So basically, if a user Tweets that entry on his Twitter then we would give him some points to use on the website (not money). Although this thing is plausible with Facebook but not with Twitter in my knowledge.
I am willing to try to both ways by Twitter Tweet Button or TweetMeme Retweet Facility. However, I could not find a facility for a callback at neither of these.
I am implementing a similar functionality in Facebook and I can see the light at the end of the tunnel with using FBML JS SDK. HOwever, if something similar can be achieved with Twitter then it would be awesome.
Would love to hear more from you guys,
Kind Regards,
Khuram
They've fixed this with the intents function:
https://dev.twitter.com/pages/intents-events
twttr.events.bind('tweet', function(event) {
// Do something there
});
or for clicking
twttr.events.bind('click', function(event) {
var click_type = event.region;
});
using Twitters #anywhere api, you can set an onTweet function that does something when someone tweets.
here is a 6-step tutorial, see number 4
A default tweetBox can be called after the element with the comments class with the following snippet.
twttr.anywhere(function(twitter) {
twitter(".comments").tweetBox();
});
So if you want a custom label, content, and a callback when the tweet has been sent, use this code.
twitter(".comments").tweetBox({
label: 'What do you think about this article?',
defaultContent: '#nettuts ',
onTweet: function(plain, html){
// Actions when tweet is sent
}
});
opening tweet intent pop from JS code will send a callback. You need to put your tweet URL in herf of anchor tag
HTML:
<a target="_blank" href="https://twitter.com/intent/tweet?text=itismytext&url=http://google.com"> twitter share</a>
JavaScript:
$(document).ready(function(){
twttr.events.bind('tweet', function(event) {
console.log(event);
// OR
alert(JSON.stringify(event));
});
});

Resources