Ejemplo n.º 1
0
 def getMyId(self):
     try:
         api = InstagramAPI(access_token=self._accessToken)
         self.myId = api.user().id
     except:
         return None
     return self.myId
Ejemplo n.º 2
0
class InstagramUtils(object):

    INSTAGRAM_CLIENT_ID = '38079a9f3f054e3da845e0e7e6202e18'
    INSTAGRAM_CLIENT_SECRET = 'f933e5ecc3504d1498f4a5bf6a0c0b74'

    def __init__(self):
        self.api = InstagramAPI(client_id=InstagramUtils.INSTAGRAM_CLIENT_ID,
                                client_secret=InstagramUtils.INSTAGRAM_CLIENT_SECRET)

    def get_user_by_username(self, username):
        users = self.api.user_search(q=username)
        users = filter(lambda user: user.username == username, users)
        if users:
            return users[0]
        else:
            return None

    def get_user_page(self, username):
        return 'https://instagram.com/%s/' % username

    def load_user_feed(self, user_id, **kwargs):
        try:
            feed, next_url = self.api.user_recent_media(user_id=user_id, **kwargs)
        except InstagramAPIError as e:
            feed = None
        return feed
Ejemplo n.º 3
0
def main(configFile=None):
    ''' Deletes all subscriptions from the Instagram server. Typically called
        on a new dotcloud push just to make sure its all clear.'''

    print "----------->", configFile
    # Get the config information into a single object
    p = getConfigParameters(configFile)
    
        # Get the client and secret keys
    api = InstagramAPI(client_id=p.client, client_secret=p.secret)
    
    # Get all current subs
    subs = api.list_subscriptions()

    # For each active sub, delete it
    if subs['meta']['code'] == 200:
        
        for sub in subs['data']:
            
            if sub['type'] == 'subscription':
                deleted = api.delete_subscriptions(id=int(sub['id']))
        
        # Final check - make sure they're definitely all gone
        subs = api.list_subscriptions()
        if len(subs['data']) == 0:
            success = True
        else:
            success = False
    
    else:
        success = False
Ejemplo n.º 4
0
def ageOffSubscriptions(p, collHandle, ageOff, protectedSubs):
    ''' Deletes subscriptions from the Instagram server based on the age and protection level
        in the subs collection. If protect=True, then it must be manually deleted'''

    out = []
    
    # Get the client and secret keys
    api = InstagramAPI(client_id=p.client, client_secret=p.secret)

    # Get the expired non-protected subscriptions
    subs, ids = getExpiredSubs(collHandle, ageOff, protectedSubs)
    
    # Delete the subscriptions from the instagram server
    for sub in subs:
        print sub
        deleted = api.delete_subscriptions(id=int(sub))
        print deleted
        out.append(deleted)
        if deleted['meta']['code'] != 200:
            print 'Failed to delete subscription %s' %(sub)

    # Delete the nextUrl object files (kept in the config directory)
    for objId in ids:
        f = os.path.join(os.path.dirname(p.configFile), objId)
        try:
            os.remove(f)
        except:
            print 'Failed to delete the subscription next URL file: \n %s\n' %(f)
            
    return out
Ejemplo n.º 5
0
def get_photos(max_tag_id=None):
    
    api = InstagramAPI(client_id=g.instagram_id, 
                       client_secret=g.instagram_secret, 
                       redirect_uri='http://www.gummiognina.com/')
                       
    data, next_url = api.tag_recent_media(tag_name=TAG_NAME, 
                                          count=PAGE_COUNT, 
                                          max_tag_id=max_tag_id)
    
    def _to_dict(obj):
        d = dict()
        if not isinstance(obj, dict):
            obj = obj.__dict__
        for key, value in obj.iteritems():
            if isinstance(value, (ApiModel, dict)):
                d[key] = _to_dict(value)
            elif isinstance(value, list):
                d[key] = map(unicode, value)
            else:
                d[key] = unicode(value)
        return d
    
    def yield_images():
        for obj in data:
            yield _to_dict(obj)
    
    qs = urlparse(next_url).query
    max_tag_id = parse_qs(qs).get('max_tag_id', [None])[0]
    
    return (_to_dict(obj) for obj in data), max_tag_id
Ejemplo n.º 6
0
def subscription(request):
	print request
	if request.method == 'GET':
		challenge = request.GET['hub.challenge']
		return HttpResponse(challenge)
	elif request.method == 'POST':
		subscription_objects = json.loads(request.body)
		api = InstagramAPI(client_id=INSTAGRAM_CLIENT_ID, client_secret=INSTAGRAM_CLIENT_SECRET)
		for obj in subscription_objects:
			try:
				photo = api.media(obj['object_id'])
				parse_photo = ParsePy.ParseObject("instagram_photo")
				parse_photo.url = photo.images['standard_resolution'].url
				parse_photo.url_thumb = photo.images['thumbnail'].url
				parse_photo.timestamp = photo.created_time
				likes = []
				for user in photo.likes:
					likes.append(parse_user_from_instagram(user))
				parse_photo.likes = likes;
				comments = []
				for comment in photo.comments:
					comments.appent(parse_comment_from_instagram(comment))
				parse_photo.comments(comments)
				parse_photo.location = parse_location_from_instagram(photo.location)
				parse_photo.save()
			except AttributeError:
				pass
		print request
Ejemplo n.º 7
0
def main(configFile=None):
    ''' Deletes all subscriptions from the Instagram server. Typically called
        on a new dotcloud push just to make sure its all clear.'''

    print "----------->", configFile
    # Get the config information into a single object
    p = getConfigParameters(configFile)

    # Get the client and secret keys
    api = InstagramAPI(client_id=p.client, client_secret=p.secret)

    # Get all current subs
    subs = api.list_subscriptions()

    # For each active sub, delete it
    if subs['meta']['code'] == 200:

        for sub in subs['data']:

            if sub['type'] == 'subscription':
                deleted = api.delete_subscriptions(id=int(sub['id']))

        # Final check - make sure they're definitely all gone
        subs = api.list_subscriptions()
        if len(subs['data']) == 0:
            success = True
        else:
            success = False

    else:
        success = False
Ejemplo n.º 8
0
def isfollow(uid, api=None):
    if not api:
        api = InstagramAPI(access_token=session.get('access_token', ''))
        data = api.user_relationship(user_id=uid)
        if data.outgoing_status == 'follows':
            return True
    return False
Ejemplo n.º 9
0
def ageOffSubscriptions(p, collHandle, ageOff, protectedSubs):
    ''' Deletes subscriptions from the Instagram server based on the age and protection level
        in the subs collection. If protect=True, then it must be manually deleted'''

    out = []

    # Get the client and secret keys
    api = InstagramAPI(client_id=p.client, client_secret=p.secret)

    # Get the expired non-protected subscriptions
    subs, ids = getExpiredSubs(collHandle, ageOff, protectedSubs)

    # Delete the subscriptions from the instagram server
    for sub in subs:
        print sub
        deleted = api.delete_subscriptions(id=int(sub))
        print deleted
        out.append(deleted)
        if deleted['meta']['code'] != 200:
            print 'Failed to delete subscription %s' % (sub)

    # Delete the nextUrl object files (kept in the config directory)
    for objId in ids:
        f = os.path.join(os.path.dirname(p.configFile), objId)
        try:
            os.remove(f)
        except:
            print 'Failed to delete the subscription next URL file: \n %s\n' % (
                f)

    return out
Ejemplo n.º 10
0
 def get(self):
     if has_login():
         return redirect(url_for('views.home'))
     redirect_url = url_for('views.home')
     code = request.args.get('code', '')
     redirect_uri = INSTAGRAM_REDIRECT_URI
     if request.args.get('uri', ''):
         redirect_url = request.args.get('uri')
         redirect_uri += '?uri=' + redirect_url
     api = InstagramAPI(client_id=INSTAGRAM_CLIENT_ID,
                        client_secret=INSTAGRAM_CLIENT_SECRET,
                        redirect_uri=redirect_uri)
     try:
         access_token = api.exchange_code_for_access_token(code)
         print access_token
     except:
         return InternalServerError(u'InternalServerError')
     user = (User.query
             .filter_by(id=access_token[1]['id']).first())
     if user:
         user.update(access_token=access_token[0],
                     name=access_token[1]['username'],
                     avatar=access_token[1]['profile_picture'])
     else:
         user = User.create(id=access_token[1]['id'],
                            name=access_token[1]['username'],
                            avatar=access_token[1]['profile_picture'],
                            access_token=access_token[0])
         redirect_url = url_for('views.welcome')
     session.permanent = True
     session['uid'] = user.id
     session['username'] = user.name
     session['access_token'] = user.access_token
     return redirect(redirect_url)
Ejemplo n.º 11
0
def list(tag):
    api = InstagramAPI(client_id=CLIENT_ID)
    items, next = api.tag_recent_media(count=12, tag_name=tag)
    if is_nonmobile(request.environ):
        return render_template("_item.html", items=items)
    else:
        return render_template("_mitem.html", items=items)
Ejemplo n.º 12
0
def isfollow(ukey, api=None):
    if not api:
        api = InstagramAPI(access_token=session.get('access_token', ''))
    data = api.user_relationship(user_id=ukey)
    outgoing = data.outgoing_status
    if outgoing == 'follows':
        return True
    return False
Ejemplo n.º 13
0
 def get_posts(user_social_auth, last_updated_time):
     api = InstagramAPI(
         access_token=user_social_auth.extra_data['access_token'])
     formatted_time = helper.datetime_to_timestamp(
         last_updated_time) if last_updated_time else None
     recent_media, next_ = api.user_recent_media(
         user_id=user_social_auth.uid, min_timestamp=formatted_time)
     return recent_media
Ejemplo n.º 14
0
 def post(self, mid):
     api = InstagramAPI(access_token=request.access_token)
     form = MediaCommentForm()
     if not form.validate():
         media_info = self._get_media(api, mid)
         return render('media.html', form=form, **media_info)
     api.create_media_comment(media_id=mid, text=form.content.data)
     media_info = self._get_media(api, mid)
     return render('media.html', form=form, **media_info)
Ejemplo n.º 15
0
def get_user(uid, access_token):
    try:
        api = InstagramAPI(access_token=access_token)
        user = api.user(uid)
        return user
    except InstagramAPIError, e:
        if e.error_type in ['APINotAllowedError-you', 'APINotFoundError-this']:
            delete_worker(uid)
            print e.error_type
        return e
Ejemplo n.º 16
0
def process_instagram_update(update):
    subscription_id = update.get('subscription_id')
    subscription = Subscription.objects.filter(
        subscription_id=subscription_id).first()

    if not subscription:
        return

    api = InstagramAPI(
        client_id=subscription.config.get('app_id'),
        client_secret=subscription.config.get('app_secret'))

    tag = update['object_id']
    media, next = api.tag_recent_media(30, 0, tag)

    for image in media:
        post, created = Post.objects.get_or_create(
            subscription=subscription,
            source_id=image.id,
            created_at=image.created_time.replace(tzinfo=pytz.utc)
        )

        if not created:
            continue

        post.data = {
            'filter': image.filter,
            'link': image.link,
            'type': image.type,
            'tags': [t.name for t in image.tags],
            'user': {
                'id': image.user.id,
                'username': image.user.username,
                'full_name': image.user.full_name,
                'profile_picture': image.user.profile_picture,
                'website': image.user.website,
                'bio': image.user.bio,
            },
            'images': {
                'thumbnail': image.get_thumbnail_url(),
                'small': image.get_low_resolution_url(),
                'default': image.get_standard_resolution_url(),
            }
        }
        if getattr(image, 'caption', None):
            post.data['caption'] = image.caption.text

        if getattr(image, 'location', None) \
            and getattr(image.location, 'point', None):
                post.data['location'] = {
                    'latitude': image.location.point.latitude,
                    'longitude': image.location.point.longitude,
                }

        post.save()
Ejemplo n.º 17
0
 def isTokenValid(self):
     try:
         api = InstagramAPI(access_token=self._accessToken)
         api.user()
     except InstagramAPIError as e:
         return ErrorCode.E_INVALID_TOKEN
     except:
         self._logger.exception('InstaBase::isTokenValid() exception')
         return ErrorCode.E_FAILED
     else:
         return ErrorCode.S_OK
Ejemplo n.º 18
0
def get_user(uid, access_token):
    try:
        api = InstagramAPI(access_token=access_token)
        user = api.user(uid)
        return user
    except InstagramAPIError, e:
        if e.error_type in ['APINotAllowedError-you',
                            'APINotFoundError-this']:
            delete_worker(uid)
            print e.error_type
        return e
Ejemplo n.º 19
0
 def get(self):
     mid = request.args.get('mid', '')
     ukey = session.get('ukey', '')
     api = InstagramAPI(access_token=session.get('access_token', ''))
     likes = api.media_likes(media_id=mid)
     ret = False
     for i in likes:
         if ukey == i.id:
             ret = True
             break
     return json_response(ret)
Ejemplo n.º 20
0
 def get(self):
     action = request.args.get('action', 'create_comment')
     mid = request.args.get('mid', '')
     text = request.args.get('text', '')
     api = InstagramAPI(access_token=session.get('access_token', ''))
     if action == 'create_comment':
         api.create_media_comment(media_id=mid, text=text)
     elif action == 'delete_comment':
         cid = request.args.get('comment_id', '')
         api.delete_comment(media_id=mid, comment_id=cid)
     return json_response('ok')
Ejemplo n.º 21
0
 def get(self):
     if has_login():
         return redirect(url_for('views.welcome'))
     redirect_uri = INSTAGRAM_REDIRECT_URI
     if request.args.get('uri', ''):
         redirect_uri += '?uri=' + request.args.get('uri')
     api = InstagramAPI(client_id=INSTAGRAM_CLIENT_ID,
                        client_secret=INSTAGRAM_CLIENT_SECRET,
                        redirect_uri=redirect_uri)
     try:
         redirect_uri = api.get_authorize_login_url(scope=INSTAGRAM_SCOPE)
     except InstagramAPIError:
         return InternalServerError(u'Server Error')
     return redirect(redirect_uri)
Ejemplo n.º 22
0
def refresh_user_pic():
    users = UserModel.query.all()
    for user in users:
        print user
        try:
            ret = urllib.urlopen(user.pic)
            if ret.code != 200:
                print 'refresh!'
                api = InstagramAPI(access_token=user.access_token)
                new = api.user(user_id=user.ukey)
                user.pic = new.profile_picture
        except Exception:
            pass
    db.session.commit()
Ejemplo n.º 23
0
def get_item(instagram_id):
    api = InstagramAPI(client_id='f7a905471d5c4f29a8f6797c83499bb6')
    media = api.media(instagram_id)

    item = Item()
    item.link = media.link
    if(type(media.caption) is not NoneType):
        item.caption = media.caption.text
    item.image_url = media.images['standard_resolution'].url
    item.thumbnail_url = media.images['thumbnail'].url
    item.user_name = media.user.username
    item.user_profile_url = media.user.profile_picture
    item.create_time = media.created_time

    return item
Ejemplo n.º 24
0
def photos(request, code=None):
    code = request.GET.get('code', None)
    client_id = settings.INSTAGRAM_CLIENT_ID
    client_secret = settings.INSTAGRAM_CLIENT_SECRET
    redirect_uri = settings.INSTAGRAM_REDIRECT_URI
    api = InstagramAPI(client_id=client_id, client_secret=client_secret,
        redirect_uri=redirect_uri)
    if not code:
        redirect_url = api.get_authorize_login_url()
        return redirect(redirect_url)

    access_token = api.exchange_code_for_access_token(code)
    api = InstagramAPI(access_token=access_token[0])
    media = api.user_recent_media(user_id=access_token[1]['id'], count=10)

    # create the base dir for all the downloads
    if not os.path.exists(settings.BASE_PHOTOS_DIR):
        os.makedirs(settings.BASE_PHOTOS_DIR)

    user_dir = os.path.join(settings.BASE_PHOTOS_DIR, access_token[1]['username'])
    if not os.path.exists(user_dir):
        os.makedirs(user_dir)
    os.chdir(user_dir)

    metadata = []

    for md in media[0]:
        if not md.type == 'image':
            continue
        url = md.get_standard_resolution_url()
        filename = url.split('/')[-1]
        try:
            f = open(filename,'wb') 
            f.write(urllib.urlopen(url).read())
            f.close()
            metadata.append({
                'filename': filename,    
                'url': url,
                'created_time': str(md.created_time),
                'caption': md.caption
            })
        except IOError as e:
            print e.message
            
    with open('metadata.json', 'w+') as fp:
        json.dump(metadata, fp)

    return HttpResponse('<h3>Your photos have been downloaded to %s !<h3>' % user_dir)
Ejemplo n.º 25
0
def get_instub_feed(access_token, min_id=None):
    print min_id
    try:
        api = InstagramAPI(access_token=access_token)
        medias_list = []
        next_ = True
        while next_:
            next_url = None if next_ is True else next_
            medias, next_ = api.user_media_feed(with_next_url=next_url,
                                                min_id=min_id)
            medias_list.extend(medias)
        return medias_list
    except InstagramAPIError, e:
        if e.error_type in ['APINotAllowedError-you', 'APINotFoundError-this']:
            pass
        return []
Ejemplo n.º 26
0
 def post(self):
     access_token = random.choice(OPEN_ACCESS_TOKENS)
     api = InstagramAPI(access_token=access_token)
     next_url = None
     done = False
     while not done:
         medias = api.tag_recent_media(tag_name='zhinsta',
                                       with_next_url=next_url)
         next_url = medias[1]
         for m in medias[0]:
             tmp = add_show(m)
             if tmp:
                 done = True
         if not next_url:
             break
     return 'ok'
Ejemplo n.º 27
0
    def get(self, id):
        api = InstagramAPI(access_token=request.access_token)
        media, likes = self._get_meida(id, api)
        errors = self._get_errors(media, likes, id)
        if errors:
            return errors

        uid = media.user.id
        is_follow = False
        if request.uid:
            try:
                is_follow = isfollow(uid, api)
            except InstagramAPIError:
                return InternalServerError('Internal server error')

        media_user = self._get_media_user(uid, api)
        if not media_user:
            return InternalServerError('Internal server error')

        is_star = False
        for i in likes:
            if request.uid and request.uid == i.id:
                is_star = True

        return render_template('media.html',
                               media=media,
                               isfollow=is_follow,
                               media_user=media_user,
                               likes=likes[:5],
                               is_star=is_star)
Ejemplo n.º 28
0
 def get_api(self):
     if not hasattr(self, '_api'):
         self._api = InstagramAPI(
             client_id=settings.CONNECTED_ACCOUNTS_INSTAGRAM_CONSUMER_KEY,
             client_secret=settings.CONNECTED_ACCOUNTS_INSTAGRAM_CONSUMER_SECRET,
             access_token=self.account.get_token())
     return self._api
Ejemplo n.º 29
0
def complete(request):
    code = request.GET['code']
    access_token = api.exchange_code_for_access_token(code)
    auth_api = InstagramAPI(access_token=access_token[0])
    user, _ = User.objects.get_or_create(
        username=access_token[1].get('username')
    )
    # Don't repeat this!
    user.backend = 'django.contrib.auth.backends.ModelBackend'
    #authenticate(username=user.username, password=user.password)
    login(request, user)

    # Move to worker
    recent_media, _ = auth_api.user_recent_media(count=0)
    for media in recent_media:
        photo, created = Photo.objects.get_or_create(
            user=user,
            instagram_id=media.id
        )
        if created:
            img_temp = NamedTemporaryFile(delete=True)
            with img_temp:
                request = requests.get(
                    media.images['standard_resolution'].url,
                    stream=True
                )
                for block in request.iter_content(1024):
                    if not block:
                        break
                    img_temp.write(block)
                img_temp.flush()
                photo.image.save(
                    '{}.jpg'.format(photo.instagram_id),
                    File(img_temp)
                )
            image_path = photo.image.path
            valid_faces = detect_faces(image_path)
            for face in valid_faces:
                face_image_path = make_face_images(image_path, face)
                with open(face_image_path):
                    face = Face.objects.create(
                        user=user,
                        photo=photo,
                    )
                    face.image.name = face_image_path
                    face.save()
    return redirect('choose')
Ejemplo n.º 30
0
 def get(self):
     action = request.args.get('action', 'follow')
     ukey = request.args.get('ukey', '')
     api = InstagramAPI(access_token=session.get('access_token', ''))
     if action == 'follow':
         api.follow_user(user_id=ukey)
         m = FollowModel(ukey=session.get('ukey', ''),
                         follow_ukey=ukey,
                         username=session.get('username', ''))
         db.session.add(m)
     if action == 'unfollow':
         api.unfollow_user(user_id=ukey)
         m = FollowModel.query.get((session.get('ukey', ''), ukey))
         if m:
             db.session.delete(m)
     db.session.commit()
     return json_response('ok')
Ejemplo n.º 31
0
def get_instub_feed(access_token, min_id=None):
    print min_id
    try:
        api = InstagramAPI(access_token=access_token)
        medias_list = []
        next_ = True
        while next_:
            next_url = None if next_ is True else next_
            medias, next_ = api.user_media_feed(with_next_url=next_url,
                                                min_id=min_id)
            medias_list.extend(medias)
        return medias_list
    except InstagramAPIError, e:
        if e.error_type in ['APINotAllowedError-you',
                            'APINotFoundError-this']:
            pass
        return []
Ejemplo n.º 32
0
 def get_api(self, request):
     if not hasattr(self, '_api'):
         rel_to = self.model._meta.get_field('account').rel.to
         connected_account = get_object_or_404(rel_to, pk=request.GET.get('account'))
         self._api = InstagramAPI(
             client_id=settings.CONNECTED_ACCOUNTS_INSTAGRAM_CONSUMER_KEY,
             client_secret=settings.CONNECTED_ACCOUNTS_INSTAGRAM_CONSUMER_SECRET,
             access_token=connected_account.get_token())
     return self._api
Ejemplo n.º 33
0
    def __init__(self, token, ip, secret, tag_list, log=None, pause=None):
        """
        :param token: Access_token of account
        :param ip: Machines IP
        :param secret: Client secret
        :param tag_list: List of hastags to interact with
        :param log: Where to save info. Default "instabot.log"
        :param pause: Time to wait before interacting again. Default 1 second"
        """
        super(InstaBot, self).__init__()
        self.api = InstagramAPI(access_token=token, client_ips=ip,
                                client_secret=secret)
        self.tag_list = tag_list
        self.log = "instabot.log" if log is None else log
        self.pause = 1 if pause is None else pause
        self.db = DB()

        self.__count = 0
Ejemplo n.º 34
0
 def get(self):
     likes = (LikeModel.query
              .filter(LikeModel.ukey == '448621019')
              .order_by(LikeModel.date_created.desc())
              .limit(5).all())
     access_token = random.choice(OPEN_ACCESS_TOKENS)
     api = InstagramAPI(access_token=access_token)
     media = api.media(likes[0].media)
     if isinstance(media, InstagramAPIError):
         return notfound(u'服务器暂时出问题了')
     medias = ShowModel.query.filter(
         ShowModel.mid.in_([x.media for x in likes[1:]]))
     users = (RecommendModel.query
              .order_by(RecommendModel.order.desc())
              .limit(24).all())
     return render('home.html',
                   media=media,
                   medias=medias,
                   users=users)
Ejemplo n.º 35
0
    def get(self, name):
        next_url = request.args.get('next_url', None)

        api = InstagramAPI(access_token=request.access_token)
        tag = api.tag(name)
        media = api.tag_recent_media(tag_name=name,
                                     with_next_url=next_url)
        tag = gevent.spawn(api.tag, name)
        media = gevent.spawn(api.tag_recent_media,
                             tag_name=name, with_next_url=next_url)
        gevent.joinall([tag, media])
        try:
            tag, media = tag.get(), media.get()
        except InstagramAPIError:
            return notfound(u'服务器暂时出问题了')

        next_url = media[1]
        media = media[0]
        return render('tag.html', tag=tag, media=media, next_url=next_url)
Ejemplo n.º 36
0
    def _authenticate(self, user):
        try:
            social_auth = user.social_auth.get(provider='instagram')
            token_key = social_auth.extra_data['access_token']
        except (ObjectDoesNotExist, KeyError):
            raise CredentialsNotFound('instagram', user)

        return InstagramAPI(
            client_secret=settings.SOCIAL_AUTH_INSTAGRAM_SECRET,
            access_token=token_key)
Ejemplo n.º 37
0
def get_medias(uid, access_token, min_id=None):
    print uid, access_token, min_id
    try:
        api = InstagramAPI(access_token=access_token)
        medias_list = []
        next_ = True
        while next_:
            next_url = None if next_ is True else next_
            medias, next_ = api.user_recent_media(user_id=uid,
                                                  with_next_url=next_url,
                                                  min_id=min_id)
            medias_list.extend(medias)
        print len(medias_list)
        return medias_list
    except InstagramAPIError, e:
        if e.error_type in ['APINotAllowedError-you', 'APINotFoundError-this']:
            delete_worker(uid)
            print e.error_type
        return e
Ejemplo n.º 38
0
def get_medias(uid, access_token, min_id=None):
    print uid, access_token, min_id
    try:
        api = InstagramAPI(access_token=access_token)
        medias_list = []
        next_ = True
        while next_:
            next_url = None if next_ is True else next_
            medias, next_ = api.user_recent_media(
                user_id=uid, with_next_url=next_url,
                min_id=min_id)
            medias_list.extend(medias)
        print len(medias_list)
        return medias_list
    except InstagramAPIError, e:
        if e.error_type in ['APINotAllowedError-you',
                            'APINotFoundError-this']:
            delete_worker(uid)
            print e.error_type
        return e
Ejemplo n.º 39
0
    def get(self, name):
        next_url = request.args.get('next_url', None)

        api = InstagramAPI(access_token=request.access_token)
        tag = api.tag(name)
        media = api.tag_recent_media(tag_name=name,
                                     with_next_url=next_url)
        tag = gevent.spawn(api.tag, name)
        media = gevent.spawn(api.tag_recent_media,
                             tag_name=name, with_next_url=next_url)
        gevent.joinall([tag, media])
        try:
            tag, media = tag.get(), media.get()
        except InstagramAPIError:
            return InternalServerError('Internal server error')

        next_url = media[1]
        media = media[0]
        pager = Pager(tag.media_count)
        return render_template('tag.html', tag=tag, pager=pager,
                                media=media, next_url=next_url)
Ejemplo n.º 40
0
 def get(self):
     if has_login():
         return redirect(url_for('view.show'))
     redirect_url = url_for('view.show')
     code = request.args.get('code', '')
     redirect_uri = INSTAGRAM_REDIRECT_URI
     if request.args.get('uri', ''):
         redirect_url = request.args.get('uri')
         redirect_uri += '?uri=' + redirect_url
     api = InstagramAPI(client_id=INSTAGRAM_CLIENT_ID,
                        client_secret=INSTAGRAM_CLIENT_SECRET,
                        redirect_uri=redirect_uri)
     try:
         access_token = api.exchange_code_for_access_token(code)
     except:
         return apierror()
     user = (UserModel.query
             .filter_by(ukey=access_token[1]['id']).first())
     if user:
         user.access_token = access_token[0]
         user.username = access_token[1]['username']
         user.pic = access_token[1]['profile_picture']
     else:
         user = UserModel(ukey=access_token[1]['id'],
                          username=access_token[1]['username'],
                          pic=access_token[1]['profile_picture'],
                          access_token=access_token[0])
         db.session.add(user)
         redirect_url = url_for('view.welcome')
     db.session.commit()
     admin = AdminModel.query.get(user.ukey)
     session.permanent = True
     session['ukey'] = user.ukey
     session['username'] = user.username
     session['access_token'] = user.access_token
     session['is_admin'] = True if admin else False
     return redirect(redirect_url)
Ejemplo n.º 41
0
class MuslimahGalau(Instapy):

    instagram = InstagramAPI(access_token=ACCESS_TOKEN,
                             client_secret=CLIENT_SECRET)
    insta_post = InstagramSession(
        username=USERNAME,
        password=PASSWORD,
        guid='3efc0996-85bd-11e5-857d-74de2b6b05c3',
        device_id='android-3efc0996-85bd-11e5-857d-74de2b6b05c3',
        user_agent=
        'Instagram 4.2.2 Android (10/1.5.2; 120; 480x800; samsung; GT-N7000; GT-N7000; smdkc210; en_US)'
    )
    user_followed = USERS
    tags = [
        '#muslimahgalau', '#muslimah', '#galau', '#akhowat', '#akhwat',
        '#tausiyah'
    ]
    IMAGES_PATH = '/home/ramdani/projects/auto-repost/muslimah_images/'
Ejemplo n.º 42
0
    def get(self, uid=None):
        next_url = request.args.get('next_url', None)
        if next_url and 'instagram' not in next_url:
            next_url = signer.loads(next_url)
        api = InstagramAPI(access_token=request.access_token)

        user = gevent.spawn(wrap_errors(InstagramAPIError, api.user),
                            user_id=uid)
        feeds = gevent.spawn(wrap_errors(InstagramAPIError,
                                         api.user_recent_media),
                             user_id=uid,
                             with_next_url=next_url)
        if request.uid:
            isfollows = spawn(isfollow, uid, api)
        else:
            isfollows = spawn(lambda x: False, uid)

        gevent.joinall([user, feeds, isfollows])
        user, feeds, isfollows = user.get(), feeds.get(), isfollows.get()
        errors = [
            e for e in (user, feeds, isfollows)
            if isinstance(e, InstagramAPIError)
        ]
        if errors:
            if any([e.error_type == 'APINotAllowedError' for e in errors]):
                return render_template('profile-noauth.html', uid=uid)
            if any([e.error_type == 'APINotFoundError' for e in errors]):
                return NotFound(u'User Not Found')
            return InternalServerError('Internal Server Error')

        next_url = feeds[1] if feeds else None
        next_url = signer.dumps(next_url) if next_url else next_url
        feeds = feeds[0] if feeds else []
        isme = False
        if request.uid and uid == request.uid:
            isme = True
        return render_template('profile.html',
                               user=user,
                               feeds=feeds,
                               isme=isme,
                               isfollow=isfollows,
                               next_url=next_url)
Ejemplo n.º 43
0
    def _get_users(self, uid, user_type='followed'):
        next_url = request.args.get('next_url', None)
        if next_url and 'instagram' not in next_url:
            next_url = signer.loads(next_url)
        api = InstagramAPI(access_token=request.access_token)
        user = spawn(api.user, uid)
        if user_type == 'following':
            users = spawn(api.user_follows, uid, with_next_url=next_url)
        else:
            users = spawn(api.user_followed_by, uid, with_next_url=next_url)
        isfollows = False
        if request.uid:
            isfollows = spawn(isfollow, uid, api)
        else:
            isfollows = spawn(lambda x: False, uid)

        gevent.joinall([user, users, isfollows])
        user, users, isfollows = user.get(), users.get(), isfollows.get()
        errors = get_errors(user, users, isfollows)
        if errors:
            return InternalServerError('Internal Server Error')

        next_url = users[1]
        next_url = signer.dumps(next_url) if next_url else next_url
        users = users[0]

        isme = False
        if request.uid and uid == request.uid:
            isme = True
        context = {
            'user': user,
            'users': users,
            'next_url': next_url,
            'isfollows': isfollows,
            'isme': isme,
        }
        return context
Ejemplo n.º 44
0
 def get(self):
     action = request.args.get('action', 'like')
     mid = request.args.get('mid', '')
     api = InstagramAPI(access_token=session.get('access_token', ''))
     if action == 'like':
         api.like_media(media_id=mid)
         media = api.media(mid)
         m = LikeModel(ukey=session.get('ukey', ''), media=mid,
                       username=session.get('username', ''),
                       media_username=media.user.username)
         db.session.add(m)
         add_show(media)
     if action == 'unlike':
         api.unlike_media(media_id=mid)
         m = LikeModel.query.get((session.get('ukey', ''), mid))
         if m:
             db.session.delete(m)
     db.session.commit()
     return json_response('ok')
Ejemplo n.º 45
0
import networkx as nx

from bottle import *

picked_pic_db = 'db_nnpicks.txt'
picked_pic_db_backup = 'db_nnpicks.txt.backup'
picked_pic_db_debug = 'db_nnpicks_debug.txt'
good_users_db = 'db_good_users.txt'
good_users_db_debug = 'db_good_users_debug.txt'
great_pics_db = "db_great_pics.txt"
great_pics_db_debug = "db_great_pics_debug.txt"
network_db = 'db_network.txt'
network_db_backup = 'db_network.txt.backup'
network_db_debug = 'db_network_debug.txt'
access_token = '1529897738.2d6fe64.87556684de0d4ce1aa6afbf423a8cada'
api = InstagramAPI(access_token=access_token)
HOST = 'localhost'

debug_mode = 0
first_run = False
try:
    shutil.copyfile(picked_pic_db, picked_pic_db_backup)
except:
    print("Error during backup. Exiting.")
    print("*** Remaining API Calls = %s/%s" %
          (api.x_ratelimit_remaining, api.x_ratelimit))
    sys.exit(0)

menu = {}
menu["HOME"] = "/"
menu["GOOD USERS"] = "/good-users"
Ejemplo n.º 46
0
def item(id):
    api = InstagramAPI(client_id=CLIENT_ID)
    item = api.media(media_id=id)
    return render_template("_mimage.html", item=item)
Ejemplo n.º 47
0
from __future__ import print_function
from __future__ import division
from instagram import client, subscriptions, InstagramAPI
import sys
from datetime import date, timedelta
import json
import time
import datetime
import shutil
import operator
from pylab import *
import math

access_token = '1529897738.2d6fe64.87556684de0d4ce1aa6afbf423a8cada'
api = InstagramAPI(access_token=access_token)

debug_mode = 0
first_run = False
picked_pic_db = 'db_nnpicks.txt'
picked_pic_db_backup = 'db_nnpicks.txt.backup'
picked_pic_db_debug = 'db_nnpicks_debug.txt'
good_users_db = 'db_good_users.txt'
good_users_db_debug = 'db_good_users_debug.txt'
report_file = "nnreport.html"

try:
    shutil.copyfile(picked_pic_db, picked_pic_db_backup)
except:
    print("Error during backup. Exiting.")
    print("*** Remaining API Calls = %s/%s" %
          (api.x_ratelimit_remaining, api.x_ratelimit))
Ejemplo n.º 48
0
    def getData(self, since=None, until=None):
        """
        Get data from Instagram feed

        In:
            since           --  The start time to get data
                                given None means current time
                                or given python's datetime instance as input
            until           --  The end time to get date
                                given None means yesterday
                                or given python's datetime instance as input

            Example: (Please note that the direction to retrieve data is backward)
                Now   --->   2012/04/01   --->   2012/01/01
                You can specify since=None and until=<datetime of 2012/01/01>
                or since=<datetime of 2012/04/01> until=<datetime of 2012/01/01>

        Out:
            Return a python dict object
            {
                'data': {               # List of data
                    'id': {
                        'id': 'postId',
                        'message': 'Text',
                        'photos': [ '/path/to/file' ],
                        'createdTime': <datetime object>,
                        'place': {      # *optional*
                            'id': 'locationId',
                            'name': 'locationName',
                            'latitude': nnn.nnn,
                            'longitude' mmm.mmm
                        }
                    }, ...
                },
                'count': 30,                    # count in data dic
                'retCode': ErrorCode.S_OK,    # returned code which is instance of ErrorCode

            }
        """
        retDict = {
            'retCode': ErrorCode.E_FAILED,
            'count': 0,
            'data': {},
        }

        if not until:
            until = datetime.now() - timedelta(1)

        tokenValidRet = self.isTokenValid()
        if ErrorCode.IS_FAILED(tokenValidRet):
            retDict['retCode'] = tokenValidRet
            return retDict

        if not self.myId:
            return retDict

        sinceTimestamp = self._datetime2Timestamp(since) + 1 if since else None
        untilTimestamp = self._datetime2Timestamp(until) - 1 if until else None
        api = InstagramAPI(access_token=self._accessToken)
        for media in api.user_recent_media(max_pages=999,
                                           min_timestamp=untilTimestamp,
                                           max_timestamp=sinceTimestamp):
            if not media:
                break
            for data in media:
                data = self._transformFormat(data)
                self._dumpData(data)
                retDict['data'][data['id']] = data

        retDict['count'] = len(retDict['data'])
        retDict['retCode'] = ErrorCode.S_OK
        return retDict
Ejemplo n.º 49
0
from instagram import InstagramAPI
import io

api = InstagramAPI(client_id='CLIENT_ID', client_secret='CLIENT_SECRET')

log = io.open(r'InstagramFolder/instagram.txt', 'wb')
hashtags = ['pizza', 'cheese']  #add as many search terms you need here
lat = 38.907192
long = -77.036871
dist = 1000  #in meters

# Search location by long+lat


def search_by_lat_long(latitude, longitude, distance):
    media_search = api.media_search(lat=latitude,
                                    lng=longitude,
                                    distance=distance)
    for media in media_search:
        log.write(u'\n--&&&***--')
        log.write(media.user.username + ' ')
        if (media.caption):
            log.write(media.caption.text.encode('utf8') + '---')
        if (media.location):
            log.write(media.location.name + ' ')
        if (media.images):
            log.write(media.images['standard_resolution'].url)
        elif (media.videos):
            log.write(media.videos['standard_resolution'].url)

Ejemplo n.º 50
0
import matplotlib.patches as mpatches
import mpld3
import pandas as pd

# Sets how many post to get
post_count = 40
# Creates a threshold for neutral post
neutral_min = 0.04
neutral_max = 0.215
min_subjectivity = 0.3
# Sets hashtag to be analyze (do no include the hashtag symbol)
hash_tag = 'cats'
# Set up Instagram API
client_id = ''  # Replace with your key
client_secret = ''  # Replace with your key
api = InstagramAPI(client_id=client_id, client_secret=client_secret)


def get_ids():
    # Get all ids for all post
    ids, next = api.tag_recent_media(tag_name=hash_tag, count=post_count)
    temp, max_tag = next.split('max_tag_id=')
    max_tag = str(max_tag)

    while next and len(ids) < post_count:
        more_ids, next = api.tag_recent_media(tag_name=hash_tag, count=max_tag)
        temp, max_tag = next.split('max_tag_id=')
        max_tag = str(max_tag)
        for id in more_ids:
            if len(ids) < post_count:
                ids.append(id)
Ejemplo n.º 51
0
from __future__ import print_function
from __future__ import division
from instagram import client, subscriptions, InstagramAPI
import sys
from datetime import date, timedelta
import json
import time
import datetime
import shutil
import operator
from pylab import *

#access_token='1529897738.f4dfaeb.53403a45baed421ca216921b2f136c97'
#access_token='1529897738.2d6fe64.87556684de0d4ce1aa6afbf423a8cada'
access_token = '1546646729.2d6fe64.91d6953b286d467ea889016903648d96'
api = InstagramAPI(access_token=access_token)
print_all_users = 0


def is_empty(any_structure):
    if any_structure:
        #print('Structure is not empty.')
        return False
    else:
        #print('Structure is empty.')
        return True


#open source and results files
print("*** Remaining API Calls = %s/%s" %
      (api.x_ratelimit_remaining, api.x_ratelimit))
Ejemplo n.º 52
0
def mlist(tag):
    app.logger.debug("tag=" + tag)
    api = InstagramAPI(client_id=CLIENT_ID)
    items, next = api.tag_recent_media(count=12, tag_name=tag)
    return render_template("_mitem.html", items=items)
Ejemplo n.º 53
0
        bridge.twitter_last_id = new_tweets[0].id
        bridge.updated = datetime.now()

    new_tweets.reverse()

    #
    # Instagram
    #

    new_instas = []

    if bridge.instagram_access_code:

        l.debug(f"-- INSTAGRAM: {bridge.instagram_handle} --")

        api = InstagramAPI(access_token=bridge.instagram_access_code, client_secret=c.INSTAGRAM_SECRET)

        try:
            recent_media, _ = api.user_recent_media(user_id=bridge.instagram_account_id)
        except Exception as e:
            l.error(e)
            continue

        for media in recent_media:

            ts = datetime_to_timestamp(media.created_time)

            if ts > bridge.instagram_last_id:
                new_instas.append(media)

        if c.SEND and len(new_instas) != 0: