Extracting users friend list from facebook graph api v2.3 - facebook-graph-api

I am using facebook SDK 4.0.1. I gave permission for user_friends but I am not able to get friend list of the user. I am getting the count of the user's friends but I want the name of the user's friends and ids
private FacebookCallback<LoginResult> mcallback = new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
accessToken = loginResult.getAccessToken();
Log.d("Access Token", accessToken.toString());
Profile profile = Profile.getCurrentProfile();
// Log.d("PROFILE","PROFILE IMAHE"+profile.getName());
displayWelcomeMessage(profile);
GraphRequestBatch batch = new GraphRequestBatch(
GraphRequest.newMeRequest(accessToken, new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject jsonObject, GraphResponse response) {
try {
SharedPreferences.Editor editor = prefs.edit();
editor.putString(Constant.KEY_ID,jsonObject.getString("id"));
editor.putString(Constant.KEY_USER_NAME,jsonObject.getString("name"));
editor.putString(Constant.KEY_USER_FNAME,jsonObject.getString("first_name"));
editor.putString(Constant.KEY_USER_LNAME,jsonObject.getString("last_name"));
// hometown = jsonObject.getJSONObject("hometown");
// editor.putString(Constant.KEY_USER_HOMETOWN,hometown.getString("name"));
editor.putString(Constant.KEY_USER_EMAIL,jsonObject.getString("email"));
editor.putString(Constant.KEY_USER_GENDER,jsonObject.getString("gender"));
// editor.putString(Constant.KEY_USER_DOB,jsonObject.getString("birthday"));
editor.commit();
// town = hometown.getString("name");
// personId = jsonObject.getString("id");
// gen = jsonObject.getString("gender");
// email = jsonObject.getString("email");
Log.d("RESPONCE", "RESPONCE user=" + jsonObject.toString());
Log.d("RESPONCE", "RESPONCE =" + response.toString());
}
catch (JSONException e) {
e.printStackTrace();
}
}
}),
GraphRequest.newMyFriendsRequest(accessToken, new GraphRequest.GraphJSONArrayCallback() {
#Override
public void onCompleted(JSONArray jsonArray, GraphResponse response) {
//Lo Application code for users friends
Log.d("RESPONCE FRIEND", "RESPONCE FRIEND=" + jsonArray.toString());
Log.d("RESPONCE FRIEND", "RESPONCE =" + response.toString());
response.getJSONArray();
}
}));
batch.addCallback(new GraphRequestBatch.Callback() {
#Override
public void onBatchCompleted(GraphRequestBatch graphRequests) {
// Application code for when the batch finishes
}
});
batch.executeAsync();

Since v2.0 of the Graph API, it is only possible to get friends who authorized your App too - for privacy reasons. More information can be found in this and many other threads about that exact same question: Facebook Graph Api v2.0+ - /me/friends returns empty, or only friends who also use my app

Related

Contact phone numbers Lync SDK 2013

Hello I'm using Lync SDK 2013, to display number phones from contact in ListBox, and use the Items (phone number) to call this number by my API. So i did a WPF application, that contains just a ListBox, and 2 buttons (Call - Hang up). My apllication is added as custom command in Lync, in RightClick in the contact. and it doesn't have any Lync Controls. So what i want to do is: if i Right Click on the contact, my application launches and gives me the number phone List in the ListBox. I did it with a WPF that contains the controls: ContactSearchInputBox (to search a contact) and ContactSearchResultList and it works very Well, I don't know how to do it without controls.
Any One Can Help Me !!!! :(
You need to read and understand the Lync SDK 2013 Lync Contact documentation.
If you wish to "simulate" the Lync Contact "search" (as per the Client search) then you need to look into the search API.
The other concepts you need to understand is the results returned from all the API are NOT guaranteed to return all the Lync Contact data that asked for.
There is no way with the Lync SDK to "load" all the contact information which is what most people seem to not understand.
The results returned are what the local cache has and no more. To get the all the Lync Contact information you need to understand the ContactSubscription model.
For each Lync Contact that you wish to be notified of field updates (or loads) you "subscribe" to the Lync Contact and then you will be notified via the Contact.ContactInformationChanged event.
So your UI must to able to auto-update the information as the fields get loaded / updated from any initial value returned from any Lync Contact value.
public partial class ChoosePhoneNumber : Window
{
LyncClient lync_client;
Contact contact;
ContactSubscription contact_subscription;
List<ContactInformationType> contact_information_list;
ContactManager contact_manager;
public ChoosePhoneNumber()
{
InitializeComponent();
connect_lync();
get_subscribed_contact(this.contact);
}
}
private void connect_lync()
{
try
{
lync_client = LyncClient.GetClient();
contact_manager = lync_client.ContactManager;
}
catch (ClientNotFoundException)
{
MessageBox.Show("Client is ot running", "Error While GetClient", MessageBoxButton.OK, MessageBoxImage.Error);
}
}
private void get_subscribed_contact(Contact contact)
{
List<object> contact_phone_numbers_list = new List<object>();
contact_information_list = new List<ContactInformationType>();
contact_information_list.Add(ContactInformationType.ContactEndpoints);
contact_information_list.Add(ContactInformationType.DisplayName);
contact = contact_manager.GetContactByUri("number"); // I put here the number phone of a contact in my list
contact_subscription = LyncClient.GetClient().ContactManager.CreateSubscription();
contact_subscription.AddContact(contact);
contact.ContactInformationChanged += Contact_ContactInformationChanged;
contact_subscription.Subscribe(ContactSubscriptionRefreshRate.High, contact_information_list);
List<object> endpoints = (List<object>)contact.GetContactInformation(ContactInformationType.ContactEndpoints);
var phone_numbers_list = endpoints.Where<object>(N => ((ContactEndpoint)N).Type == ContactEndpointType.HomePhone ||
((ContactEndpoint)N).Type == ContactEndpointType.MobilePhone || ((ContactEndpoint)N).Type == ContactEndpointType.OtherPhone
|| ((ContactEndpoint)N).Type == ContactEndpointType.WorkPhone).ToList<object>();
var name = contact.GetContactInformation(ContactInformationType.DisplayName);
if (phone_numbers_list != null)
{
foreach (var phone_number in phone_numbers_list)
{
contact_phone_numbers_list.Add(((ContactEndpoint)phone_number).DisplayName);
}
conboboxPhoneNumbers.ItemsSource = contact_phone_numbers_list;
}
}
private void Contact_ContactInformationChanged(object sender, ContactInformationChangedEventArgs e)
{
var contact = (Contact)sender;
if (e.ChangedContactInformation.Contains(ContactInformationType.ContactEndpoints))
{
update_endpoints(contact);
}
}
private void update_endpoints(Contact contact)
{
if ((lync_client != null) && (lync_client.State == ClientState.SignedIn))
{
ContactEndpoint endpoints = (ContactEndpoint)contact.GetContactInformation(ContactInformationType.ContactEndpoints);
}
}
public partial class App : Application
{
protected override void OnStartup(StartupEventArgs e)
{
App.Current.DispatcherUnhandledException += Current_DispatcherUnhandledException; ;
try
{
string argsParam = "Contacts=";
if (e.Args.Length > 1)
{
if (e.Args[2].Contains(argsParam))
{
var contacts_sip_uri = e.Args[2].Split('<', '>')[1];
Params.contacts = contacts_sip_uri;
}
}
}
catch (Exception ex)
{
MessageBox.Show("Reading Startup Arguments Error - " + ex.Message);
}
}
private void Current_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
{
string message = e.Exception.Message;
if (e.Exception.InnerException != null)
{
message += string.Format("{0}Inner Exception: {1}", Environment.NewLine, e.Exception.InnerException.Message);
}
MessageBox.Show(message, "Unhandled Exception", MessageBoxButton.OK, MessageBoxImage.Error);
}
}
Params is a public static class that contains just contact as public static string contacts { get; set; }
public static class ParamContact
{
public static string contacts { get; set; }
}

Accessing public information using a specific userID on facebook graph api

Someone is logged into my app. I need to display some profiles of people that might not be on this person's friends list. Is that possible, or is it a privacy issue. A person's "public profile" should be accessible right?
I tried to get the first name, profile picture and gender
Bundle parameters = new Bundle();
parameters.putString("fields", "first_name,gender");
try {
new GraphRequest(
AccessToken.getCurrentAccessToken(),
"/" + user.getUserID(),
parameters,
HttpMethod.GET,
new GraphRequest.Callback() {
public void onCompleted(GraphResponse response) {
JSONObject facebookResponse = response.getJSONObject();
try {
final String first_name = facebookResponse.getString("first_name");
final String gender = facebookResponse.getString("gender");
Bundle params = new Bundle();
params.putBoolean("redirect", false);
params.putString("type", "square");
params.putInt("width", 200);
params.putInt("height", 200);
new GraphRequest(
AccessToken.getCurrentAccessToken(),
"/" + user.getUserID() + "/picture",
params,
HttpMethod.GET,
new GraphRequest.Callback() {
public void onCompleted(GraphResponse response) {
JSONObject facebookResponse = response.getJSONObject();
try {
JSONObject data = facebookResponse.getJSONObject("data");
String url = data.getString("url");
Name.setText(first_name);
Gender.setText(gender);
mNetworkImageView.setImageUrl(url, mImageLoader);
facebookResponseListener.updatedUserObject(first_name, url, gender, pos);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
).executeAsync();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
).executeAsync();
} catch (Exception uee) {
uee.printStackTrace();
}
all of this is inside the getView() if a listview (it's where I display the profiles). While testing, I'm getting all the information of the friends of the logged in person, but the "gender" property in the response object is missing from the non-friend. Only the name and userID is being returned.
It's all explained in the docs (https://developers.facebook.com/docs/facebook-login/permissions):
gender & locale can only be accessed if:
The person queried is the person using the app.
The person queried is using the app, and is a friend of the person
using the app.
The person queried is using the app, is not a friend of the person
using the app, but the app includes either an app access token or an
appsecret_proof argument with the call.

ASP.NET Identity + Facebook login: Pass in "rerequest?"

(Using ASP.NET Identity 2.1, Microsoft.Owin.Security.Facebook 3.0.1 in a Web API project)
From here: https://developers.facebook.com/docs/facebook-login/login-flow-for-web/v2.2
This is because once someone has declined a permission, the Login Dialog will not re-ask them for it unless you explicitly tell the dialog you're re-asking for a declined permission.
You do this by adding the auth_type: rerequest flag to your FB.login() call:
FB.login(
function(response) {
console.log(response);
},
{
scope: 'user_likes',
auth_type: 'rerequest'
}
);
When you do that, the Login Dialog will re-ask for the declined permission. The dialog will look very much like the dialog in the section on re-asking for permissions but will let you re-ask for a declined permission.
So, using ASP.NET Identity's integration with Facebook login, I know how to pass in the requested scope, but if the user declines the permission, I need to pass in the extra parameter "auth_type" : 'rerequest." How do I do that?
You first add your custom FacebookAuthenticationProvider
public class FacebookProvider : FacebookAuthenticationProvider
{
public override void ApplyRedirect(FacebookApplyRedirectContext context)
{
//To handle rerequest to give some permission
string authType = string.Empty;
if (context.Properties.Dictionary.ContainsKey("auth_type"))
{
authType = string.Format("&auth_type={0}", context.Properties.Dictionary["auth_type"]);
}
//If you have popup loggin add &display=popup
context.Response.Redirect(string.Format("{0}{1}{2}", context.RedirectUri, "&display=popup", authType));
}
}
now in the startup you need to use this provider
var options = new FacebookAuthenticationOptions
{
AppId = "appid",
AppSecret = "secret",
Provider = new FacebookProvider
{
OnAuthenticated = async context =>
{
foreach (var x in context.User)
{
if (x.Key == "birthday")
{
context.Identity.AddClaim(new Claim("dateofbirth", x.Value.ToString()));
}
else
{
context.Identity.AddClaim(new Claim(x.Key, x.Value.ToString()));
}
}
context.Identity.AddClaim(new Claim("fb_accecctoken", context.AccessToken));
await Task.FromResult(context);
}
}
};
options.Scope.Add("public_profile");
options.Scope.Add("email");
options.Scope.Add("user_birthday");
options.Scope.Add("user_location");
app.UseFacebookAuthentication(options);
and finally in your account controller you need to set auth_type when you need
private const string XsrfKey = "xsrfkey";
internal class ChallengeResult : HttpUnauthorizedResult
{
public ChallengeResult(string provider, string redirectUri)
: this(provider, redirectUri, null, false)
{
}
public ChallengeResult(string provider, string redirectUri, string userId, bool isRerequest)
{
LoginProvider = provider;
RedirectUri = redirectUri;
UserId = userId;
IsRerequest = isRerequest;
}
public string LoginProvider { get; set; }
public string RedirectUri { get; set; }
public string UserId { get; set; }
public bool IsRerequest { get; set; }
public override void ExecuteResult(ControllerContext context)
{
var properties = new AuthenticationProperties { RedirectUri = RedirectUri };
if (UserId != null)
{
properties.Dictionary[XsrfKey] = UserId;
}
if (IsRerequest)
{
properties.Dictionary["auth_type"] = "rerequest";
}
context.HttpContext.GetOwinContext().Authentication.Challenge(properties, LoginProvider);
}
}
I had the same issue when I wanted to ensure the user had accepted all my permissions. As you probably know this can be detected by calling the /me/permissions url.
So I eventually solved it by simply deleting my app from the user's account.
You can do so by doing a DELETE request on the /me/permissions URL as documented here.
This will remove all permissions you requested from the user, so next time you try authenticating him through Facebook, the prompt appears again.

Birthday of Friend's using facebook api 2.0

I am trying to get birthday of my friends, those who have installed my sample app. Below is my code.
new Request(simpleFacebook.getSession(), "/" + id, null, HttpMethod.GET,
new Request.Callback() {
#Override
public void onCompleted(Response response) {
String rawResponse = response.getRawResponse();
AppLog.showLog(TAG, "Friend response is " + rawResponse);
}
}
).executeAsync();
But in response there is no any "birthday" filed.
I also used simplefacebook library. Using below code
PictureAttributes pictureAttributes = Attributes.createPictureAttributes();
pictureAttributes.setType(PictureAttributes.PictureType.SQUARE);
pictureAttributes.setWidth(250);
pictureAttributes.setHeight(250);
Profile.Properties properties = new Profile.Properties.Builder()
.add(Profile.Properties.NAME)
.add(Profile.Properties.BIRTHDAY)
.add(Profile.Properties.PICTURE)
.add(Profile.Properties.ID)
.build();
simpleFacebook.getProfile(id, properties, new OnProfileListener() {
#Override
public void onComplete(Profile response) {
String id = response.getId();
String name = response.getName();
String birthday = response.getBirthday();
String pictureUrl = response.getPicture();
AppLog.showLog(TAG, "Single friend Detail: " + id + "\t" +
name + "\t" + birthday + "\t" + pictureUrl);
FbFriendsDao fbFriendsDao = new FbFriendsDao(LoginActivity.this);
fbFriendsDao.openForWrite();
fbFriendsDao.insertFriends(new FbFriendDto(id, name, birthday, pictureUrl));
}
#Override
public void onException(Throwable throwable) {
super.onException(throwable);
}
#Override
public void onFail(String reason) {
super.onFail(reason);
}
#Override
public void onThinking() {
super.onThinking();
}
});
But it gives null in birthday filed.
Please help to solve this problem. Thanks in advance.
As #luschn mentioned, all friends_* permissions have been removed, including friends_birthday.
However it is still possible to get some data if:
The friend you want the birthday for is also a user of your app
The friend has provided the user_birthday permission (note you'll need this approved by FB)
You can do this by adding "birthday" to the fields key in me/friends:
me/friends?fields=id,name,birthday
Alternatively, you could simply save the user data to your own database when the user signs up and then retrieve it later, which would give you exactly the same outcome.
Check out the changelog: https://developers.facebook.com/docs/apps/changelog
All friends_* permissions have been removed
That includes friends_birthday, so it is not possible to get the birthday of a friend anymore.

Facebook and twitter oAuth redirect URL after login in j2me blackberry 7.1, but onAuthorize() not called

I want to integrate facebook and twitter sharing functionality in my j2me blackberry application. I have added relative jar files and able to login on respective APIs. But in both twitter and facebook, after login redirect URL is called but onAuthorize() method is not invoked and so I am not able to get access token and so not able to post anything on twitter and facebook.
Below is my twitter implementation code:
class ShowAuthBrowser extends MainScreen implements OAuthDialogListener
{
BrowserField b = new BrowserField();
public ShowAuthBrowser()
{
UiApplication.getUiApplication().invokeLater(new Runnable(){
public void run(){
UiApplication.getUiApplication().popScreen();
}
});
//}
add(b);
pageWrapper = new BrowserFieldOAuthDialogWrapper(b,CONSUMER_KEY,CONSUMER_SECRET,CALLBACK_URL,this);
pageWrapper.setOAuthListener(this);
}
public void doAuth( String pin )
{
try
{
if ( pin == null )
{
pageWrapper.login();
//Dialog.alert( "pin is null" );
}
else
{
this.deleteAll();
add(b);
//Dialog.alert( "pin is null else" );
pageWrapper.login(pin);
}
}
catch ( Exception e )
{
final String message = "Error loggin Twitter: " + e.getMessage();
Dialog.alert( message );
}
}
public void onAccessDenied(String response ) {
updateScreenLog( "Acceso denegado! -> " + response );
}
public void onAuthorize(final Token token) {
UiApplication.getUiApplication().invokeLater(new Runnable(){
public void run(){
Dialog.alert("mytoken::"+token);
UiApplication.getUiApplication().popScreen();
}
});
final Token myToken = token;
storeToekn.set("twitter_token", myToken.getToken());
storeToekn.commit();
UiApplication.getUiApplication().invokeLater( new Runnable() {
public void run() {
// sharing code...
}
});
}
public void onFail(String arg0, String arg1) {
updateScreenLog("Error authenticating user! -> " + arg0 + ", " + arg1);
}
}
can someone please help me out for this?