Web App Bot throws invalid status code 'Unauthorized' on Facebook Channel - facebook

I'm developing a Facebook with the Microsoft.Bot.Builder Framework (4.2.2)
The Bot Works on emulator and on Azure with the "Test in Web Chat" Really fine. But on the Facebook Channel I get an "There was an error sending this message to your bot: HTTP status code InternalServerError"
My log stream says:
019-04-12 13:23:22.154 +00:00 [Information]
Microsoft.AspNetCore.Hosting.Internal.WebHost: Request starting
HTTP/1.1 POST
http://thomasreigltestbot1995.azurewebsites.net/api/messages
application/json; charset=utf-8 688
2019-04-12 13:23:22.155 +00:00 [Information]
Microsoft.Bot.Builder.Integration.IAdapterIntegration: Received an
incoming activity. ActivityId: Vg2USjaJGCZ1Ib_-
LTftnL9F6qg_DCJaV3XbIqGzSpisuO10eYLezkjHJxSVcYAAUWQvynDJbUyfvyBgN30B3w
2019-04-12 13:23:22.155 +00:00 [Information]
Microsoft.Bot.Builder.Integration.IAdapterIntegration: Sending
activity. ReplyToId: Vg2USjaJGCZ1Ib_-
LTftnL9F6qg_DCJaV3XbIqGzSpisuO10eYLezkjHJxSVcYAAUWQvynDJbUyfvyBgN30B3w
2019-04-12 13:23:22.388 +00:00 [Error]
Facebook_Events_Bot.FacebookEventsBot: Exception caught :
Microsoft.Bot.Schema.ErrorResponseException: Operation returned an
invalid status code 'Unauthorized'at
Microsoft.Bot.Connector.Conversations.
This is my simple Bot from this repo:
https://github.com/Microsoft/BotBuilder-Samples/tree/master/samples/csharp_dotnetcore/23.facebook-events
public class FacebookEventsBot : IBot
{
private const string DialogId = "question";
/// </summary>
private readonly DialogSet _dialogs;
private Tuple<int, string> tuple;
public FacebookEventsBot(BotAccessors accessors)
{
if (accessors == null)
{
throw new ArgumentNullException(nameof(accessors));
}
_dialogs = new DialogSet(accessors.ConversationDialogState);
_dialogs.Add(new AttachmentPrompt(DialogId));
}
public async Task OnTurnAsync(ITurnContext turnContext, CancellationToken cancellationToken = default(CancellationToken))
{
const string facebookPageNameOption = "Facebook Page Name";
const string quickRepliesOption = "Quick Replies";
const string postBackOption = "PostBack";
if (turnContext == null)
{
throw new ArgumentNullException(nameof(turnContext));
}
// Check if we are on the Facebook channel.
if (turnContext.Activity.ChannelId == Channel.Channels.Facebook)
{
// Analyze Facebook payload from channel data.
ProcessFacebookPayload(turnContext.Activity.ChannelData);
// Initially the bot offers to showcase 3 Facebook features: Quick replies, PostBack and getting the Facebook Page Name.
// Below we also show how to get the messaging_optin payload separately as well.
switch (turnContext.Activity.Text)
{
// Here we showcase how to obtain the Facebook page name.
// This can be useful for the Facebook multi-page support provided by the Bot Framework.
// The Facebook page name from which the message comes from is in turnContext.Activity.Recipient.Name.
case facebookPageNameOption:
{
var reply = turnContext.Activity.CreateReply($"This message comes from the following Facebook Page: {turnContext.Activity.Recipient.Name}");
await turnContext.SendActivityAsync(reply);
break;
}
// Here we send a HeroCard with 2 options that will trigger a Facebook PostBack.
case postBackOption:
{
var dialogContext = await _dialogs.CreateContextAsync(turnContext, cancellationToken);
var results = await dialogContext.ContinueDialogAsync(cancellationToken);
var card = new HeroCard
{
Text = "Is 42 the answer to the ultimate question of Life, the Universe, and Everything?",
Buttons = new List<CardAction>
{
new CardAction() { Title = "Yes", Type = ActionTypes.PostBack, Value = "Yes" },
new CardAction() { Title = "No", Type = ActionTypes.PostBack, Value = "No" },
},
};
var reply = turnContext.Activity.CreateReply();
reply.Attachments = new List<Attachment> { card.ToAttachment() };
await turnContext.SendActivityAsync(reply);
break;
}
// By default we offer the users different actions that the bot supports, through quick replies.
case quickRepliesOption:
default:
{
var reply = turnContext.Activity.CreateReply("What Facebook feature would you like to try? Here are some quick replies to choose from!");
reply.SuggestedActions = new SuggestedActions()
{
Actions = new List<CardAction>()
{
new CardAction() { Title = quickRepliesOption, Type = ActionTypes.PostBack, Value = quickRepliesOption },
new CardAction() { Title = facebookPageNameOption, Type = ActionTypes.PostBack, Value = facebookPageNameOption },
new CardAction() { Title = postBackOption, Type = ActionTypes.PostBack, Value = postBackOption },
},
};
await turnContext.SendActivityAsync(reply);
break;
}
}
}
else
{
// Check if we are on the Facebook channel.
if (turnContext.Activity.ChannelId == Channel.Channels.Facebook)
{
// Here we can check for messaging_optin webhook event.
// Facebook Documentation for Message optin:
// https://developers.facebook.com/docs/messenger-platform/reference/webhook-events/messaging_optins/
}
await turnContext.SendActivityAsync($"Received activity of type {turnContext.Activity.Type}.");
}
}
private void ProcessFacebookPayload(object channelData)
{
// At this point we know we are on Facebook channel, and can consume the Facebook custom payload
// present in channelData.
var facebookPayload = (channelData as JObject)?.ToObject<FacebookPayload>();
if (facebookPayload != null)
{
// PostBack
if (facebookPayload.PostBack != null)
{
OnFacebookPostBack(facebookPayload.PostBack);
}
// Optin
else if (facebookPayload.Optin != null)
{
OnFacebookOptin(facebookPayload.Optin);
}
// Quick reply
else if (facebookPayload.Message?.QuickReply != null)
{
OnFacebookQuickReply(facebookPayload.Message.QuickReply);
}
// TODO: Handle other events that you're interested in...
}
}
private void OnFacebookOptin(FacebookOptin optin)
{
// TODO: Your optin event handling logic here...
}
private void OnFacebookPostBack(FacebookPostback postBack)
{
// TODO: Your PostBack handling logic here...
}
private void OnFacebookQuickReply(FacebookQuickReply quickReply)
{
// TODO: Your quick reply event handling logic here...
}
}
}

Related

Facebook complains that the app is not secure

When I try to login via Facebook, it throws the following error;
facebook has detected app isn't using a secure connection to transfer information
But I'm pretty sure that it is secured via 'Let's encrypt'.
I have checked Web and Client OAuth login boxes and set the corresponding redirect uris on developer facebook.
On maui side, I am calling the following code piece and AppSettings.BaseUrl is correct, I have checked that;
WebAuthenticatorResult authResult = await WebAuthenticator.Default.AuthenticateAsync(
new WebAuthenticatorOptions()
{
Url = new Uri($"{AppSettings.BaseUrl}account/authentication/{scheme}"),
CallbackUrl = new Uri("tibi://"),
PrefersEphemeralWebBrowserSession = true
});
And on backend side, the following api is requested;
[HttpGet("authentication/{scheme}")]
[AllowAnonymous]
public async Task Get([FromRoute] string scheme)
{
var auth = await Request.HttpContext.AuthenticateAsync(scheme);
if (!auth.Succeeded
|| auth?.Principal == null
|| !auth.Principal.Identities.Any(id => id.IsAuthenticated)
|| string.IsNullOrEmpty(auth.Properties.GetTokenValue("access_token")))
{
// Not authenticated, challenge
await Request.HttpContext.ChallengeAsync(scheme);
}
else
{
var claims = auth.Principal.Identities.FirstOrDefault()?.Claims;
var email = string.Empty;
email = claims?.FirstOrDefault(c => c.Type == System.Security.Claims.ClaimTypes.Email)?.Value;
// Get parameters to send back to the callback
var qs = new Dictionary<string, string>
{
{ "access_token", auth.Properties.GetTokenValue("access_token") },
{ "refresh_token", auth.Properties.GetTokenValue("refresh_token") ?? string.Empty },
{ "expires_in", (auth.Properties.ExpiresUtc?.ToUnixTimeSeconds() ?? -1).ToString() },
{ "email", email }
};
// Build the result url
var url = callbackScheme + "://#" + string.Join(
"&",
qs.Where(kvp => !string.IsNullOrEmpty(kvp.Value) && kvp.Value != "-1")
.Select(kvp => $"{WebUtility.UrlEncode(kvp.Key)}={WebUtility.UrlEncode(kvp.Value)}"));
// Redirect to final url
Request.Host = HostString.FromUriComponent(AppSettingsProvider.GatewayUrl);
Request.HttpContext.Response.Redirect(url);
}
}
Challenge is invoked successfully and redirects me to the Facebook login but when I sign in, I get the error above.

Payrexx integration in flutter webview

As described here https://developers.payrexx.com/docs/mobile-apps-javascript
I would like to interact with the javascript events of an iframe I want to create in the webview_flutter plugin.
The following example code is given in the official documentation
window.addEventListener('message', handleMessage(this), false);
and
function handleMessage(e) {
if (typeof e.data === 'string') {
try {
var data = JSON.parse(e.data);
} catch (e) {}
if (data && data.payrexx) {
jQuery.each(data.payrexx, function(name, value) {
switch (name) {
case 'transaction':
if (typeof value === 'object') {
if (value.status === 'confirmed') {
//handling success
} else {
//handling failure
}
}
break;
}
});
}
}
}
Do you know a way to do this? I have implemented an iframe in which there is the address of my gateway, but it is impossible to check if the payment has taken place.
Sounds good. The Payrexx iFrame sends a post message with the transaction details (including transaction status) to the parent window (e.g. your Flutter webview) after the payment (on the Payrexx result page). So you only need to add an event listener for type "message" in your webview as in the example:
window.addEventListener('message', handleMessage(this), false);
Please make sure you also send a post message into the Payrexx iFrame as soon as the iFrame is loaded (onload event):
let iFrame = document.getElementById('IFRAME-ID');
if (iFrame) {
iFrame.contentWindow.postMessage(
JSON.stringify({
origin: window.location.origin,
}),
iFrame.src,
);
}
Now you are ready to receive and handle the messages from the Payrexx iFrame:
private handleMessage(e): void {
try {
let message = JSON.parse(e.data);
if (typeof message !== 'object' ||
!message.payrexx ||
!message.payrexx.transaction) {
return;
}
let transaction = message.payrexx.transaction;
console.log(transaction);
} catch (e) {
}
};
Last but not least:
Make sure you also check the transaction status via transaction webhook (server-to-server notification):
https://docs.payrexx.com/developer/guides/webhook

In AspBoilerPlate - Unauthorized error when calling from Angular when Windows Authentication is On

Have already raised this before and thought I have addressed it as per what suggested on THIS and THIS but seems not!
I am using ABP template (Angular and ASP .NET CORE Application) on Full .Net Framework. I simply want to use Windows Authentication to Authenticate user.
I added [Authorize] to the Authenticate in the TokenAuthController and have finally got the HttpContext.User.Identity.Name populated but only when I call the Authenticate from the Swagger (http://localhost:21021/swagger). But I am getting Unauthorized error when calling the method from Angular (login.service.ts):
POST http://localhost:21021/api/TokenAuth/Authenticate 401 (Unauthorized)
Here is the steps I have taken so far:
Changed launchSetting.json:
"iisSettings": {
"windowsAuthentication": true,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:21021/",
"sslPort": 0
}
},
Added ExternalAuthenticationSource:
public class WindowsAuthSource : DefaultExternalAuthenticationSource<Tenant, User>, ITransientDependency
{
public override string Name
{
get { return "Windows Authentication"; }
}
public override Task<bool> TryAuthenticateAsync(string userNameOrEmailAddress, string plainPassword, Tenant tenant)
{
return Task.FromResult(true);
}
}
Added it to CoreModule:
Configuration.Modules.Zero().UserManagement.ExternalAuthenticationSources.Add<WindowsAuthSource>();
4.Adjust AuthConfigurer:
services.AddAuthentication(opt => {
opt.DefaultScheme = IISDefaults.AuthenticationScheme;
opt.DefaultAuthenticateScheme = IISDefaults.AuthenticationScheme;
opt.DefaultChallengeScheme = IISDefaults.AuthenticationScheme;
});
Adjust StartUp.cs:
services.Configure<IISOptions>(iis =>
{
iis.AuthenticationDisplayName = "WINDOWS";
iis.AutomaticAuthentication = true;
});
Changed Authenticate method in the TokenAuthController:
public async Task<AuthenticateResultModel> Authenticate([FromBody]
AuthenticateModel model)
{
//var username = WindowsIdentity.GetCurrent().Name.Split('\\').Last();
var username = HttpContext.User.Identity.Name;
model.UserNameOrEmailAddress = username;
var loginResult = await GetLoginResultAsync(
model.UserNameOrEmailAddress,
model.Password,
null
);
var accessToken = CreateAccessToken(CreateJwtClaims(loginResult.Identity));
return new AuthenticateResultModel
{
AccessToken = accessToken,
EncryptedAccessToken = GetEncrpyedAccessToken(accessToken),
ExpireInSeconds = (int)_configuration.Expiration.TotalSeconds,
UserId = loginResult.User.Id
};
}
Sending dummy username and password from login.service.ts:
authenticate(finallyCallback?: () => void): void {
finallyCallback = finallyCallback || (() => { });
//Dummy data
this.authenticateModel.userNameOrEmailAddress = "DummyUsername";
this.authenticateModel.password = "DummyPassword";
this._tokenAuthService
.authenticate(this.authenticateModel)
.finally(finallyCallback)
.subscribe((result: AuthenticateResultModel) => {
this.processAuthenticateResult(result);
});
}

Facebook Share in ios.Xamarin

I'm trying to implement the Facebook share functionality in my little xamarin iOS app. I've already downloaded the latest version of Facebook iOS SDK from nuget, but I don't know how to use it. Is there anyone who has done that already , so he can send me some normal info on that ?
Much appreciated before hands :)
I have implemented share for twitter and fb .
iOS version
you can share using native social services from ios and if not available use
OAuth2Authenticator to get access token then post using FB graph
public void ShareViaSocial(string serviceType, string urlToShare)
{
socialKind = serviceType == "Twitter" ? SLServiceKind.Twitter : SLServiceKind.Facebook;
if (SLComposeViewController.IsAvailable(socialKind))
{
_socialComposer = serviceType == "Twitter" ? SLComposeViewController.FromService(SLServiceType.Twitter) : SLComposeViewController.FromService(SLServiceType.Facebook);
_socialComposer.AddUrl(new Uri(urlToShare));
viewController.PresentViewController(_socialComposer, true, () =>
{
_socialComposer.CompletionHandler += (result) =>
{
Device.BeginInvokeOnMainThread(() =>
{
viewController.DismissViewController(true, null);
if (result == SLComposeViewControllerResult.Done)
{ OnShare(this, ShareStatus.Successful); }
else
{ OnShare(this, ShareStatus.NotSuccessful); }
});
};
});
}
//If user doest have fb app and no credential for social services we use fb graph
else if (socialKind == SLServiceKind.Facebook)
{
var auth = new OAuth2Authenticator(
clientId: SharedConstants.FacebookLiveClientId,
scope: SharedConstants.FacebookScopes,
authorizeUrl: new Uri(SharedConstants.FacebookAuthorizeUrl),
redirectUrl: new Uri(SharedConstants.FacebookRedirectUrl));
viewController.PresentViewController((UIViewController)auth.GetUI(), true, null);
auth.AllowCancel = true;
auth.Completed += (s, e) =>
{
//hide the webpage after completed login
viewController.DismissViewController(true, null);
// We presented the UI, so it's up to us to dimiss it on iOS.
if (e.IsAuthenticated)
{
Account fbAccount = e.Account;
Dictionary<string, string> dictionaryParameters = new Dictionary<string, string>() { { "link", urlToShare } };
var requestUrl = new Uri("https://graph.facebook.com/me/feed");
var request = new OAuth2Request(SharedConstants.requestMethodPOST, requestUrl, dictionaryParameters, fbAccount);
request.GetResponseAsync().ContinueWith(this.requestResult);
}
else { OnShare(this, ShareStatus.NotSuccessful); }
};
auth.Error += Auth_Error;
}
//If user doest have twitter app and no credential for social services we use xanarub auth for token and call twitter api for sending tweets
else
{
var auth = new OAuth1Authenticator(
SharedConstants.TwitterConsumerKey,
SharedConstants.TwitterConsumerSecret,
new Uri(SharedConstants.TwitterRequestUrl),
new Uri(SharedConstants.TwitterAuth),
new Uri(SharedConstants.TwitterAccessToken),
new Uri(SharedConstants.TwitterCallBackUrl));
auth.AllowCancel = true;
// auth.ShowUIErrors = false;
// If authorization succeeds or is canceled, .Completed will be fired.
auth.Completed += (s, e) =>
{
// We presented the UI, so it's up to us to dismiss it.
viewController.DismissViewController(true, null);
if (e.IsAuthenticated)
{
Account twitterAccount = e.Account;
Dictionary<string, string> dictionaryParameters = new Dictionary<string, string>() { { "status", urlToShare } };
var request = new OAuth1Request(SharedConstants.requestMethodPOST, new Uri("https://api.twitter.com/1.1/statuses/update.json"), dictionaryParameters, twitterAccount);
//for testing var request = new OAuth1Request("GET",new Uri("https://api.twitter.com/1.1/account/verify_credentials.json "),null, twitterAccount);
request.GetResponseAsync().ContinueWith(this.requestResult);
}
else { OnShare(this, ShareStatus.NotSuccessful); }
};
auth.Error += Auth_Error;
//auth.IsUsingNativeUI = true;
viewController.PresentViewController((UIViewController)auth.GetUI(), true, null);
}
}

How to solve requirement of "On/Off publishing" for 'read article' action

Now facebook require to have these options when you want to use bulit-in actions like READ.
"A clear way for users to control the publishing of their actions back to Open Graph. In the example News app below, a clear "On/Off" switch is provided that applies to all future Read actions within the app. When a user toggles the switch to "Off", this prevents the app from publishing Read actions from that point on. Toggling the switch back to "On" reenables the publishing. "
"A clear way for users to remove articles that were just shared through your app. In the example below, a user can easily remove a recent article that was shared as a result of a Read action that was published by the app."
sample pictures are here: https://developers.facebook.com/docs/opengraph/actions/builtin/#read under title "Publish Awareness"
How to create easy button to stop sharing and to remove shared articles? The best one will
I was searching for solution for one week without results...
Your question has two parts to it, one is storing the user preference and the other is share/unshare option to be given on the article page. The first part of the question is simple and can be achieved by simply having a small database table with minimum of two columns (for simplicity sake), userid (a varchar or long int) and share (a bool or a bit). Give an option to the user to toggle this share bit by giving an on/off button which changes the share value from 1 to 0 (true to false) and vice versa for a specified userid. Now before taking a social action (like read), check for this share bit in database for the logged facebook user and perform actions accordingly.
Now to answer the second part of your question, you may use the Facebook JavaScript SDK to make api calls to news.read action and provide a callback to store the returned id of the shared article. Use the same id to then provide option of unshare for the user. Assuming that you have jQuery included in your page, something like below should work (I wrote and tested it in a jiffy, should work in most cases)
Include the below script in your page
//set this at page load or from authResponse object
var fbDataObj = {
user_id : <some user id>,
access_token: <some access token>
};
//set currentPostFBUrl to your article url
var currentPostFBUrl = "http://www.yourpageurl.com";
var publishPost = function (articleLink, callback) {
FB.api(
'/' + fbDataObj.user_id + '/news.reads',
'post',
{ article: articleLink,
access_token: fbDataObj.access_token },
function(response) {
if (!response || response.error) {
//alert('Error occured');
if (typeof callback === 'function') {
callback({text: "error", id: ""});
}
} else {
//alert('Share was successful! Action ID: ' + response.id);
if (typeof callback === 'function') {
callback({text: "success", id: response.id});
}
}
});
};
var deletePost = function (postId, callback) {
FB.api(
postId,
'delete',
{ access_token: fbDataObj.access_token },
function(response) {
if (!response || response.error) {
//alert('Error occured');
if (typeof callback === 'function') {
callback({text: "error", id: ""});
}
} else {
//alert('Unshare was successful!');
if (typeof callback === 'function') {
callback({text: "success", id: ""});
}
}
});
};
var publishOrDeleteArticle = function (btn_obj) {
var btn_name = btn_obj.attr("name");
if (isNaN(parseInt(btn_name, 10))) {
publishPost(currentPostFBUrl, function(status){
if (status.text === "success") {
btn_obj.attr("name", status.id);
btn_obj.text("Unshare");
}
});
}
else {
deletePost(btn_name, function(status){
if (status.text === "success") {
btn_obj.attr("name", "share");
btn_obj.text("Share")
}
});
}
};
Now in your page do something like this
Edit:
(Also set currentPostFBUrl to your article url like below)
var currentPostFBUrl = "http://www.yourpageurl.com";
//within script tag
$(document).ready(function(){
$("#btn_share").click(function(e){
e.preventDefault();
publishOrDeleteArticle($(this));
});
});
//your actual share/unshare button
<a id="btn_share" name="share" href="#">Share</a>
On the final note I have written one wrapper js class for one of the recent facebook application that I was working on. With this you can read/unread an article with just one line of code. There are other WordPress wrappers inside as well but that can be left alone in this case, at the simplest you may use the object as below after providing the initial configuration and init (check the attached code below). There might be a few bugs in the code and the methods might not be complete and extensive because I'm still working on it but for the time being it should solve the purpose. The below wrapper methods can also be used in the above mentioned code for clarity. Feel free to use/modify the code, give feedback and comments and also reply back in case any issues are identified.
/*!
* --------------------------------------------------------------------------------------
* Utility Library for Facebook Application
* Contains wrapper methods for WordPress JSON API (named WPJsonApi)
* and for Facebook Javascript SDK (named FBJsWrapper)
* Dependency : jQuery, Facebook JavaScript SDK
* Author : Emad Alam
* Date: Thu Jun 07 21:11:03 2012 +0530
* --------------------------------------------------------------------------------------
* Notes:
* Including this script adds a global object called FBAppUtil to the window object.
* You may initialize the object with init method, providing init time configurations.
* Once FBAppUtil object is initted, you get two sub-ojects, WPJsonApi & FBJsWrapper.
* These two objects can be initted individually or while initing the main FBAppUtil.
* Both the objects have a buffer that stores the last fetched data and responses.
* Methods are provided to access these buffers individually.
* Once the sub-objects are configured, their methods can be called from their references.
*
* Example Usage:
* //main object init. config can be given at this time
* FBAppUtil.init();
*
* var wpJsonApiConfig = {
* apiUrl : "http://www.example.com/wordpress/api",
* permalinkEnabled : true,
* crossDomain : true
* };
* FBAppUtil.WPJsonApi.init(wpJsonApiConfig);
*
* // now you may use all the methods of FBAppUtil.WPJsonApi
* FBAppUtil.WPJsonApi.getRecentPosts(someParams, someCallback);
* FBAppUtil.WPJsonApi.getPost(someIdOrSlug, someCallback);
* var data = FBAppUtil.WPJsonApi.lastFetched();
* var response = FBAppUtil.WPJsonApi.lastResponse();
*
* // other facebook related scripts and sdks initializations
* // at this point you should be having the FB object initialized
* // you may pass the authResponse object to init the FBJsWrapper or
* // populate one of your own to pass it to the FBJsWrapper.init(authResponse)
*
* var fbJsWrapperConfig = {
* userID : <logged in userId>,
* accessToken : <user's accessToken>,
* signedRequest : <from authResponse object>,
* expiresIn : <from authResponse object>
* };
* FBAppUtil.FBJsWrapper.init(fbJsWrapperConfig);
*
* // now you may use all the methods of FBAppUtil.FBJsWrapper
* FBAppUtil.FBJsWrapper.sendAppRequest("some message", someCallback);
* FBAppUtil.FBJsWrapper.share(someArticleUrl, someCallback);
* FBAppUtil.FBJsWrapper.unshare(someId, someCallback);
* var fbdata = FBAppUtil.FBJsWrapper.dataFromLastCall();
* var fbresponse = FBAppUtil.FBJsWrapper.responseFromLastCall();
*/
(function (window) {
/** Local helper Buffer Class - Start **/
var LocalBuffer = function (size) {
//enforce 'new' - object creation pattern
if (!(this instanceof LocalBuffer)) {
return new LocalBuffer(size);
}
//private variables
var _buffer = {
data : [], //data fetched from the last successfull call
response : [] //response from the last call
},
_size = (function (size){
var n = parseInt(size || 10, 10);
return isNaN(n) ? 10 : n;
}(size)); //default buffer size
var _pushToBuffer = function (name, data) {
if (typeof _buffer[name][_size-1] !== 'undefined') {
_buffer[name].shift(); //remove the first element in case the buffer is full
}
_buffer[name].push(data);
};
var _readFromBuffer = function (name) {
var len = _buffer[name].length;
return len === 0 ? {} : _buffer[name][len-1]; //read the last inserted without popping
};
var _getDataFromBuffer = function () {
return _readFromBuffer("data");
};
var _getResponseFromBuffer = function () {
return _readFromBuffer("response");
};
//expose methods
this.pushToBuffer = _pushToBuffer,
this.readFromBuffer = _readFromBuffer,
this.getDataFromBuffer = _getDataFromBuffer,
this.getResponseFromBuffer = _getResponseFromBuffer
};
/** Local helper Buffer Class - End **/
/** WordPress JSON API Plugin wrapper - Start **/
var WPJsonApi;
(function () {
var instance;
WPJsonApi = function (config) {
if (!(this instanceof WPJsonApi)) {
return new WPJsonApi(config);
}
if (instance) {
return instance;
}
instance = this;
//config variables
var apiUrl, //complete url for the api
cross_domain, //jsonp cross domain calls
permalink_enabled, //whether permalink enabled
templates, //TODO: templating system
buffer_size; //size of the buffer
//private variables
var _buffer; //the LocalBuffer object
//form the final api url string for the json call
var _getControllerUrl = function (controller_name) {
var url = apiUrl; //base url
if (!permalink_enabled) {
url += "/?json=" + controller_name;
if (cross_domain) {
url += "&callback=?";
}
} else {
url += "/" + controller_name;
if (cross_domain) {
url += "/?callback=?";
}
}
return url;
};
//fetch posts using the jQuery getJSON
//push data and response to buffer
//on successfull fetch, return array of post objects to the callback
var _getRecentPosts = function (paramObj, callback) {
var url = _getControllerUrl("get_recent_posts"); //base url for the specified controller
if (typeof paramObj === 'function') {
callback = paramObj; //no parameters provided only callback
paramObj = {};
}
paramObj = paramObj || {};
$.getJSON(url, paramObj, function(data) {
if (data.status === "ok") {
_buffer.pushToBuffer("response",
{
status : "ok",
success : "Successfully fetched the post for the specified id/slug."
}
);
_buffer.pushToBuffer("data", data);
if (typeof callback === 'function') {
callback(data.posts);
}
} else if (data.status === "error") {
_buffer.pushToBuffer("response",
{
status: "error",
error : data.error
}
);
} else {
_buffer.pushToBuffer("response",
{
status: "error",
error : "Unknown error!"
}
);
}
}
);
};
//fetch post by it's id or slug using the jQuery getJSON
//push data and response to buffer
//on successfull fetch, return the post object to the callback
var _getPost = function (paramObj, callback) {
var url = _getControllerUrl("get_post"), //base url for the specified controller
id = parseInt(paramObj, 10); //assume the parameter to be id
paramObj = paramObj || {};
if (typeof paramObj !== 'object') {
if (typeof paramObj === 'number' || !isNaN(id)) {
paramObj = {id : id};
} else if (typeof paramObj === 'string') {
paramObj = {slug : paramObj};
}
}
if (isNaN(parseInt(paramObj.id, 10)) && !paramObj.slug) {
throw {
status: "error",
error : "Provide a valid id or slug to get a post."
};
}
//TODO: Avoid server hit by searching and returning the post
// from the local buffer for the specified id/slug
$.getJSON(url, paramObj, function(data) {
if (data.status === "ok") {
_buffer.pushToBuffer("response",
{
status : "ok",
success : "Successfully fetched the post for the specified id/slug."
}
);
_buffer.pushToBuffer("data", data);
if (typeof callback === 'function') {
callback(data.post);
}
} else if (data.status === "error") {
_buffer.pushToBuffer("response",
{
status: "error",
error : data.error
}
);
} else {
_buffer.pushToBuffer("response",
{
status: "error",
error : "Unknown error!"
}
);
}
}
);
};
//initialize the object and add methods to it
var _init = function (config) {
if (typeof config === 'undefined') {
throw {
status: "error",
error : "Provide a valid configuration object to initialize WPJsonApi."
};
}
apiUrl = config.apiUrl || "/api", //assume base url relative to current page
cross_domain = config.crossDomain || false, //jsonp cross domain calls
permalink_enabled = config.permalinkEnabled || true, //assume permalink enabled
templates = config.templates || {}, //TODO: templating mechanisms
buffer_size = config.bufferSize || 10, //assume buffer size to be 10
_buffer = new LocalBuffer(buffer_size); //new buffer object
//expose the methods and variables
this.getRecentPosts = _getRecentPosts; //method for fetching recent posts
this.getPost = _getPost; //method to fetch the post by id or slug
this.lastFetched = _buffer.getDataFromBuffer; //last fetched data from the buffer
this.lastResponse = _buffer.getResponseFromBuffer; //response from the last roundtrip to server
};
//init the object if config is provided while creating
if (typeof config !== 'undefined') {
_init(config);
}
//expose init
this.init = _init;
};
}());
/** WordPress JSON API Plugin wrapper - End **/
/** FB JavaScript SDK wrapper - Start **/
var FBJsWrapper;
(function () {
var instance;
FBJsWrapper = function (config) {
if (!(this instanceof FBJsWrapper)) {
return new FBJsWrapper(config);
}
if (instance) {
return instance;
}
instance = this;
//config variables
var access_token, //user access token
expires_in, //time to expire
signed_request, //the signed request object
user_id; //user id of the current connected user
//private variables
var _buffer, //the LocalBuffer object
_token_valid = true; //assume the access token to be valid
var _isTokenValid = function () {
//TODO: Implement the method to check for invalid access tokens or
// invalid calls to FB APIs
return _token_valid;
};
var _read = function (article, callback) {
//TODO: Avoid repeated code, make a generic function
var paramObj = {}; //start with an empty parameter
paramObj.article = article; //add article to the parameter object
//if token is invalid, no further calls are possible, so return
if (!_isTokenValid()) {
//TODO: Provide a better way of handling this
throw {
status: "error",
error : "Provide a valid configuration object to initialize FBJsWrapper."
};
}
if (!(!access_token || 0 === access_token.length)) {
paramObj.access_token = access_token; //access token not empty, add it to the parameter object
}
//TODO: Make a generic function to handle this call
FB.api(
'/' + user_id + '/news.reads',
'post',
paramObj,
function(response) {
var i,
message, // response error message
exists = false, //assume the words don't exist in the message
probable_words = [ "session has expired",
"session has been invalidated",
"session is invalid",
"has not authorized" ]; //list of words that may denote an invalid token
//no response, return
if (!response) {
_buffer.pushToBuffer("response",
{
status : "error",
error : "No response returned by the server!"
}
);
return;
}
//some error
if (response.error) {
message = response.error.message.toLowerCase(); //case insensetive match
for (i in probable_words) {
if (message.indexOf(probable_words[i]) > -1) {
exists = true;
break;
}
}
if (exists) {
_token_valid = false; //denotes invalid token
}
_buffer.pushToBuffer("response",
{
status : "error",
error : exists ? "Invalid access token!" : response.error.message
}
);
} else {
_buffer.pushToBuffer("response",
{
status : "ok",
success : "Successfully read the specified article."
}
);
_buffer.pushToBuffer("data", response);
if (typeof callback === 'function') {
callback(response.id);
}
}
});
};
var _unread = function (articleId, callback) {
//TODO: Avoid repeated code, make a generic function
var paramObj = {}; //start with an empty parameter
//if token is invalid, no further calls are possible, so return
if (!_isTokenValid()) {
//TODO: Provide a better way of handling this
throw {
status: "error",
error : "Provide a valid configuration object to initialize FBJsWrapper."
};
}
if (!(!access_token || 0 === access_token.length)) {
paramObj.access_token = access_token; //access token not empty, add it to the parameter object
}
//TODO: Make a generic function to handle this call
FB.api(
articleId,
'delete',
paramObj,
function(response) {
var i,
message, // response error message
exists = false, //assume the words don't exist in the message
probable_words = [ "session has expired",
"session has been invalidated",
"session is invalid",
"has not authorized" ]; //list of words that may denote an invalid token
//no response, return
if (!response) {
_buffer.pushToBuffer("response",
{
status : "error",
error : "No response returned by the server!"
}
);
return;
}
//some error
if (response.error) {
message = response.error.message.toLowerCase();//case insensetive match
for (i in probable_words) {
if (message.indexOf(probable_words[i]) > -1) {
exists = true;
break;
}
}
if (exists) {
_token_valid = false; //denotes invalid token
}
_buffer.pushToBuffer("response",
{
status : "error",
error : exists ? "Invalid access token!" : response.error.message
}
);
} else {
_buffer.pushToBuffer("response",
{
status : "ok",
success : "Successfully unread the specified article."
}
);
_buffer.pushToBuffer("data", response);
if (typeof callback === 'function') {
callback();
}
}
});
};
var _sendAppRequest = function (message, callback) {
var paramObj = {}; //start with an empty parameter
if (typeof message === 'function') { //no message only callback provided
callback = message;
message = 'Invite friends to this app.';
}
paramObj.method = 'apprequests';
paramObj.message = message.toString();
if (!(!access_token || 0 === access_token.length)) {
paramObj.access_token = access_token; //access token not empty, add it to the parameter object
paramObj.display = 'iframe'; //access token provided, iframe can be used
} else {
paramObj.display = 'popup'; //no access token present, use popup dialog
}
FB.ui(paramObj, function (request, to) {
//TODO: Handle the error conditions
_buffer.pushToBuffer("response",
{
status : "ok",
success : "Successfully sent the app request."
}
);
_buffer.pushToBuffer("data", { request: request, to: to });
if (typeof callback === 'function') {
callback(request, to);
}
});
};
var _init = function (config) {
if (typeof config === 'undefined') {
throw {
status: "error",
error : "Provide a valid configuration object to initialize FBJsWrapper."
};
}
access_token = config.accessToken || "", //assume a blank access token, will try to call FB.api without it
expires_in = config.expiresIn || 0, //jsonp cross domain calls
signed_request = config.signedRequest || {}, //signed request parameter
user_id = config.userID || 'me', //assume 'me' (for a user it's user_id but for pages and apps it might be something else)
buffer_size = config.bufferSize || 10, //default buffer size
_buffer = new LocalBuffer(buffer_size); //local buffer object
//expose the methods and variables
this.sendAppRequest = _sendAppRequest; //method for sending the app request from a dialog
this.share = _read; //method to read an article, news.read
this.unshare = _unread //method to unread a previously read article
this.dataFromLastCall = _buffer.getDataFromBuffer; //last fetched data from the buffer
this.responseFromLastCall = _buffer.getResponseFromBuffer; //response from the last roundtrip to server
};
//init the object if config is provided while creating
if (typeof config !== 'undefined') {
_init(config);
}
//expose init
this.init = _init;
};
}());
/** FB JavaScript SDK wrapper - End **/
/** The main Utility Class - Start **/
var FBAppUtil;
(function () {
var instance;
FBAppUtil = function () {
if (!(this instanceof FBAppUtil)) {
return new FBAppUtil();
}
if (instance) {
return instance;
}
instance = this;
var _init = function (config) {
if (typeof config !== 'undefined'){
if (typeof config.WPJsonApi !== 'undefined') {
this.WPJsonApi = new WPJsonApi(config.WPJsonApi); //WPJsonApi configuration provided while init
} else {
this.WPJsonApi = new WPJsonApi();
}
if (typeof config.FBJsWrapper !== 'undefined') {
this.FBJsWrapper = new FBJsWrapper(config.FBJsWrapper); //FBJsWrapper configuration provided while init
} else {
this.FBJsWrapper = new FBJsWrapper();
}
} else {
this.WPJsonApi = new WPJsonApi();
this.FBJsWrapper = new FBJsWrapper();
}
};
//expose the methods and variables
this.init = _init;
};
})();
/** The main Utility Class - End **/
// Expose the Utility to the global object
window.FBAppUtil = new FBAppUtil();
})(window);
FBAppUtil.FBJsWrapper.share(someArticleUrl, someCallback);
FBAppUtil.FBJsWrapper.unshare(someId, someCallback);
With articles, facebook recommend that you place the trigger on a 'readmore' or some other kind of 'next page' button/link so that there is a very high probability that the user is actually reading the article.
To achieve this, you could either;
place a small form in/on every article, with a radio button/ckeckbox
asking do you want to publish this (Yes/No) -- OR
add a section to your user preferences on your site with the same
type of form as in 1. Then you could take this a bit further, giving
them the option to set a preference for each section, category or
page of your site.
Either way, however you decide to invoke the action (readmore or next page etc.), that needs to submit the form, check whether the answer is yes/no (publish or not) then publish the action accordingly.
Using session variables might be an option too! It would be pretty neat to offer users the ability to publish/not publish actions for their current session. This could be handled in the same form being presented to the user at the start of each session and even give them a 3rd option, 'ask me everytime'.
As far as deleting an existing action is concerned, this can be done by getting the instance of the action and running the delete command in a similar way to that of creation. As I said, this depends on how you're triggering - CURL, js api etc... Check the FB dev docs for the method you're using.
Hope this helps!
Gez
On/Off publishing is not related to Facebook Graph API, you have to implement this on your side. there should be a flag viz is_publish related to user table. If user give permission by click on the user On/Off button than you can publish the action, and one thing more action can be published only if user stay on article page for at-least 10 seconds and for this you can do
setTimeout('readArticle()', 10000);
Hope this helps!