Package com.commafeed.backend.favicon

Source Code of com.commafeed.backend.favicon.FacebookFaviconFetcher

package com.commafeed.backend.favicon;

import java.net.URI;
import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets;
import java.util.List;

import javax.inject.Inject;
import javax.inject.Singleton;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import org.apache.http.NameValuePair;
import org.apache.http.client.utils.URLEncodedUtils;

import com.commafeed.backend.HttpGetter;
import com.commafeed.backend.HttpGetter.HttpResult;
import com.commafeed.backend.model.Feed;

@Slf4j
@RequiredArgsConstructor(onConstructor = @__({ @Inject }))
@Singleton
public class FacebookFaviconFetcher extends AbstractFaviconFetcher {

  private final HttpGetter getter;

  @Override
  public byte[] fetch(Feed feed) {
    String url = feed.getUrl();

    if (!url.toLowerCase().contains("www.facebook.com")) {
      return null;
    }

    String userName = extractUserName(url);
    if (userName == null) {
      return null;
    }

    String iconUrl = String.format("https://graph.facebook.com/%s/picture?type=square&height=16", userName);

    byte[] bytes = null;
    String contentType = null;

    try {
      log.debug("Getting Facebook user's icon, {}", url);

      HttpResult iconResult = getter.getBinary(iconUrl, TIMEOUT);
      bytes = iconResult.getContent();
      contentType = iconResult.getContentType();
    } catch (Exception e) {
      log.debug("Failed to retrieve YouTube icon", e);
    }

    if (!isValidIconResponse(bytes, contentType)) {
      bytes = null;
    }
    return bytes;
  }

  private String extractUserName(String url) {
    URI uri = null;
    try {
      uri = new URI(url);
    } catch (URISyntaxException e) {
      log.debug("could not parse url", e);
      return null;
    }
    List<NameValuePair> params = URLEncodedUtils.parse(uri, StandardCharsets.UTF_8.name());
    for (NameValuePair param : params) {
      if ("id".equals(param.getName())) {
        return param.getValue();
      }
    }
    return null;
  }

}
TOP

Related Classes of com.commafeed.backend.favicon.FacebookFaviconFetcher

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.