Beispiel #1
0
def like_post(driver):
    url = get_url(driver)
    try:
        Like.select().where(Like.url == url).get()
    except Like.DoesNotExist:
        pass
    else:
        log.info('Post has already been liked {url}'.format(url=url))
        return False

    try:
        like_btn = driver.find_element_by_xpath("//span[@aria-label='Like']")
    except NoSuchElementException:
        log.info('Could not find like button {}'.format(driver.current_url))
        time.sleep(1)

        return False
    else:
        log.info('Found like button. Trying to like {}'.format(
            driver.current_url))
        like_btn.click()

        Like.create(url=url)

    log.info('Liked picture {url}'.format(url=url))

    return True
Beispiel #2
0
def album_detail_page(album_id=0, page=0):
    if page <= 0:
        abort(404)

    album = model_to_dict(Album.get(Album.id == album_id))
    if not album:
        abort(404)
    total_page = int(math.ceil(album['count'] * 1.0 / config.ITEMS_PER_PAGE))

    comments = list(Comment.select().where(
        Comment.entry_id == album_id).order_by(Comment.t).dicts())
    likes = list(Like.select().where(Like.entry_id == album_id).dicts())

    uids = list(
        set([c['authorId'] for c in comments] + [l['uid'] for l in likes]))
    users = dict([(u['uid'], {
        'name': u['name'],
        'headPic': u['headPic']
    }) for u in User.select().where(User.uid.in_(uids)).dicts()])

    photos = list(Photo.select().where(Photo.album_id == album_id).order_by(
        Photo.pos).paginate(page, config.ITEMS_PER_PAGE).dicts())
    return render_template("album.html",
                           album=album,
                           page=page,
                           total_page=total_page,
                           comments=comments,
                           likes=likes,
                           users=users,
                           photos=photos)
Beispiel #3
0
def entry_comments_api(entry_id=0):
    comments = list(Comment.select().where(
        Comment.entry_id == entry_id).order_by(Comment.t).dicts())
    likes = list(Like.select().where(Like.entry_id == entry_id).dicts())

    uids = list(
        set([c['authorId'] for c in comments] + [l['uid'] for l in likes]))
    users = dict()

    u_start = 0
    u_size = 64
    while u_start < len(uids):
        for u in User.select().where(
                User.uid.in_(uids[u_start:u_start + u_size])).dicts():
            users[u['uid']] = {'name': u['name'], 'headPic': u['headPic']}
        u_start += u_size

    for like in likes:
        like['name'] = users.get(like['uid'], {}).get('name', '')
        like['headPic'] = users.get(like['uid'], {}).get('headPic', '')

    for comment in comments:
        comment['headPic'] = users.get(comment['authorId'],
                                       {}).get('headPic', '')

    ret = dict(comments=comments, likes=likes, users=users)
    if request.path.split('/')[1] == 'comments':
        return jsonify(ret)
    return ret
Beispiel #4
0
def entry_comments_api(entry_id=0):
    comments = list(
        Comment.select().where(Comment.entry_id == entry_id).order_by(Comment.t).dicts()
    )
    likes = list(Like.select().where(Like.entry_id == entry_id).dicts())

    uids = list(
        set([c["authorId"] for c in comments] + [like["uid"] for like in likes])
    )
    users = {}

    u_start = 0
    u_size = 64
    while u_start < len(uids):
        for u in (
            User.select().where(User.uid.in_(uids[u_start : u_start + u_size])).dicts()
        ):
            users[u["uid"]] = {"name": u["name"], "headPic": u["headPic"]}
        u_start += u_size

    for like in likes:
        like["name"] = users.get(like["uid"], {}).get("name", "")
        like["headPic"] = users.get(like["uid"], {}).get("headPic", "")

    for comment in comments:
        comment["headPic"] = users.get(comment["authorId"], {}).get("headPic", "")

    ret = dict(comments=comments, likes=likes, users=users)
    if request.path.split("/")[1] == "comments":
        return jsonify(ret)
    return ret
Beispiel #5
0
def entry_comments_api(entry_id=0):
    comments = list(Comment.select().where(
        Comment.entry_id == entry_id).order_by(Comment.t).dicts())
    likes = list(Like.select().where(Like.entry_id == entry_id).dicts())
    uids = list(
        set([c['authorId'] for c in comments] + [l['uid'] for l in likes]))
    users = dict([(u['uid'], {
        'name': u['name'],
        'headPic': u['headPic']
    }) for u in User.select().where(User.uid.in_(uids)).dicts()])
    return jsonify(comments=comments, likes=likes, users=users)
Beispiel #6
0
def photo_detail_page(photo_id=0):
    photo = model_to_dict(Photo.get(Photo.id == photo_id))
    if not photo:
        abort(404)

    comments = list(Comment.select().where(
        Comment.entry_id == photo_id).order_by(Comment.t).dicts())
    likes = list(Like.select().where(Like.entry_id == photo_id).dicts())

    # TODO: show comments in photo detail page
    return render_template("photo.html",
                           photo=photo,
                           comments=comments,
                           likes=likes)
    def get(self, user):
        '''
        "analytics about how many likes was made"
        Example url: /api/activity/username
        :param user: username
        :return: when user was login last time
        and when he mades a last request to the service
        '''
        app.logger.info(request)

        def time_query(query):
            post_time = []
            for content in query:
                post_time.append(str(content.timestamp))
            if len(post_time) > 1:
                return post_time[-1]
            elif len(post_time) > 0:
                return post_time[0]
            else:
                return 0

        jwt_token = request.headers.get('authorization', None)
        if jwt_token:
            try:
                decoded = jwt.decode(jwt_token,
                                     JWT_SECRET_KEY,
                                     algorithms='HS256')
                iat = datetime.datetime.fromtimestamp(int(decoded['iat']))

            except (jwt.DecodeError, jwt.ExpiredSignatureError):
                return {'message': 'Token is invalid'}

        user_id = User.get(User.username == user)
        post_time_query = Post.select().where(Post.user_id == user_id)
        like_time_query = Like.select().where(Like.user_id == user_id)
        unlike_time_query = Unlike.select().where(Unlike.user_id == user_id)

        return {
            'login time': str(iat),
            'post time': time_query(post_time_query),
            'like time': time_query(like_time_query),
            'unlike time': time_query(unlike_time_query),
            'code': 200
        }
Beispiel #8
0
 def resolve_liked_by(source, info):
     return [
         like.user for like in Like.select().where(Like.post == source.id)
     ]
    def get(self):
        '''
        "analytics about how many likes was made"
        Example url: /api/analitics/?date_from=2020-02-02&date_to=2020-02-15
        :return: analytics aggregated by day
        '''
        data = parser_like_count.parse_args()
        app.logger.info(request)
        date___from, date___to = data['date_from'], data['date_to']
        date__from = date___from + ' 00:00:00.000001'
        date__to = date___to + ' 00:00:00.000001'
        date_from = datetime.datetime.strptime((date__from),
                                               '%Y-%m-%d %H:%M:%S.%f')
        date_to = datetime.datetime.strptime((date__to),
                                             '%Y-%m-%d %H:%M:%S.%f')
        all_like = Like.select().where((Like.timestamp > date_from)
                                       & (Like.timestamp < date_to)).count()
        all_unlike = Unlike.select().where((Unlike.timestamp > date_from) & (
            Unlike.timestamp < date_to)).count()

        days = []
        day = (Like.select(
            Like.timestamp).where((Like.timestamp > date_from)
                                  & (Like.timestamp < date_to)).tuples())
        for d in day:
            days.append(d[0].strftime("%m/%d/%Y"))
        days_list = list(reversed(list(unique_everseen(days))))

        count_likes = []
        query = (Like.select(fn.count(Like.id).alias('count')).group_by(
            fn.date_trunc(
                'day',
                Like.timestamp)).where((Like.timestamp > date_from)
                                       & (Like.timestamp < date_to)).tuples())
        for q in query:
            count_likes.append(q[0])
        agr_like = dict(zip(days_list, count_likes))

        unlike_days = []
        unlike_day = (Unlike.select(
            Unlike.timestamp).where((Unlike.timestamp > date_from)
                                    & (Unlike.timestamp < date_to)).tuples())
        for d in unlike_day:
            unlike_days.append(d[0].strftime("%m/%d/%Y"))
        unlike_days_list = list(reversed(list(unique_everseen(unlike_days))))

        count_unlikes = []
        query = (Unlike.select(fn.count(Unlike.id).alias('count')).group_by(
            fn.date_trunc('day', Unlike.timestamp)).where(
                (Unlike.timestamp > date_from)
                & (Unlike.timestamp < date_to)).tuples())
        for q in query:
            count_unlikes.append(q[0])

        agr_unlike = dict(zip(unlike_days_list, count_unlikes))
        app.logger.info('count likes by day')
        return {
            'all like from period': all_like,
            'all unlike from period': all_unlike,
            'count likes by day': agr_like,
            'count unlikes by day': agr_unlike,
            'code': 200
        }
    def post(self):
        data = parser_like.parse_args()
        app.logger.info(request)
        like = data['like']
        post_id = data['post_id']
        username = get_jwt_identity()
        user_id = User.select().where(User.username == username)
        if Post.select().where((Post.user_id == user_id)
                               & (Post.id == post_id)).count() > 0:
            app.logger.info(
                'This post is yours. You are not entitled to this action')
            return {
                'message':
                'This post is yours. You are not entitled to this action',
                'code': 200
            }
        else:
            if like == 'True':
                if Like.select().where((Like.user_id == user_id) &
                                       (Like.post_id == post_id)).count() > 0:
                    resp = jsonify({
                        'refresh': True,
                        'action': 'like',
                        'code': 200
                    })
                    return resp

                elif Unlike.select().where((Unlike.user_id == user_id) & (
                        Unlike.post_id == post_id)).count() > 0:
                    try:
                        category = Unlike.get((Unlike.user_id == user_id)
                                              & (Unlike.post_id == post_id))
                        category.delete_instance()
                        app.logger.info(
                            'delete_instance_Unlike{}'.format(post_id))

                    except:
                        app.logger.error('Something went wrong (False)')
                        return {
                            'message': 'Something went wrong (False)',
                            'code': 500
                        }
                try:
                    Like.create(user_id=user_id, post_id=post_id)
                    resp = jsonify({
                        'refresh': True,
                        'action': 'like',
                        'code': 200
                    })
                    return resp

                except:
                    app.logger.error(
                        'Something went wrong (delete_instance_Unlike)')
                    return {
                        'message':
                        'Something went wrong (delete_instance_Unlike)',
                        'code': 500
                    }

            elif like == 'False':
                if Unlike.select().where((Unlike.user_id == user_id) & (
                        Unlike.post_id == post_id)).count() > 0:
                    resp = jsonify({
                        'refresh': True,
                        'action': 'unlike',
                        'code': 200
                    })
                    return resp
                elif Like.select().where((Like.user_id == user_id) & (
                        Like.post_id == post_id)).count() > 0:
                    try:
                        category = Like.get((Like.user_id == user_id)
                                            & (Like.post_id == post_id))
                        category.delete_instance()
                        app.logger.info(
                            'delete_instance_Like{}'.format(post_id))

                    except:
                        app.logger.error(
                            'Something went wrong (delete_instance_Like)')
                        return {
                            'message':
                            'Something went wrong (delete_instance_Like)',
                            'code': 500
                        }
                try:
                    Unlike.create(user_id=user_id, post_id=post_id)  #
                    resp = jsonify({
                        'refresh': True,
                        'action': 'unlike',
                        'code': 200
                    })
                    return resp

                except:
                    app.logger.error('Something went wrong (False)')
                    return {
                        'message': 'Something went wrong (False)',
                        'code': 500
                    }