Select 30 random friends and send app requests - facebook-graph-api

**HI i am trying to send app request to 30 random friends of the user. So i want to get user ids of 30 facebook friends parse it and feed the uids into
function sendRequestToRecipients() {
var user_ids = document.getElementsByName("user_ids")[0].value;
FB.ui({method: 'apprequests',
message: 'sample message',
to: 'id of friend1,id of friend2,id of friend 3,,,,,,,'
}, requestCallback);
}**
Below is the full sample code...
<script>
FB.init({
appId : 'appid',
frictionlessRequests: true,
});
we have to put ids of friend here.....
function sendRequestToRecipients() {
var user_ids = document.getElementsByName("user_ids")[0].value;
FB.ui({method: 'apprequests',
message: 'sample message',
to: 'id of friend,id of friend'
}, requestCallback);
}
function sendRequestViaMultiFriendSelector() {
FB.ui({method: 'apprequests',
message: 'sample message'
}, requestCallback);
}
function requestCallback(response) {
// Handle callback here
}
</script>

FB.api({ method: 'friends.get' }, function(result) {
var user_ids="" ;
var totalFriends = result.length;
var randNo = Math.floor(Math.random() * totalFriends);
var numFriends = result ? Math.min(30,totalFriends) : 0;
if (numFriends > 0) {
for (var i=0; i<numFriends; i++) {
user_ids+= (',' + result[randNo]);
randNo ++;
if(randNo >= totalFriends){
randNo = 0;
}
}
}
profilePicsDiv.innerHTML = user_ids;
alert(user_ids);
});
Refer my answer at Facebook App invitation request

Related

How to POST data for evaluation in middleware in loopback?

I want to use custom API to evaluate data which are posted by applications but remote methods are not accepted in middleware in loopback
module.exports = function () {
const http = require('https');
var request = require('request');
var { Lib } = require('Lib');
var lib = new Lib;
verification.checkID = function (ID, cb) {
cb(null, 'ID is :' + ID);
}
verification.remoteMethod('greet', {
accepts: {
arg: 'ID',
type: 'string'
},
returns: {
arg: 'OK',
type: 'string'
}
});
module.exports = function () {
const http = require('https');
var request = require('request');
var { Lib } = require('Lib');
var lib = new Lib;
verification.checkID = function (ID, cb) {
cb(null, 'ID is :' + ID);
}
verification.remoteMethod('greet', {
'http': { // add the verb here
'path': '/greet',
'verb': 'post'
},
accepts: {
arg: 'ID',
type: 'string'
},
returns: {
arg: 'OK',
type: 'string'
}
});
Update
module.exports = function(server) {
// Install a `/` route that returns server status
var router = server.loopback.Router();
router.get('/', server.loopback.status());
router.get('/ping', function(req, res) { // your middle ware function now you need to call the next() here
res.send('pong');
});
server.use(router);
};
To evaluate is something i am not getting please check this link too Intercepting error handling with loopback
Regarding to fallowing question How to make a simple API for post method?
I find my solution in fallowing way:
module.exports = function(server) {
const https = require('https');
var request = require('request');
return function verification(req, res, next) {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE');
res.setHeader('Access-Control-Allow-Headers', 'Content-Type');
res.setHeader('Access-Control-Allow-Credentials', true);
var request;
var response;
var body = '';
// When a chunk of data arrives.
req.on('data', function (chunk) {
// Append it.
body += chunk;
});
// When finished with data.
req.on('end', function () {
// Show what just arrived if POST.
if (req.method === 'POST') {
console.log(body);
}
// Which method?
switch (req.method) {
case 'GET':
Verify url and respond with appropriate data.
handleGet(req, res);
Response has already been sent.
response = '';
break;
case 'POST':
// Verify JSON request and respond with stringified JSON response.
response = handlePost(body);
break;
default:
response = JSON.stringify({ 'error': 'Not A POST' });
break;
}
// Send the response if not empty.
if (response.length !== 0) {
res.write(response);
res.end();
}
// Paranoid clear of the 'body'. Seems to work without
// this, but I don't trust it...
body = '';
});
// If error.
req.on('error', function (err) {
res.write(JSON.stringify({ 'error': err.message }));
res.end();
});
//
};
function handlePost(body) {
var response = '';
var obj = JSON.parse(body);
// Error if no 'fcn' property.
if (obj['fcn'] === 'undefined') {
return JSON.stringify({ 'error': 'Request method missing' });
}
// Which function.
switch (obj['fcn']) {
// Calculate() requres 3 arguments.
case 'verification':
// Error if no arguments.
if ((obj['arg'] === 'undefined') || (obj['arg'].length !== 3)) {
response = JSON.stringify({ 'error': 'Arguments missing' });
break;
}
// Return with response from method.
response = verification(obj['arg']);
break;
default:
response = JSON.stringify({ 'error': 'Unknown function' });
break;
}
return response;
};
function verification(arg) {
var n1 = Number(arg[0]);
var n2 = Number(arg[1]);
var n3 = Number(arg[2]);
var result;
// Addem up.
result = n1 + n2 + n3;
// Return with JSON string.
return JSON.stringify({ 'result': result });
};
};

AWS Lambda Get Image and Upload to S3

I am working in a AWS Lambda function. I am successfully making an API call to the NASA APOD and getting back the values. I want to take the url for the image and download that image and then upload into S3. I am getting an error when I try to access the "test.jpg" image, "Error: EACCES: permission denied, open 'test.jpg'". If I move the S3bucket.putObject outside the http.request, I get data is equal to null. I know I am missing something simple. Thought?
function GetAPOD(intent, session, callback) {
var nasa_api_key = 'demo-key'
, nasa_api_path = '/planetary/apod?api_key=' + nasa_api_key;
var options = {
host: 'api.nasa.gov',
port: 443,
path: nasa_api_path,
method: 'GET'
};
var req = https.request(options, function (res) {
res.setEncoding('utf-8');
var responseString = '';
res.on('data', function (data) {
responseString += data;
});
res.on('end', function () {
console.log('API Response: ' + responseString);
var responseObject = JSON.parse(responseString)
, image_date = responseObject['date']
, image_title = responseObject['title']
, image_url = responseObject['url']
, image_hdurl = responseObject['hdurl']
, image_desc = responseObject['explanation'];
var s3Bucket = new AWS.S3( { params: {Bucket: 'nasa-apod'} } );
var fs = require('fs');
var file = fs.createWriteStream("test.jpg");
var request = http.get(image_url, function(response) {
response.pipe(file);
var data = {Key: "test.jpg", Body: file};
s3Bucket.putObject(data, function(err, data) {
if (err) {
console.log('Error uploading data: ', data);
}
else {
console.log('succesfully uploaded the image!');
}
});
});
});
});
req.on('error', function (e) {
console.error('HTTP error: ' + e.message);
});
//req.write();
req.end();
}
You need to be writing the file to /tmp. That's the only directory in the Lambda environment that you will have write access to.
I got it!! Thank you Mark B for the help. I was able to get the data from the stream without saving it locally and then writing to the bucket. I did have to change my IAM role to allow the putObject for S3.
function GetAPOD(intent, session, callback) {
var nasa_api_key = 'demo-key'
, nasa_api_path = '/planetary/apod?api_key=' + nasa_api_key;
var options = {
host: 'api.nasa.gov',
port: 443,
path: nasa_api_path,
method: 'GET'
};
var req = https.request(options, function (res) {
res.setEncoding('utf-8');
var responseString = '';
res.on('data', function (data) {
responseString += data;
});
res.on('end', function () {
// console.log('API Response: ' + responseString);
var responseObject = JSON.parse(responseString)
, image_date = responseObject['date']
, image_title = responseObject['title']
, image_url = responseObject['url']
, image_hdurl = responseObject['hdurl']
, image_desc = responseObject['explanation'];
var image_name = image_date + '.jpg';
var s3 = new AWS.S3();
var s3Bucket = new AWS.S3( { params: {Bucket: 'nasa-apod'} } );
var request = http.get(image_url, function(response) {
var image_stream = null;
response.on('data', function (data) {
image_stream = data;
});
response.on('end', function () {
var param_data = {Key: image_name, Body: image_stream, ContentType: "image/jpeg", ContentLength: response.headers['content-length']};
s3Bucket.putObject(param_data, function(err, output_data) {
if (err) {
console.log('Error uploading data to S3: ' + err);
}
});
});
});
request.end();
});
});
req.on('error', function (e) {
console.error('HTTP error: ' + e.message);
});
req.end();
}

Implementing feed of Facebook page in the website

I have to implement the Facebook feed (our website page in Facebook) in the home page.
I tried with this plugin (https://developers.facebook.com/docs/plugins/like-box-for-pages), but I couldn't change the display style. Example, I don't want to display logo, page title and images in the feed.
Graph API + JSON + jQuery seems the way to get and customize the Facebook feed before adding website. Image is attached for how to display the feed.
I went through the API's page of Facebook. But, I need some direction to follow if anyone have already done this.
I am using the below to get the feed.
$(document).ready(function () {
$.ajax({
url: 'https://graph.facebook.com/1234/feed?access_token=cxcx&callback=?', //Replace with your own access token
dataType: 'json',
success: displayFacebookFeed,
error:alertError
});
});
It's working fine, but the message I am accessing has links, which comes as text.
var html="";
$.each(result.data, function (i, item) {
var body = item.message;
if (!body) {
body = item.description;
}
html += "<li>" + body + "</li>";
});
So for an example.
9 Sensational Traits of Highly Promotable Employees | Inc.com https://www.inc.com/jeff-haden/9-sensational-traits-of-highly-promotable-employees.html
In the above feed, I want this as link, but its coming as plain text.
Is there any suggestion?
How about the Activity Feed for your domain, using the Activity Feed plugin?
https://developers.facebook.com/docs/plugins/activity
Here is a solution I came up with for a project a while back. Definitely not plug+play since it is integrated with my javascript architecture but hopefully can get you started:
"use strict";
var Facebook = function(sb, options) {
options = options || {};
var language = options.language || "en_US";
var self = this;
var access_token = encodeURIComponent(YOUR ACCESS TOKEN);
var listenerQueue = [];
var loading = false;
var FACEBOOK;
var appId = YOUR APP ID;
if (window.FB) {
FACEBOOK = window.FB;
}
(function _load() {
if (!loading) {
loading = true;
window.fbAsyncInit = function() {
// init the FB JS SDK
FACEBOOK = window.FB;
FACEBOOK.init({
appId : appId,
status : true,
oauth : true,
cookie : true,
xfbml : true
});
sb.publish("facebook:initialized");
};
// Load the SDK asynchronously
(function(d, s, id){
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) {return;}
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/" + language + "/all.js";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
}
})();
(function() {
sb.subscribe('facebook:initialized', function() {
listenForLogin();
if (listenerQueue.length) {
clearListenerQueue();
}
});
})();
function listenForLogin() {
FACEBOOK.Event.subscribe('auth.authResponseChange', function(response) {
if (response.status === 'connected') {
getLoggedInUserData();
} else {
}
});
}
function getLoggedInUserData() {
FACEBOOK.api('/me', function(response) {
sb.publish('facebook:loggedIn', response);
});
}
function clearListenerQueue() {
if (FACEBOOK) {
for (var i=0; i<listenerQueue.length; i++) {
listenerQueue[i].fn.apply(this, listenerQueue[i].args);
}
listenerQueue = [];
}
}
function sharePage(url, options) {
var opts = options || {};
if (FACEBOOK) {
FACEBOOK.ui(
{
method: 'feed',
name: opts.name || '',
caption: opts.caption || '',
description: opts.description || '',
link: url,
picture: opts.picture || ''
},
function(response) {
var success = (response && response.post_id);
sb.publish('facebook:shared', {response : response, success : success});
}
);
} else {
listenerQueue.push({fn : sharePage, args : [url, options]});
}
return self;
}
function getPosts(fbHandleOrId, options) {
options = options || {};
if (FACEBOOK) {
var limit = options.limit || '10';
var graphPOSTS = '/' + fbHandleOrId +'/posts/?date_format=U&access_token=' + access_token + "&limit=" + limit;
FACEBOOK.api(graphPOSTS, function(response) {
sb.publish('facebook:gotPosts', {response : response, handleUsed : fbHandleOrId});
});
} else {
listenerQueue.push({fn : getPosts, args : [fbHandleOrId, options]});
}
}
function getStatuses(fbHandleOrId, options) {
options = options || {};
if (FACEBOOK) {
var limit = options.limit || '10';
var graphStatuses = '/' + fbHandleOrId + "/feed/?access_token=" + access_token + "&limit=" + limit;
FACEBOOK.api(graphStatuses, function(response) {
sb.publish('facebook:gotStatuses', {response : response, handleUsed: fbHandleOrId});
});
} else {
listenerQueue.push({fn : getStatuses, args : [fbHandleOrId, options]});
}
}
function getNextPageOfPosts(nextPostsUrl, options) {
options = options || {};
if (FACEBOOK) {
FACEBOOK.api(nextPostsUrl, function(response) {
sb.publish('facebook:gotNextPosts', {response : response, handleUsed : fbHandleOrId});
});
} else {
listenerQueue.push({fn : getNextPageOfPosts, args : [nextPostsUrl, options]});
}
}
function getPublicUserInfo(fbHandleOrId, options) {
options = options || {};
var graphUSER = '/'+ fbHandleOrId +'/?fields=name,picture&callback=?';
if (FACEBOOK) {
FACEBOOK.api(graphUSER, function(response) {
var returnObj = {response : response, handleUsed : fbHandleOrId};
sb.publish('facebook:gotPublicUserInfo', returnObj);
});
} else {
listenerQueue.push({fn : getPublicUserInfo, args : [fbHandleOrId, options]});
}
}
function getLikes(pageHandle, options) {
options = options || {};
var graphLIKES = '/' + pageHandle + '/?fields=likes';
if (FACEBOOK) {
FACEBOOK.api(graphLIKES, function(response) {
var returnObj = {response : response, handleUsed: pageHandle};
sb.publish('facebook:gotLikes', returnObj);
});
} else {
listenerQueue.push({fn : getLikes, args : [pageHandle, options]});
}
}
function login() {
if (FACEBOOK) {
FACEBOOK.getLoginStatus(function(response) {
if (response.status !== "connected") {
// not logged in
FACEBOOK.login(function() {}, {scope : 'email'});
} else {
getLoggedInUserData();
}
});
} else {
listenerQueue.push({fn : login, args : []});
}
}
function getNextPageOfPosts(callback) {
callback = callback || function() {};
}
return {
getLikes : getLikes,
getPublicUserInfo : getPublicUserInfo,
getCurrentUser : getLoggedInUserData,
getNextPageOfPosts : getNextPageOfPosts,
getPosts : getPosts,
getStatuses : getStatuses,
sharePage : sharePage,
login : login
}
};
Facebook has now just added;
NOTE: With the release of Graph API v2.3, the Activity Feed plugin is deprecated and will stop working on June 23rd 2015.
The Activity feed displays the most interesting, recent activity taking place on your site, using actions (such as likes) by your friends and other people. https://developers.facebook.com/docs/plugins/activity
you can use the FB Javascript SDK
if i remember correctly this should work should users already have a facebook permission setup for your web site. or you don't mine asking them for basic authentication
FB.login(function(){
FB.api('/v2.0/page_group_address_or_id/feed', 'GET', '', function(feedContent){
// handle rendering the feed in what ever design you like
console.log(feedContent);
});
});
the only other way would be to use server side to get an oAuth access and use your own access token though php making a request to the GraphAPI server

Express Passport unable to get facebook friends list

When attempting to use the Facebook api to get the friends list of a verified account it seems to work except that the friends list returned is empty.
facebook.js
var https = require('https');
exports.getFbData = function(accessToken, apiPath, callback) {
var options = {
host: 'graph.facebook.com',
port: 443,
path: apiPath + '?access_token=' + accessToken, //apiPath example: '/me/friends'
method: 'GET'
};
var buffer = ''; //this buffer will be populated with the chunks of the data received from facebook
var request = https.get(options, function(result){
result.setEncoding('utf8');
result.on('data', function(chunk){
buffer += chunk;
});
result.on('end', function(){
callback(buffer);
});
});
request.on('error', function(e){
console.log('error from facebook.getFbData: ' + e.message)
});
request.end();
}
app.js
app.get('/', function (req, res) {
if (req.session.myID != null && req.session.myName != null) {
User.findOne({sessionID: req.session.myID, username: req.session.myName}, function (err, doc) {
if (err) {throw err}
else if (doc != null) {
facebook.getFbData(doc.facebookToken, '/me/friends', function(data){
console.log(data);
res.render('index');
});
}
else {
//console.log("not logged in");
res.render('index');
}
});
}
else {
//console.log("not logged in");
res.render('index');
}
});
passport.use(new FacebookStrategy({
clientID: FACEBOOK_APP_ID,
clientSecret: FACEBOOK_APP_SECRET',
callbackURL: "http://localhost:3000/auth/facebook/callback",
profileFields: ['id', 'displayName']
},
function(accessToken, refreshToken, profile, done) {
User.findOne(..., function(err, user) {
if (err) { return done(err); }
user.facebookID = profile.id;
user.facebookToken = accessToken;
user.save();
return done(null, user);
});
}
));
app.get('/auth/facebook', passport.authenticate('facebook',
{scope: 'user_friends'})
);
app.get('/auth/facebook/callback',
passport.authenticate('facebook', { failureRedirect: '/login' }),
function(req, res) {
// Successful authentication, redirect home.
res.redirect('/');
}
);
The console.log in the facebook.getFbData callback prints:
{"data":[]}
This code actually works correctly. However it does not fetch the whole friends list, only the list of friends who also have the app.

facebook authentication to auto popup instead click button

I've tried the fowlling code
https://developers.facebook.com/blog/post/2011/07/21/updated-javascript-sdk-and-oauth-2-0-roadmap/
It works to authenticate
now i want to auto popup once page is loaded instead of having people click ont he button again
I edited and was able to trigger the autopopup , but that only works if i keep the button
How can i remove the button and still have it work?
this is what i've done:
<!DOCTYPE html>
<html xmlns:fb="https://www.facebook.com/2008/fbml">
<head>
<title>
New JavaScript SDK
</title>
</head>
<body>
<div id="fb-root"></div>
<h2>Updated JS SDK example</h2><br />
<div id="user-info"></div>
<p><button id="fb-auth">Login</button></p>
<script>
window.fbAsyncInit = function() {
FB.init({ appId: 'xxx',
status: true,
cookie: true,
xfbml: true,
oauth: true});
function updateButton(response) {
var button = document.getElementById('fb-auth');
if (response.authResponse) {
//user is already logged in and connected
var userInfo = document.getElementById('user-info');
FB.api('/me', function(response) {
userInfo.innerHTML = '<img src="https://graph.facebook.com/'
+ response.id + '/picture">' + response.name;
button.innerHTML = 'Logout';
});
button.onclick = function() {
FB.logout(function(response) {
var userInfo = document.getElementById('user-info');
userInfo.innerHTML="";
});
};
} else {
//user is not connected to your app or logged out
//button.innerHTML = 'Login';
// button.onclick = function() {
FB.login(function(response) {
if (response.authResponse) {
FB.api('/me', function(response) {
var userInfo = document.getElementById('user-info');
userInfo.innerHTML =
'<img src="https://graph.facebook.com/'
+ response.id + '/picture" style="margin-right:5px"/>'
+ response.name;
});
} else {
//user cancelled login or did not grant authorization
}
}, {scope:'email'});
}
//}
}
// run once with current status and whenever the status changes
FB.getLoginStatus(updateButton);
FB.Event.subscribe('auth.statusChange', updateButton);
};
(function() {
var e = document.createElement('script'); e.async = true;
e.src = document.location.protocol
+ '//connect.facebook.net/en_US/all.js';
document.getElementById('fb-root').appendChild(e);
}());
</script>
</body>
</html>
<script>
(function() {
var e = document.createElement('script'); e.async = true;
e.src = document.location.protocol
+ '//connect.facebook.net/en_US/all.js';
document.getElementById('fb-root').appendChild(e);
}());
window.fbAsyncInit = function() {
FB.init({ appId: 'xxx',
status: true,
cookie: true,
xfbml: true,
oauth: true});
fbLoginStatus();
});
function fbLoginStatus()
{
FB.getLoginStatus(function(response) {
console.log(response);
if (response.status === 'connected') {
access_token = FB.getAuthResponse()['accessToken'];
myinfo();
} else {
fblogin();
}
});
}
function fblogin()
{
FB.login(function(response) {
if (response.authResponse) {
console.log(response);
access_token = FB.getAuthResponse()['accessToken'];
myinfo();
} else {
console.log('User cancelled login or did not fully authorize.');
}
}, {scope: 'email'});
}
function myinfo()
{
FB.api('/me', function(response) {
userid = response.id ;
alert(userid);
user_name = response.name;
alert(user_name);
});
}
</script>
Try this code, it will work exactly what you want.
Here's the code. I think the above code should work too.
<script>
window.fbAsyncInit = function(){
FB.init({
appId: '1486670758257443',
status: true,
cookie: true,
xfbml: true,
oauth: true,
version : 'v2.1'
});
fbLoginStatus();
};
(function(d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) return;
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/en_US/sdk.js";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
function fbLoginStatus(){
FB.getLoginStatus(function(response) {
console.log(response);
if (response.status === 'connected') {
var access_token = FB.getAuthResponse()['accessToken'];
console.log(access_token);
} else {
fblogin();
}
});
}
function fblogin(){
FB.login(function(response) {
if (response.authResponse) {
var access_token = FB.getAuthResponse()['accessToken'];
console.log(access_token);
} else {
console.log('Authorization failed.');
}
},{ //permissions
scope: 'email'
});
}
</script>
and one thing to mention that, according to facebook doc, the popup should be opened by click event. Here's what they're saying.
Calling FB.login results in the JS SDK attempting to open a popup window. As such, this method should only be called after a user click event, otherwise the popup window will be blocked by most browsers.