Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.example.igbot.api;
- import com.example.igbot.util.Sleeper;
- import org.apache.commons.io.IOUtils;
- import org.json.simple.JSONArray;
- import org.json.simple.JSONObject;
- import org.json.simple.parser.JSONParser;
- import org.json.simple.parser.ParseException;
- import java.io.BufferedReader;
- import java.io.DataOutputStream;
- import java.io.IOException;
- import java.io.InputStreamReader;
- import java.net.HttpURLConnection;
- import java.net.URL;
- import java.util.ArrayList;
- import java.util.List;
- public final class Instagram {
- private final String accessToken;
- public Instagram(String accessToken) {
- this.accessToken = accessToken;
- }
- public List<Media> recent(String tagName) throws IOException {
- if (tagName.contains("#") || tagName.contains(" ") || tagName.isEmpty()) {
- throw new AssertionError("Invalid tag: " + tagName);
- }
- JSONObject jsonObj = request("https://api.instagram.com/v1/tags/" + tagName
- + "/media/recent?access_token=" + accessToken, "GET", null);
- // JsonUtil.stdoutJson(jsonObj);
- JSONArray data = (JSONArray) jsonObj.get("data");
- final List<Media> out = new ArrayList<>(data.size());
- for (int i = 0; i < data.size(); i++) {
- JSONObject mediaJsonObject = (JSONObject) data.get(i);
- // if (i == 0) {
- // System.out.println("===");
- // JsonUtil.stdoutJson(mediaJsonObject);
- // System.out.println("===");
- // }
- JSONObject likes = (JSONObject) mediaJsonObject.get("likes");
- long likesCount = (long) likes.get("count");
- String id = (String) mediaJsonObject.get("id");
- JSONObject userObj = (JSONObject) mediaJsonObject.get("user");
- String userId = (String) userObj.get("id");
- boolean userHasLiked = (boolean) mediaJsonObject.get("user_has_liked");
- String link = (String) mediaJsonObject.get("link");
- Media m = new Media(id, userId, userHasLiked, link, likesCount);
- out.add(m);
- }
- return out;
- }
- public User userInfo(String userId) throws IOException {
- JSONObject response = request(
- "https://api.instagram.com/v1/users/" + userId + "/?access_token=" + accessToken,
- "GET", null);
- // System.out.println("userInfo out:");
- // JsonUtil.stdoutJson(response);
- JSONObject data = (JSONObject) response.get("data");
- String id = (String) data.get("id");
- String bio = (String) data.get("bio");
- String website = (String) data.get("website");
- String fullName = (String) data.get("full_name");
- JSONObject counts = (JSONObject) data.get("counts");
- long media = (long) counts.get("media");
- long follows = (long) counts.get("follows");
- long followedBy = (long) counts.get("followed_by");
- return new User(id, fullName, bio, website, media, follows, followedBy);
- }
- public void like(String mediaId) throws IOException {
- RequestResult result = request2("https://api.instagram.com/v1/media/" + mediaId + "/likes",
- "POST", "access_token=" + accessToken);
- if (result.responseCode != 200) {
- throw new BadResponseCodeException(
- "Non-200 response code: " + result.responseCode + ": " + result.responseMessage);
- }
- }
- /**
- * @return true if ok, false if media isn't liked
- */
- public boolean unlike(String mediaId) throws IOException {
- RequestResult result = request2("https://api.instagram.com/v1/media/" + mediaId +
- "/likes?access_token=" + accessToken, "DELETE", null);
- if (result.responseCode == 200) {
- return true;
- }
- if (result.responseCode == 400 &&
- result.error.contains("the user has not liked this media")) {
- System.out.println("Media " + mediaId + " hasn't been liked");
- return false;
- }
- System.err.println("Error: " + result.error);
- throw new BadResponseCodeException(
- "Non-200 response code: " + result.responseCode + ": " + result.responseMessage);
- }
- public void follow(String userId) throws IOException {
- RequestResult result = request2("https://api.instagram.com/v1/users/" + userId
- + "/relationship?access_token=" + accessToken, "POST", "action=follow");
- if (result.responseCode != 200) {
- throw new BadResponseCodeException(
- "Non-200 response code: " + result.responseCode + ": " + result.responseMessage);
- }
- }
- public List<String> selfFollow() throws IOException {
- final List<String> out = new ArrayList<>();
- String url = "https://api.instagram.com/v1/users/self/follows?access_token=" + accessToken;
- int page = 1;
- while (true) {
- System.out.println("Reading page " + page + " of self follows");
- JSONObject response = request(url, "GET", null);
- // System.out.println("selfFollow response:");
- // JsonUtil.stdoutJson(response);
- JSONArray data = (JSONArray) response.get("data");
- for (int i = 0; i < data.size(); i++) {
- JSONObject jsonObject = (JSONObject) data.get(i);
- String userId = (String) jsonObject.get("id");
- out.add(userId);
- }
- String nextUrl = null;
- JSONObject pagination = (JSONObject) response.get("pagination");
- if (pagination != null) {
- nextUrl = (String) pagination.get("next_url");
- }
- if (nextUrl == null) {
- break;
- }
- url = nextUrl;
- page++;
- Sleeper.sleepBetweenActions();
- }
- return out;
- }
- public void unfollow(String userId) throws IOException {
- RequestResult result = request2("https://api.instagram.com/v1/users/" + userId
- + "/relationship?access_token=" + accessToken, "POST", "action=unfollow");
- if (result.responseCode != 200) {
- throw new BadResponseCodeException(
- "Non-200 response code: " + result.responseCode + ": " + result.responseMessage);
- }
- }
- private static JSONObject request(String url, String method, String content) throws IOException {
- RequestResult result = request2(url, method, content);
- if (result.responseCode != 200) {
- System.err.println("Error: " + result.error);
- throw new IOException(
- "Non-200 response code: " + result.responseCode + ": " + result.responseMessage);
- }
- return result.response;
- }
- private static RequestResult request2(String url, String method, String content)
- throws IOException {
- final URL urlObject = new URL(url);
- final HttpURLConnection httpCon = (HttpURLConnection) urlObject.openConnection();
- httpCon.setDoOutput(true);
- httpCon.setRequestMethod(method);
- if (content != null) {
- DataOutputStream wr = new DataOutputStream(httpCon.getOutputStream());
- wr.writeBytes(content);
- wr.close();
- }
- final int responseCode = httpCon.getResponseCode();
- if (responseCode != 200) {
- String errorStreamContents = IOUtils.toString(httpCon.getErrorStream());
- return new RequestResult(null, responseCode, httpCon.getResponseMessage(),
- errorStreamContents);
- }
- JSONParser parser = new JSONParser();
- JSONObject jsonObj;
- try (BufferedReader in = new BufferedReader(new InputStreamReader(httpCon.getInputStream()))) {
- jsonObj = (JSONObject) parser.parse(in);
- } catch (ParseException e) {
- throw new RuntimeException(e);
- }
- return new RequestResult(jsonObj, responseCode, httpCon.getResponseMessage(), null);
- }
- private static final class RequestResult {
- private final JSONObject response;
- private final int responseCode;
- private final String responseMessage;
- private final String error;
- private RequestResult(JSONObject response, int responseCode, String responseMessage,
- String error) {
- this.response = response;
- this.responseCode = responseCode;
- this.error = error;
- this.responseMessage = responseMessage;
- }
- }
- public static final class BadResponseCodeException extends RuntimeException {
- private BadResponseCodeException(String message) {
- super(message);
- }
- }
- public final class Media {
- private final String id;
- private final String authorId;
- private final boolean userLiked;
- private final String url;
- private final long likesCount;
- public Media(String id, String authorId, boolean userLiked, String url, long likesCount) {
- this.id = id;
- this.authorId = authorId;
- this.userLiked = userLiked;
- this.url = url;
- this.likesCount = likesCount;
- }
- public String getId() {
- return id;
- }
- public String getAuthorId() {
- return authorId;
- }
- public boolean isUserLiked() {
- return userLiked;
- }
- public String getUrl() {
- return url;
- }
- public long getLikesCount() {
- return likesCount;
- }
- @Override
- public String toString() {
- return "Media{" +
- "id='" + id + '\'' +
- ", authorId='" + authorId + '\'' +
- ", userLiked=" + userLiked +
- ", url='" + url + '\'' +
- ", likesCount=" + likesCount +
- '}';
- }
- }
- public final class User {
- private final String id;
- private final String fullName;
- private final String bio;
- private final String website;
- private final long mediaCount;
- private final long followsCount;
- private final long followersCount;
- public User(String id, String fullName, String bio, String website, long mediaCount,
- long followsCount, long followersCount) {
- this.id = id;
- this.fullName = fullName;
- this.bio = bio;
- this.website = website;
- this.mediaCount = mediaCount;
- this.followsCount = followsCount;
- this.followersCount = followersCount;
- }
- public String getId() {
- return id;
- }
- public String getFullName() {
- return fullName;
- }
- public String getBio() {
- return bio;
- }
- public String getWebsite() {
- return website;
- }
- public long getMediaCount() {
- return mediaCount;
- }
- public long getFollowsCount() {
- return followsCount;
- }
- public long getFollowersCount() {
- return followersCount;
- }
- @Override
- public String toString() {
- return "User{" +
- "id='" + id + '\'' +
- ", fullName='" + fullName + '\'' +
- ", bio='" + bio + '\'' +
- ", website='" + website + '\'' +
- ", mediaCount=" + mediaCount +
- ", followsCount=" + followsCount +
- ", followersCount=" + followersCount +
- '}';
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement