Advertisement
Guest User

Instagram.java

a guest
Feb 18th, 2015
443
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 10.53 KB | None | 0 0
  1. package com.example.igbot.api;
  2.  
  3. import com.example.igbot.util.Sleeper;
  4.  
  5. import org.apache.commons.io.IOUtils;
  6. import org.json.simple.JSONArray;
  7. import org.json.simple.JSONObject;
  8. import org.json.simple.parser.JSONParser;
  9. import org.json.simple.parser.ParseException;
  10.  
  11. import java.io.BufferedReader;
  12. import java.io.DataOutputStream;
  13. import java.io.IOException;
  14. import java.io.InputStreamReader;
  15. import java.net.HttpURLConnection;
  16. import java.net.URL;
  17. import java.util.ArrayList;
  18. import java.util.List;
  19.  
  20. public final class Instagram {
  21.  
  22.   private final String accessToken;
  23.  
  24.   public Instagram(String accessToken) {
  25.     this.accessToken = accessToken;
  26.   }
  27.  
  28.   public List<Media> recent(String tagName) throws IOException {
  29.  
  30.     if (tagName.contains("#") || tagName.contains(" ") || tagName.isEmpty()) {
  31.       throw new AssertionError("Invalid tag: " + tagName);
  32.     }
  33.  
  34.     JSONObject jsonObj = request("https://api.instagram.com/v1/tags/" + tagName
  35.         + "/media/recent?access_token=" + accessToken, "GET", null);
  36.  
  37. //    JsonUtil.stdoutJson(jsonObj);
  38.  
  39.     JSONArray data = (JSONArray) jsonObj.get("data");
  40.     final List<Media> out = new ArrayList<>(data.size());
  41.     for (int i = 0; i < data.size(); i++) {
  42.  
  43.       JSONObject mediaJsonObject = (JSONObject) data.get(i);
  44. //      if (i == 0) {
  45. //        System.out.println("===");
  46. //        JsonUtil.stdoutJson(mediaJsonObject);
  47. //        System.out.println("===");
  48. //      }
  49.       JSONObject likes = (JSONObject) mediaJsonObject.get("likes");
  50.       long likesCount = (long) likes.get("count");
  51.       String id = (String) mediaJsonObject.get("id");
  52.       JSONObject userObj = (JSONObject) mediaJsonObject.get("user");
  53.       String userId = (String) userObj.get("id");
  54.       boolean userHasLiked = (boolean) mediaJsonObject.get("user_has_liked");
  55.       String link = (String) mediaJsonObject.get("link");
  56.       Media m = new Media(id, userId, userHasLiked, link, likesCount);
  57.       out.add(m);
  58.     }
  59.  
  60.     return out;
  61.   }
  62.  
  63.   public User userInfo(String userId) throws IOException {
  64.     JSONObject response = request(
  65.         "https://api.instagram.com/v1/users/" + userId + "/?access_token=" + accessToken,
  66.         "GET", null);
  67.  
  68. //    System.out.println("userInfo out:");
  69. //    JsonUtil.stdoutJson(response);
  70.  
  71.     JSONObject data = (JSONObject) response.get("data");
  72.     String id = (String) data.get("id");
  73.     String bio = (String) data.get("bio");
  74.     String website = (String) data.get("website");
  75.     String fullName = (String) data.get("full_name");
  76.     JSONObject counts = (JSONObject) data.get("counts");
  77.     long media = (long) counts.get("media");
  78.     long follows = (long) counts.get("follows");
  79.     long followedBy = (long) counts.get("followed_by");
  80.  
  81.     return new User(id, fullName, bio, website, media, follows, followedBy);
  82.   }
  83.  
  84.   public void like(String mediaId) throws IOException {
  85.     RequestResult result = request2("https://api.instagram.com/v1/media/" + mediaId + "/likes",
  86.         "POST", "access_token=" + accessToken);
  87.     if (result.responseCode != 200) {
  88.       throw new BadResponseCodeException(
  89.           "Non-200 response code: " + result.responseCode + ": " + result.responseMessage);
  90.     }
  91.   }
  92.  
  93.   /**
  94.    * @return true if ok, false if media isn't liked
  95.    */
  96.   public boolean unlike(String mediaId) throws IOException {
  97.     RequestResult result = request2("https://api.instagram.com/v1/media/" + mediaId +
  98.         "/likes?access_token=" + accessToken, "DELETE", null);
  99.     if (result.responseCode == 200) {
  100.       return true;
  101.     }
  102.     if (result.responseCode == 400 &&
  103.         result.error.contains("the user has not liked this media")) {
  104.       System.out.println("Media " + mediaId + " hasn't been liked");
  105.       return false;
  106.     }
  107.     System.err.println("Error: " + result.error);
  108.     throw new BadResponseCodeException(
  109.         "Non-200 response code: " + result.responseCode + ": " + result.responseMessage);
  110.   }
  111.  
  112.   public void follow(String userId) throws IOException {
  113.     RequestResult result = request2("https://api.instagram.com/v1/users/" + userId
  114.         + "/relationship?access_token=" + accessToken, "POST", "action=follow");
  115.     if (result.responseCode != 200) {
  116.       throw new BadResponseCodeException(
  117.           "Non-200 response code: " + result.responseCode + ": " + result.responseMessage);
  118.     }
  119.   }
  120.  
  121.   public List<String> selfFollow() throws IOException {
  122.  
  123.     final List<String> out = new ArrayList<>();
  124.     String url = "https://api.instagram.com/v1/users/self/follows?access_token=" + accessToken;
  125.     int page = 1;
  126.  
  127.     while (true) {
  128.  
  129.       System.out.println("Reading page " + page + " of self follows");
  130.       JSONObject response = request(url, "GET", null);
  131. //      System.out.println("selfFollow response:");
  132. //      JsonUtil.stdoutJson(response);
  133.  
  134.       JSONArray data = (JSONArray) response.get("data");
  135.       for (int i = 0; i < data.size(); i++) {
  136.         JSONObject jsonObject = (JSONObject) data.get(i);
  137.         String userId = (String) jsonObject.get("id");
  138.         out.add(userId);
  139.       }
  140.  
  141.       String nextUrl = null;
  142.       JSONObject pagination = (JSONObject) response.get("pagination");
  143.       if (pagination != null) {
  144.         nextUrl = (String) pagination.get("next_url");
  145.       }
  146.       if (nextUrl == null) {
  147.         break;
  148.       }
  149.       url = nextUrl;
  150.       page++;
  151.       Sleeper.sleepBetweenActions();
  152.     }
  153.  
  154.     return out;
  155.   }
  156.  
  157.   public void unfollow(String userId) throws IOException {
  158.     RequestResult result = request2("https://api.instagram.com/v1/users/" + userId
  159.         + "/relationship?access_token=" + accessToken, "POST", "action=unfollow");
  160.     if (result.responseCode != 200) {
  161.       throw new BadResponseCodeException(
  162.           "Non-200 response code: " + result.responseCode + ": " + result.responseMessage);
  163.     }
  164.   }
  165.  
  166.   private static JSONObject request(String url, String method, String content) throws IOException {
  167.     RequestResult result = request2(url, method, content);
  168.     if (result.responseCode != 200) {
  169.       System.err.println("Error: " + result.error);
  170.       throw new IOException(
  171.           "Non-200 response code: " + result.responseCode + ": " + result.responseMessage);
  172.     }
  173.     return result.response;
  174.   }
  175.  
  176.   private static RequestResult request2(String url, String method, String content)
  177.       throws IOException {
  178.  
  179.     final URL urlObject = new URL(url);
  180.     final HttpURLConnection httpCon = (HttpURLConnection) urlObject.openConnection();
  181.     httpCon.setDoOutput(true);
  182.     httpCon.setRequestMethod(method);
  183.  
  184.     if (content != null) {
  185.       DataOutputStream wr = new DataOutputStream(httpCon.getOutputStream());
  186.       wr.writeBytes(content);
  187.       wr.close();
  188.     }
  189.  
  190.     final int responseCode = httpCon.getResponseCode();
  191.     if (responseCode != 200) {
  192.       String errorStreamContents = IOUtils.toString(httpCon.getErrorStream());
  193.       return new RequestResult(null, responseCode, httpCon.getResponseMessage(),
  194.           errorStreamContents);
  195.     }
  196.  
  197.     JSONParser parser = new JSONParser();
  198.     JSONObject jsonObj;
  199.  
  200.     try (BufferedReader in = new BufferedReader(new InputStreamReader(httpCon.getInputStream()))) {
  201.       jsonObj = (JSONObject) parser.parse(in);
  202.     } catch (ParseException e) {
  203.       throw new RuntimeException(e);
  204.     }
  205.     return new RequestResult(jsonObj, responseCode, httpCon.getResponseMessage(), null);
  206.   }
  207.  
  208.   private static final class RequestResult {
  209.  
  210.     private final JSONObject response;
  211.     private final int responseCode;
  212.     private final String responseMessage;
  213.     private final String error;
  214.  
  215.     private RequestResult(JSONObject response, int responseCode, String responseMessage,
  216.         String error) {
  217.       this.response = response;
  218.       this.responseCode = responseCode;
  219.       this.error = error;
  220.       this.responseMessage = responseMessage;
  221.     }
  222.   }
  223.  
  224.   public static final class BadResponseCodeException extends RuntimeException {
  225.  
  226.     private BadResponseCodeException(String message) {
  227.       super(message);
  228.     }
  229.   }
  230.  
  231.   public final class Media {
  232.  
  233.     private final String id;
  234.     private final String authorId;
  235.     private final boolean userLiked;
  236.     private final String url;
  237.     private final long likesCount;
  238.  
  239.     public Media(String id, String authorId, boolean userLiked, String url, long likesCount) {
  240.       this.id = id;
  241.       this.authorId = authorId;
  242.       this.userLiked = userLiked;
  243.       this.url = url;
  244.       this.likesCount = likesCount;
  245.     }
  246.  
  247.     public String getId() {
  248.       return id;
  249.     }
  250.  
  251.     public String getAuthorId() {
  252.       return authorId;
  253.     }
  254.  
  255.     public boolean isUserLiked() {
  256.       return userLiked;
  257.     }
  258.  
  259.     public String getUrl() {
  260.       return url;
  261.     }
  262.  
  263.     public long getLikesCount() {
  264.       return likesCount;
  265.     }
  266.  
  267.     @Override
  268.     public String toString() {
  269.       return "Media{" +
  270.           "id='" + id + '\'' +
  271.           ", authorId='" + authorId + '\'' +
  272.           ", userLiked=" + userLiked +
  273.           ", url='" + url + '\'' +
  274.           ", likesCount=" + likesCount +
  275.           '}';
  276.     }
  277.   }
  278.  
  279.   public final class User {
  280.  
  281.     private final String id;
  282.     private final String fullName;
  283.     private final String bio;
  284.     private final String website;
  285.     private final long mediaCount;
  286.     private final long followsCount;
  287.     private final long followersCount;
  288.  
  289.     public User(String id, String fullName, String bio, String website, long mediaCount,
  290.         long followsCount, long followersCount) {
  291.       this.id = id;
  292.       this.fullName = fullName;
  293.       this.bio = bio;
  294.       this.website = website;
  295.       this.mediaCount = mediaCount;
  296.       this.followsCount = followsCount;
  297.       this.followersCount = followersCount;
  298.     }
  299.  
  300.     public String getId() {
  301.       return id;
  302.     }
  303.  
  304.     public String getFullName() {
  305.       return fullName;
  306.     }
  307.  
  308.     public String getBio() {
  309.       return bio;
  310.     }
  311.  
  312.     public String getWebsite() {
  313.       return website;
  314.     }
  315.  
  316.     public long getMediaCount() {
  317.       return mediaCount;
  318.     }
  319.  
  320.     public long getFollowsCount() {
  321.       return followsCount;
  322.     }
  323.  
  324.     public long getFollowersCount() {
  325.       return followersCount;
  326.     }
  327.  
  328.     @Override
  329.     public String toString() {
  330.       return "User{" +
  331.           "id='" + id + '\'' +
  332.           ", fullName='" + fullName + '\'' +
  333.           ", bio='" + bio + '\'' +
  334.           ", website='" + website + '\'' +
  335.           ", mediaCount=" + mediaCount +
  336.           ", followsCount=" + followsCount +
  337.           ", followersCount=" + followersCount +
  338.           '}';
  339.     }
  340.   }
  341. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement