Exemplo n.º 1
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
Exemplo n.º 2
0
def comment_to_dict(comment):
    comment_dict = {
        'id': comment.id,
        'text': comment.text,
        'created_time': datetime_to_timestamp(comment.created_at),
        'from': user_to_dict(comment.user)
    }

    return comment_dict
Exemplo n.º 3
0
Arquivo: app.py Projeto: 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'))
Exemplo n.º 4
0
    def find_tags(self, coords, distance, max_date, min_date, logger):
        self.all_media = set()
        max_stamp = max_date
        attempts = self.MAX_ATTEMPTS

        while max_stamp > min_date:
            try:
                logger.debug(
                    "Send request {0}: lat:{1} long:{2} dist:{3} max:{4} count:{5}"
                    .format(threading.current_thread().ident, coords[0],
                            coords[1], distance, max_stamp,
                            self.MAX_SEARCH_COUNT))
                media = self.__api.media_search(lat=coords[0],
                                                lng=coords[1],
                                                distance=distance,
                                                max_timestamp=max_stamp,
                                                count=self.MAX_SEARCH_COUNT)
            except InstagramAPIError as ex:
                if ex.error_type == "Rate limited":
                    raise InstaGrabberBanException(ex.error_message,
                                                   ex.status_code)
                else:
                    raise ex
            except InstagramClientError as ex:
                if attempts > 0:
                    attempts -= 1
                    continue
                else:
                    raise ex
            logger.debug("Answer received {0}".format(
                threading.current_thread().ident))

            if len(media) == 0: break

            self.all_media |= set(media)

            if max_stamp <= datetime_to_timestamp(media[-1].created_time):
                max_stamp = max_stamp - 3600
            else:
                max_stamp = datetime_to_timestamp(media[-1].created_time)
Exemplo n.º 5
0
def media_to_dict(media):
    media_dict = {
        'id': media.id,
        'user': user_to_dict(media.user),
        'images': {},
        'videos': {},
        'user_has_liked': media.user_has_liked,
        'like_count': media.like_count,
        'likes': [],
        'comment_count': media.comment_count,
        'comments': [],
        'created_time': datetime_to_timestamp(media.created_time),
        'location': None,
        'caption': None,
        'tags': [],
        'users_in_photo': [],
        'link': media.link,
        'filter': media.filter
    }

    if hasattr(media, 'images'):
        for version, image in media.images.iteritems():
            media_dict['images'][version] = image_to_dict(image)

    if hasattr(media, 'videos'):
        for version, video in media.videos.iteritems():
            media_dict['videos'][version] = image_to_dict(video)

    if hasattr(media, 'likes'):
        for like in media.likes:
            media_dict['likes'].append(user_to_dict(like))

    if hasattr(media, 'comments'):
        for comment in media.comments:
            media_dict['comments'].append(comment_to_dict(comment))

    if hasattr(media, 'location'):
        media_dict['location'] = location_to_dict(media.location)

    if hasattr(media, 'caption'):
        if media.caption is not None:
            media_dict['caption'] = comment_to_dict(media.caption)

    if hasattr(media, 'tags'):
        for tag in media.tags:
            media_dict['tags'].append(tag_to_dict(tag))

    if hasattr(media, 'users_in_photo'):
        for user_in_photo in media.users_in_photo:
            media_dict['users_in_photo'].append(user_in_photo_to_dict(user_in_photo))

    return media_dict
Exemplo n.º 6
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'))
Exemplo n.º 7
0
    def id(self):
        ts = datetime_to_timestamp(self.data.created_time)

        return ts
Exemplo n.º 8
0
    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:
            bridge.instagram_last_id = datetime_to_timestamp(new_instas[0].created_time)
    new_instas.reverse()

    #
    # Post Toots to Twitter
    #

    tweet_poster = TweetPoster(c.SEND, session, twitter_api, bridge)

    if bridge.t_settings.post_to_twitter_enabled and len(new_toots) > 0:
Exemplo n.º 9
0
 def is_media_in_range(m):
     return datetime_to_timestamp(m.created_time) < max_timestamp and \
            datetime_to_timestamp(m.created_time) >= min_timestamp
Exemplo n.º 10
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