Set prefilled text content in Facebook using SDK via SharePhotoContent - facebook

I need to post both text and images on a Facebook wall. For that, I can't use intent sharing because I want to share text too. So I implemented the Facebook SDK. But I still can't see my text content / caption on the wall. Here is my code.
private void publishImage() {
ArrayList<SharePhoto> sharePhotos = new ArrayList<>();
int imageFolderSize;
File imageFolder = new File(getActivity().getExternalCacheDir(), "attachments/images");
if( imageFolder.exists()) {
imageFolderSize = imageFolder.listFiles().length;
ArrayList<File> attachments = new ArrayList<>();
if (imageFolder.exists()) {
Collections.addAll(attachments, imageFolder.listFiles());
}
if (imageFolderSize > 0) {
for (int i = 0; i < attachments.size(); i++) {
File file = attachments.get(i);
if (file.exists()) {
if (file.getAbsolutePath().endsWith(".png")) {
try {
SharePhoto photo = new SharePhoto.Builder().setBitmap(BitmapFactory.decodeFile(file.getAbsolutePath()))
.setCaption("Welcome To Facebook Photo Sharing on steroids!")
.build();
sharePhotos.add(photo);
}catch (Exception e){
RMLog.debug("Execp: e"+e.toString());
}
}
}
}
}
}
SharePhotoContent scontent = new SharePhotoContent.Builder().addPhotos(sharePhotos ).build();
if(ShareDialog.canShow(SharePhotoContent.class))
{
shareDialog.show(scontent);
Toast.makeText(getActivity(), "Succsesfully posted on your wall",
Toast.LENGTH_LONG).show();
}
}

Related

Umbraco 8.17 How to get page id of a different page?

I needed to get to a different page if certain conditions were meet within my SurfaceController. If you have the page ID of the page you need to get to this is ease. The problem was I did not want to hard code a page id in the action method in the controller. I had a lot of problems trying to figure it out, so I thought I would provide my solution in case someone else is having the same issue.
int homePageID = 0;
try
{
homePageID = Umbraco.ContentAtXPath("//home").FirstOrDefault().Id;
}
catch(Exception e) { }
if(homePageID > 0)
{
return RedirectToUmbracoPage(homePageID);
}
else
{
return CurrentUmbracoPage();
}
Note that for this line "homePageID = Umbraco.ContentAtXPath("//home").FirstOrDefault().Id;" you use the page alias not the page name.
I hope this helps.
int homePageID = 0;
try
{
homePageID = Umbraco.ContentAtXPath("//home").FirstOrDefault().Id;
}
catch(Exception e) { }
if(homePageID > 0)
{
return RedirectToUmbracoPage(homePageID);
}
else
{
return CurrentUmbracoPage();
}

How to attach multiple videos and photos to a status post with Facebook graph API

I'm trying to publish a post with multiple attached videos and photos via the Facebook Graph API. I uploaded the videos and photos first using a batch request and get the ids successfully for the uploaded media. Then I pass the media ids along with the post data using attached_media. Things work fine for single or multiple photos. But not for a single video or multiple videos. I got this error: "Graph returned an error: (#10) Application does not have permission for this action" whenever ids of videos are included in attached_media.
I know as a user you have the ability to attach multiple videos and photos to a Facebook post. Does the Facebook Graph API just flat out not support this for multiple videos?
I am working with C# and Unity
Here is the function that uploads videos and then sends a post with attached result videos ids:
private IEnumerator UploadMediaWithStatus(string message, string[] mediaUrls)
{
FacebookPostStatusUpdatedEvent.Invoke("Submitting FB post ... ");
var curPage = m_UserPages[FacebookFeedsList.GetInstance().ActiveFeed] as IDictionary<string, object>;
var fbClient = new FacebookClient(curPage["access_token"].ToString());
List<string> mediaIDs = new List<string> ();
foreach (string mediaUrl in mediaUrls)
{
WWW _media = new WWW("file://" + mediaUrl);
yield return _media;
if (!System.String.IsNullOrEmpty(_media.error))
{
FacebookPostStatusUpdatedEvent.Invoke("FB post failed: error loading media " + mediaUrl);
//TruLogger.LogError("cant load Image : " + _image.error);
yield break;
}
byte[] mediaData = null;
FacebookMediaObject medObj = new FacebookMediaObject();
JsonObject p = new JsonObject();
mediaData = _media.bytes;
medObj.SetValue(mediaData);
medObj.FileName = "InteractiveConsole.mp4";
medObj.ContentType = "multipart/form-data";
p.Add("description", message);
p.Add("source", medObj);
uploadedImgID = "";
fbClient.PostCompleted += OnPostImageUploadComplete;
fbClient.PostAsync("/me/videos", p);
//wait for image upload status and hopefully it returned a media ID on successful image upload
while (uploadedImgID == "")
{
//if image updload failed because of rate limit failure we can just abort rest of this
if (rateLimitErrorOccurred)
{
rateLimitErrorOccurred = false;
yield break;
}
yield return true;
}
//if video uploaded succesfully
if (uploadedImgID != null)
{
mediaIDs.Add (uploadedImgID);
var response = (JsonObject)fbClient.Get("/" + uploadedImgID + "?fields=status,published");
TruLogger.LogError("Video Status Details: " + response.ToString());
string vidStatus = (response["status"] as IDictionary<string, object>)["video_status"] as string;
while( vidStatus != "ready")
{
yield return new WaitForSeconds(5.0f);
response = (JsonObject)fbClient.Get("/" + uploadedImgID + "?fields=status,published");
TruLogger.LogError("Video Status Details: " + response.ToString());
vidStatus = (response["status"] as IDictionary<string, object>)["video_status"] as string;
}
TruLogger.LogError("Video ready");
yield return new WaitForSeconds(5.0f);
}
}
if (mediaIDs.Count > 0)
{
curPage = m_UserPages[FacebookFeedsList.GetInstance().ActiveFeed] as IDictionary<string, object>;
fbClient = new FacebookClient(curPage["access_token"].ToString());
JsonObject p = new JsonObject();
p.Add("message", message);
for (int i = 0; i < mediaIDs.Count; i++)
{
p.Add ("attached_media["+ i + "]", "{\"media_fbid\":\"" + mediaIDs[i] + "\"}");
}
fbClient.PostCompleted += OnPostUploadComplete;
fbClient.PostAsync("/me/feed", p);
}
}
void OnPostImageUploadComplete(object sender, FacebookApiEventArgs args)
{
//if successful store resulting ID of image on Facebook
try
{
var json = args.GetResultData<JsonObject>();
uploadedImgID = json["id"].ToString();
//TruLogger.LogError(json.ToString());
}
catch (Exception e)
{
apiPostStatusMessage = "FB post failed: media upload error";
TruLogger.LogError (e.Message);
TruLogger.LogError (e.InnerException.ToString());
FacebookOAuthException oEx = (FacebookOAuthException)(e.InnerException);
if (oEx != null) {
TruLogger.LogError ("Error Type: " + oEx.ErrorType);
TruLogger.LogError ("Error Code: " + oEx.ErrorCode);
TruLogger.LogError ("Error Subcode: " + oEx.ErrorSubcode);
apiAbortErrorCode = oEx.ErrorCode;
if (apiAbortErrorCode == 32 || apiAbortErrorCode == 4)
{
rateLimitErrorOccurred = true;
apiPostAbortErrorMessage = "WHOOPS! Looks like you have exceeded the daily API rate quota for one or more of your feeds. You may have to wait between 1-24 hours until Facebook replenishes your balance for these feeds: \n\n" + e.InnerException.ToString ();
}
else
{
rateLimitErrorOccurred = false;
apiPostAbortErrorMessage = "WHOOPS! Looks like your session has expired or become invalid. Try Signing in again to revalidate your session: \n\n" + e.InnerException.ToString ();
}
}
else
{
rateLimitErrorOccurred = false;
apiAbortErrorCode = -1;
apiPostAbortErrorMessage = "WHOOPS! Looks like your session has expired or become invalid. Try Signing in again to revalidate your session: \n\n" + e.InnerException.ToString ();
}
uploadedImgID = null;
}
}
//generic call back for any post calls
void OnPostUploadComplete(object sender, FacebookApiEventArgs args)
{
try
{
var json = args.GetResultData();
TruLogger.LogError(json.ToString());
apiPostStatusMessage = "FB post successfully submitted";
//FacebookPostStatusUpdatedEvent.Invoke("FB post successfully submitted");
}
catch (Exception e)
{
apiPostStatusMessage = "FB post failed to submit";
//FacebookPostStatusUpdatedEvent.Invoke("FB post failed to submit");
TruLogger.LogError (e.Message);
TruLogger.LogError (e.InnerException.ToString());
FacebookOAuthException oEx = (FacebookOAuthException)(e.InnerException);
if (oEx != null) {
TruLogger.LogError ("Error Type: " + oEx.ErrorType);
TruLogger.LogError ("Error Code: " + oEx.ErrorCode);
TruLogger.LogError ("Error Subcode: " + oEx.ErrorSubcode);
apiAbortErrorCode = oEx.ErrorCode;
if (apiAbortErrorCode == 32 || apiAbortErrorCode == 4)
{
rateLimitErrorOccurred = true;
apiPostAbortErrorMessage = "WHOOPS! Looks like you have exceeded the daily API rate quota for one or more of your feeds. You may have to wait between 1-24 hours until Facebook replenishes your balance for these feeds: \n\n" + e.InnerException.ToString ();
}
else
{
rateLimitErrorOccurred = false;
apiPostAbortErrorMessage = "WHOOPS! Looks like your session has expired or become invalid. Try Signing in again to revalidate your session: \n\n" + e.InnerException.ToString ();
}
}
else
{
rateLimitErrorOccurred = false;
apiAbortErrorCode = -1;
apiPostAbortErrorMessage = "WHOOPS! Looks like your session has expired or become invalid. Try Signing in again to revalidate your session: \n\n" + e.InnerException.ToString ();
}
}
}
Facebook doesn't directly allow to upload multiple videos or photos with videos on the business page. However, it is possible on a personal page so as an alternate solution you can create a post on a personal page and share it on the business page.
Check this video for more information: https://www.youtube.com/watch?v=AoK_1S71q1o

Call facebook graphrequest multiple times

i'm developpig an app in which i need to call the fb graphrequest multiple times , but those calls needs to be one after the other, the first one will get me the user friends, and the other calls will be done in a loop (for each friend ) get the "likes" that that friend made, now with the code that i made, the first one gives me the friends but the second one (the loop instruction) won't work, i guess it has somehing to do with the async calls but i don't know how to make them serial calls, here's my code :
GraphRequest request = GraphRequest.newMyFriendsRequest(
AccessToken.getCurrentAccessToken(),
new GraphRequest.GraphJSONArrayCallback() {
#Override
public void onCompleted(JSONArray array, GraphResponse response) {
JSONObject jsonArray = response.getJSONObject();
try {
length = jsonArray.getJSONArray("data").length();
for (int i = 0; i < length; i++) {
AlertDialog a = new AlertDialog.Builder(liste_peronalisee.this).create();
a.setTitle("Erreur");
id[i] = jsonArray.getJSONArray("data").getJSONObject(i).getString("id");
a.setMessage(id[i]);
a.show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
request.executeAsync();
for(int i=0;i<id.length;i++)
request = GraphRequest.newGraphPathRequest(
AccessToken.getCurrentAccessToken(),
"/".concat(id[i]).concat("/likes"),
new GraphRequest.Callback() {
#Override
public void onCompleted(GraphResponse response) {
JSONObject jsonArray = response.getJSONObject();
try {
length = jsonArray.getJSONArray("data").length();
for (int i = 0; i < length; i++) {
AlertDialog a = new AlertDialog.Builder(liste_peronalisee.this).create();
a.setTitle("Erreur");
id[i] = jsonArray.getJSONArray("data").getJSONObject(i).getString("name");
a.setMessage(id[i]);
a.show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
request.executeAsync();
i need a quick answer, thanks in advance

Facebook SDK: SharePhotoContent Not Working

am developing an app with sharing text and multiple images in a single post using facebook sdk. I used the following code, but nothing happens in my fb wall post. Whats wrong in the code please anybody help. thanks in advance.
private void publishImage() {
ArrayList<SharePhoto> sharePhotos = new ArrayList<>();
int imageFolderSize;
File imageFolder = new File(getActivity().getExternalCacheDir(), "attachments/images");
if( imageFolder.exists()) {
imageFolderSize = imageFolder.listFiles().length;
ArrayList<File> attachments = new ArrayList<>();
if (imageFolder.exists()) {
Collections.addAll(attachments, imageFolder.listFiles());
}
if (imageFolderSize > 0) {
for (int i = 0; i < attachments.size(); i++) {
File file = attachments.get(i);
if (file.exists()) {
if (file.getAbsolutePath().endsWith(".png")) {
try {
SharePhoto photo = new SharePhoto.Builder().setBitmap(BitmapFactory.decodeFile(file.getAbsolutePath()))
.setCaption("Welcome To Facebook Photo Sharing on steroids!")
.build();
sharePhotos.add(photo);
}catch (Exception e){
RMLog.debug("Execp: e"+e.toString());
}
}
}
}
}
}
SharePhotoContent scontent = new SharePhotoContent.Builder().addPhotos(sharePhotos
).build();
if(ShareDialog.canShow(SharePhotoContent.class))
{ ShareApi.share(scontent, null);
Toast.makeText(getActivity(), "Succsesfully posted on your wall",
Toast.LENGTH_LONG).show();
}
}

apache HttpClient to access facebook

Any examples, tips, guidance for the following scenario?
I have used Apache HttpClient to simulate the functionality of browser to access facebook through java application. to do that first i have to provide user credentials. i have used examples provided in the following web site.
http://svn.apache.org/viewvc/httpcomponents/oac.hc3x/trunk/src/examples/
But non of these methods works for facebook, following is the test code i have written for this purpose. i have not provided the all the methods written, only the method used to login to the facebook account is given here. relay appreciate any help
private static int connectAndLogin(String email, String pass){
logger.trace("Facebook: =========connectAndLogin begin===========");
String httpResponseBody = getMethod("http://www.facebook.com/login.php");
if(httpResponseBody == null){
//Why don't we try again?
try
{
Thread.sleep(1000);
}
catch (InterruptedException e)
{
logger.trace(e.getMessage());
}
httpResponseBody = getMethod("http://www.facebook.com/login.php");
}
logger.trace("Facebook: ========= get login page ResponseBody begin===========");
logger.trace(httpResponseBody);
logger.trace("Facebook: +++++++++ get login page ResponseBody end+++++++++");
logger.trace("Facebook: Initial cookies: ");
List<Cookie> cookies = getCookies();
if (cookies.isEmpty()) {
logger.trace("Facebook: None");
} else {
for (int i = 0; i < cookies.size(); i++) {
logger.trace("Facebook: - " + cookies.get(i).toString());
}
}
if(httpResponseBody == null){
logger.warn("Facebook: Warning: Failed to get facebook login page.");
}
try
{
HttpPost httpost = new HttpPost("http://www.facebook.com/login.php");
List <NameValuePair> nvps = new ArrayList <NameValuePair>();
nvps.add(new BasicNameValuePair("email", email));
nvps.add(new BasicNameValuePair("pass", pass));
//don't know if is this necessary
nvps.add(new BasicNameValuePair("login", ""));
httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
logger.info("Facebook: #executing post method to:" + "http://www.facebook.com/login.php");
HttpResponse loginPostResponse = getHttpClient().execute(httpost);
HttpEntity entity = loginPostResponse.getEntity();
logger.trace("Facebook: Login form post: " + loginPostResponse.getStatusLine());
if (entity != null) {
logger.trace("Facebook: "+EntityUtils.toString(entity));
entity.consumeContent();
} else {
logger.error("Facebook: Error: login post's response entity is null");
return FacebookErrorCode.kError_Login_GenericError;
}
logger.trace("Facebook: Post logon cookies:");
cookies = getCookies();
if (cookies.isEmpty()) {
logger.trace("Facebook: None");
} else {
for (int i = 0; i < cookies.size(); i++) {
logger.trace("Facebook: - " + cookies.get(i).toString());
}
}
int statusCode = loginPostResponse.getStatusLine().getStatusCode();
logger.info("Facebook: Post Method done(" + statusCode + ")");
switch(statusCode){
case 100: break;//we should try again;
case 301:
case 302:
case 303:
case 307:
{
//redirect
// Header[] headers = loginPostResponse.getAllHeaders();
// for (int i=0; i<headers.length; i++) {
// logger.trace("Facebook: "+headers[i]);
// }
// Header locationHeader = loginPostResponse.getFirstHeader("location");
// if(locationHeader != null){
// homePageUrl = locationHeader.getValue();
// logger.info("Facebook: Redirect Location: " + homePageUrl);
// if(homePageUrl == null
// || !homePageUrl.contains("facebook.com/home.php")){
// logger.error("Facebook: Login error! Redirect Location Url not contains \"facebook.com/home.php\"");
// return FacebookErrorCode.kError_Login_GenericError;
// }
// } else {
// logger.warn("Facebook: Warning: Got no redirect location.");
// }
}
break;
default:;
}
}
catch (IOException ioe)
{
logger.error("Facebook: IOException\n" + ioe.getMessage());
return FacebookErrorCode.kError_Global_ValidationError;
}
logger.trace("Facebook: =========connectAndLogin end==========");
return FacebookErrorCode.Error_Global_NoError;
}
The following code, based on that sample, worked for me:
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet("http://www.facebook.com/login.php");
HttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
System.out.println("Login form get: " + response.getStatusLine());
if (entity != null) {
entity.consumeContent();
}
System.out.println("Initial set of cookies:");
List<Cookie> cookies = httpclient.getCookieStore().getCookies();
if (cookies.isEmpty()) {
System.out.println("None");
} else {
for (int i = 0; i < cookies.size(); i++) {
System.out.println("- " + cookies.get(i).toString());
}
}
HttpPost httpost = new HttpPost("http://www.facebook.com/login.php");
List <NameValuePair> nvps = new ArrayList <NameValuePair>();
nvps.add(new BasicNameValuePair("email", "******"));
nvps.add(new BasicNameValuePair("pass", "*******"));
httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
response = httpclient.execute(httpost);
entity = response.getEntity();
System.out.println("Double check we've got right page " + EntityUtils.toString(entity));
System.out.println("Login form get: " + response.getStatusLine());
if (entity != null) {
entity.consumeContent();
}
System.out.println("Post logon cookies:");
cookies = httpclient.getCookieStore().getCookies();
if (cookies.isEmpty()) {
System.out.println("None");
} else {
for (int i = 0; i < cookies.size(); i++) {
System.out.println("- " + cookies.get(i).toString());
}
}
httpclient.getConnectionManager().shutdown();
I am not sure if your code was managing properly cookies (and session id kept within one of them), maybe that was the problem. Hope this will help you.
Just to make clear version issue: I was using HttpClient version 4.X, not the old one (3.X). They differ significantly.
Perhaps you should use a tool, such as Selenium
Have you taken a look at HtmlUnit. It wraps the HttpClient to create a headless Java browser, with javaScript execution. This way you are not trying to hack the individual forms all the time.