Example #1
0
def get_medias(user_id, all=False):
    print('get_medias user_id=%s, all=%s' % (user_id, all))
    api = InstagramAPI(access_token=ACCESS_TOKEN, client_secret=CLIENT_SECRET)
    medias = []
    # media_urls = []
    more_medias, _ = api.user_recent_media()
    # media_urls.extend(get_media_urls(more_medias))
    if more_medias:
        medias.extend(more_medias)
    loop = 100 if all else 1
    while more_medias and loop > 0:
        try:
            print('get_medias max_id=%s' % more_medias[-1].id)
            more_medias, _ = api.user_recent_media(max_id=more_medias[-1].id)
            if not more_medias:
                print('get_medias no more data, break')
                break
            print('get_medias new medias count: %s' % len(more_medias))
            medias.extend(more_medias)
            # media_urls.extend(get_media_urls(more_medias))
            time.sleep(3)
        except Exception, e:
            print("error:%s on get_medias:%s" % (e, loop))
            time.sleep(10)
        loop -= 1
Example #2
0
def user(username, page=1):
    u = InstagramAPI(access_token=session['access_token'],
                     client_secret=secret.secrets['client_secret'])
    id = u.user_search(username)[0].id
    user_media, next_ = u.user_recent_media(user_id=id,count=20)

    for i in range(1, page):
        user_media, next_ = u.user_recent_media(user_id=id,
                                                count=20,
                                                with_next_url=next_)
    photos_thumbnail = []
    photos_standard = []
    title = username + " Recent Media-Page " + str(page)
    prev_page = False
    next_page = False
    if next_:
        prev_page = True
    if page != 1:
        next_page = True
    for media in user_media:
        photos_thumbnail.append("%s" % media.images['thumbnail'].url)
        photos_standard.append("%s" % media.images['standard_resolution'].url)
    return render_template("recent.html", thumb=photos_thumbnail,
                           photos=photos_standard, prev=prev_page,
                           next=next_page, page=page, title=title)
Example #3
0
def get_medias(user_id, all=False):
    print('get_medias user_id=%s, all=%s' % (user_id, all))
    api = InstagramAPI(access_token=ACCESS_TOKEN, client_secret=CLIENT_SECRET)
    medias = []
    # media_urls = []
    more_medias, _ = api.user_recent_media()
    # media_urls.extend(get_media_urls(more_medias))
    if more_medias:
        medias.extend(more_medias)
    loop = 100 if all else 1
    while more_medias and loop > 0:
        try:
            print('get_medias max_id=%s' % more_medias[-1].id)
            more_medias, _ = api.user_recent_media(max_id=more_medias[-1].id)
            if not more_medias:
                print('get_medias no more data, break')
                break
            print('get_medias new medias count: %s' % len(more_medias))
            medias.extend(more_medias)
            # media_urls.extend(get_media_urls(more_medias))
            time.sleep(3)
        except Exception, e:
            print("error:%s on get_medias:%s" % (e, loop))
            time.sleep(10)
        loop -= 1
Example #4
0
class InstagramClient:
    """ Find muscal user's recent posts
        return a list of album and artist names.
    """
    def __init__(self):
        # Make an unauthenticated connection
        self.api = InstagramAPI(
            client_id=INSTAGRAM_AUTH['CLIENT_ID'],
            client_secret=INSTAGRAM_AUTH['CLIENT_SECRET'])

    def search_user(self):
        # Find the user based on settings
        return self.api.user_search(q=INSTAGRAM_USER)

    def get_user_id(self):
        # Convert the user name specified into a user_id
        return self.search_user()[0].id

    def recent_media(self):
        # Get a list of the most recent posts.
        user_id = self.get_user_id()
        get_media, next_page = self.api.user_recent_media(user_id=user_id,
                                                          count=30)
        media = get_media
        while next_page:  # Paginate using the query string returned
            qry_str = next_page.split("?")[-1]
            max_id = parse_qs(qry_str)['max_id'][0]
            get_media, next_page = self.api.user_recent_media(user_id=user_id,
                                                              count=30,
                                                              max_id=max_id)
            media = media + get_media

        return media

    def get_recent_album_details(self):
        # Add the album artist details to self.recent_albums
        recent_media = []
        for media in self.recent_media():
            try:
                caption_text = media.caption.text
                artist, album = self.parse_name(caption_text)
            except AttributeError:
                print "Cannot get caption text for %s" % media.link
                artist, album = (None, None)
            if artist and album:
                recent_media.append((artist, album))
        return recent_media

    def parse_name(self, comment_text):
        # Parse album and artist from the comment
        try:
            tag, artist, album = comment_text.split("-")
            if tag.strip() != TARGET_TAG:
                raise ValueError  # lazy way to skip non 3old3new posts
        except ValueError:
            # if there are too few dashes, move on
            print "Cannot parse %s " % comment_text
            return [None, None]

        return artist.strip(), album.strip()
Example #5
0
 def update(self, access_token):
     api = InstagramAPI(access_token=access_token, client_secret=client_secret)
     recent_media, next_ = api.user_recent_media(user_id=self.user_id, count=100)
     num = len(recent_media)
     while next_ and num < 100:
         more_recent_media, next_ = api.user_recent_media(with_next_url=next_)
         recent_media.extend(more_recent_media)
         num = len(recent_media)
def get_all_media(user, access_token, filename, min_timestamp, max_timestamp):
	media_table = {'Data' : []}
	api = InstagramAPI(access_token=access_token)
	# The next variable is used for pagination while the 
	# recent_media variable is to extract the first "page"
	# of results
	recent_media, next = api.user_recent_media(user_id=user,
						   min_timestamp=min_timestamp,
						   max_timestamp=max_timestamp)
	
	# As long as there is a next_url or next_id, keep iterating
	while next:
		# While there is a next page to grab, store the result
		# in a temporary variable and store the next_url to the
		# next variable
		more_media, next = api.user_recent_media(with_next_url=next)
		
		# Add the results of the temporary variable to the recent_media
		# variable
		recent_media.extend(more_media)
		
	# List out the media for the user
	for media in recent_media:
		user_ = media.user.username
		images = media.link
		# Caption is empty if post does not have one
		caption = ""
		if media.caption:
			caption = media.caption.text
		created_time = str(media.created_time)
		img_id = str(media.id)
		
		media_table['Data'].append({'User' : user_,
					    'Image' : images,
					    'Created_time' : created_time,
					    'Caption' : caption.encode('utf-8'),
					    'Img_ID' : img_id,
					    'Likes' : media.like_count,
					    'Comments' : media.comment_count,
					    'Filter' : media.filter})
	
	# write json data to csv file
	media_data = media_table['Data']
	csv_file = open(filename, 'wb')
	csv_writer = csv.writer(csv_file)

	count = 0

	for data in media_data:
		if count == 0:
			header = data.keys()
			csv_writer.writerow(header)
			count += 1
		csv_writer.writerow(data.values())

	csv_file.close()
	print "%s created successfully" % filename
	return media_table
Example #7
0
    def check_access_tokens(self):

        for accessToken in Config.ACCESS_TOKENS:
            try:
                api = InstagramAPI(access_token=accessToken, client_secret=Config.CLIENT_SECRET, client_id=Config.CLIENT_ID)
                api.user_recent_media(user_id="self", count=1)
                logging.info("Access Token %s is valid, remaining: %s" % (accessToken, api.x_ratelimit_remaining))
                self.accessTokenPools[accessToken] = int(api.x_ratelimit_remaining)
            except InstagramAPIError as e:
                logging.warning("Ran out of quota for this access token:%s" % accessToken)
Example #8
0
    def handle(self, *args, **options):

        self.stdout.write('Getting Youtube!')
        # get youtube vids
        videos = requests.get(
            settings.YT_URL.format(
                id=settings.YT_PLAYLIST,
                key=settings.YT_ACCESS_TOKEN,
            )
        ).json()

        for vid in videos['items']:
            yt_id = vid['snippet']['resourceId']['videoId']
            yt_desc = vid['snippet']['description']
            yt_title = vid['snippet']['title']

            v,c = YoutubeLike.objects.get_or_create(yt_id=yt_id)

            if c:
                v.description = yt_desc
                v.title = yt_title
                v.save()

        self.stdout.write('Getting Instagram!')
        # get insta likes
        api = InstagramAPI(access_token=settings.INSTA_ACCESS_TOKEN,
            client_secret=settings.INSTA_ACCESS_SECRET)

        _id = InstagramLike.objects.all().last()

        items = (api.user_recent_media(min_id=_id.insta_id) if _id else
            api.user_recent_media())

        for item in items[0]:
            ig_pk = item.id
            ig_desc = item.caption.text if item.caption else ''
            ig_user = item.user.username
            ig_image = item.images['standard_resolution'].url
            ig_link = item.link
            ig_like_count = item.like_count
            ig_com_count = item.comment_count

            ig,c = InstagramLike.objects.get_or_create(insta_id=ig_pk)

            if c:
                ig.caption = ig_desc
                ig.user = ig_user
                ig.url = ig_link
                ig.photo = ig_image
                ig.likes = ig_like_count
                ig.comments = ig_com_count
                ig.save()

        self.stdout.write('All set!')
    def transform_uid(self, uid, access_token, cache=None):
        print >> sys.stderr, "[%s] extracting posts" % uid
        # Extract the posts for this users
        api = InstagramAPI(access_token=access_token,
                           client_id=client_id,
                           client_secret=client_secret)
        media_feed, mf_next_ = api.user_recent_media(user_id=uid,
                                                     count=feed_limit)
        while mf_next_:
            more, mf_next_ = api.user_recent_media(with_next_url=mf_next_)
        print >> sys.stderr, "[%s] found %d posts" % (uid, len(media_feed))

        return (media_feed, self.transform(uid, media_feed, cache))
Example #10
0
  def transform_uid(self, uid, access_token, cache = None):
    print >> sys.stderr, "[%s] extracting posts" % uid
    # Extract the posts for this users
    api = InstagramAPI(
      access_token=access_token, 
      client_id=client_id,
      client_secret=client_secret)
    media_feed, mf_next_ = api.user_recent_media(user_id = uid, count = feed_limit)
    while mf_next_:
      more, mf_next_ = api.user_recent_media(with_next_url=mf_next_)
    print >> sys.stderr, "[%s] found %d posts" % (uid, len(media_feed))

    return (media_feed, self.transform(uid, media_feed, cache))
Example #11
0
def get_medias(user_id, all=False):
    api = InstagramAPI(access_token=ACCESS_TOKEN, client_secret=CLIENT_SECRET)
    medias, next_ = api.user_recent_media(user_id=user_id, count=100)
    count = 10000 if all else 5
    while next_ and count > 0:
        print('next: %s' % next_)
        try:
            more_medias, next_ = api.user_recent_media(with_next_url=next_)
            if more_medias:
                medias.extend(more_medias)
            time.sleep(3)
        except Exception, e:
            print("error:%s on get_medias:%s" % (e, next_))
            time.sleep(10)
        count -= 1
def statistics(profile):
    profile = profile
    api = InstagramAPI(access_token=profile.access_token,
                       client_secret=CLIENT_SECRET)

    account = api.user(profile.id)

    count_media = account.counts['media']
    follows = account.counts['follows']
    followed_by = account.counts['followed_by']

    # Получаем все медиа
    all_media, next_ = api.user_recent_media(user_id=profile.id)
    while next_:
        more_media, next_ = api.user_recent_media(user_id=profile.id,
                                                  with_next_url=next_)
        all_media.extend(more_media)

    likes = 0
    comments = 0
    count_videos = 0
    count_images = 0

    for media in all_media:
        likes += media.like_count
        comments += media.comment_count
        if media.type == "video":
            count_videos += 1
        if media.type == "image":
            count_images += 1

    # Среднее вол-во лайков
    likes_average = likes / len(all_media)

    # показатель вовлеченности
    involvement = (likes_average / follows) * 100

    statistics = Statistics(profile=profile,
                            likes=likes,
                            likes_average=likes_average,
                            comments=comments,
                            follows=follows,
                            followed_by=followed_by,
                            count_media=count_media,
                            count_images=count_images,
                            count_videos=count_videos,
                            involvement=involvement)
    statistics.save()
def get_likes_from_media(user, access_token, filename, min_timestamp, max_timestamp):
	media_likes = {'Data' : []}
	api = InstagramAPI(access_token=access_token)
	
	recent_media, next = api.user_recent_media(user_id=user,
					           min_timestamp=min_timestamp,
						   max_timestamp=max_timestamp)
	for media in recent_media:
		media_like = api.media_likes(media.id)
		for like in media_like:
			media_likes['Data'].append({'Username' : like.username.encode('utf-8'),
						    'Profile_pic' : like.profile_picture,
						    'User_id' : str(like.id),
						    'Full_name' : like.full_name.encode('utf-8'),
						    'Media_ID' : media.id,
						    'Image' : media.link})
	
	likes_data = media_likes['Data']
	csv_file = open(filename, 'wb')
	csv_writer = csv.writer(csv_file)

	count = 0

	for data in likes_data:
		if count == 0:
			header = data.keys()
			csv_writer.writerow(header)
			count += 1
		csv_writer.writerow(data.values())
	
	csv_file.close()
	print "%s created successfully" % filename
	return media_likes
Example #14
0
File: app.py Project: apiccato/feed
def instagram():
	user_api = InstagramAPI(access_token=session['instagram_user']['access_token'])
	recent_media, next = user_api.user_recent_media(count=10)
	medias = []
	for media in recent_media:
		medias.append(json.loads(oembed(media.link, 350))['html'])
	return medias
Example #15
0
 def get_ajax(self, request, *args, **kwargs):
     try:
         instagram = Instagram.objects.all()[0]
         api = InstagramAPI(access_token=instagram.access_token)
         media, discard = api.user_recent_media(
             user_id=instagram.user_id, count=24)
         json_dict = {
             "thumbnails": [{"url": n.images.get("thumbnail").url,
                        "width": n.images.get("thumbnail").width,
                        "height": n.images.get("thumbnail").height,
                        } for n in media],
             "low_resolution": [{"url": n.images.get("low_resolution").url,
                        "width": n.images.get("low_resolution").width,
                        "height": n.images.get("low_resolution").height,
                        } for n in media],
             "standard_resolution": [{"url": n.images.get("standard_resolution").url,
                        "width": n.images.get("standard_resolution").width,
                        "height": n.images.get("standard_resolution").height,
                        } for n in media],
             }
     except IndexError:
         json_dict = {
             "media": []
         }
     return self.render_json_response(json_dict)
Example #16
0
def get_instagram_photos(tag):

    # É necessário configurar os campos INSTAGRAM_TOKEN e INSTAGRAM_USER
    # no conf.py

    try:
        access_token = current_app.config['INSTAGRAM_TOKEN']
    except KeyError:
        access_token = ""

    try:
        user_id = current_app.config['INSTAGRAM_USER']
    except KeyError:
        user_id = ""

    api = InstagramAPI(access_token=access_token)
    recent_media, next = api.user_recent_media(user_id=user_id, count=-1)
    photos = []
    for media in recent_media:
        if hasattr(media, 'tags'):
            if tag in [ t.name for t in media.tags ]:
                content = { 'url': media.images['standard_resolution'].url,
                            'thumb': media.images['thumbnail'].url,
                            'caption': media.caption.text }
                photos.append(content)

    return photos
Example #17
0
def auth_request():
    api = InstagramAPI(access_token=OTHER['access_token'])
    target_ids = api.user_search(OTHER['target'])

    target_id = None
    for search_hit in target_ids:
        if search_hit.username == OTHER['target']:
            target_id = search_hit.id
            break

    if target_id == None:
        logging.error('Did not find user, please check username')
        return []

    my_name   = api.user().username
    logging.debug('Starting check recent media')
    recent_media, url = api.user_recent_media(user_id=target_id, count = 20)
    liked_media = []
    for media in recent_media:
        logging.debug('Processing media %s' % media.id)
        users = api.media_likes(media.id)
        will_like = True
        for user in users:
            if user.username == my_name:
                will_like = False
                break
        if will_like:
            logging.debug('Liking media %s' % media.id)
            api.like_media(media.id)
            liked_media.append(media)
        else:
            logging.debug('Already liked media %s, aborting like' % media.id)

    return liked_media
Example #18
0
def get_user_photos():
    access_token = session.get("access_token", None)
    try:
        api = InstagramAPI(access_token=access_token,
                           client_secret=instagram_config['client_secret'])
        recent_media, next = api.user_recent_media()
        media_data = []
        for media in recent_media:
            caption = str(media.caption)
            text = re.sub(r".* said ", "", caption)
            data = {
                "image_url": media.get_standard_resolution_url(),
                "content_text": text
            }
            media_data.append(data)

        print "data obtained"
        print json.dumps(media_data)
        lastthing = emotions(media_data)
        if lastthing:
            #return "Success!" # try
            return render_template("result.html",
                                   playlist_uri=lastthing[0],
                                   emotion=lastthing[1],
                                   moods=",".join(
                                       map(str, MS_EMOTIONS[lastthing[1]])))

    except Exception as e:
        return str(e)
    def fetch_medias(cls, count):
        try:
            last_media = cls.objects.latest()
        except InstagramMedia.DoesNotExist:
            last_media = None

        min_time = ''
        if last_media:
            min_time = time.mktime(last_media.created.utctimetuple())

        user = InstagramUser.objects.all()[0]
        api = InstagramAPI(access_token=user.access_token)
        medias = api.user_recent_media(min_timestamp=min_time, count=count)
        if not (medias and medias[0]):
            raise StopIteration

        for media in medias[0]:
            if cls.objects.filter(instagram_id=media.id).exists():
                # TODO: check and update metadata
                continue

            caption = media.caption and media.caption.text or u''
            insta_media = cls(instagram_id=media.id,
                              created=media.created_time,
                              caption=caption,
                              comment_count=media.comment_count,
                              like_count=media.like_count,
                              url=media.link or u'',
                              thumbnail_url=media.images['thumbnail'].url,
                              standard_url=media.get_standard_resolution_url())
            yield insta_media
Example #20
0
def instagram2(key):
	api = InstagramAPI(client_id='b64f54dc4fb3486f87b55d92381e2625', client_secret='b5fa80c366b94cc980c882855630fe92')
	for item in api.user_recent_media(user_id=key, count=20, max_id=100):
		photo = item.images
		print dp, username, did,web, bio
	lol = "text"
	return lol
Example #21
0
def index(request):
	success = False
	if request.method == 'POST':
		form = contactForm(request.POST)
		if form.is_valid():
			success = True
			cd = form.cleaned_data
			asunto = u'Por: %s mail: %s Tipo de servicio: %s Plan: %s' % (cd['nombre'], cd['email'], cd['tipoServicio'], cd['planes'])
			content = u'Email contacto: %s \nAsunto: %s \nTelefono: %s \nDescripcion: %s' % (cd['email'], asunto, cd['telefono'], cd['texto'])
			send_mail(asunto, content, cd['email'], ['*****@*****.**'])
	else:
		form = contactForm()

	api = InstagramAPI(client_id='e78042ef1e834e75a28291aee734d615', client_secret='a299e7f23d0840f9b473417ea7c38c33')
	recent_media, next = api.user_recent_media(user_id="621890719", count=6)
	lista_media_url = []
	#lista_media_texto = []
	lista_media_likes = []
	lista_media_link = []
	for media in recent_media:
		lista_media_link.append(media.link)
		lista_media_url.append(media.images['standard_resolution'].url)
		#lista_media_texto.append(media.caption.text)
		lista_media_likes.append(str(media.like_count))
	zip_media = zip(lista_media_link, lista_media_url, lista_media_likes)
	logos =  LogoEmpresa.objects.all()
	ctx = {'form': form, 'success': success, 'zip_media': zip_media, 'logos': logos}
	return render_to_response('homepage/index.html', ctx, context_instance=RequestContext(request))
Example #22
0
def test_instagram(request):
    """
    Testpage for instagram
    Get access token manually first,
    see https://github.com/Instagram/python-instagram/blob/master/get_access_token.py
    Got mine through http://www.blueprintinteractive.com/tutorials/instagram/uri.php?code=71520761ada343ef882abb5c7a54a9fd
    """
    api = get_object_or_404(ApiLink, name="Instagram")


    instagram = InstagramAPI(access_token=api.access_token)
    #Access token secret = user_id!
    recent_media, next = instagram.user_recent_media(user_id=api.access_token_secret, count=10)

    photos = []
    for media in recent_media:
        direc = dir(media)
        photos.append('<img src="%s" />' % media.images['thumbnail'].url)
        #Check if media is video or image
        media_type = 'pic' if media.type == "image" else "vid"


    return render(request, 'apis/api_instagram.html', {
        'content': recent_media,
    })
Example #23
0
def crawl_all_feeders():
    api = InstagramAPI(access_token=access_token)

    try:
        #recent_media, next_ = api.user_recent_media(user_id="mmoorr", count=10)
        media_feed, next_ = api.user_media_feed(count=20)
    except InstagramAPIError as ie:
        print("Instagram API error" + str(ie))
        return
    except Exception as e:
        print("General exception" + str(e))
        return
    
    crawled={}
    for media in media_feed:
        if media.user.id in crawled: continue
        crawled[media.user.id] = True
        try:
            recent_media, next_ = api.user_recent_media(user_id=media.user.id, count=10)
            user_info           = api.user(user_id=media.user.id)
        except InstagramAPIError as ie:
            print("Instagram API error" + str(ie))
            return
        except Exception as e:
            print("General exception" + str(e))
            return
        print ("Got %d items for user %s"%(len(recent_media), media.user))
        print ("This is %s, ID %s, bio %s, followed by %s"%(user_info.full_name, 
                                                            user_info.id, 
                                                            user_info.bio, 
                                                            user_info.counts['followed_by']))
        print ("++")
    def fetch_medias(cls, count):
        try:
            last_media = cls.objects.latest()
        except InstagramMedia.DoesNotExist:
            last_media = None

        min_time = ''
        if last_media:
            min_time = time.mktime(last_media.created.utctimetuple())

        user = InstagramUser.objects.all()[0]
        api = InstagramAPI(access_token=user.access_token)
        medias = api.user_recent_media(min_timestamp=min_time, count=count)
        if not (medias and medias[0]):
            raise StopIteration

        for media in medias[0]:
            if cls.objects.filter(instagram_id=media.id).exists():
                # TODO: check and update metadata
                continue

            caption = media.caption and media.caption.text or u''
            insta_media = cls(instagram_id=media.id,
                              created=media.created_time,
                              caption=caption,
                              comment_count=media.comment_count,
                              like_count=media.like_count,
                              url=media.link or u'',
                              thumbnail_url=media.images['thumbnail'].url,
                              standard_url=media.get_standard_resolution_url())
            yield insta_media
Example #25
0
def insta(search_term):
	returnval=''

	api = InstagramAPI(access_token=ACCESS_TOKEN, client_secret=CLIENT_SECRET)

	try:
		username = search_term
		#print username
		if ' ' in username:
			username = username.replace(' ', '')

		if not api.user_search(username, 1):
			return "No user by that name was found."
		else:
			userid = api.user_search(username, 1)[0].id
			recent_media, next_ = api.user_recent_media(user_id=userid,count=5)
			for media in recent_media:
			   #text = media.caption.text
			   link = media.link
			   returnval += '~'+link+'\n'

			return returnval

	except InstagramAPIError as e:
	   if (e.status_code == 400):
	      return "Cannot retrieve data. User is set to private."
	   if (e.status_code == 404):
	   	  return "Content not found."
Example #26
0
def instagram(key):
	api = InstagramAPI(client_id='b64f54dc4fb3486f87b55d92381e2625', client_secret='b5fa80c366b94cc980c882855630fe92')
	for item in api.user_recent_media(user_id=key, count=20, max_id=100):
		photo = item.images
		print dp, username, did,web, bio
	lol = "text"
	return lol
Example #27
0
def populate(access_token):
    'Populate database with default data'
    user_id = app.config.get('INSTAGRAM_USER_ID')

    api = InstagramAPI(access_token=access_token)
    feed = api.user_recent_media(user_id=user_id, max_pages=2000, as_generator=True)

    all_tags = {}
    for media in get_media(feed):
        # Add photos
        caption = media.caption.text if media.caption else None
        photo = Photo(
            instagram_id=media.id,
            caption=caption,
            created_time=media.created_time,
            link=media.link)
        db.session.add(photo)

        # Add tags, ensure we do not duplicate tags
        if hasattr(media, 'tags'):
            tags = {t.name: all_tags.get(t.name, Tag(name=t.name)) for t in media.tags}
            all_tags.update(tags)
            photo.tags.extend(tags.values())

        # Add images
        images = [Image(height=i.height, width=i.width, url=i.url, type=i_type)
                  for i_type, i in media.images.iteritems()]
        db.session.add_all(images)
        photo.images.extend(images)

        # TODO: Locations.

    db.session.add_all(all_tags.values())
    db.session.commit()
Example #28
0
def update_user(user, download):
    api = InstagramAPI(
        access_token=settings.INSTAGRAM_ACCESS_TOKEN,
        client_secret=settings.INSTAGRAM_CLIENT_SECRET)

    recent_media, next = api.user_recent_media(user_id=user)
    update_photos(photos=recent_media, download=download)
Example #29
0
def auth_request():  
    api = InstagramAPI(access_token=OTHER['access_token'],client_secret=CONFIG['client_secret'])
    target_ids = api.user_search(OTHER['target'],1)
    if len(target_ids) > 1:
        logging.error('Found mutiple users, please check username')
        return

    target_id = target_ids[0].id
    my_name   = api.user().username
    logging.debug('Starting check recent media')
    recent_media, url = api.user_recent_media(user_id=target_id, count = 1)
    liked_media = []
    for media in recent_media:
        logging.debug('Processing media %s' % media.id)
        users = api.media_likes(media.id)
        will_like = True
        for user in users:
            if user.username == my_name:
                will_like = False
                break
        if will_like:
            logging.debug('Liking media %s' % media.id)
            api.like_media(media.id)
            liked_media.append(media)
        else:
            logging.debug('Already liked media %s, aborting like' % media.id)

    return liked_media
Example #30
0
def downloads_photos():
    # Open StringIO to grab in memory ZIP contents
    zip_mem = BytesIO()
    zipFile = zipfile.ZipFile(zip_mem, 'w')

    api = InstagramAPI(access_token=session['access_token'])
    recent_media, next = api.user_recent_media()

    for media in recent_media:
        f_name = media.images['standard_resolution'].url.rsplit('/', 1)[1]
        r = requests.get(media.images['standard_resolution'].url, stream=True)
        if r.status_code == 200:
            with BytesIO() as img_mem:
                for chunk in r.iter_content(1024 * 10):
                    img_mem.write(chunk)
                print "Adding:", f_name
                zipFile.writestr(f_name, img_mem.getvalue())

    zipFile.close()
    zip_mem.seek(0)

    download_fname = datetime.today().strftime("%Y-%m-%d")
    return send_file(zip_mem,
                     mimetype="application/zip",
                     attachment_filename="photodl-%s.zip" % download_fname,
                     as_attachment=True)
Example #31
0
def inst2sina(userid):
    """ 同步最新一条instagram状态到微博 """
    api = InstagramAPI(access_token=INST_CONF['access_token'])
    recent_media, next = api.user_recent_media(user_id=userid, count=1)
    # 验证request返回值正常,如果不正常,可能是access_token过期
    if recent_media['meta']['code'] == 200:
        s = Sina(SINA_CONF['app_key'], SINA_CONF['app_secret'], SINA_CONF['redirect_uri'], SINA_CONF['access_token'])
        
        if recent_media['data'][0]['location'] != None:
            if recent_media['data'][0]['caption']:
                id = s.postTweet(' '.join([recent_media['data'][0]['caption']['text'], recent_media['data'][0]['link']]), 
                recent_media['data'][0]['images']['standard_resolution']['url'], 
                lat=str(recent_media['data'][0]['location']['latitude']), long=str(recent_media['data'][0]['location']['longitude']))
            else:
                id = s.postTweet(recent_media['data'][0]['link'], recent_media['data'][0]['images']['standard_resolution']['url'], 
                lat=str(recent_media['data'][0]['location']['latitude']), long=str(recent_media['data'][0]['location']['longitude']))
        else:
            if recent_media['data'][0]['caption']:
                id = s.postTweet(' '.join([recent_media['data'][0]['caption']['text'], recent_media['data'][0]['link']]), 
                recent_media['data'][0]['images']['standard_resolution']['url'])
            else:
                id = s.postTweet(recent_media['data'][0]['link'], recent_media['data'][0]['images']['standard_resolution']['url'])
    else:
        return None
    return id
Example #32
0
def get_instagram_photos(tag):

    # É necessário configurar os campos INSTAGRAM_TOKEN e INSTAGRAM_USER
    # no conf.py

    try:
        access_token = current_app.config['INSTAGRAM_TOKEN']
    except KeyError:
        access_token = ""

    try:
        user_id = current_app.config['INSTAGRAM_USER']
    except KeyError:
        user_id = ""

    api = InstagramAPI(access_token=access_token)
    recent_media, next = api.user_recent_media(user_id=user_id, count=-1)
    photos = []
    for media in recent_media:
        if hasattr(media, 'tags'):
            if tag in [t.name for t in media.tags]:
                content = {
                    'url': media.images['standard_resolution'].url,
                    'thumb': media.images['thumbnail'].url,
                    'caption': media.caption.text
                }
                photos.append(content)

    return photos
Example #33
0
 def get_ajax(self, request, *args, **kwargs):
     try:
         instagram = Instagram.objects.all()[0]
         api = InstagramAPI(access_token=instagram.access_token)
         media, discard = api.user_recent_media(user_id=instagram.user_id,
                                                count=24)
         json_dict = {
             "thumbnails": [{
                 "url": n.images.get("thumbnail").url,
                 "width": n.images.get("thumbnail").width,
                 "height": n.images.get("thumbnail").height,
             } for n in media],
             "low_resolution": [{
                 "url":
                 n.images.get("low_resolution").url,
                 "width":
                 n.images.get("low_resolution").width,
                 "height":
                 n.images.get("low_resolution").height,
             } for n in media],
             "standard_resolution": [{
                 "url":
                 n.images.get("standard_resolution").url,
                 "width":
                 n.images.get("standard_resolution").width,
                 "height":
                 n.images.get("standard_resolution").height,
             } for n in media],
         }
     except IndexError:
         json_dict = {"media": []}
     return self.render_json_response(json_dict)
Example #34
0
def inst2tenc(userid):
    """ 同步最新一条instagram状态到腾讯微博 """
    api = InstagramAPI(access_token=INST_CONF['access_token'])
    recent_media, next = api.user_recent_media(user_id=userid, count=1)
    # 验证request返回值正常,如果不正常,可能是access_token过期
    if recent_media['meta']['code'] == 200:
        t = Tenc(TENC_CONF['app_key'], TENC_CONF['app_secret'], TENC_CONF['callback_url'], TENC_CONF['access_token'], TENC_CONF['openid'])
   
        if recent_media['data'][0]['location'] != None:
            if recent_media['data'][0]['caption']:
                id = t.postPic(' '.join([recent_media['data'][0]['caption']['text'],recent_media['data'][0]['link']," #instagram#"]), 
                recent_media['data'][0]['images']['standard_resolution']['url'], 
                lat=str(recent_media['data'][0]['location']['latitude']), long=str(recent_media['data'][0]['location']['longitude']))
            else:
                id = t.postPic(recent_media['data'][0]['link'], recent_media['data'][0]['images']['standard_resolution']['url'], 
                lat=str(recent_media['data'][0]['location']['latitude']), long=str(recent_media['data'][0]['location']['longitude']))
        else:
            if recent_media['data'][0]['caption']:
                id = t.postPic(' '.join([recent_media['data'][0]['caption']['text'], recent_media['data'][0]['link']," #instagram#"]), 
                recent_media['data'][0]['images']['standard_resolution']['url'])
            else:
                id = t.postPic(recent_media['data'][0]['link'], recent_media['data'][0]['images']['standard_resolution']['url'])
    else:
        return None
    return id
Example #35
0
def insta(search_term):
	returnval=''

	api = InstagramAPI(access_token=ACCESS_TOKEN, client_secret=CLIENT_SECRET)

	try:
		username = search_term
		#print username
		if ' ' in username:
			username = username.replace(' ', '')

		if not api.user_search(username, 1):
			return "No user by that name was found."
		else:
			userid = api.user_search(username, 1)[0].id
			recent_media, next_ = api.user_recent_media(user_id=userid,count=5)
			for media in recent_media:
			   #text = media.caption.text
			   link = media.link
			   returnval += '~'+link+'\n'

			return returnval

	except InstagramAPIError as e:
	   if (e.status_code == 400):
	      return "Cannot retrieve data. User is set to private."
	   if (e.status_code == 404):
	   	  return "Content not found."
Example #36
0
def index(request):
    template_name = 'shop/index.html'
    latest_products = Product.objects.all().order_by('-created_at')[:3]
    latest_articles = Article.objects.all().order_by('-created_at')[:3]
    api = InstagramAPI(access_token=ig_access_token, client_secret=ig_client_secret)
    recent_media, next_ = api.user_recent_media(user_id="239869696", count=10)
    facebook_data = get_facebook()
    return render(request, template_name, {'recent_media' : recent_media, 'facebook_data' : facebook_data, 'latest_products' : latest_products, 'latest_articles' : latest_articles })
Example #37
0
def subscribe(key):
	api = InstagramAPI(client_id='14c7fb94b134473d9ee9cc449face034', client_secret='1738e7489ef24de0abef9a0dbfa8d3ea')
	api.create_subscription(object='tag', object_id=key, aspect='media', callback_url='http://127.0.0.1:3001/insta/thefuturepark')
	for item in api.user_recent_media(user_id=key, count=20, max_id=100):
		photo = item.images
		print dp, username, did,web, bio
	lol = "text"
	return lol
Example #38
0
File: app.py Project: sicXnull/moa
def instagram_oauthorized():

    code = request.args.get('code', None)

    if code:

        client_id = app.config['INSTAGRAM_CLIENT_ID']
        client_secret = app.config['INSTAGRAM_SECRET']
        redirect_uri = url_for('instagram_oauthorized', _external=True)
        api = InstagramAPI(client_id=client_id,
                           client_secret=client_secret,
                           redirect_uri=redirect_uri)

        try:
            access_token = api.exchange_code_for_access_token(code)
        except OAuth2AuthExchangeError as e:
            flash("Instagram authorization failed")
            return redirect(url_for('index'))
        except ServerNotFoundError as e:
            flash("Instagram authorization failed")
            return redirect(url_for('index'))

        if 'bridge_id' in session:
            bridge = get_or_create_bridge(bridge_id=session['bridge_id'])

            if not bridge:
                pass  # this should be an error
        else:
            bridge = get_or_create_bridge()

        bridge.instagram_access_code = access_token[0]

        data = access_token[1]
        bridge.instagram_account_id = data['id']
        bridge.instagram_handle = data['username']

        user_api = InstagramAPI(access_token=bridge.instagram_access_code,
                                client_secret=client_secret)

        try:
            latest_media, _ = user_api.user_recent_media(
                user_id=bridge.instagram_account_id, count=1)
        except Exception:
            latest_media = []

        if len(latest_media) > 0:
            bridge.instagram_last_id = datetime_to_timestamp(
                latest_media[0].created_time)
        else:
            bridge.instagram_last_id = 0

        db.session.commit()

    else:
        flash("Instagram authorization failed")

    return redirect(url_for('index'))
    def handle(self, *args, **options):

        api = InstagramAPI(access_token=settings.INSTAGRAM_ACCESS_TOKEN)

        for account in InstagramAccount.objects.all():
            latest_image = account.latest_image

            if latest_image:
                recent_media, next = api.user_recent_media(user_id=account.instagram_id, min_id=latest_image.instagram_id)
            else:
                recent_media, next = api.user_recent_media(user_id=account.instagram_id)

            for media in recent_media:
                media_id = media.id.split('_')[0]
                if not latest_image or media_id != str(latest_image.instagram_id):
                    InstagramImage.objects.create(account=account,
                                                  instagram_id=media_id,
                                                  instagram_link=media.link,
                                                  url=media.images['standard_resolution'].url)
Example #40
0
def main(request):
    from instagram.client import InstagramAPI

    access_token = "1483928180.10bb1f3.2aaef28f7ad943988b89fe42e56ed016"
    api = InstagramAPI(access_token=access_token)
    instagram_photo_urls = []
    recent_media, next_ = api.user_recent_media(user_id=1483928180, count=20) 
    for media in recent_media:
        instagram_photo_urls.extend([media.images['standard_resolution'].url])
    return render(request, 'base.html', {'instagram_photo_urls': instagram_photo_urls})
Example #41
0
def get_insta_post(name):
    access_token = os.environ.get("IG_ACCESS_TOKEN")
    if not access_token:
        _get_access_token()

    api = InstagramAPI(access_token=access_token)
    recent_media, nxt = api.user_recent_media(user_id=name, count=5)

    for media in recent_media:
        print('thumb_url', media.get_thumbnail_url())
def main(request):
    from instagram.client import InstagramAPI

    access_token = "1661752703.cf0499d.024fa351763946409a1ff477999b3200"
    api = InstagramAPI(access_token=access_token)
    instagram_photo_urls = []
    recent_media, next_ = api.user_recent_media(user_id=1661752703, count=20)
    for media in recent_media:
        instagram_photo_urls.extend([media.images['standard_resolution'].url])
    return render(request, 'base.html', {'instagram_photo_urls': instagram_photo_urls})
def rss(request):
	api = InstagramAPI(access_token=settings.INSTAGRAM_TOKEN)

	media, next = api.user_recent_media(user_id=settings.INSTAGRAM_UID, count=20)

	return render_to_response (
		'hipstagram/rss.xml', 
		{ 'media': media }, 
		mimetype='application/xml'
	) 
Example #44
0
def getInstagrams(userid, last, init):
    insta_creds = creds['instagram']
    api = InstagramAPI(client_id=insta_creds['client_id'],
                       client_secret=insta_creds['client_secret'])

    photos = []
    try:
        api = InstagramAPI(access_token=insta_creds['access_token'])
        media_feed, next = api.user_recent_media(user_id=userid)
        for m in media_feed:
            photos = instaAppend(m, photos, last, init)
        counter = 1
        while next and counter < 100:
            media_feed, next = api.user_recent_media(user_id=userid,
                                                     with_next_url=next)
            for m in media_feed:
                photos = instaAppend(m, photos, last, init)
            counter += 1
    except Exception, e:
        print e
Example #45
0
def main(request):
    from instagram.client import InstagramAPI

    access_token = "1661752703.cf0499d.024fa351763946409a1ff477999b3200"
    api = InstagramAPI(access_token=access_token)
    instagram_photo_urls = []
    recent_media, next_ = api.user_recent_media(user_id=1661752703, count=20)
    for media in recent_media:
        instagram_photo_urls.extend([media.images['standard_resolution'].url])
    return render(request, 'base.html',
                  {'instagram_photo_urls': instagram_photo_urls})
Example #46
0
def pics(limit=4):

    api = InstagramAPI(access_token=auth.INSTAGRAM_ACCESS_TOKEN,
                       client_secret=auth.INSTAGRAM_CLIENT_SECRET)

    recent_media, _next = api.user_recent_media(user_id='6204130', count=10)

    # Only include images, no videos
    images = [p for p in recent_media if p.type == 'image']
    images.sort(key=lambda p: p.created_time, reverse=True)

    return images[:limit]
def main():
    token = auth()
    api = InstagramAPI(access_token=token)

    recent_media, next = api.user_recent_media()
    photos = []
    
    recent = api.

    for media in recent_media:
        # photos.append(media.images.url)
        print(media.values)
Example #48
0
def instagram_oauthorized():

    code = request.args.get('code', None)

    if 'twitter' in session and 'mastodon' in session and code:

        client_id = app.config['INSTAGRAM_CLIENT_ID']
        client_secret = app.config['INSTAGRAM_SECRET']
        redirect_uri = url_for('instagram_oauthorized', _external=True)
        api = InstagramAPI(client_id=client_id,
                           client_secret=client_secret,
                           redirect_uri=redirect_uri)

        try:
            access_token = api.exchange_code_for_access_token(code)
        except OAuth2AuthExchangeError as e:
            flash("Instagram authorization failed")
            return redirect(url_for('index'))

        # look up settings
        bridge = db.session.query(Bridge).filter_by(
            mastodon_user=session['mastodon']['username'],
            twitter_handle=session['twitter']['screen_name'],
        ).first()

        bridge.instagram_access_code = access_token[0]

        data = access_token[1]
        bridge.instagram_account_id = data['id']
        bridge.instagram_handle = data['username']

        user_api = InstagramAPI(access_token=bridge.instagram_access_code,
                                client_secret=client_secret)

        try:
            latest_media, _ = user_api.user_recent_media(
                user_id=bridge.instagram_account_id, count=1)
        except Exception:
            latest_media = []

        if len(latest_media) > 0:
            bridge.instagram_last_id = datetime_to_timestamp(
                latest_media[0].created_time)
        else:
            bridge.instagram_last_id = 0

        db.session.commit()

    else:
        flash("Instagram authorization failed")

    return redirect(url_for('index'))
Example #49
0
def home():

    insta_api = InstagramAPI(access_token=local_settings.INSTAGRAM_TOKEN)
    feed = insta_api.user_recent_media(count=15)
    medias = feed[0]

    rdd_api = readability.oauth(local_settings.READABILITY_CLIENT_KEY,
                                local_settings.READABILITY_CLIENT_SECRET,
                                token=local_settings.READABILITY_USER_TOKEN)
    bookmarks = rdd_api.get_bookmarks(limit=10)

    #    ['author', 'content', 'content_size', 'date_published', 'domain', 'excerpt', 'id', 'next_page_href', 'processed', 'short_url', 'title', 'url', 'word_count']
    return render_template("index.html", medias=medias, bookmarks=bookmarks)
Example #50
0
 def get_context_data(self, *args, **kwargs):
     try:
         instagram = Instagram.objects.all()[0]
         api = InstagramAPI(access_token=instagram.access_token)
         try:
             media, discard = api.user_recent_media(
                 user_id=instagram.user_id, count=24)
         except InstagramAPIError as e:
             logger.error(e)
             return {"media": []}
         return {"media": media}
     except IndexError:
         return {"media": []}
Example #51
0
def find_identifier():
# if instagram info is in session variables, then display user photos
	if 'instagram_access_token' in session and 'instagram_user' in session:
		api = InstagramAPI(access_token=session['instagram_access_token'])

		identifier = re.compile("We've teamed up with our friends")
		users_to_follow = 'knowlita, acme_nyc'
		user_list = users_to_follow.split(',')
		user_list = [x.strip(' ') for x in user_list]  
		
		uids = []
		for key_user in user_list:
			user_search = api.user_search(q=key_user)
			uids.append(user_search[0].id)

		media_ids = []
		for uid in uids:
			recent_media, next = api.user_recent_media( user_id=uid , count=30)
			for media in recent_media:
				if media.caption != None:
					if identifier.search(media.caption.text):
						media_ids.append((media.id, media.images['standard_resolution'].url))
					else:
						recent_media, next = api.user_recent_media( with_next_url = next)
						for media in recent_media:
							if media.caption != None:
								if identifier.search(media.caption.text):
									media_ids.append((media.id, media.images['standard_resolution'].url))

		
		templateData = {
			'media_ids' : media_ids,
			'uids' : uids
		}

		return render_template('find_identifier.html', **templateData)
	else:
		return redirect('/connect')
Example #52
0
def get_last_media_thumbnails_urls_from_user(username, client_id, client_secret, number_of_photos=15):
    """Return a list of urls of thumbnails for the user,
    None if the user does not exist"""
    api = InstagramAPI(client_id=client_id, client_secret=client_secret)
    user_id = get_user_id_from_username(username, client_id)
    thumbnails_urls = []
    image_counter = 0
    print "Querying for images..."
    try:
        recent_media, next_ = api.user_recent_media(user_id=user_id)
    except InstagramAPIError as e:
        print "Error: instagram.bind.InstagramAPIError"
        print "Exact error: " + str(e)
        return None

    # First get of images, I was getting 33 when asking for 50, and 20 when not specifying
    for media in recent_media:
        image_counter += 1
        thumbnails_urls.append(media.images['thumbnail'].url)
        # If we have enough, stop here
        if image_counter >= number_of_photos:
            return thumbnails_urls
    # Keep getting images until we are done
    while image_counter < number_of_photos:
        print "Querying for extra images... (Got " + str(image_counter) + " until now)"
        try:
            recent_media, next_ = api.user_recent_media(with_next_url=next_)
        except InstagramAPIError:
            # No more images!
            break
        for idx, media in enumerate(recent_media):
            image_counter += 1
            thumbnails_urls.append(media.images['thumbnail'].url)
            # if we have enough, also stop already
            if image_counter >= number_of_photos:
                return thumbnails_urls
    # Return what we got, if we didn't get to satisfy the quantity asked for
    return thumbnails_urls
Example #53
0
def User_Recent_Media(page=1):
    u = InstagramAPI(access_token=session['access_token'],
                     client_secret=secrets['client_secret'])
    recent_media, next_ = u.user_recent_media()
    for i in range(1, page):
        recent_media, next_ = u.user_recent_media(count=20,
                                                  with_next_url=next_)
    photos_thumbnail = []
    photos_standard = []
    title = "User Recent Media-Page " + str(page)
    prev_page = False
    next_page = False
    if next_:
        prev_page = True
    if page != 1:
        next_page = True
    for media in recent_media:
        photos_thumbnail.append("{}".format(media.images['thumbnail'].url))
        photos_standard.append("{}".format(media.images['standard_resolution']
                               .url))
    return render_template("recent.html", thumb=photos_thumbnail,
                           photos=photos_standard, prev=prev_page,
                           next=next_page, page=page, title=title)
Example #54
0
    def post(self):
        import hashlib
        import hmac
        import logging
        from StringIO import StringIO
        from time import time
        from urllib2 import urlopen
        from django.utils import simplejson
        from dropbox import helper as dropbox_helper

        payload = self.request.body

        # verify payload
        signature = self.request.headers['X-Hub-Signature']
        client_secret = settings.INSTAGRAM_CONFIG['client_secret']
        hashing_obj = hmac.new(client_secret.encode("utf-8"),
                               msg=payload.encode("utf-8"),
                               digestmod=hashlib.sha1)
        digest = hashing_obj.hexdigest()

        if digest != signature:
            logging.info("Digest and signature differ. (%s, %s)" %
                         (digest, signature))
            return

        changes = simplejson.loads(payload)
        for change in changes:
            profiles = Profile.all()
            profiles.filter("ig_user_id =", change['object_id'])
            profile = profiles.get()

            if not profile:
                logging.info("Cannot find profile %s", change['object_id'])
                continue

            instagram_client = InstagramAPI(
                access_token=profile.ig_access_token)

            media, _ = instagram_client.user_recent_media(count=1)
            media = media[0]

            media_file = urlopen(media.images['standard_resolution'].url)
            media_data = media_file.read()

            dropbox_file = StringIO(media_data)
            dropbox_file.name = ("%s.jpg" % int(time()))

            dropbox_client = dropbox_helper.authenticated_client(profile)
            dropbox_client.put_file(settings.DROPBOX_CONFIG['root'],
                                    "/Instagram Photos/", dropbox_file)