BlackBerry - Facebook extended permissions - rest

I've just found a great sample of Facebook Connect on Blackberry by Eki Y. Baskoro,
The following is a short HOWTO on using Facebook Connect on Blackberry. I created a simple Facade encapsulating the Facebook REST API as well as added 'rough' MVC approach for screen navigation. I have tested on JDE 4.5 using 8320 simulator. This is still work in progress and all work is GPLed.
It works great for reading stuff.
NB Don't forget to get Facebook App Key and set it in TestBB class.
But now I want to post something on my wall. So I've add new method to FacebookFacade class using Stream.publish API:
/***
* Publishes message to the stream.
* #param message - message that will appear on the facebook stream
* #param targetId - The ID of the user, Page, group, or event where
* you are publishing the content.
*/
public void streamPublish(String message, String targetId)
{
Hashtable arguments = new Hashtable();
arguments.put("method", "stream.publish");
arguments.put("message", message);
arguments.put("target_id", targetId);
try {
JSONObject result = new JSONObject(
int new JSONTokener(sendRequest(arguments)));
int errorCode = result.getInt("error_code");
if (errorCode != 0) System.out.println("Error Code: "+errorCode);
} catch (Exception e) {
System.out.println(e);
}
}
/***
* Publishes message on current user wall.
* #param message - message that will appear on the facebook stream
*/
public void postOnTheWall(String message)
{
String targetId = String.valueOf(getLoggedInUserId());
streamPublish(message, targetId);
}
This will return Error code 200, "The user hasn't authorized the application to perform this action"
First I thought it's related with Facebook -> Application Settings -> Additional Permissions -> Publish recent activity (one line stories) to my wall but even checked, no difference...
Then I've found this post explains that issue related with extended permissions.
This in turn should be fixed by modifying url a little in LoginScreen class :
public LoginScreen(FacebookFacade facebookFacade) {
this.facebookFacade = facebookFacade;
StringBuffer data = new StringBuffer();
data.append("api_key=" + facebookFacade.getApplicationKey());
data.append("&connect_display=popup");
data.append("&v=1.0");
//revomed
//data.append("&next=http://www.facebook.com/connect/login_success.html");
//added
data.append("&next=http://www.facebook.com/connect/prompt_permissions.php?" +
"api_key="+facebookFacade.getApplicationKey()+"&display=popup&v=1.0"+
"&next=http://www.facebook.com/connect/login_success.html?"+
"xxRESULTTOKENxx&fbconnect=true" +
"&ext_perm=read_stream,publish_stream,offline_access");
data.append("&cancel_url=http://www.facebook.com/connect/login_failure.html");
data.append("&fbconnect=true");
data.append("&return_session=true");
(new FetchThread("http://m.facebook.com/login.php?"
+ data.toString())).start();
}
Unfortunately it's not working. Still Error Code 200 in return to stream.publish request...
Do you have any suggestions how to resolve this?
Thank you!

I have posted the updated API on my website (http://www.baskoro.web.id/facebook-connect-blackberry-HOWTO.html) and this should solve this issue. Please let me know otherwise.
Salam. Cheers!
Eki

Related

Callback function issues in FB.API for Unity

I am using Unity 5.5.2f1 pro and facebook's SDK v 7.9.4
I have a script which after login (managed in a previous scene) sends an API request to FB asking for friends, name and email and sends that info as a POST to a php website.
code:
[Serializable]
public struct FBData {
public string first_name;
public string email;
public string friends;
public string id;}
public class UserManagement : MonoBehaviour {
string urlSaveUserData="some php website";
public Text testTxt;
FBData parsedData;
// Use this for initialization
void Start () {
//Check if it's the first time the user is opening the app.
if (UserInfo.FIRST_TIME) {
//update text (only used for testing, should be removed in production.)
testTxt.text = "Your user id is: " + UserInfo.ID;
//Perform FB.API call to get User Data.
getUserData ();
//Save in SQL table. (won't get here if line in getUserData() is active)
StartCoroutine ("saveUserData");
} else {
//do something else.
}
note: Since this is meant for iOS I have to test it on a device so I'm using text in the screen to display info (think of it as a badly implemented print statement).
The problem: In my callback function for FB.API I write in the text Gameobject (aka testTxt) the parsed information from the response which is saved in the Custom UserInfo clss. It display's correctly but the code gets stuck there. It doesn't continue to the next function. HOWEVER, if I delete/comment that line and don't display anything in the text field. The codes does continue to the POST function BUT the information from the API call is not passed, i.e my custom class is empty (leading me to believe the callback function is not called at all).
public void getUserData(){
string query = "me?fields=first_name,email,friends";
FB.API (query, HttpMethod.GET, Apicallback, new Dictionary<string, string> ());
}
private void Apicallback(IGraphResult result){
//Parse Graph response into a specific class created for this result.
parsedData = JsonUtility.FromJson<FBData>(result.RawResult);
//Pass each field into UserInfo class.
UserInfo.EMAIL = parsedData.email;
UserInfo.FRIENDS = parsedData.friends;
UserInfo.NAME = parsedData.first_name;
UserInfo.FACEBOOKID = parsedData.id;
/*problem area, if I comment line below, then previous information is apparently not stored. If left as is then testTxt displays correct information but code gets stuck there. */
testTxt.text = "This is the info from USerInfoInside the APICallback: " + UserInfo.EMAIL + UserInfo.FRIENDS + UserInfo.FACEBOOKID;
}
The function below is to send info to php website, is there for illustrative purposes:
code:
public IEnumerator saveUserData() {
//get user info (this information is EMPTY if line in getUserData() is commented.
parsedData.id = UserInfo.FACEBOOKID;
parsedData.friends = UserInfo.FRIENDS;
parsedData.first_name = UserInfo.NAME;
parsedData.email = UserInfo.EMAIL;
//translate data into json
string JsonBodyData = JsonUtility.ToJson (parsedData);
//Custom web request (POST method doesnt seem to work very well, documentation example sends empty form)
var w = new UnityWebRequest(urlSaveUserData, "POST");
byte[] bodyRaw = new System.Text.UTF8Encoding().GetBytes(JsonBodyData);
w.uploadHandler = (UploadHandler) new UploadHandlerRaw(bodyRaw);
w.downloadHandler = (DownloadHandler) new DownloadHandlerBuffer();
w.SetRequestHeader("Content-Type", "application/json");
yield return w.Send();
//work with received data...}
Im stuck here any help is appreciated. Thanks!
Be sure to use EscapeURL when using strings directly for JSON or HTTP POST and GET methods. The lack of this treatment tends to screw things over, particulary in iOS platforms.
From what I can see, this code
string query = "me?fields=first_name,email,friends";
should instead be escaped as
string query = WWW.EscapeURL("me?fields=first_name,email,friends");
so characters like "?" won't get encoded as an URL symbol.
I'm assuming you don't need to do that for your illustrative example, because UnityWebRequest already escapes your POST request strings internally, but I can't fully confirm that.

Weird error message for denied fb app item submission

This is not for Facebook api authentication but for item permission management for the app.
I'm currently in the process of resubmitting my application for item approval. One of the items I previously submitted and was rejected was the read_friendlists item. Here's the weird part..
This is the error message that I got from the submission:
it looks like you haven't made any API requests to access content with the read_friendlists permission in the last 30 days
I don't understand what the message means. Im in the process of getting this permission.
You might have to explicitly request those Fields in the request parameter when asking Friend's data.
for example
private void makeMyFriendsRequest(final Session session) {
Request request = Request.newMyFriendsRequest(session, new Request.GraphUserListCallback() {
#Override
public void onCompleted(List<GraphUser> users, Response response) {
// If the response is successful
if (session == Session.getActiveSession()) {
for (GraphUser user : users) {
System.out.println(user.getFirstName() + " " + user.getLastName());
System.out.println(users.get(i).getId());
GraphLocation loc = users.get(i).getLocation();
System.out.println(loc != null ? loc.getCity() : "loc not available");
}
}
}
});
// here add fields explicitly
Bundle bundle = request.getParameters();
bundle.putString("fields", "id,first_name,last_name,birthday,location");
request.executeAsync();
I hope this will help.

Facebook4j library post photo issue

I am using the facebook4j library for integrating facebook api in java. However, I face issues when I try to post a photo with a place attribute.
Media media = new Media(new File(<image-path-here>));
PhotoUpdate update = new PhotoUpdate(media);
update.message("photo upload test");
update.setPlace("Bangalore");
facebook.postPhoto(update);
But I get the following exception:SEVERE: Servlet.service() for servlet [post] in context with path [/Sample] threw exception [message - An unknown error has occurred.FacebookException{statusCode=500, errorType='OAuthException', errorMessage='An unknown error has occurred.', errorCode=1, errorSubcode=-1, version=2.2.0}
Turns out that without the 'setplace' its works completely fine. I am not sure if I am doing the right way and searched the web to get some samples as well. But could not find one, can anyone please suggest what am I doing wrong here? I can post the photo on facebook without setting the location but I need to set location for image.
Thanks
With my solution, I upload the image to server and upload that file to facebook. you can see the below example.
/**
* NOTE: Post Photo To Wall Facebook
* #param String idToObject
* #param File filePhoto (This is real file from server)
* #return List<String>
*/
public String postToWallPhoto(String idToObject, UploadedFile uploadedFile) {
PhotoUpdate photoUpdate = null;
try {
Media media=new Media(uploadedFile.getFile());
photoUpdate = new PhotoUpdate(media);
photoUpdate.message(postItem.getGroupMessage());
String idPost = facebook.postPhoto(idToObject, photoUpdate);
} catch (FacebookException e) {
e.printStackTrace();
}
return idPost;
}
Can you try this.
PostUpdate post= update = new PostUpdate("#Minh Nguyen")
.picture(new URL("Img_url"));
facebook.postFeed(id,post);

Trouble posting comments with the LWUIT Facebook API

I'm working on a mobile project and decided to try out the LWUIT framework for development. So far it has been quite interesting although I wish the documentation was a bit better.
I run into a problem trying to post content to facebook using the recently released Facebook API. I'm able to authenticate without issues. However, when I try to post comments to the user's wall, I get a http 404 error.
Has anyone else had this sort of challenge. Below is an excerpt from my code;
protected boolean onShareScreenPost() {
// If the resource file changes the names of components this call will break notifying you that you should fix the code
//boolean val = super.onShareScreenPost();
Form shareForm = Display.getInstance().getCurrent();
final TextField shareField = findShareField(shareForm);
String postText = shareField.getText();
try {
makeFacebookAuthenticationRequest();
FaceBookAccess.getInstance().postOnWall(me.getId(), postText);
} catch (IOException ex) {
ex.printStackTrace();
//Include a dialog saying unable to post or connect to the internet or whatever
}
return true;
}
private void makeFacebookAuthenticationRequest() throws IOException {
FaceBookAccess.getInstance().authenticate("125527160846284", "http://a.b.c/", new String[]{ "publish_stream"});
me = new User();
FaceBookAccess.getInstance().getUser("me", me, new ActionListener() {
public void actionPerformed(ActionEvent evt) {
System.out.println("returned user");
}
});
}
Seeing this question 24 hours later makes me feel a bit silly.
The answer was quite simple and staring me in the face all along. I needed to wait for the Facebook API to return a User object before making additional calls to the API. Failure to do this resulted in a null reference for my user object and this was being used in the wall post request causing the facebook api to return a http 404.
Hope this helps someone...

How to mention user/page in post on wall using facebook api?

I've found format
#[id:1:anchor]
where id is user id or page id and anchor is text displayed.
This format is not documented on official facebook dev page, thus working.
What is the status of issue? Are there any alternatives?
There is no way to add tags in text this way via the API. There were loopholes which allowed this to work but they were closed shortly afterwards
i got the solution for this, here the using c# code:
protected void btnPost_Click(object sender, EventArgs e)
{
var client = new FacebookClient("YOUR FB TOKEN HERE");
var parameters = new Dictionary<string, object>
{
{"message", "YOUR STATUS HERE" },
{"tags" , "YOUR FRIENDS FB ID HERE"},
{"place" , "YOUR PLACE ID HERE"}
};
client.Post("me/feed", parameters);
lblPost.ForeColor = System.Drawing.Color.Red;
lblPost.Text = "Status Updated!";