Example #1
0
def _handle_instagram(url):
    """http*://instagram.com/p/*"""
    from instagram.client import InstagramAPI

    CLIENT_ID = '879b81dc0ff74f179f5148ca5752e8ce'

    api = InstagramAPI(client_id=CLIENT_ID)

    # todo: instagr.am
    m = re.search('instagram\.com/p/([^/]+)', url)
    if not m:
        return

    shortcode = m.group(1)

    r = bot.get_url("http://api.instagram.com/oembed?url=http://instagram.com/p/%s/" % shortcode)

    media = api.media(r.json()['media_id'])

    print(media)

    # media type video/image?
    # age/date? -> media.created_time  # (datetime object)

    # full name = username for some users, don't bother displaying both
    if media.user.full_name.lower() != media.user.username.lower():
        user = "******" % (media.user.full_name, media.user.username)
    else:
        user = media.user.full_name

    if media.caption:
        return "%s: %s [%d likes, %d comments]" % (user, media.caption.text, media.like_count, media.comment_count)
    else:
        return "%s [%d likes, %d comments]" % (user, media.like_count, media.comment_count)
Example #2
0
def get_insta_user(short_link, debug=1):
    """ Get instagram userid from a link posted on twitter """
    print "Fetching instagram user. "
    try:
        response = urllib2.urlopen(
            short_link)  # Some shortened url, eg: http://t.co/z8P2xNzT8k
        url_destination_https = response.url
        url_destination = url_destination_https.replace('https', 'http', 1)

        # from link get the media_id
        consumer = oembed.OEmbedConsumer()
        endpoint = oembed.OEmbedEndpoint(
            'https://api.instagram.com/oembed?url=', ['http://instagr.am/p/*'])
        consumer.addEndpoint(endpoint)
        media_id_code = re.split('/', url_destination)[-2]
        url_destination = 'http://instagr.am/p/' + media_id_code
        response = consumer.embed(url_destination)
        media_id = response['media_id']

        api = InstagramAPI(client_id=iconf.client_id,
                           client_secret=iconf.client_secret)
    except:
        if debug:
            print 'Unable to find picture from link.'
        return 'null'

    try:
        media = api.media(media_id)
        return [media.user.id, media.user.username]
    except:
        if debug:
            print 'Unable to fetch instagram ID - most likely private user'
        return 'null'
Example #3
0
def _handle_instagram(url):
    """http*://instagram.com/p/*"""
    from instagram.client import InstagramAPI

    CLIENT_ID = '879b81dc0ff74f179f5148ca5752e8ce'

    api = InstagramAPI(client_id=CLIENT_ID)

    # todo: instagr.am
    m = re.search('instagram\.com/p/([^/]+)', url)
    if not m:
        return

    shortcode = m.group(1)

    r = bot.get_url("http://api.instagram.com/oembed?url=http://instagram.com/p/%s/" % shortcode)

    media = api.media(r.json()['media_id'])

    print(media)

    # media type video/image?
    # age/date? -> media.created_time  # (datetime object)

    # full name = username for some users, don't bother displaying both
    if media.user.full_name.lower() != media.user.username.lower():
        user = "******" % (media.user.full_name, media.user.username)
    else:
        user = media.user.full_name

    if media.caption:
        return "%s: %s [%d likes, %d comments]" % (user, media.caption.text, media.like_count, media.comment_count)
    else:
        return "%s [%d likes, %d comments]" % (user, media.like_count, media.comment_count)
Example #4
0
def get_media_from_id(media_id, access_token):

	authed_api = InstagramAPI(access_token=access_token)

	media = authed_api.media(media_id)

	return media
Example #5
0
 def _augment_data(self):
     """ Populates any missing fields via api(media_id) """
     api = InstagramAPI(access_token=self._access_token)
     for i in self._instagrams_list:
         if not 'img_url' in i or not 'link_url' in i or not 'main_color' in i:
             # Only do actual api query if we are missing something (ex: new entries)
             media = api.media(i['media_id'])
             i['title'] = media.caption.text if media.caption else ""
             i['img_url'] = media.images['standard_resolution'].url
             i['link_url'] = media.link
             i['main_color'] = palette(url=i['img_url'], n=1)[0] # First in palette
             print "Loaded new media: '%s' (title: '%s')" % (i['media_id'], i['title'])
Example #6
0
def polaroid(request, media='382136859166585123_236683403'):

	if not request.session.get('token'):
		return redirect('totem.views.auth')
	token = request.session.get('token')
	output = {}

	api = InstagramAPI(access_token=token)
	media = api.media(media_id=media)

	output['media'] = media
	
	return render_to_response('totem/polaroid.html', output, context_instance=RequestContext(request))
Example #7
0
def _handle_instagram(url):
    """http*://*instagram.com/p/*"""
    from instagram.client import InstagramAPI

    CLIENT_ID = '879b81dc0ff74f179f5148ca5752e8ce'

    api = InstagramAPI(client_id=CLIENT_ID)

    # todo: instagr.am
    m = re.search(r"instagram\.com/p/([^/]+)", url)
    if not m:
        return

    shortcode = m.group(1)

    r = bot.get_url("http://api.instagram.com/oembed?url=http://instagram.com/p/%s/" % shortcode)

    media = api.media(r.json()['media_id'])

    # media type video/image?
    # age/date? -> media.created_time  # (datetime object)

    # full name = username for some users, don't bother displaying both
    if media.user.full_name.lower() != media.user.username.lower():
        user = "******" % (media.user.full_name, media.user.username)
    else:
        user = media.user.full_name

    if media.like_count or media.comment_count:
        info = "["
        if media.like_count:
            info += "%d ♥" % media.like_count
        if media.comment_count:
            info += ", %d comments" % media.comment_count
        info += "]"
    else:
        info = ""

    if media.caption:
        if len(media.caption.text) > 145:
            caption = "{0:.145}…".format(media.caption.text)
        else:
            caption = media.caption.text

        return "%s: %s %s" % (user, caption, info)
    else:
        return "%s: %s" % (user, info)
Example #8
0
def get_insta_user(short_link, debug=1):
	""" Get instagram userid from a link posted on twitter """
	print " Fetching instagram user "
	try:
		print short_link
		response = urllib2.urlopen(short_link) # Some shortened url, eg: http://t.co/z8P2xNzT8k
		#print response.__dict__
		url_destination_https = response.url
		url_destination = url_destination_https.replace('https','http',1)

		# from link get the media_id
		consumer = oembed.OEmbedConsumer()
		endpoint = oembed.OEmbedEndpoint('https://api.instagram.com/oembed?url=', ['http://instagr.am/p/*'])
		consumer.addEndpoint(endpoint)
		print url_destination
		media_id_code = re.split('/',url_destination)[-2]
		print media_id_code
		url_destination = 'http://instagr.am/p/'+media_id_code
		response = consumer.embed(url_destination)
		print response
		media_id = response['media_id']
		print 'media id'
		print media_id
		print response
		#https://api.instagram.com/oembed/?url=http://instagram.com/p/bNd86MSFv6/&beta=true

		api = InstagramAPI(client_id='d09ed38ad8f14bd7bc7fdf6e7ebd9340', client_secret='0de686fbad2543968159c573f33e9409')
	except:
			if debug:
				print 'Unable to find picture from link.'
			return 'null'

	try:
		media = api.media(media_id)
		#if debug:
		print media.user.id
		return [media.user.id, media.user.username]
	except:
		if debug:
			print 'Unable to fetch instagram ID - most likely private user'
		return 'null'
Example #9
0
			recent_media, next=api.tag_recent_media(tag_name=tagname, max_id=max_tag_id, count=media_crawl)
		time.sleep(d*random.random()+1)
	except Exception as er:
			err(er)
			fails=maxfails+1
			break
	calls=calls+1
	random.seed()

	m_obj=re.search(r".+max_tag_id=(.+)", next)
	if m_obj:
		max_tag_id=m_obj.group(1) 

	for media in recent_media:
		try:
	    		mediainfo=api.media(media.id)
			calls=calls+1
			time.sleep(d*random.random()+1)
		except Exception as er:
			err(er)
			continue
			print "media error"
			print media.id
			fails=fails+1
		if not(mediainfo.user.username in usernames):
			usernames.add(mediainfo.user.username)
		    	users.add(mediainfo.user)
			print mediainfo.user
		crawled=crawled+1

i=0
Example #10
0
class provider(basicProvider):
    ''' This class is used to:
        1. Make the connection to the Instagram API
        2. Get user's Photos
        3. Get OPENi album Photos
        4. Post Photos to OPENi album
    '''
    def __init__(self, access_token):
        ''' Initiate the connector '''
        self.connector = InstagramAPI(access_token=access_token)

    #   region Media API
    #   As described here: http://redmine.openi-ict.eu/projects/openi/wiki/Media_API

    #   region Photo Object
    #   As described here: http://redmine.openi-ict.eu/projects/openi/wiki/Photo_Mapping

    def get_a_photo(self, data):
        ''' GET API_PATH/[PHOTO_ID] '''
        # /media/media-id (ie media/628147512937366504_917877895)
        print data['media_id']
        raw_data = self.connector.media(data['media_id'])
        print raw_data
        response = {
            'meta': {
                'total_count': 1,
                'next': None
            },
            'data': [
                self.format_photo_response(
                    raw_data.id, self.check_if_exists(raw_data, 'type',
                                                      'image'), 'openi',
                    raw_data.link, raw_data.user.id, raw_data.user.username,
                    raw_data.user.website, raw_data.caption.text,
                    raw_data.link, self.defJsonRes,
                    self.check_if_exists(raw_data, 'location'),
                    raw_data.created_time, self.defJsonRes,
                    self.check_if_exists(raw_data, 'tags'), self.defJsonRes,
                    self.defJsonRes)
            ]
        }
        return response

    def get_all_photos_for_account(self, data):
        ''' GET API_PATH/[ACCOUNT_ID]/photos '''
        # /users/user-id (ie users/917877895)
        raw_datas, next = self.connector.user_recent_media(data['account_id'])
        print raw_datas
        response = {
            'meta': {
                'total_count': len(raw_datas),
                'next': next
            },
            'data': []
        }
        for raw_data in raw_datas:
            response['data'].append(
                self.format_photo_response(
                    raw_data.id, self.check_if_exists(raw_data, 'type',
                                                      'image'), 'openi',
                    raw_data.link, raw_data.user.id, raw_data.user.username,
                    raw_data.user.website, raw_data.caption.text,
                    raw_data.link, self.defJsonRes,
                    self.check_if_exists(raw_data, 'location'),
                    raw_data.created_time, self.defJsonRes,
                    self.check_if_exists(raw_data, 'tags'), self.defJsonRes,
                    self.defJsonRes))
        return response

    #   region Connections

    def get_photo_comments(self, data):
        ''' GET API_PATH/[PHOTO_ID]/comments '''
        # /media/media-id/comments (ie media/628147512937366504_917877895/comments)
        raw_datas = self.connector.media_comments(data['media_id'])
        response = {
            'meta': {
                'total_count': len(raw_datas['data'])
            },
            'data': []
        }
        for raw_data in raw_datas['data']:
            response['data'].append(
                self.format_comment_response(
                    raw_data['id'], 'Photo Comment', 'openi', defJsonRes,
                    raw_data['from']['id'], raw_data['from']['username'],
                    defJsonRes, raw_data['created_time'], defJsonRes,
                    defJsonRes, raw_data['text'], defJsonRes))
        return response

    def post_comment(self, data):
        ''' POST API_PATH/[PHOTO_ID]/comments '''
        # /media/media-id/comments (ie media/628147512937366504_917877895/comments)
        # 'error_message': 'Please visit http://bit.ly/instacomments for commenting access' Please email apidevelopers[at]instagram.com for access.
        return defaultMethodResponse

    def delete_comment(self, data):
        ''' DELETE API_PATH/[COMMENT_ID] '''
        # /media/media-id/comments/comment-id (ie media/628147512937366504_917877895/comments/628902539272471262)
        response = self.connector.delete_comment(data['media_id'],
                                                 data['comment_id'])
        return response

    def like_a_photo(self, data):
        ''' POST API_PATH/[PHOTO_ID]/likes '''
        # /media/media-id/likes (ie media/628147512937366504_917877895/likes)
        response = self.connector.like_media(data['media_id'])
        return response

    def get_photo_likes(self, data):
        ''' GET API_PATH/[PHOTO_ID]/likes '''
        # /media/media-id/likes (ie media/628147512937366504_917877895/likes)
        raw_datas = self.connector.media_likes(data['media_id'])
        response = {
            'meta': {
                'total_count': len(raw_datas['data'])
            },
            'data': []
        }
        for raw_data in raw_datas['data']:
            response['data'].append(
                self.format_comment_response(
                    defJsonRes,  #id
                    'Photo Like',  #obj_type
                    'openi',  #service
                    defJsonRes,  #url
                    raw_data['id'],  #from:id
                    raw_data['username'],  #from:username
                    defJsonRes,  #from:url
                    defJsonRes,  #time:created_time
                    defJsonRes,  #time:edited_time
                    defJsonRes  #target_id
                ))
        return 'Not supported by this service'

    def unlike_photo(self, data):
        ''' DELETE API_PATH/[PHOTO_ID]/likes '''
        # /media/media-id/likes (ie media/628147512937366504_917877895/likes)
        response = self.connector.unlike_media(data['media_id'])
        return response
class Instagram:
    def __init__(self):
        self.api = InstagramAPI(client_id=CLIENT_ID, client_secret=CLIENT_SECRET, redirect_uri=REDIRECT_URI)

    def set_access_token(self, access_token):
        self.api = InstagramAPI(access_token=access_token)

    def media_popular(self, **params):
        popular = memcache.get("popular_feed")
        if not popular:
            popular = self.api.media_popular(count=params["count"], max_id=params["max_id"])
            memcache.add("popular_feed", popular, 300)
        return popular

    def user_media_feed(self, **params):
        user_id = params["user_id"]
        max_id = params["max_id"]
        count = params["count"]

        feed = memcache.get("user_media_feed_%s_%s" % (user_id, max_id))
        if not feed:
            feed = self.api.user_media_feed(count=count, max_id=max_id)
            memcache.add("user_media_feed_%s_%s" % (user_id, max_id), feed, 300)
        return feed

    def user_liked_feed(self, **params):
        user_id = params["user_id"]
        max_id = params["max_id"]
        count = params["count"]
        feed = memcache.get("user_liked_feed_%s_%s" % (user_id, max_id))
        if not feed:
            feed = self.api.user_liked_feed(count=count, max_like_id=max_id)
            memcache.add("user_liked_feed_%s_%s" % (user_id, max_id), feed, 300)
        return feed

    def user(self, user_id):
        user = memcache.get("user_%s" % (user_id))
        if not user:
            user = self.api.user(user_id)
            user["full_name"] = escape(user["full_name"].encode("utf-8"))
            user["full_name"] = self._convert_emoji(user["full_name"])
            memcache.add("user_%s" % (user_id), user, 300)
        return user

    def media(self, media_id):
        media = memcache.get("media_%s" % media_id)
        if not media:
            media = self.api.media(media_id)
            media.user["full_name"] = escape(media.user["full_name"].encode("utf-8"))
            media.user["full_name"] = self._convert_emoji(media.user["full_name"])
            if media.caption:
                media.caption["text_original"] = media.caption["text"]
                media.caption["text"] = escape(media.caption["text"].encode("utf-8"))
                media.caption["text"] = self._convert_emoji(media.caption["text"])
                media.caption["text"] = self._convert_tag_to_link(media.caption["text"])
            memcache.add("media_%s" % media_id, media, 300)
        return media

    def media_comments(self, media_id):
        comments = memcache.get("media_comments_%s" % (media_id))
        if not comments:
            converter = emoji.factory("softbank", "utf-8")
            converter.prefix = '<span class="emoji emoji_'
            converter.suffix = '"></span>'
            comments = self.api.media_comments(media_id)
            for comment in comments:
                comment["text"] = escape(comment["text"].encode("utf-8"))
                comment["text"] = self._convert_emoji(comment["text"])
                comment["text"] = self._convert_tag_to_link(comment["text"])
            memcache.add("media_comments_%s" % (media_id), comments, 300)
        return comments

    def media_likes(self, media_id):
        likes = memcache.get("media_likes_%s" % (media_id))
        if not likes:
            likes = self.api.media_likes(media_id)
            memcache.add("media_likes_%s" % (media_id), likes, 300)
        return likes

    def user_recent_media(self, **params):
        user_id = params["user_id"]
        max_id = params["max_id"]
        feed = memcache.get("user_recent_media_%s_%s" % (user_id, max_id))
        if not feed:
            feed = self.api.user_recent_media(user_id=user_id, max_id=max_id)
            memcache.add("user_recent_media_%s_%s" % (user_id, max_id), feed, 300)
        return feed

    def user_follows(self, **params):
        user_id = params["user_id"]
        count = params["count"]
        cursor = params["cursor"]
        follows = memcache.get("user_follows_%s_%s_%s" % (user_id, count, cursor))
        if not follows:
            follows = self.api.user_follows(user_id=user_id, count=count, cursor=cursor)
            for user in follows[0]:
                user["full_name"] = escape(user["full_name"].encode("utf-8"))
                user["full_name"] = self._convert_emoji(user["full_name"])
            memcache.add("user_follows_%s_%s_%s" % (user_id, count, cursor), follows, 300)
        return follows

    def user_followed_by(self, **params):
        user_id = params["user_id"]
        count = params["count"]
        cursor = params["cursor"]
        follows = memcache.get("user_followed_by_%s_%s_%s" % (user_id, count, cursor))
        if not follows:
            follows = self.api.user_followed_by(user_id=user_id, count=count, cursor=cursor)
            for user in follows[0]:
                user["full_name"] = escape(user["full_name"].encode("utf-8"))
                user["full_name"] = self._convert_emoji(user["full_name"])
            memcache.add("user_followed_by_%s_%s_%s" % (user_id, count, cursor), follows, 300)
        return follows

    def like_media(self, **params):
        user_id = params["user_id"]
        media_id = params["media_id"]
        max_id = params["max_id"]

        self.api.like_media(media_id)
        memcache.add("user_has_liked_%s_%s" % (user_id, media_id), True, 300)
        memcache.delete("media_likes_%s" % (media_id))

    def unlike_media(self, **params):
        user_id = params["user_id"]
        media_id = params["media_id"]
        max_id = params["max_id"]

        self.api.unlike_media(media_id)
        memcache.delete("user_has_liked_%s_%s" % (user_id, media_id))
        memcache.delete("media_likes_%s" % (media_id))

    def create_media_comment(self, **params):
        media_id = params["media_id"]
        text = params["text"]
        self.api.create_media_comment(media_id=media_id, text=text)
        memcache.delete("media_%s" % media_id)
        memcache.delete("media_comments_%s" % media_id)

    def user_find_by_username(self, username):
        user = memcache.get("user_find_by_username_%s" % (username))

        if not user:
            users = self.api.user_search(q=username, count=None)
            for u in users:
                if username == u["username"]:
                    user = u
                    memcache.add("user_find_by_username_%s" % (username), user)

        return user

    def tag_recent_media(self, **params):
        tag_name = params["tag_name"]
        count = params["count"]
        max_id = params["max_id"]

        feed = memcache.get("tag_recent_media_%s_%s" % (tag_name, max_id))

        if not feed:
            feed = self.api.tag_recent_media(tag_name=tag_name, count=count, max_id=max_id)
            memcache.add("tag_recent_media_%s_%s" % (tag_name, max_id), feed, 300)

        return feed

    def get_authorize_login_url(self, **params):
        uri = memcache.get("authorize_login_uri")
        if not uri:
            uri = self.api.get_authorize_login_url(scope=params["scope"])
            memcache.add("authorize_login_uri", uri, 300)
        return uri

    def _convert_emoji(self, text):
        converter = emoji.factory("softbank", "utf-8")
        converter.prefix = '<span class="emoji emoji_'
        converter.suffix = '"></span>'
        text = converter.convert(text)
        return text

    def _convert_tag_to_link(self, text):
        text = re.sub(r"#([a-zA-Z0-9\-]+)", '<a href="/tag/\g<1>">#\g<1></a>', text)
        return text

    def relationship(self, **params):
        owner_id = params["owner_id"]
        my_id = params["my_id"]

        relationship = memcache.get("relationship_%s_%s" % (my_id, owner_id))
        if not relationship:
            relationship = self.api.relationship(owner_id)
            memcache.add("relationship_%s_%s" % (my_id, owner_id), relationship, 300)

        return relationship

    def follow_user(self, **params):
        owner_id = params["owner_id"]
        my_id = params["my_id"]

        relationship = self.api.follow_user(user_id=owner_id)
        memcache.delete("relationship_%s_%s" % (my_id, owner_id))
        return relationship

    def unfollow_user(self, **params):
        owner_id = params["owner_id"]
        my_id = params["my_id"]

        relationship = self.api.unfollow_user(user_id=owner_id)
        memcache.delete("relationship_%s_%s" % (my_id, owner_id))
        return relationship
Example #12
0
class provider(basicProvider):
    ''' This class is used to:
        1. Make the connection to the Instagram API
        2. Get user's Photos
        3. Get OPENi album Photos
        4. Post Photos to OPENi album
    '''
    def __init__(self, access_token):
        ''' Initiate the connector '''
        self.connector = InstagramAPI(access_token=access_token)
    
    #   region Media API
    #   As described here: http://redmine.openi-ict.eu/projects/openi/wiki/Media_API
    
    #   region Photo Object
    #   As described here: http://redmine.openi-ict.eu/projects/openi/wiki/Photo_Mapping
    
    def get_a_photo(self, data):
        ''' GET API_PATH/[PHOTO_ID] '''
        # /media/media-id (ie media/628147512937366504_917877895)
        print data['media_id']
        raw_data = self.connector.media(data['media_id'])
        print raw_data
        response = {
                    'meta':
                        {
                         'total_count': 1,
                         'next': None
                        },
                    'data': [self.format_photo_response(
                                        raw_data.id,
                                        self.check_if_exists(raw_data, 'type', 'image'),
                                        'openi',
                                        raw_data.link,
                                        raw_data.user.id,
                                        raw_data.user.username,
                                        raw_data.user.website,
                                        raw_data.caption.text,
                                        raw_data.link,
                                        self.defJsonRes,
                                        self.check_if_exists(raw_data, 'location'),
                                        raw_data.created_time,
                                        self.defJsonRes,
                                        self.check_if_exists(raw_data, 'tags'),
                                        self.defJsonRes,
                                        self.defJsonRes
                                        )]
                    }
        return response

    def get_all_photos_for_account(self, data):
        ''' GET API_PATH/[ACCOUNT_ID]/photos '''
        # /users/user-id (ie users/917877895)
        raw_datas, next = self.connector.user_recent_media(data['account_id'])
        print raw_datas
        response = {
                    'meta': 
                        {
                        'total_count': len(raw_datas),
                        'next': next
                        },
                    'data' : [] }
        for raw_data in raw_datas:
            response['data'].append(self.format_photo_response(
                                         raw_data.id,
                                         self.check_if_exists(raw_data, 'type', 'image'),
                                         'openi',
                                         raw_data.link,
                                         raw_data.user.id,
                                         raw_data.user.username,
                                         raw_data.user.website,
                                         raw_data.caption.text,
                                         raw_data.link,
                                         self.defJsonRes,
                                         self.check_if_exists(raw_data, 'location'),
                                         raw_data.created_time,
                                         self.defJsonRes,
                                         self.check_if_exists(raw_data, 'tags'),
                                         self.defJsonRes,
                                         self.defJsonRes
                                         ))
        return response

    #   region Connections

    def get_photo_comments(self, data):
        ''' GET API_PATH/[PHOTO_ID]/comments '''
        # /media/media-id/comments (ie media/628147512937366504_917877895/comments)
        raw_datas = self.connector.media_comments(data['media_id'])
        response = {
                    'meta': 
                        {
                        'total_count': len(raw_datas['data'])
                        },
                    'data' : [] }
        for raw_data in raw_datas['data']:
            response['data'].append(self.format_comment_response(
                                         raw_data['id'],
                                         'Photo Comment',
                                         'openi',
                                         defJsonRes,
                                         raw_data['from']['id'],
                                         raw_data['from']['username'],
                                         defJsonRes,
                                         raw_data['created_time'],
                                         defJsonRes,
                                         defJsonRes,
                                         raw_data['text'],
                                         defJsonRes
                                         ))
        return response

    def post_comment(self, data):
        ''' POST API_PATH/[PHOTO_ID]/comments '''
        # /media/media-id/comments (ie media/628147512937366504_917877895/comments)
        # 'error_message': 'Please visit http://bit.ly/instacomments for commenting access' Please email apidevelopers[at]instagram.com for access.
        return defaultMethodResponse

    def delete_comment(self, data):
        ''' DELETE API_PATH/[COMMENT_ID] '''
        # /media/media-id/comments/comment-id (ie media/628147512937366504_917877895/comments/628902539272471262)
        response = self.connector.delete_comment(data['media_id'], data['comment_id'])
        return response

    def like_a_photo(self, data):
        ''' POST API_PATH/[PHOTO_ID]/likes '''
        # /media/media-id/likes (ie media/628147512937366504_917877895/likes)
        response = self.connector.like_media(data['media_id'])
        return response

    def get_photo_likes(self, data):
        ''' GET API_PATH/[PHOTO_ID]/likes '''
        # /media/media-id/likes (ie media/628147512937366504_917877895/likes)
        raw_datas = self.connector.media_likes(data['media_id'])
        response = {
                    'meta': 
                        {
                        'total_count': len(raw_datas['data'])
                        },
                    'data' : [] }
        for raw_data in raw_datas['data']:
            response['data'].append(self.format_comment_response(
                                         defJsonRes,#id
                                         'Photo Like',#obj_type
                                         'openi',#service
                                         defJsonRes,#url
                                         raw_data['id'],#from:id
                                         raw_data['username'],#from:username
                                         defJsonRes,#from:url
                                         defJsonRes,#time:created_time
                                         defJsonRes,#time:edited_time
                                         defJsonRes#target_id
                                         ))
        return 'Not supported by this service'

    def unlike_photo(self, data):
        ''' DELETE API_PATH/[PHOTO_ID]/likes '''
        # /media/media-id/likes (ie media/628147512937366504_917877895/likes)
        response = self.connector.unlike_media(data['media_id'])
        return response


    #   endregion Connections

    #   endregion Photo Object

    #   endregion Media API
Example #13
0
def page_visit(usernm, userid,page=1):
    if usernm == g.user.user_name and str(userid) == str(g.user.un_id):
        post_user=g.user
        tab=""
        if request.method == 'POST':
            f = request.form
            for key in f.keys():
                for value in f.getlist(key):
                    if value is not None:
                        new_url=value
                        tab=key


        if post_user.first_login ==0 and tab=="first_import":
            userAPI = InstagramAPI(access_token=session['instagram_access_token'])        
            r_media, next = userAPI.user_recent_media(user_id=session['instagram_user'].get('id'),count=2)  
            if len(r_media)>0:
                for m in r_media:
                    loc = Images(img_url=m.images['low_resolution'].url, user_id=post_user.un_id, created_time=m.created_time, media_id=m.id)
                    sessionn.add(loc)
                    
            while next:
                r_media, next = userAPI.user_recent_media(with_next_url=next,count=2)   
                for m in r_media:
                    loc = Images(img_url=m.images['low_resolution'].url, user_id=post_user.un_id, created_time=m.created_time)
                    sessionn.add(loc)
            post_user.first_login = 1
            sessionn.commit()

        r_media = sessionn.query(Images).filter_by(user_id=userid).all()

        # Update url for images added by subscriptions
        if len(r_media)>0:
            for ind_r_media in r_media:
                if ind_r_media.img_url == None:
                    userAPI = InstagramAPI(access_token=session['instagram_access_token'])
                    media = userAPI.media(ind_r_media.media_id)
                    ind_r_media.img_url = media.images['low_resolution'].url
                    ind_r_media.created_time=media.created_time

        # Update urls
        if len(r_media)>0:
            for rm in r_media:
                strr="url"+str(rm.un_id)
                if strr==""+tab:
                    rm.user_link = value 
                                           
            for rmm in r_media:
                strrr="delete"+str(rmm.un_id)
                if strrr==""+tab:
                    sessionn.delete(rmm)


        print session['instagram_access_token']
        sessionn.commit()

        # r_media = sessionn.query(Images).filter_by(user_id=userid).all()
        media_pagination = sessionn.query(Images).filter_by(user_id=userid).order_by(Images.created_time.desc())
        media_pagination = paginate(media_pagination, page,POSTS_PER_PAGE_SMM,False)

        return render_template("link_adder.html", post_user=post_user, media = media_pagination,user_id=userid,user_name=usernm)
    else:
        return render_template("invalid_login.html")
Example #14
0
    for submission in r.get_domain_listing('instagram.com', sort='new',limit=25):
        if len(re.findall('http[s]?://instagram.com/p/\S+|http[s]?://www.instagram.com/p/\S+', str(submission.url))) > 0:
            to_be_done.append(submission)

    for submission in to_be_done:
        logging.info("To be processed: " + str(submission.url))


    for submission in to_be_done:
        if (str(submission.id), ) in curs.execute("SELECT ID FROM reddit"):
            logging.info("Already processed submission " + str(submission.id))
            continue
        else:
            try:
                media_id = get_media_id.get_media_id(str(submission.url)).encode('utf-8').strip()
                this_media = api.media(media_id)

                media_type = this_media.type.encode('utf-8').capitalize()
                formatted_comment = comments.comment.format(media_type)

                author_full_name = this_media.user.full_name.encode('utf-8')
                author_name = this_media.user.username.encode('utf-8')
                author_url = "http://www.instagram.com/%s" % author_name
                post_url = this_media.link.encode('utf-8')
                post_date = this_media.created_time.strftime("%Y-%m-%d %H:%M:%S")
                caption = escape.escape_chars(this_media.caption.text.encode('utf-8')) if this_media.caption.text != None else ""
                media_url = this_media.images['standard_resolution'].url.encode('utf-8') if media_type == "Image" else this_media.videos['standard_resolution'].url.encode('utf-8')
                rehosted_url = rehost.rehost(media_url)

                try:
                    curs.execute("INSERT INTO reddit (ID, TIMESTAMP) VALUES (?, CURRENT_TIMESTAMP)",(str(submission.id),))