All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.sola.instagram.InstagramSession Maven / Gradle / Ivy

package com.sola.instagram;

/*
 Copyright (c) 2012 Sola Ogunsakin

 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in all
 copies or substantial portions of the Software.

 The Software shall be used for Good, not Evil.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 SOFTWARE.
 */
import com.sola.instagram.auth.AccessToken;
import com.sola.instagram.exception.InstagramException;
import com.sola.instagram.io.DeleteMethod;
import com.sola.instagram.io.GetMethod;
import com.sola.instagram.io.PostMethod;
import com.sola.instagram.io.UriFactory;
import com.sola.instagram.model.*;
import com.sola.instagram.util.PaginatedCollection;
import com.sola.instagram.util.PaginationIterator;
import com.sola.instagram.util.UriConstructor;

import java.util.HashMap;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONArray;

/**
 * Constains a methods used to interact with the API.
 * 
 * @author Sola Ogunsakin
 * @version 2012-08-22
 */
public class InstagramSession {

	String accessToken;
	User currentUser;
	UriConstructor uriConstructor;
	HashMap> pageMap;
	String proxyAddress;
	int proxyPort;
	
	public InstagramSession() {}
	
	/**
	 * Creates a new Instagram session
	 * 
	 * @param accessToken
	 *            the session's access token
	 */
	public InstagramSession(AccessToken accessToken) {
		setAccessToken(accessToken.getTokenString());
		this.uriConstructor = new UriConstructor(getAccessToken());
	}
	
	/**
	 * Sets an HTTP proxy for api requests
	 * 
	 * @param address
	 *            ip address of the proxy
	 * @param port
	 *            port number of the proxy	            
	 */	
	public void setHttpProxy(String address, int port) {
		proxyAddress = address;
		proxyPort = port;
	}

	/**
	 * Removes the HTTP proxy config            
	 */	
	public void removeHttpProxy() {
		proxyAddress = null;
	}	
	
	public GetMethod makeGetMethod() {
		if(proxyAddress == null) {
			return new GetMethod();
		} else {
			return new GetMethod(proxyAddress, proxyPort);
		}
	}	

	public PostMethod makePostMethod() {
		if(proxyAddress == null) {
			return new PostMethod();
		} else {
			return new PostMethod(proxyAddress, proxyPort);
		}
	}		
	
	public DeleteMethod makeDeleteMethod() {
		if(proxyAddress == null) {
			return new DeleteMethod();
		} else {
			return new DeleteMethod(proxyAddress, proxyPort);
		}
	}	

	protected String getAccessToken() {
		return accessToken;
	}

	protected void setAccessToken(String accessToken) {
		this.accessToken = accessToken;
	}
	
	/**
	 * Finds and returns a user with the given id. Throws an InstagramException
	 * if none is found or the user with that id cannot be accessed
	 * 
	 * @param userId
	 *            id of the user
	 * @return The user with the id passed
	 */
	public User getUserById(int userId) throws Exception {
		HashMap map = new HashMap();
		map.put("user_id", userId);
		try {
			JSONObject userObject = (makeGetMethod()
					.setMethodURI(uriConstructor.constructUri(
							UriFactory.Users.GET_DATA, map, true))).call()
					.getJSON();
			if (userObject.has("data")) {
				return new User(userObject.getJSONObject("data"),
						getAccessToken());
			} else {
				throw new InstagramException("User with id = " + userId
						+ " cannot be accessed" + " or may not exist");
			}
		} catch (InstagramException e) {
			throw new InstagramException(
					"User with id = "
							+ userId
							+ " cannot be accessed"
							+ " or may not exist. This user may have deleted their account");
		}
	}

	/**
	 * Finds and returns the most recent media published by the user with the id
	 * passed. 
	 * 
	 * @param userId
	 *            id of the user
	 * @throws Exception,  JSONException
	 * @return List of recent media published by the user, within the page
	 *         number passed
	 */
	public PaginatedCollection getRecentPublishedMedia(int userId)
			throws Exception {
		HashMap map  = new HashMap();
		map.put("user_id", userId);
		String uriString = uriConstructor.constructUri(
				UriFactory.Users.GET_RECENT_MEDIA, map, true);
		ArrayList media = new ArrayList();		
		PaginationIterator iterator =  new PaginationIterator(media, uriString) {
			@Override
			public void handleLoad(JSONArray mediaItems) throws JSONException {
				for (int i = 0; i < mediaItems.length(); i++) {
					list.add(Media.fromJSON(mediaItems.getJSONObject(i),
							getAccessToken()));
				}					
			}
		};

		return new PaginatedCollection(media, iterator);
	}

	/**
	 * Gets the recent media in the current user's feed
	 * 
	 * @throws Exception,  JSONException
	 * @return List of recent media in the current user's feed
	 */
	public PaginatedCollection getFeed() throws Exception {	
		String uriString = uriConstructor.constructUri (
								UriFactory.Users.GET_FEED, null, true
						  );
		ArrayList media = new ArrayList();
		PaginationIterator iterator =  new PaginationIterator(media, uriString) {
			@Override
			public void handleLoad(JSONArray mediaItems) throws JSONException {
				for (int i = 0; i < mediaItems.length(); i++) {
					list.add(Media.fromJSON(mediaItems.getJSONObject(i),
							getAccessToken()));
				}					
			}
		};
		return new PaginatedCollection(media, iterator);
	}
	
	/**
	 * Gets the recent media that the current user has liked. 
	 * 
	 * @throws Exception,  JSONException
	 * @return List of recent media that the current user has liked
	 */
	public PaginatedCollection getLikedMedia() throws Exception {
		String uriString = uriConstructor.constructUri(
									UriFactory.Users.GET_LIKED_MEDIA, null, true);
		ArrayList media = new ArrayList();
		PaginationIterator iterator =  new PaginationIterator(media, uriString) {
			@Override
			public void handleLoad(JSONArray mediaItems) throws JSONException {
				for (int i = 0; i < mediaItems.length(); i++) {
					list.add(Media.fromJSON(mediaItems.getJSONObject(i),
							getAccessToken()));
				}					
			}
		};
		return new PaginatedCollection(media, iterator);		
	}

	/**
	 * Gets the media with the id passed. Throws an InstagramException if no
	 * media with that is is found.
	 * 
	 * @param mediaId
	 *            the id of the media to be returned
	 * @throws Exception,  JSONException
	 * @return The media with the id passed
	 */
	public Media getMedia(String mediaId) throws Exception {
		HashMap map = new HashMap();
		map.put("media_id", mediaId);
		JSONObject object = (makeGetMethod().setMethodURI(uriConstructor
				.constructUri(UriFactory.Media.GET_MEDIA, map, true)))
				.call().getJSON();
		return Media.fromJSON(object.getJSONObject("data"), getAccessToken());
	}

	/**
	 * Searches for media by location and creation time.
	 * 
	 * @param latitude
	 *            latitude of location
	 * @param longitude
	 *            longitude of location
	 * @param minTimestamp
	 *            the min timestamp of media to be returned. Can be null if
	 *            needed.
	 * @param maxTimestamp
	 *            the max timestamp of media to be returned. Can be null if
	 *            needed.
	 * @param distance
	 *            the of the location. Can be null if needed.
	 * @throws Exception,  JSONException
	 * @return List of recent media that meet the search parameters
	 */
	public List searchMedia(Object latitude, Object longitude,
			Object minTimestamp, Object maxTimestamp, Object distance)
			throws Exception {
		ArrayList media = new ArrayList();
		String uri = UriFactory.Media.SEARCH_MEDIA + "?access_token="
				+ getAccessToken() + "&lat=" + latitude + "&lng=" + longitude
				+ "&min_timestamp=" + minTimestamp + "&max_timestamp="
				+ maxTimestamp + "&distance=" + distance;
		JSONObject object = (makeGetMethod()
								.setMethodURI(uri)
							).call().getJSON();
		JSONArray mediaItems = object.getJSONArray("data");
		for (int i = 0; i < mediaItems.length(); i++) {
			media.add(Media.fromJSON(mediaItems.getJSONObject(i),
					getAccessToken()));
		}
		return media;
	}

	/**
	 * Finds and returns the most popular media on instagram.
	 * 
	 * @throws Exception,  JSONException
	 * @return List of the most popular media on instagram.
	 */
	public List getPopularMedia() throws Exception {
		JSONObject object = null; 
		ArrayList media = new ArrayList();
		String uriString = uriConstructor.constructUri(
				UriFactory.Media.GET_POPULAR_MEDIA, null, true);

		object = (makeGetMethod().setMethodURI(uriString)).call().getJSON();

		JSONArray mediaItems = object.getJSONArray("data");
		for (int i = 0; i < mediaItems.length(); i++) {
			media.add(Media.fromJSON(mediaItems.getJSONObject(i),
					getAccessToken()));
		}
		return media;
	}

	/**
	 * Searches for users by name.
	 * 
	 * @param name
	 *            the full name or username of the user to be returned
	 * @throws Exception,  JSONException
	 * @return List of users who match the search criteria
	 */
	public List searchUsersByName(String name) throws Exception {
		ArrayList users = new ArrayList();
		String uriString = uriConstructor.constructUri(
				UriFactory.Users.SEARCH_USER_BY_NAME, null, true)
				+ "&q="
				+ name;
		JSONArray userObjects = (makeGetMethod().setMethodURI(uriString))
				.call().getJSON().getJSONArray("data");
		for (int i = 0; i < userObjects.length(); i++) {
			users.add(new User(userObjects.getJSONObject(i),
					getAccessToken()));
		}
		return users;
	}

	/**
	 * Gets a list of users that the user, whose id is passed, follows. 
	 * 
	 * @param userId
	 *            id of the user whose follow list is to be returned
	 * @throws Exception,  JSONException
	 * @return List of users by page, that the user, whose id is passed,
	 *         follows.
	 */
	public PaginatedCollection getFollows(int userId)
			throws Exception {
		HashMap map = new HashMap();
		map.put("user_id", userId);
		String uriString = uriConstructor.constructUri(
				UriFactory.Relationships.GET_FOLLOWS, map, true);
		ArrayList users = new ArrayList();
		PaginationIterator iterator =  new PaginationIterator(users, uriString) {
			@Override
			public void handleLoad(JSONArray userObjects) throws JSONException {
				for (int i = 0; i < userObjects.length(); i++) {
					list.add(new User(userObjects.getJSONObject(i),
							getAccessToken()));
				}				
			}
		};
		return new PaginatedCollection(users, iterator);		
	}

	public PaginatedCollection getFollowers(int userId) throws Exception {
		HashMap map = new HashMap();
		map.put("user_id", userId);
		String uriString = uriConstructor.constructUri(
				UriFactory.Relationships.GET_FOLLOWERS, map, true);
		ArrayList users = new ArrayList();
		PaginationIterator iterator =  new PaginationIterator(users, uriString) {
			@Override
			public void handleLoad(JSONArray userObjects) throws JSONException {
				for (int i = 0; i < userObjects.length(); i++) {
					list.add(new User(userObjects.getJSONObject(i),
							getAccessToken()));
				}				
			}
		};
		return new PaginatedCollection(users, iterator);
	}

	public List getFollowRequests() throws Exception,  JSONException,
				JSONException {
		JSONObject object = null;
		ArrayList users = new ArrayList();
		String uriString = uriConstructor.constructUri(
				UriFactory.Relationships.GET_FOLLOW_REQUESTS, null, true);

		object = (makeGetMethod().setMethodURI(uriString)).call().getJSON();

		JSONArray userObjects;
		userObjects = object.getJSONArray("data");
		for (int i = 0; i < userObjects.length(); i++) {
			users.add(new User(userObjects.getJSONObject(i),
					getAccessToken()));
		}
		return users;
	}

	public Relationship getRelationshipWith(int userId)
			throws Exception {
		JSONObject object = null;
		HashMap map = new HashMap();
		map.put("user_id", userId);
		String uriString = uriConstructor.constructUri(
				UriFactory.Relationships.GET_RELATIONSHIP_STATUS, map, true);

		object = (makeGetMethod().setMethodURI(uriString)).call().getJSON();

		return new Relationship(object.getJSONObject("data"),
				getAccessToken());
	}

	public boolean modifyRelationship(int userId, Relationship.Action action)
			throws Exception {
		String actionString = "";
		JSONObject object = null;
		HashMap map = new HashMap();
		map.put("user_id", userId);
		HashMap args = new HashMap();

		switch (action) {
		case BLOCK:
			actionString = "block";
			break;
		case UNBLOCK:
			actionString = "unblock";
			break;
		case APPROVE:
			actionString = "approve";
			break;
		case DENY:
			actionString = "deny";
			break;
		case FOLLOW:
			actionString = "follow";
			break;
		case UNFOLLOW:
			actionString = "unfollow";
			break;
		}

		args.put("action", actionString);
		String uriString = uriConstructor.constructUri(
				UriFactory.Relationships.MUTATE_RELATIONSHIP, map, true);
		object = (makePostMethod().setPostParameters(args)
				.setMethodURI(uriString)).call().getJSON();
	
		return object.getJSONObject("meta").getInt("code") == 200;
	}

	public Comment postComment(String mediaId, String text)
			throws Exception {
		JSONObject object = null;
		HashMap map = new HashMap();
		map.put("media_id", mediaId);
		HashMap args = new HashMap();
		args.put("text", text);
		args.put("access_token", getAccessToken());
		String uriString = uriConstructor.constructUri(
				UriFactory.Comments.POST_MEDIA_COMMENT, map, false);
		object = (makePostMethod().setPostParameters(args)
				.setMethodURI(uriString)).call().getJSON();
		return new Comment(object.getJSONObject("data"), getAccessToken());
	}

	public boolean removeComment(String mediaId, String commentId)
			throws Exception {
		JSONObject object = null;
		HashMap map = new HashMap();
		map.put("media_id", mediaId);
		map.put("comment_id", commentId);
		String uriString = uriConstructor.constructUri(
				UriFactory.Comments.DELETE_MEDIA_COMMENT, map, true);
		object = (makeDeleteMethod()
					.setMethodURI(uriString)
				).call().getJSON();

		return object.getJSONObject("meta").getInt("code") == 200;
	}

	public boolean likeMedia(String mediaId) throws Exception,  JSONException {
		JSONObject object = null;
		HashMap map = new HashMap();
		map.put("media_id", mediaId);
		HashMap args = new HashMap();
		args.put("access_token", getAccessToken());
		String uriString = uriConstructor.constructUri(
				UriFactory.Likes.SET_LIKE, map, false);
		object = (makePostMethod().setPostParameters(args)
				.setMethodURI(uriString)).call().getJSON();
		return object.getJSONObject("meta").getInt("code") == 200;
	}

	public boolean removeMediaLike(String mediaId) 
			throws Exception {
		JSONObject object = null;
		HashMap map = new HashMap();
		map.put("media_id", mediaId);
		String uriString = uriConstructor.constructUri(
				UriFactory.Likes.REMOVE_LIKE, map, true);
		object = (makeDeleteMethod().setMethodURI(uriString)).call().getJSON();
		return object.getJSONObject("meta").getInt("code") == 200;
	}

	public Tag getTag(String tagName) 
			throws Exception {
		JSONObject object = null;
		HashMap map = new HashMap();
		map.put("tag_name", tagName);
		String uriString = uriConstructor.constructUri(UriFactory.Tags.GET_TAG,
				map, true);
		object = (makeGetMethod().setMethodURI(uriString)).call().getJSON();
		return new Tag(object.getJSONObject("data"), getAccessToken());
	}

	public PaginatedCollection getRecentMediaForTag(String tagName)
			throws Exception {
		HashMap map = new HashMap();
		map.put("tag_name", tagName);
		String uriString = uriConstructor.constructUri(
				UriFactory.Tags.GET_RECENT_TAGED_MEDIA, map, true);
		ArrayList media = new ArrayList();
		PaginationIterator iterator =  new PaginationIterator(media, uriString) {
			@Override
			public void handleLoad(JSONArray mediaItems) throws JSONException {
				for (int i = 0; i < mediaItems.length(); i++) {
					list.add(Media.fromJSON(mediaItems.getJSONObject(i),
							getAccessToken()));
				}					
			}
		};
		return new PaginatedCollection(media, iterator);
	}

	public List searchTags(String tagName) throws Exception {
		JSONObject object = null;
		String uriString = uriConstructor.constructUri(
				UriFactory.Tags.SEARCH_TAGS, null, true) + "&q=" + tagName;
		object = (makeGetMethod().setMethodURI(uriString)).call().getJSON();
		ArrayList tags = new ArrayList();
		JSONArray tagItems = object.getJSONArray("data");
		for (int i = 0; i < tagItems.length(); i++) {
			tags.add(new Tag(tagItems.getJSONObject(i), getAccessToken()));
		}
		return tags;
	}

	public Location getLocation(int locationId) throws Exception {
		JSONObject object = null;
		HashMap map = new HashMap();
		map.put("location_id", locationId);
		String uriString = uriConstructor.constructUri(
				UriFactory.Locations.GET_LOCATION, map, true);
		object = (makeGetMethod().setMethodURI(uriString)).call().getJSON();
		return new Location(object.getJSONObject("data"), getAccessToken());
	}

	public PaginatedCollection getRecentMediaFromLocation(int locationId)
			throws Exception {
		HashMap map = new HashMap();
		map.put("location_id", locationId);
		String uriString = uriConstructor.constructUri(
				UriFactory.Locations.GET_MEDIA_FROM_LOCATION, map, true);
		ArrayList media = new ArrayList();
		PaginationIterator iterator =  new PaginationIterator(media, uriString) {
			@Override
			public void handleLoad(JSONArray mediaItems) throws JSONException {
				for (int i = 0; i < mediaItems.length(); i++) {
					list.add(Media.fromJSON(mediaItems.getJSONObject(i),
							getAccessToken()));
				}					
			}
		};
		return new PaginatedCollection(media, iterator);
	}
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy