Páginas

2011-09-30

[drops.log]: An inverse path, from photo to album

Wow! I’ve been absent since last week. My logs didn’t increase much in the while. I keep groping the Facebook Graph API with the restFB java wrapper.

It is easy to get the photos from a album. This post is about the inverse. The current task is to find what album a photo belongs. Let me put some context. Imagine you are using the Facebook Real-time Updates API to read feed and get every time user share/post something. Sometimes it is a new album. But when the feed is fired up with a new album you get only the cover photo from the album.
So now I need to check out what album holds that picture to iterate in it and do my app job. I read a comment in the StackOverflow saying the old REST API covered that easily, but the current graph api doesn’t do such a good job. Thankfully they already caught the album ID is encoded in the link attribute.
So... Let’s cut the talk and show where is the album ID in a Facebook Graph API Photo object. A photo object has a attribute link like this:
"link": "https://www.facebook.com/photo.php?fbid=255682667892372&set=a.255682644460941.54884.100000719217155&type=1",
If we think for a moment it could become clear the set parameter in the URL could provide something and even more the a could stand for album. That is it! Have you caught? Parse from set=a. until the next dot and you got the album id that keeps the photo. (Yeah. That easy.)
So, let's extract that field and retrieve the album, and iterate for the fellow photos in a album. Since my Facebook Graph API wrapper is restFB let’s use Java regular expression.
//posts is a Post list retrived from a user's feed
Post post = posts.get(i);
if(post.getType() != null && post.getType().equals("photo")) {
	//Got a photo
	if(post.getCaption() != null) {
		//it is from a new album
		
		//this regex compilation could be static
		final String ALBUM_REGEX = "(?<=set=a\\.)\\d+";
		Pattern pattern = Pattern.compile(ALBUM_REGEX);
		Matcher matcher = pattern.matcher(post.getLink());
		if(matcher.find()) {
			String albumId = matcher.group();
			Connection< Photo > photos = fbcClient.fetchConnection(albumId + "/photos", Photo.class);
			for(Photo photo : photos.getData()) {
				//do your job with the photos
			}
		}
	}
}
I would love the album ID would be encoded in the Photo object too. It would be much more Object Oriented and far easier. Enough of complains. I guess that is all. Until next post, with more drops of logs from a Computer Scientist’s life.

[+/-] show/hide