Facebook api multiple request - facebook

I am creating a facebook application generator. And I need to check if the user has currently added the application on this facebook page or not.
In order to do that, i first request facebook api to give a list of his pages. Then i loop through all the pages. And request for apps on each of these pages.
Lastly i compare the appId with the one user just created and displays the display the warning accordingly.
The problem is , when i loop through each of the pageId and request FbApi for subpages, the request response is delayed and the for each loop completes its cycle before the results are fetched from facebook.
Here is my code, which is quite complex... Any ideas to fix the issue is highly appreciated.
FB.login(function (response) {
FB.api('/me/accounts', function (apiresponse) {
var totalPages = apiresponse.data.length;
var pageIndex = 0;
$.each(apiresponse.data, function (pageNumber, pageData) {
var pageAccessToken = pageData.access_token;
var tabPageName = pageData.name;
var tabPageId = pageData.id;
FB.api("/" + tabPageId + "/tabs", function (response) {
var foundApp = false
$.each(response.data, function (index, value) {
var exsistingAppId = (value.id).split("app_").pop();
if (exsistingAppId == fbAppId) {
foundApp = true;
}
});
if (foundApp === true) {
var data = {
PageId: tabPageId,
Url: window.location.href.split("/").pop()
}
$.ajax({
type: "POST",
url: '/facebook/Match',
contentType: "application/json",
data: JSON.stringify(data),
success: function (data) {
if (data == "True") {
$("#addToFacebookModal ul").append("<li><span class='pageTab'><a class='pageTabName' target='_blank' href='https://facebook.com/profile.php?id=" +tabPageId + "'>" +tabPageName + "</a></span><a class='deleteAppFromPageTab' data-id='" +tabPageId + "' data-accessToken='" +pageAccessToken + "'>[x]</a></li>");
alreadyAdded.push(true);
} else {
alreadyAdded.push(false);
}
pageIndex++;
if (pageIndex == totalPages) {
console.log("Total Pages = " + totalPages + ", Looped through = " + alreadyAdded.length);
if (alreadyAdded.indexOf(true) >= 0) {
$("#addToFacebookModal").modal();
} else {
addToFacebook();
}
}
}
});
}
else {
pageIndex++;
}
});
});
});
}, { scope: 'manage_pages' });
Here is pseudocode of what i am doing
var myVariable
-Fb.Api Callback function returns response array
-Loop through the response array
-Get new Response array based on the previous response in that array
-Loop through each item of the new response array and compare it with myVariable.
The problem is that responses are delayed while the loop finishes up before the responses arrive. As i result i cant compare the nested Item with myVariable.

If by "facebook page" you mean a business page / organization page (not a profile), you can get the same information more easily by checking the endpoint '/{{page_id}}/tabs/{{app_id}}.
Replace page_id with the ID of the page you want to check and app_id similarly with your app ID. I don't have working code at the moment, but something like this:
FB.api(
'/' + checkPageID + '/tabs/{{app_id}}',
function (response) {
// Do console.log(response) to figure out how to see if installed or not
}
)

YOu can use fields expansion:
https://developers.facebook.com/docs/graph-api/using-graph-api/v2.3#fieldexpansion
FB.api('/me/accounts', {fields: 'name, address{city}'},function (response)
{
//do something here.
}

Related

SharePoint CAML + REST + Paging issue

I suppose I have found another SP bug... but maybe I do something wrong.
I have this POST request:
https://dmsdev/coll/f7c592adcb4c4e5996c2de00d444a94c/_api/Web/Lists/GetByTitle('1')/GetItems?$expand=ContentType&$select=Id,SonarDocId,ContentTypeId,EncodedAbsURL,Modified,ContentType/Name
With body:
{"query":{"ViewXml":"<View><Query><OrderBy><FieldRef Name='Modified'/></OrderBy></Query><RowLimit>50</RowLimit></View>","ListItemCollectionPosition":{"PagingInfo":"Paged=TRUE&p_Modified=2017-08-10T07:25:28"}}}
As you can see I do a CAML query with ORDER BY Modified column and I want to take items starting from the item after the item with some modified date but looks like this is not working... I mean similar request on other SP environment works, and on the other env it is not working... it takes all items starting from the first one after ordering by modified... I have no idea what is wrong :/
You could check my sample test script.
<script type="text/javascript">
function restCallwithCaml(listName, caml,PID) {
/// get the site url
var siteUrl = _spPageContextInfo.siteAbsoluteUrl;
/// set request data
var data = {
"query": {
"__metadata":
{ "type": "SP.CamlQuery" },
"ViewXml": caml,
"ListItemCollectionPosition": {
"PagingInfo": "Paged=TRUE&p_ID=" + PID
}
}
};
/// make an ajax call
return $.ajax({
url: siteUrl + "/_api/web/lists/GetByTitle('" + listName + "')/GetItems",
method: "POST",
data: JSON.stringify(data),
headers: {
"X-RequestDigest": $("#__REQUESTDIGEST").val(),
'content-type': 'application/json;odata=verbose',
'accept': 'application/json;odata=verbose'
}
});
}
function GetItemsPaging() {
var pageLimit = 2;
var pageNumber = 0;
var caml = "<View><Query><Where><Geq><FieldRef Name='ID'/><Value Type='Number'>1</Value></Geq></Where></Query><RowLimit>" + pageLimit + "</RowLimit></View>";
var listName = "ChildB";
restCallwithCaml(listName, caml, pageNumber).done(function (data) {
if (data.d.results.length == pageLimit) {
pageNumber++;
//add to array or display
var PID=data.d.results[data.d.results.length - 1].Id;
alert(PID);
restCallwithCaml(listName, caml, PID).done(function (data) {
//add to array or display
alert(data.d.results[data.d.results.length - 1].Id);
})
}
});
}
</script>
Original thread
The problem was with my understanding of how this whole thing works + time zones
I had to write a paging query eg:
Paged=TRUE&p_ID=10&p_Modified=2018-12-14T18:52:00
So I had to add p_Modified parameter from the last item from the previous page... Additionally this data has to be in UTC, so for example I can execute get query with the time returned by the CAML
https://server/site/_api/web/RegionalSettings/TimeZone/localTimeToUTC(#date)?#date='2018-12-14T11:52:00'
And date returned by this call should be passed in p_Modified.

Posting custom stories to Facebook with batch request

I have a web application that allows users to post custom stories to their Facebook timeline with the list of fitness exercises they have performed.
The first version is looping through the exercises and calling FP.api for each exercise and it works fine.
Now I would like to make a single call to FB.api with a batch request to speed up the posting and that's where I'm having trouble.
Here is the code with the loop that works fine (exids is an array of numbers):
function postToFB(exids)
{
fbi = 0;
fblength = exids.length;
for (var i = 0; i < fblength; i++)
{
FB.api(
'me/' + vitNamespace + ':perform',
'post',
{
exercise: "http://www.vitalclub.net/scripts/getExforFB.php?exid=" + exids[i],
'fb:explicitly_shared': true
},
function(response) {
...
});
}
}
and here is the code with the batch request that returns an error:
function postToFB(exids)
{
var batcharr = [];
for (var i = 0; i < exids.length; i++)
batcharr.push({ method: 'post', relative_url: 'me/' + vitNamespace + ':perform', body: "exercice=http://www.vitalclub.net/scripts/getExforFB.php%3Fexid%3D" + exids[i] + "&fb:explicitly_shared=true" });
FB.api(
'/',
'post',
{ batch: batcharr, include_headers: false },
function(response) {
...
});
}
The error I get (for each exercise) is the following: The action you're trying to publish is invalid because it does not specify any reference objects. At least one of the following properties must be specified: exercise.
I presume this has to do with the way the body in the batch request is formatted but I cannot find the right way to format it. I have tried using encodeURIComponent on the URL representing the exercise but the error is the same.
Anybody has an idea of what the problem is?
Thanks,
Jean
OK, my bad. It was really a stupid error. I had written the parameter "exercise" in French instead of English (so "exercice" instead of "exercise") and that's where the problem was.
I'm also now using $.param to format the parameters so I now have:
var batcharr = [];
var opts;
for (var i = 0; i < exids.length; i++)
{
opts = { exercise: "http://www.vitalclub.net/scripts/getExforFB.php?exid=" + exids[i], 'fb:explicitly_shared': true };
batcharr.push({ method: 'post', relative_url: 'me/' + vitNamespace + ':perform', body: $.param(opts) });
}
before calling FB.api and it works like a charm!

Whats the angular way of autodirecting incomplete url's?

when i want to get to
http://www.koran-auf-deutsch.de/koran-deutsch/23-die-glaubigen-al-mominun/
and just enter
http://www.koran-auf-deutsch.de/koran-deutsch/23
i get directly to the url. i would like to get a similar behaviour
in my angular app, where would you inject that functionality? any ideas?
angular.module('app', []).
config(['$routeProvider', function($routeProvider) {
$routeProvider.
when('/:id', {controller: RedirectCtrl}).
when('/:id/:title', {templateUrl: 'partials/post.html', controller: PostCtrl}).
otherwise({redirectTo: '/404'});
}]);
function RedirectCtrl($routeParam, $http) {
var post_id = $routeParams.id;
// get title by id
$http.get('/api_url_to_get_title_by_id').success(function (data) {
window.location = "/" + post_id + "/" + data.title;
});
}
RedirectCtrl.$inject = ['$routeParams', '$http'];

How should I retrieve original pictures included with the Facebook posts?

My application uses the Facebook Javascript SDK to add wall posts to the feed of a community's page, and to retrieve them again. Pictures included with the posts are processed and placed somewhere on the Facebook servers.
When these posts are retrieved the links to the pictures turn out to be links pointing to the fbcdn.net server.
Is there a way to access the original links?
Update:
Here is my code posting a post:
// The "params" variable contains a field called "picture"
// (which is a link pointing to my picture)
FB.addWallPost = function (params, pageId, token, complete) {
var fbApiParams = {
access_token: token
};
$.extend(fbApiParams, params);
FB.api(pageId + '/feed', 'post', fbApiParams, function (response) {
// FB.apiCallDone is a function checking if there's any positive response
if (FB.apiCallDone(response)) {
complete(response.id);
}
else {
complete(null);
}
});
}
And these lines retrieve the posts:
FB.getWallPosts = function (wallPostsIds, token, complete) {
if (wallPostsIds && wallPostsIds != null && wallPostsIds.length) {
var wallPostsIdsStr = wallPostsIds.join(',');
var fbApiParams = {
ids: wallPostsIdsStr,
access_token: token
};
FB.api('/', fbApiParams, function (response) {
if (FB.apiCallDone(response)) {
var wallPosts = dictElemsToArr(response);
complete(wallPosts);
}
else {
complete([]);
}
});
}
else {
complete([]);
}
}
If you're posting pictures to Facebook, they will be stored locally by Facebook.
It is up to your application to store the path of the original images if your application requires this information.

FaceBook API: Get the Request Object for a request Id - logged into the account that sent the request. Using the "Requests Dialog" API

I am using the "Requests Dialog" to create Facebook requests. Inorder to get the user that the requests were sent to I need to access the Request object using the graph API. I have tried most of the permissions settings that seemed appropriate (read_requests and user_about_me) to get the request object, but instead I get a false in the response. Am I using the wrong permissions?
I am able to access the request object using the graph API from the account that the request was sent to.
http://developers.facebook.com/docs/reference/dialogs/requests/
Return Data - A comma-separated list
of the request_ids that were created.
To learn who the requests were sent
to, you should loop through the
information for each request object
identified by a request id.
I've been asking myself this question a while ago:
How to retrieve all the requests sent by me?
The answer: you can't!
You have two options:
Store the request_id returned when the user sent the request, so you can later access them and get the data you need
Knowing the receiver!
Proof of the above, you can check the friend_request table. The indexable field is the uid_to field!
This is if you want it in know Iframe mode as you don't need Iframe mode any more
function sendRequest() {
FB.ui({
method: 'apprequests',
title: 'Invite friends to join you',
message: 'Come play with me.'
},
function (res) {
if (res && res.request_ids) {
var requests = res.request_ids.join(',');
$.post('FBRequest.ashx',
{ request_ids: requests },
function (resp) { });
}
});
return false;
}
If you want to find out the user ids of the people you just sent a request to. Then this code is what you need:
var request = {
message: msg,
method: 'apprequests',
title: 'Select some of your friends'
};
FB.ui(request, function (data) {
if (data && data.request_ids) {
// Get the uid of the person(s) who was/were invited
var uids = new Array();
FB.api("/?ids=" + data.request_ids.join(), function(data2) {
for (i = 0; i<data.request_ids.length; i++) {
uids[i] = data2[data.request_ids[i]]['to']['id'];
}
# do something with uids here
});
}
});
Don't know if this helps, but here's how I handle it.
Javascript:
function sendRequest() {
FB.ui({
display: 'iframe',
method: 'apprequests',
title: 'Invite friends to join you',
message: 'Come play with me.'
},
function (res) {
if (res && res.request_ids) {
var requests = res.request_ids.join(',');
$.post('FBRequest.ashx',
{ request_ids: requests },
function (resp) { });
}
});
return false;
}
Server side (FBRequest.ashx):
// get operation and data
var ids = HttpContext.Current.Request["request_ids"];
// if we have data
if(ids != null) {
// make batch graph request for request details
var requestIds = ids.Split(',').Select(i => long.Parse(i)).ToList();
var fbApp = new FacebookWebClient([AppId],[AppSecret]);
dynamic parameters = new ExpandoObject();
parameters.ids = ids;
dynamic requests = fbApp.Get(parameters);
// cycle through graph results and do stuff
dynamic req = null;
for(int i=0;i<requestIds.Count;i++) {
try {
req = requests[requestIds[i].ToString()];
// do stuff with request, save to DB, etc.
} catch (Exception ex) {
// error in finding request, continue...
}
}
}
You can access the list of user id's as part of the return data
FB.ui({
method: 'apprequest',
message: 'Use this thing',
}, function(result){
//a list of ids are in here
result.to;
});