difficulty in posting videos on facebook - android

I am making an application in which i want to post videos on facebook.While i try to do that,i am getting this error:
Facebook Error: (#100) Requires extended permission: video_upload or Requires extended permission: publish_actions
This is the code:
mUploadButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
byte[] data = null;
AssetFileDescriptor fileDesc = getResources().openRawResourceFd(
R.raw.movie);
String dataPath = fileDesc.toString();
String dataMsg = "Your video description here.";
String dataName = "movie.mp4";
Bundle param;
AsyncFacebookRunner mAsyncRunner = new AsyncFacebookRunner(mFacebook);
InputStream is ;
try
{
is = fileDesc.createInputStream();
// is = new FileInputStream(dataPath);
if(is != null)
data = readBytes(is);
param = new Bundle();
param.putString("message", dataMsg);
param.putString("filename", dataName);
param.putByteArray("video", data);
mAsyncRunner.request("me/videos", param, "POST", new SampleRequestListener(), null);
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
}
});
Please tell me what is the problem and how to solve it.

The problem is contained in the error message. It is a fairly clear error message I think.
In the Authentication flow for your app, you have not requested that the user grant you the video_upload, publish_actions or publish_stream Permission - any of those three will allow video uploads, but the third is more wide-ranging and triggers a second page on the auth dialog.
Check whichever SDK you're using to see if it has a convenient wrapper to ask for additional permissions in the auth flow. In the regular Oauth flow, you just add the list of permissions needed as the scope parameter in your call to the Oauth dialog

Related

Android Google+ unable to get authorization code

I want to enable server-side Calendar API access for my android app.
I have followed the steps given here .
I am getting a null value for the authorization code.
I think I am giving wrong values for 'scope' field and the 'server_client_id' field.
Please give me an example showing correct fields values for 'scope' and 'server_client_id' in the getToken() method.
Thanks for any help.
PS- I have used google+ sign in for android given here for connecting to a google account.
EDIT- Here is my code. I have given the OAuth 2.0 scope for the Google Calendar API in the scope field.
I have taken Client ID for Android application from Developers Console and put in 'serverClientID' field. This is probably where I am wrong. I don't know how to get Server's Client ID which is required by the
public class AsyncGetAuthToken extends AsyncTask<String, Void, String>{
#Override
protected String doInBackground(String... params) {
Bundle appActivities = new Bundle();
appActivities.putString(GoogleAuthUtil.KEY_REQUEST_VISIBLE_ACTIVITIES,
"MainActivity");
String scopeString = "https://www.googleapis.com/auth/calendar.readonly";
String serverClientID = CLIENT_ID;
String scopes = "oauth2:server:client_id:" + serverClientID + ":api_scope:" + scopeString;
String code = null;
try {
code = GoogleAuthUtil.getToken(
MainActivity.this, // Context context
Plus.AccountApi.getAccountName(mGoogleApiClient), // String accountName
scopes, // String scope
appActivities // Bundle bundle
);
} catch (IOException transientEx) {
// network or server error, the call is expected to succeed if you try again later.
// Don't attempt to call again immediately - the request is likely to
// fail, you'll hit quotas or back-off.
return null;
} catch (UserRecoverableAuthException e) {
// Requesting an authorization code will always throw
// UserRecoverableAuthException on the first call to GoogleAuthUtil.getToken
// because the user must consent to offline access to their data. After
// consent is granted control is returned to your activity in onActivityResult
// and the second call to GoogleAuthUtil.getToken will succeed.
startActivityForResult(e.getIntent(), AUTH_CODE_REQUEST_CODE);
return null;
} catch (GoogleAuthException authEx) {
// Failure. The call is not expected to ever succeed so it should not be
// retried.
return null;
} catch (Exception e) {
throw new RuntimeException(e);
}
return null;
}
}
And in my onActivityResult, I look for the Auth Code
if (requestCode == AUTH_CODE_REQUEST_CODE) {
if (responseCode == RESULT_OK){
Bundle extra = intent.getExtras();
String oneTimeToken = extra.getString("authtoken");
Log.d("LOG", "one time token" + oneTimeToken);
}
}

posting status to twitter using twitter4j in android

im trying to post status updates to twitter. I am using the Twitter4j lib. My code runs without crashing but in the log cat is says "401:Authentication credentials
(https://dev.twitter.com/pages/auth) were missing or incorrect. Ensure that you have set valid consumer key/secret, access token/secret, and the system clock is in sync.
{"request":"\/1.1\/statuses\/update.json","error":"Read-only application cannot POST."}
any help? I have signed up on twitter and i check the read and write permissions.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Runnable runnable = new Runnable() {
public void run() {
ConfigurationBuilder builder = new ConfigurationBuilder();
builder.setOAuthConsumerKey("kkwfh72794883jjg");
builder.setOAuthConsumerSecret("77j3jgweqwewerrud3434567hgfd");
// Access Token
String access_token = "lokiujyhtgrfedvwn325zckjdhdgeAHGsw23";
// Access Token Secret
String access_token_secret = "QsRgfgHJMsjeh5762JHF2dgswrfMNQljsG";
AccessToken accessToken = new AccessToken(access_token, access_token_secret);
Twitter twitter = new TwitterFactory(builder.build()).getInstance(accessToken);
// Update status
try {
twitter4j.Status response = twitter.updateStatus("updated via myapp");
Log.d("Status", "> " + response.getText());
// Error in updating status
} catch (TwitterException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.d("Twitter Update Error", e.getMessage());
}
}
};
Thread mythread = new Thread(runnable);
mythread.start();
}
I was having similar issue. What I did was:
Check if your app has Read and Write permissions
If it doesn't, check the permissions radiobutton, and click Update Settings
After that, you must manually regenerate your access tokens (I regenerated consumer key, too)
Hope this will help other strugglers.
I think you should change your code:
Like this:
ConfigurationBuilder builder = new ConfigurationBuilder();
builder.setOAuthConsumerKey("kkwfh72794883jjg");
builder.setOAuthConsumerSecret("77j3jgweqwewerrud3434567hgfd");
OAuthAuthorization auth = new OAuthAuthorization(builder.build());
// Access Token
String access_token = "lokiujyhtgrfedvwn325zckjdhdgeAHGsw23";
// Access Token Secret
String access_token_secret = "QsRgfgHJMsjeh5762JHF2dgswrfMNQljsG";
Twitter twitter = new TwitterFactory().getInstance(auth);

Get url from uploaded video on facebook

In my app you can share the video you have just taken. I want to get the link to the video back to android so i can call another function that will input the link in the database. So basically i need to know how to get a link from video i just shared. I am using the following code.
String path;
//get the current active facebook session
Session session = Session.getActiveSession();
//If the session is open
if(session.isOpened()) {
//Get the list of permissions associated with the session
List<String> permissions = session.getPermissions();
//if the session does not have video_upload permission
if(!permissions.contains("video_upload")) {
//Get the permission from user to upload the video to facebook
Session.NewPermissionsRequest newPermissionsRequest = new Session.NewPermissionsRequest(Main_activity.this, Arrays.asList("video_upload"));
session.requestNewReadPermissions(newPermissionsRequest);
}
path = getImagePath(videoUri); //function that gets absolute path
//Create a new file for the video
File file = new File(path);
try {
//create a new request to upload video to the facebook
Request videoRequest = Request.newUploadVideoRequest(session, file, new Request.Callback() {
#Override
public void onCompleted(Response response) {
if(response.getError()==null)
{
Toast.makeText(Main_activity.this, "video shared successfully", Toast.LENGTH_SHORT).show();
Log.i("it","worked");
String atbilde =response.getGraphObject().getProperty("id").toString();
}
else
{
Toast.makeText(Uzdevumi.this, response.getError().getErrorMessage(), Toast.LENGTH_SHORT).show();
}
}
});
//Execute the request in a separate thread
videoRequest.executeAsync();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
//Session is not open
else {
Toast.makeText(getApplicationContext(), "Please login to facebook first", Toast.LENGTH_SHORT).show();
}
}
});
Edit: Changed the "String atbilde =" so it would store the video id, so now i just need to build the url by simply adding "https://www.facebook.com/video.php?v=" before the id.
The response you receive if the upload of the Video was successful should contain an id property, see
https://developers.facebook.com/docs/graph-api/reference/v2.1/user/videos/#publish
To get a playable URL, you can use this id from the response to query the Graph API like this:
/{video_id}?fields=source
Have a look at https://developers.facebook.com/docs/graph-api/reference/v2.1/video/

Facebook permissions - requesting additional permissions

I want to get a list of a users albums names and ids. You need to add the permission users_photos for this.
I created a method called fetchAlbums, and in it I am requesting additional permissions. But by the time the permissions dialog pops up, the rest of the method has already executed (without the needed permissions!).
Whats the best way to do this, add the permissions in the onCreate of the Activity?
private void fetchAlbumsFromFB() {
Session session = Session.getActiveSession();
// make a new async request
Bundle params = new Bundle();
params.putString("fields", "id, name");
new Request(
session,
"/me/albums",
params,
HttpMethod.GET,
new Request.Callback() {
public void onCompleted(Response response) {
// use response id to upload photo to that album
//errText.setText("New Album created response: " + response.toString());
//need to get the newly created album ID.
try{
JSONObject graphResponse =response.getGraphObject().getInnerJSONObject();
Toast.makeText(getApplicationContext(), "Albums " + graphResponse.toString(), Toast.LENGTH_LONG).show();
}
catch (Exception e) {
e.printStackTrace();
albID = null;
}
}
}
).executeAsync();
}
It's better to ask for user_photos permission at the starting point, when the user is authenticating the app the first time.
Since it's not an extended/publish permission, it will be asked along with the basic permissions and user wont bother too; else user will see the permission dialogs again and again that could frustrate him.
I guess, in that case this problem will be solved too.

Android Facebook Open Graph?

I am curious if I can get some help with Open Graph since I can't seem to make any sense out of the Facebook API that I have read.
Right now I have setup my Open Graph Application on Facebook. It has been approved. I am trying to submit my "objects" via the bundle params but I am curious how I setup a bundle param object like the following. Where myObject has multiple values associated with it.
Bundle params = new Bundle();
param.putString("myObject", ""); // My object has multiple values
I guess I really need to figure out how you submit something in the Bundle that has multiple properties associated with it. If anyone has any insight on this please help me out.
At first I had tried something like this.
Bundle myObject = new Bundle();
myObject("property1", "property1Value");
myObject("property2", "property2Value");
myObject("property3", "property3Value");
Bundle params = new Bundle();
params.putString("myObject", myObject);
But in hindsight I figured out why this wouldn't work.
Edit 1
Maybe this will shed some light. Keep in mind this is an Open Graph action which is not a part of the Graph API.
//Build recipe
JSONObject recipe = new JSONObject();
recipe.put("type", "myappns:recipe");
recipe.put("recipe_name", "Thai Island");
recipe.put("cook_time", "1hr. 30min.");
//Build cookbook
JSONObject cookbookParams = new JSONObject();
cookbookParams.put("type", "myappns:book");
cookbookParams.put("title", "Hot & Spicy");
cookbookParams.put("description", "This book consists of hot & spicy foods");
cookbookParams.put("recipes", new JSONArray().put(recipe));
Bundle params = new Bundle();
params.putString("cookbook", cookbookParams.toString());
AsyncFacebookRunner request = new AsyncFacebookRunner(facebook);
request.request("me/myappns:used", params, "POST", new addToTimelineListener(), null);
Here is a question though as I have been digging more into the Open Graph system. I believe I need to actually have a website setup somewhere, is this correct? I was lead to believe through the introductory documentation of Open Graph that I could create and use my Facebook application on Android without the need of any website. That is use the Open Graph system, I know I can use the application to post feeds and what not which I have done successfully.
Thanks again!
Edit 2
Dont even worry about replying I understand what my problem was now...I have to have a website somewhere hosting a Facebook application for the posts to link back too. Makes perfect sense, I haven't seen where the documentation was very direct about this...oh well now I know.
I use this code to publish on wall for multiple object properties.
private void publishPhoto(String imageURL) {
Log.d("FACEBOOK", "Post to Facebook!");
try {
JSONObject attachment = new JSONObject();
attachment.put("message",text);
attachment.put("name", "MyGreatAndroidAppTest");
attachment.put("href", "http://stackoverflow.com/users/909317/sunny");
attachment.put("description","Test Test TEst");
JSONObject media = new JSONObject();
media.put("type", "image");
media.put("src", imageURL);
media.put("href",imageURL);
attachment.put("media", new JSONArray().put(media));
JSONObject properties = new JSONObject();
JSONObject prop1 = new JSONObject();
prop1.put("text", "Text or captionText to Post");
prop1.put("href", imageURL);
properties.put(text, prop1);
// u can make any number of prop object and put on "properties" for ex: //prop2,prop3
attachment.put("properties", properties);
Log.d("FACEBOOK", attachment.toString());
Bundle params = new Bundle();
params.putString("attachment", attachment.toString());
facebook.dialog(MyProjectActivity.this, "stream.publish", params, new DialogListener() {
#Override
public void onFacebookError(FacebookError e) {
// TODO Auto-generated method stub
}
#Override
public void onError(DialogError e) {
// TODO Auto-generated method stub
}
#Override
public void onComplete(Bundle values) {
final String postId = values.getString("post_id");
if (postId != null) {
Log.d("FACEBOOK", "Dialog Success! post_id=" + postId);
Toast.makeText(MyProjectActivity.this, "Successfully shared on Facebook!", Toast.LENGTH_LONG).show();
} else {
Log.d("FACEBOOK", "No wall post made");
}
}
#Override
public void onCancel() {
// TODO Auto-generated method stub
}
});
} catch (JSONException e) {
Log.e("FACEBOOK", e.getLocalizedMessage(), e);
}
}
To see a complete example look at the wishlist example.
A complete example for Android is included. The package includes the files to be uploaded on the server and a readme file that explain how to set up all the stuff on the open graph panel.

Categories

Resources