Location not populated on Spring Social Facebook - java

I'm trying to get user location in Spring Social Facebook:
Facebook fb = ((Facebook) connection.getApi());
Page pg = fb.pageOperations().getPage(fb.userOperations().getUserProfile().getLocation().getId());
The problem is that pg.getLocation() returns null.
I also tried with
fb.fetchObject(fb.userOperations().getUserProfile().getLocation().getId(), org.springframework.social.facebook.api.Location.class)
but it does populate only the name, not country or other fields.
Trying on Graph API Explorer /v2.6/112286918797929?fields=id,name,location returns as expected:
{
"id": "112286918797929",
"name": "Sacele",
"location": {
"city": "Sacele",
"country": "Romania",
"latitude": 45.6167,
"longitude": 25.6833
}
}
Is this an issue with Spring Social Facebook?
I'm using Spring Social 1.1.4 and Spring Social Facebook 2.0.3.
I also tried Spring Social for Facebook - get user location, but unfortunately not all the places follow the name convention City, Country and some of them include in the name only the city, not the country too. Plus how can you get the geo-coordinates?

I finally got it. First of all it doesn't work with PageOperations, but it works with GraphApi.
And the code is
UserProfile userProfile = fb.userOperations().getUserProfile();
Page pg = fb.fetchObject(userProfile.getLocation().getId(), Page.class, "location");
The trick is specifying the third parameter, which represents the fields (you can specify multiple fields as strings). Now the page is populated and you can get the country like pg.getLocation().getCountry().

As you stated that, the following command
fb.fetchObject(fb.userOperations().getUserProfile().getLocation().getId(), org.springframework.social.facebook.api.Location.class)
gives response the name which is from Reference.
That's have 2 public methods: getId() and getName().
Some methods like getLocation() is depends on permission. If any user gives you permission to see his location, then you can access this method.
From documentation:
getLocation
public Reference getLocation()
The user's location. Available only with "user_location" or "friends_location" permission.
Returns: a
Reference to the user's location, if available
Code Sample:
Page profile=facebookTemplate.pageOperations().getPage(id);
String name=profile.getName();
String webside=profile.getWebsite();
String logo="http://graph.facebook.com/" + id + "/picture";
party=new FullPoliticalParty(name,color,logo,webside);
String phone=profile.getPhone() == null ? "No disponible" : profile.getPhone();
party.setPhone(phone);
org.springframework.social.facebook.api.Location loc=profile.getLocation();
if (loc != null) {
location=new LocationMapa(loc.getCity(),loc.getCountry(),loc.getStreet(),loc.getZip());
}
party.setLocation(location);
Resource Link:
Location class
Java Code Examples for
org.springframework.social.facebook.api.Page
UPDATE1:
I think you need user permissions through Graph API. Then you can access location or other info that you requested from specific user. Checking Current Permissions and Handling Missing Permissions is given in this link.
For USER permissions:
/* make the API call */
new GraphRequest(
AccessToken.getCurrentAccessToken(),
"/{user-id}/permissions",
null,
HttpMethod.GET,
new GraphRequest.Callback() {
public void onCompleted(GraphResponse response) {
/* handle the result */
}
}
).executeAsync();
For user permissions, you can go through this tutorial
For user location, you can go through this tutorial.
After getting related permission, you can get access location, longitude, latitude and other info also.

Related

Spring: Implement a share-via-link feature for web application

I have a requirement where I need to implement a share-application-state-via-link feature.
My application is a video streaming single page application consisting of some dropdown options for user to filter out available videos and a video player to play the selected videos.
Now first on the basis of dropdown options , a user selects the available videos and add it to video player. At max 4 videos could be added. Now after that, I need to share this state of my application to some other user so I get a share link(just like Share answer in StackOverflow) and I send this to other user. This other user just need to hit this URL and it will load the exact state of application with videos added to player and dropdown populated with respective options.
My Approach:
I have a /getVideo rest service which fetches the video data and send it as json response back to angular based frontend. I have created a Share button which when clicked, creates a link by adding all the selected dropdown options something like:
https://localhost:8080/MyApp/shared?genre=Action&type=web-series
I have created a method /shared which will take these params and call the /getVideo internally.
The problem here is, I need to load index.html when the above link is hit. I also have to send the getVideo data to be loaded with index.html and the application should function properly. Am not able to solve this problem and need help.
Is my approach correct? Is there any alternate way? Am using Spring-Boot for backend and angular2 for frontend.
Here is the /shared API:
#RequestMapping(value = "/shared", method = RequestMethod.GET)
public String getSharedVideo(RedirectAttributes redirectAttributes,
#RequestParam(value="genre", required=false) String genre,
#RequestParam(value="date", required=false) String date,
#RequestParam(value="type", required=false) String type,
#RequestParam(value="version", required=false) String version,
#RequestParam(value="category", required=false) String category
){
List<Lab> lab = null;
try {
lab = videoService.getVideo(genre, date, type, version, category);
redirectAttributes.addAllAttributes(lab); // how to send this data to frontend
return "index.html";
} catch(Exception e) {
LOGGER.error("EXCEPTION - " + e.getMessage());
}
Any help would be appreciated.

Spring Social Facebook: Get Facebook Post Image [duplicate]

I'm currently using the Graph API Explorer to make some tests. That's a good tool.
I want to get the user's friend list, with friends' names, ids and pictures. So I type :
https://graph.facebook.com/me/friends?fields=id,picture,name
But picture is only 50x50, and I would like a larger one in this request.
Is it possible ?
As described in this bug on Facebook, you can also request specific image sizes now via the new API "field expansion" syntax.
Like so:
https://graph.facebook.com/____OBJECT_ID____?fields=picture.type(large)
The best way to get all friends (who are using the App too, of course) with correct picture sizes is to use field expansion, either with one of the size tags (square, small, normal, large):
/me/friends?fields=picture.type(large)
(edit: this does not work anymore)
...or you can specify the width/height:
me/friends?fields=picture.width(100).height(100)
Btw, you can also write it like this:
me?fields=friends{picture.type(large)}
you do not need to pull 'picture' attribute though. there is much more convenient way, the only thing you need is userid, see example below;
https://graph.facebook.com/user_id/picture?type=large
p.s. type defines the size you want
plz keep in mind that using token with basic permissions, /me/friends will return list of friends only with id+name attributes
You can set the size of the picture in pixels, like this:
https://graph.facebook.com/v2.8/me?fields=id,name,picture.width(500).height(500)
In the similar manner, type parameter can be used
{user-id}/?fields=name,picture.type(large)
From the documentation
type
enum{small, normal, album, large, square}
Change the array of fields id,name,picture to id,name,picture.type(large)
https://graph.facebook.com/v2.8/me?fields=id,name,picture.type(large)&access_token=<the_token>
Result:
{
"id": "130716224073524",
"name": "Julian Mann",
"picture": {
"data": {
"is_silhouette": false,
"url": "https://scontent.xx.fbcdn.net/v/t1.0-1/p200x200/15032818_133926070419206_3681208703790460208_n.jpg?oh=a288898d87420cdc7ed8db5602bbb520&oe=58CB5D16"
}
}
}
You can also try getting the image if you want it based on the height or width
https://graph.facebook.com/user_id/picture?height=
OR
https://graph.facebook.com/user_id/picture?width=
The values are by default in pixels you just need to provide the int value
I researched Graph API Explorer extensively and finally found full_picture
https://graph.facebook.com/v2.2/$id/posts?fields=picture,full_picture
P.S. I noticed that full_picture won't always provide full size image I want. 'attachments' does
https://graph.facebook.com/v2.2/$id/posts?fields=picture,full_picture,attachments
Hum... I think I've found a solution.
In fact, in can just request
https://graph.facebook.com/me/friends?fields=id,name
According to http://developers.facebook.com/docs/reference/api/ (section "Pictures"), url of profile's photos can be built with the user id
For example, assuming user id is in $id :
"http://graph.facebook.com/$id/picture?type=square"
"http://graph.facebook.com/$id/picture?type=small"
"http://graph.facebook.com/$id/picture?type=normal"
"http://graph.facebook.com/$id/picture?type=large"
But it's not the final image URL, so if someone have a better solution, i would be glad to know :)
You can specify width & height in your request to Facebook graph API: http://graph.facebook.com/user_id/picture?width=500&height=500
You can size it as follows.
Use:
https://graph.facebook.com/USER_ID?fields=picture.type(large)
For details: https://developers.facebook.com/docs/graph-api/reference/user/picture/
From v2.7, /<picture-id>?fields=images will give you a list with different size of the images, the first element being the full size image.
I don't know of any solution for multiple images at once.
I got this error when I made a request with picture.type(full_picture):
"(#100) For field 'picture': type must be one of the following
values: small, normal, album, large, square"
When I make the request with picture.type(album) and picture.type(square), responses me with an image 50x50 pixel size.
When I make the request with picture.type(large), responses me with an image 200x200 pixel size.
When I make the request with picture.width(800), responses me with an image 477x477 pixel size.
with picture.width(250), responses 320x320.
with picture.width(50), responses 50x50.
with picture.width(100), responses 100x100.
with picture.width(150), responses 160x160.
I think that facebook gives the images which resized variously when the user first add that photo.
What I see here the API for requesting user Image does not support
resizing the image requested. It gives the nearest size of image, I think.
In pictures URL found in the Graph responses (the "http://photos-c.ak.fbcdn.net/" ones), just replace the default "_s.jpg" by "_n.jpg" (? normal size) or "_b.jpg" (? big size) or "_t.jpg" (thumbnail).
Hacakable URLs/REST API make the Web better.
rest-fb users (square image, bigger res.):
Connection myFriends = fbClient.fetchConnection("me/friends", User.class, Parameter.with("fields", "public_profile,email,first_name,last_name,gender,picture.width(100).height(100)"));
I think that as of now the only way to get large pictures of friends is to use FQL. First, you need to fetch a list of friends:
https://graph.facebook.com/me/friends
Then parse this list and extract all friends ids. When you have that, just execute the following FQL query:
SELECT id, url FROM profile_pic WHERE id IN (id1, id2) AND width=200 AND height=200
200 here is just an exemplary size, you can enter anything. You should get the following response:
{
"data": [
{
"id": ...,
"url": "https://fbcdn-profile-a.akamaihd.net/..."
},
{
"id": ...,
"url": "https://fbcdn-profile-a.akamaihd.net/..."
}
]
}
With each url being the link to a 200x200px image.
I have the same problem but i tried this one to solve my problem. it returns large image.
It is not the perfect fix but you can try this one.
https://graph.facebook.com/v2.0/OBJECT_ID/picture?access_token=XXXXX
try to change the size of the image by changing the pixel size from the url in each json object as follows :
for example I change s480x480 to be s720x720
Before :
https://fbcdn-sphotos-c-a.akamaihd.net/hphotos-ak-xfp1/t1.0-9/q71/s480x480/10454308_773207849398282_283493808478577207_n.jpg
After :
https://fbcdn-sphotos-c-a.akamaihd.net/hphotos-ak-xfp1/t1.0-9/q71/s720x720/10454308_773207849398282_283493808478577207_n.jpg
JS styled variant.
Just set enormous large picture width and you will get the largest variant.
FB.api(
'/' + userId,
{fields: 'picture.width(2048)'},
function (response) {
if (response && !response.error) {
console.log(response.picture.data.url);
}
}
);
You can use full_picture instead of picture key to get full size image.
Note: From Graph API v8.0 you must provide the access token for every UserID request you do.
Hitting the graph API:
https://graph.facebook.com/<user_id>/picture?height=1000&access_token=<any_of_above_token>
With firebase:
FirebaseUser user = mAuth.getCurrentUser();
String photoUrl = user.getPhotoUrl() + "/picture?height=1000&access_token=" +
loginResult.getAccessToken().getToken();
You get the token from registerCallback just like this
LoginManager.getInstance().registerCallback(mCallbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
FirebaseUser user = mAuth.getCurrentUser();
String photoUrl = user.getPhotoUrl() + "/picture?height=1000&access_token=" + loginResult.getAccessToken().getToken();
}
#Override
public void onCancel() {
Log.d("Fb on Login", "facebook:onCancel");
}
#Override
public void onError(FacebookException error) {
Log.e("Fb on Login", "facebook:onError", error);
}
});
This is what documentation says:
Beginning October 24, 2020, an access token will be required for all
UID-based queries. If you query a UID and thus must include a token:
use a User access token for Facebook Login authenticated requests
use a Page access token for page-scoped requests
use an App access token for server-side requests
use a Client access token for mobile or web client-side requests
We recommend that you only use a Client token if you are unable to use
one of the other token types.

Spring Facebook Template map fetchObject to PagedList

I'm using the following approach to return a Facebook user's music preferences:
//FIXME: Fetch results in a single operation
val likes = facebook.likeOperations().music
val artists = ArrayList<Artist>()
for (musicLiked in likes)
{
val musicProfile = facebook.fetchObject(musicLiked.id, Page::class.java, "id", "name", "genre");
artists.add(Artist(name = musicProfile.name, genre = musicProfile.genre))
}
The above approach won't scale, since we have an additional network operation for each artist the user likes.
I tried:
I tried using facebook.likeOperations.music however this doesn't fetch genre.
Question:
I would like to use facebook.fetchObject with a query that returns a PagedList. How to do this?
(No need to post example code in Kotlin if you prefer or are more familiar with Java - I'll be happy with information in any language).
Facebook api uses "fields" parameter in requests to return custom fields for objects. This parameter can be also used for liked music rest request.
me/music?fields=id,genre,name
above link will return all liked music with id, genre and name of the artist/group. Unfortunately FacebookTemplate does not have method which will apply for your needs. The method Facebook.likeOperations() returns instance of the LikeTemplate class which has constant PAGE_FIELDS with value
private static final String PAGE_FIELDS = "id,name,category,description,location,website,picture,phone,affiliation,company_overview,likes,checkins";
In above constant you do not have genre field. So you have two ways:
You can simply use facebook rest api with some rest library
You can override FacebookTemplate and return your own implementation of LikeTemplate as result of the likeOperations() method. You implementation of the LikeTemplate class should have different value in mentioned constant (added genre field at the end of the string)
Maybe some one will be more helpful but in my knowledge you do not have other options.
Thanks to advice given in #burovmarley's answer, I inspected the source and came up with:
val music = facebook.fetchConnections(userPage.id, "music", Page::class.java,
PagingParameters(25, 0, null, null).toMap(), "id,name,,genre")
for (musicLiked in music)
{
println("likes: ${musicLiked.name}, genre: ${musicLiked.genre}")
}
This allows using Spring Social Facebook as an unmodified dependency, and without issuing a pull request, which seem to be fairly slow in processing through the queue at the present time.

Spring Social for Facebook - get user location

I am using spring social Facebook to connect to facebook. The connection works well. I am trying to get the user's location with the following code:
FacebookProfile profile = facebook.userOperations().getUserProfile();
Reference rLocation = profile.getLocation();
Location location= facebook.fetchObject(rLocation.getId(), Location.class);
But what I get is an empty location object (it doesn't have any of the details). I can see that the rLocation does have a name (Los Angeles) but I also need the country.
Any idea how to get the actual Location object?
You can only get the location details that are a part of the Reference object which is the rLocation here. You can get the location city and location state but the location country is not a part of the Reference object.
Reference rLocation = profile.getLocation();
String locationName = rLocation.getName();
String[] cityAndState = locationName.split(",");
String city = cityAndState[0].trim();
String state = cityAndState[1].trim();
The Location object basically helps to get the details of a user checked in location in facebook. Please refer to the spring social facebook API for more details.
http://static.springsource.org/spring-social-facebook/docs/1.0.x/api/org/springframework/social/facebook/api/Location.html

Problems with user features with Jtwitter

My code is :
List<Status> list = new ArrayList<Status>();
User user;
Twitter twitter = new Twitter();
list = twitter.search(string);
for(int i=0; i<list.size();i++){
user=list.get(i).getUser();
System.out.print(i+1);
System.out.println(list.get(i));
System.out.println(list.get(i).getId());
System.out.println(list.get(i).getUser());
System.out.println(user.getId());
System.out.println(user.getCreatedAt());
System.out.println(user.getLocation());
System.out.println(user.getFavoritesCount());
}
The problem is that good print the status, id of status and user, but user features how user id, location, etc, prints all as null. What I can do to take the features????
Thanks for response
According to the JTwitter API Docs, calling the default constructor creates a new instance without a user. You need to authenticate with Twitter using Twitter.IHttpClient (which depends on Signpost) to get user data.
The Twitter search method is unusual in that it only returns a small part of the User information. This is a limitation from Twitter & there's nothing you can do about that.
Fields such as location will be blank.
You always get the screen-name, and this can be used to fetch the extra info via the show() method. E.g.
Twitter twitter;
List<String> userNames; // make this list from user.screenName
List<User> fullUserInfo = twitter.users().show(userNames)
If you have an up-to-date copy of JTwitter (http://www.winterwell.com/software/jtwitter.php) it is all in the javadoc.
NB: Other methods sometimes return missing fields in User, if Twitter is experiencing heavy load.

Categories