Example #1
0
 def follow(self, user):
     from models.follow import Follow
     if self.id != user.id and self.is_following(user) == False and self.is_requesting(user) == False:
         follow = Follow(follower_id=self.id, followed_id=user.id)
         follow.save()
     else:
         return 0  
Example #2
0
    def create(cls, text, user, pointRoot, parent=None):
        parentCommentKey = None
        parentComment = None
        if parent:
            parentCommentKey = ndb.Key(urlsafe=parent)
            parentComment = parentCommentKey.get()
            if not parentComment:
                raise WhysaurusException("Bad parent comment key supplied.")
            elif parentComment.level >= 8:
                raise WhysaurusException("9 levels of replies are maximum for now.")

        if pointRoot:
            comment = Comment(
                parent=parentCommentKey,
                text=text,
                userName=user.name,
                userUrl=user.url,
                avatar_url=user.avatar_url
                if hasattr(user, "avatar_url")
                else "/static/img/icon_triceratops_black_47px.png",
                parentComment=parentCommentKey,
                level=parentComment.level + 1 if parentComment else 0,
            )
            newComment = comment.transactionalCreate(pointRoot, comment)
            Follow.createFollow(user.key, pointRoot.key, "commented on")
            return newComment
        else:
            return None
Example #3
0
def follow_route(request):
    """
    Follow a card, unit, or set.
    """

    # TODO-3 simplify this method. does some of this belong in the model?

    db_conn = request["db_conn"]
    current_user = get_current_user(request)
    if not current_user:
        return abort(401)

    follow_data = dict(**request["params"])
    follow_data["user_id"] = current_user["id"]

    follow = Follow(follow_data)
    errors = follow.validate(db_conn)
    if errors:
        return 400, {"errors": errors, "ref": "4Qn9oWVWiGKvXSONQKHSy1T6"}

    follow, errors = follow.save(db_conn)
    if errors:
        return 400, {"errors": errors, "ref": "gKU6wgTItxpKyDs0eAlonCmi"}

    return 200, {"follow": follow.deliver(access="private")}
Example #4
0
def test_list_kind(db_conn, follows_table):
    """
    Expect to get follows by kind.
    """

    follows_table.insert([{
        'user_id': 'JFldl93k',
        'created': r.now(),
        'modified': r.now(),
        'entity': {
            'kind': 'card',
            'id': 'JFlsjFm',
        },
    }, {
        'user_id': 'abcd1234',
        'created': r.now(),
        'modified': r.now(),
        'entity': {
            'kind': 'card',
            'id': 'JFlsjFm',
        },
    }, {
        'user_id': 'abcd1234',
        'created': r.now(),
        'modified': r.now(),
        'entity': {
            'kind': 'unit',
            'id': 'u39Fdjf0',
        },
    }]).run(db_conn)

    assert len(Follow.list(kind='card')) == 2
    assert len(Follow.list(kind='unit')) == 1
Example #5
0
    def get(self, blip_key=None):
        blip = Blip.get(blip_key)
        if blip is None:
            return self.error(404)
        login_user = self.get_current_user()
        if blip.meeting and not blip.meeting.has_member(login_user):
            return self.error(401)
        user = blip.user
        _, profile = Profile.get_or_create_from_user(user)

        is_self = user == login_user

        has_followed = False
        if not is_self:
            has_followed = Follow.gql('WHERE from_user = :1 AND to_user = :2',
                                      login_user, user).get() is not None            

        followers = Follow.who_subscribe_you(user)
        follower_profiles = []
        for f in followers:
            c, p = Profile.get_or_create_from_user(f.from_user)
            follower_profiles.append(p)
        followees = Follow.your_subscribers(user)
        followee_profiles = []
        for f in followees:
            c, p = Profile.get_or_create_from_user(f.to_user)
            followee_profiles.append(p)


        return self.render('blip_item.html', locals())
Example #6
0
def test_list_kind(db_conn, follows_table):
    """
    Expect to get follows by kind.
    """

    follows_table.insert([{
        'user_id': 'JFldl93k',
        'created': r.now(),
        'modified': r.now(),
        'entity': {
            'kind': 'card',
            'id': 'JFlsjFm',
        },
    }, {
        'user_id': 'abcd1234',
        'created': r.now(),
        'modified': r.now(),
        'entity': {
            'kind': 'card',
            'id': 'JFlsjFm',
        },
    }, {
        'user_id': 'abcd1234',
        'created': r.now(),
        'modified': r.now(),
        'entity': {
            'kind': 'unit',
            'id': 'u39Fdjf0',
        },
    }]).run(db_conn)

    assert len(Follow.list(db_conn, kind='card')) == 2
    assert len(Follow.list(db_conn, kind='unit')) == 1
Example #7
0
    def create(cls, text, user, pointRoot, parent=None):
        parentCommentKey = None
        parentComment = None
        if parent:
            parentCommentKey = ndb.Key(urlsafe=parent)
            parentComment = parentCommentKey.get()
            if not parentComment:
                raise WhysaurusException("Bad parent comment key supplied.")
            elif parentComment.level >= 8:
                raise WhysaurusException(
                    "9 levels of replies are maximum for now.")

        if pointRoot:
            comment = Comment(
                parent=parentCommentKey,
                text=text,
                userName=user.name,
                userUrl=user.url,
                avatar_url=user.avatar_url if hasattr(user, 'avatar_url') else
                '/static/img/icon_triceratops_black_47px.png',
                parentComment=parentCommentKey,
                level=parentComment.level + 1 if parentComment else 0)
            newComment = comment.transactionalCreate(pointRoot, comment)
            Follow.createFollow(user.key, pointRoot.key, "commented on")
            return newComment
        else:
            return None
Example #8
0
def follow(username):
    idol_id = request.form.get('idol_id')
    f = Follow(fan=current_user.id, idol=idol_id)
    idol = User.get_by_id(idol_id)
    f.save()
    flash(f'You are now following {idol.username}', 'success')
    return redirect(url_for('users.show', username=idol.username))
Example #9
0
    def get(self):
        user = self.get_current_user()
        created, profile = Profile.get_or_create_from_user(user)

        followers = Follow.who_subscribe_you(user)
        follower_profiles = []
        for f in followers:
            c, p = Profile.get_or_create_from_user(f.from_user)
            follower_profiles.append(p)
        followees = Follow.your_subscribers(user)
        followee_profiles = []
        for f in followees:
            c, p = Profile.get_or_create_from_user(f.to_user)
            followee_profiles.append(p)
        try:
            page = int(self.request.get('page', '1'))
        except ValueError:
            page = 1

        pagesize = settings.BLIP_PAGE_SIZE
        paginator = SimplePaginator(BlipLink.qs_for_user(user),
                                    page, pagesize)
        blips = each_profiles(paginator.object_list, field='author')
        is_self = True
        return self.render('home.html', locals())
 def unfollow(self, user):
     from models.follow import Follow
     if self.is_following(user):
         Follow.delete().where(Follow.follower_id == self.id,
                               Follow.followed_id == user.id,
                               Follow.approved == True).execute()
     else:
         return 0
 def approve(self, user):
     from models.follow import Follow
     if user.is_requesting(self):
         Follow.update(approved=True).where(
             Follow.followed_id == self.id,
             Follow.follower_id == user.id).execute()
     else:
         return 0
 def cancel_request(self, user):
     from models.follow import Follow
     if self.is_requesting(user):
         Follow.delete().where(Follow.follower_id == self.id,
                               Follow.followed_id == user.id,
                               Follow.approved == False).execute()
     else:
         return 0
Example #13
0
def follow(request):
    followed_id = int(request.query['user_id'])
    follower_id = current_user(request).id
    form = dict(
        follower_id=follower_id,
        followed_id=followed_id,
    )
    Follow.new(form)
    return redirect('/weibo')
def create_follow(fans_id):
    fan_id = fans_id
    idol_id = current_user.id
    follow = Follow(idol_id=idol_id, fan_id=fan_id)
    follow.save()
    request_delete = Requested.delete().where(Requested.idol_id == idol_id,
                                              Requested.fan_id == fan_id)
    request_delete.execute()
    return redirect(url_for('users.show', username=current_user.name))
Example #15
0
    def follow(self, following):
        from models.follow import Follow

        if self.follow_status(following) == None:
            relationship = Follow(follower=self.id, following=following)
            if not following.private:
                relationship.is_approved = True
            return relationship.save()
        else:
            return 0
Example #16
0
 def deliver_to_followers(self):
     subscribers = Follow.who_subscribe_you(self.user)
     users = set(f.from_user for f in subscribers)
     if self.to_user:
         to_subscribers = set(Follow.who_subscribe_you(self.to_user))
         users = users.intersection(set(f.from_user for f in
                                        to_subscribers))
         users.add(self.to_user)
     #users.add(self.user)
     self.deliver_to_users(users)
Example #17
0
def follow_public(username):
    user = User.get_or_none(username=username)
    if user is not None:
        followship = Follow(followed_id=user.id, follower_id=current_user.id)
        if followship.save():
            flash(f"You have successfully followed {user.username}!",
                  'success')
            return redirect(url_for('users.show', username=username))
        else:
            flash("Follow failed!", 'danger')
            return render_template("users/profile.html")
Example #18
0
 def DeleteDuplicateFollows(self):
     q = Follow.query()
     i = 0 
     for f in q.iter():
         i = i+1
         q2 = Follow.query(ndb.AND(Follow.user == f.user, Follow.pointRoot == f.pointRoot))     
         existingFollows = q2.fetch(4)
         if len(existingFollows) > 1:
             for ef in existingFollows[1:]:
                 logging.info('Deleting follow for R:%s U:%s T:%s' % (str(ef.pointRoot), str(ef.user), ef.reason))
                 ef.key.delete()
     logging.info('Checked %d follows' % i)
Example #19
0
def add():
    u = current_user()
    if u:
        form = request.form
        print('ceuicec')

        f = Follow(form)
        f.fans = u
        f.save()
    else:
        message = '关注功能需要登录'
        return render_template('user_login.html', message=message)
Example #20
0
 def DeleteDuplicateFollows(self):
     q = Follow.query()
     i = 0 
     for f in q.iter():
         i = i+1
         q2 = Follow.query(ndb.AND(Follow.user == f.user, Follow.pointRoot == f.pointRoot))     
         existingFollows = q2.fetch(4)
         if len(existingFollows) > 1:
             for ef in existingFollows[1:]:
                 logging.info('Deleting follow for R:%s U:%s T:%s' % (str(ef.pointRoot), str(ef.user), ef.reason))
                 ef.key.delete()
     logging.info('Checked %d follows' % i)
def create():
    idol_id = request.args.get('idol_id')
    f = {}
    f['fan_id'] = current_user.id
    f['idol_id'] = idol_id
    # status currently using default as defined in model
    follow = Follow(**f)
    if follow.save():
        flash("You're now following this user", 'success')
    else: 
        for error in follow.errors:
            flash(error, 'danger')
    return redirect(url_for('users.show', id=idol_id))
Example #22
0
def delete():
    json = request.json
    log('follow delete:', json)
    uid = json['user_id']
    fid = json['follower_id']
    f = User.one(id=fid)
    if fid != session['user_id']:
        abort(401)
    elif f is None:
        abort(404)
    else:
        follow = Follow.one(user_id=uid, follower_id=fid)
        Follow.delete(follow.id)
        return '取消关注成功'
Example #23
0
def follow(id):
    user = User.get_by_id(id)
    # new_follow_instance = Follow(follower_id=current_user.id, followed_user_id=user.id) # Need to swap
    new_follow_instance = Follow(
        follower_id=user.id, followed_user_id=current_user.id)  # Need to swap
    if new_follow_instance.save():
        flash("Follow request accepted successfully")
        return redirect(url_for('users.follow_request',
                                username=current_user.name),
                        code=307)
    else:
        flash("Something went wrong")
        return redirect(url_for('users.follow_request',
                                username=current_user.name),
                        code=307)
Example #24
0
    def follow(self, following):
        from models.follow import Follow
        if Follow.get_or_none(Follow.follower == self.id,
                              Follow.following == following.id):
            return False
        else:
            if following.is_private:
                Follow.create(follower=self.id,
                              following=following.id,
                              is_approved=False)
            else:
                Follow.create(follower=self.id,
                              following=following.id,
                              is_approved=True)

            return True
Example #25
0
 def feed(cls, u):
     fs: List[Follow] = Follow.all(follower_id=u.id)
     weibos = []
     for f in fs:
         follwed_weibos = Weibo.all(user_id=f.followed_id)
         weibos.extend(follwed_weibos)
     return weibos
Example #26
0
 def is_requesting(self, user):
     from models.follow import Follow
     result = Follow.select().where(Follow.follower_id == self.id, Follow.followed_id == user.id, Follow.approved== False)
     if len(result) > 0:
         return True
     else:
         return False
Example #27
0
    def MakeFollows(self):
        """
        # ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
        ADD FOLLOWS FOR ADMIN USERS
        # ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 
        """
        nextURL = None
        firstURL = self.request.get('nexturl')
        query = PointRoot.query().order(PointRoot.url)
        if firstURL:
            query = query.filter(PointRoot.url >= firstURL)
        pointRoots = query.fetch(11)
        if len(pointRoots) == 11:
            nextURL = pointRoots[-1].url
            pointRootsToReview = pointRoots[:10]
        else:
            pointRootsToReview = pointRoots

        i = 0
        for pointRoot in pointRootsToReview:
            pointRootKey = pointRoot.key
            followers = {}

            versions = pointRoot.getAllVersions()
            for point in versions:
                if point.version == 1:
                    followers[point.authorURL] = 'created'
                elif not point.authorURL in followers:
                    followers[point.authorURL] = 'edited'

            for comment in pointRoot.getComments():
                if not comment.userUrl in followers:
                    followers[comment.userUrl] = 'commented'

            logging.info('ROOT: %s FOLLOWERS: %s' %
                         (pointRoot.url, str(followers)))
            for url in followers.iterkeys():
                followType = followers[url]
                previousNamespace = namespace_manager.get_namespace()
                if previousNamespace and previousNamespace != '':
                    namespace_manager.set_namespace('')  # DEFAULT NAMESPACE
                    usr = WhysaurusUser.getByUrl(url)
                    namespace_manager.set_namespace(previousNamespace)
                else:
                    usr = WhysaurusUser.getByUrl(url)
                logging.info('Trying to follow for U:%s, R:%s, T:%s' %
                             (url, pointRoot.url, followType))
                f = None
                f = Follow.createFollow(usr.key, pointRootKey, followType)
                if f:
                    i = i + 1
                    logging.info('ADDED follow for U:%s, R:%s, T:%s' %
                                 (url, pointRoot.url, followType))

        logging.info('Added %d follows' % i)
        if nextURL:
            t = Task(url="/MakeFollows", params={'nexturl': nextURL})
            t.add(queue_name="notifications")
            logging.info('Requeing MakeFollows task to start at url %s ' %
                         nextURL)
Example #28
0
def show(username):
    user = User.get_or_none(name=username)
    if current_user.is_authenticated:
        if user is not None:
            # followers = user.followers
            follower = Follow.get_or_none(follower_id=current_user.id,
                                          followed_user_id=user.id)
            follow_requester = Follow_Request.get_or_none(
                follow_requester_id=current_user.id,
                follow_requested_user_id=user.id)
            images = user.pictures  # Utilizing the backref
            number_of_followers = len(user.followers)
            number_of_followings = len(user.followings)
            return render_template('users/profile.html',
                                   user=user,
                                   images=images,
                                   follower=follower,
                                   follow_requester=follow_requester,
                                   number_of_followers=number_of_followers,
                                   number_of_followings=number_of_followings)
        else:
            flash("This user does not exist")
            return redirect(url_for('home'))
    else:
        flash('Please sign in to view profiles')
        return redirect(url_for('home'))
Example #29
0
    def on_success(self, data):
        event_type = "untracked"

        if data.get('direct_message'):
            event_type = "Direct Message"

            dm = DirectMessage(data)
            self.on_direct_message(dm)

        elif data.get('event') and data['event'] == 'follow':
            event_type = "Follow"

            follow = Follow(data)
            self.on_follow(follow)

        elif data.get('text'):
            event_type = "Status"
            status = Status(data)

            # ignore RTs for now
            if status.type is 'retweet':
                event_type = "{0} -- Retweet".format(event_type)
            else:
                # if it's a reply, handle as such
                # otherwise, for now, do nothing.
                if status.reply_to_user():
                    event_type = "{0} -- Reply".format(event_type)
                    self.on_reply(status)

        print "{0} data received. Type: {1}".format(self.__class__.__name__,
                                                    event_type)
        print data
Example #30
0
def unfollow(username):
    user = User.get_or_none(username=username)
    if user is not None:
        unfollow = Follow.get_or_none(followed_id=user.id)
        if unfollow.delete_instance():
            flash(f"Successfully unfollowed {user.username}!", 'success')
            return redirect(url_for('users.show', username=username))
Example #31
0
def get_user_route(request, user_id):
    """
    Get the user by their ID.
    """

    db_conn = request["db_conn"]
    user = get_user({"id": user_id}, db_conn)
    current_user = get_current_user(request)
    # Posts if in request params
    # Sets if in request params and allowed
    # Follows if in request params and allowed
    if not user:
        return abort(404)

    data = {}
    data["user"] = deliver_user(user, access="private" if current_user and user["id"] == current_user["id"] else None)

    # TODO-2 SPLITUP create new endpoints for these instead
    if "posts" in request["params"]:
        data["posts"] = [post.deliver() for post in get_posts_facade(db_conn, user_id=user["id"])]
    if "sets" in request["params"] and user["settings"]["view_sets"] == "public":
        u_sets = UserSets.get(db_conn, user_id=user["id"])
        data["sets"] = [set_.deliver() for set_ in u_sets.list_sets(db_conn)]
    if "follows" in request["params"] and user["settings"]["view_follows"] == "public":
        data["follows"] = [follow.deliver() for follow in Follow.list(db_conn, user_id=user["id"])]
    if "avatar" in request["params"]:
        size = int(request["params"]["avatar"])
        data["avatar"] = get_avatar(user["email"], size if size else None)

    return 200, data
Example #32
0
def get_feed_posts():

    # gets all of the follow instance where the user matches the followed_by field
    users_followers = Follow.select().where(
        Follow.followed_by == current_user.id)

    # iterate over all of the users that follow the current user and get all
    # of their posts
    users_feed = []
    for user in users_followers:
        posts = Post.select().where(Post.user == user.followed,
                                    Post.soft_delete == False)

        # converts each post to a dictionary, removes the password and adds it to
        # users_feed list
        for post in posts:
            post_dict = model_to_dict(post, backrefs=True, recurse=True)
            del post_dict['user']['password']
            users_feed.append(post_dict)

    # sorts all of the post in the users feed by most recent
    users_feed_sorted = sorted(users_feed,
                               key=itemgetter('timestamp'),
                               reverse=True)

    return jsonify(data=users_feed_sorted,
                   status={
                       'code': 200,
                       'message': 'Successfully got the users feed'
                   })
def delete_follow(idols_id):
    user = User.get_by_id(idols_id)
    fan_id = current_user.id
    idol_id = idols_id
    follow_delete = Follow.delete().where(Follow.idol_id == idol_id,
                                          Follow.fan_id == fan_id)
    follow_delete.execute()
    return redirect(url_for('users.show', username=user.name))
Example #34
0
def add():
    json = request.json
    log('follow add:', json)
    uid = json['user_id']
    fid = json['follower_id']
    f = User.one(id=fid)
    if fid != session['user_id']:
        abort(401)
    elif f is None:
        abort(404)
    else:
        d = {
            'user_id': uid,
            'follower_id': fid,
        }
        Follow.new(d)
        return '关注成功'
Example #35
0
    def post(self, user_id):
        user = users.get_current_user()
        o_user = User.get_by_id(int(user_id))
        u_email = user.email()
        o_email = o_user.email
        follow_user = self.request.get("follow")

        if follow_user == "follow":
            follow = Follow(user_id=u_email, following_id=o_email)
            follow.put()
            return self.redirect('/other/' + str(user_id))
        else:
            following = Follow.query(Follow.user_id == u_email,
                                     Follow.following_id == o_email).get()
            following.key.delete()

            return self.redirect('/other/' + str(user_id))
Example #36
0
def follow_route(request):
    """
    Follow a card, unit, or set.
    """

    # TODO-3 simplify this method. does some of this belong in the model?

    current_user = get_current_user(request)
    if not current_user:
        return abort(401)

    follow_data = dict(**request['params'])
    follow_data['user_id'] = current_user['id']

    follow = Follow(follow_data)
    errors = follow.validate()
    if errors:
        return 400, {
            'errors': errors,
            'ref': '4Qn9oWVWiGKvXSONQKHSy1T6'
        }

    # Ensure the entity exists   TODO-3 should this be a model validation?
    if follow['entity']['kind'] == 'topic':
        entity = Topic.get(id=follow['entity']['id'])
    else:
        entity = get_latest_accepted(follow['entity']['kind'],
                                     follow['entity']['id'])
    if not entity:
        return abort(404)

    # Ensure we don't already follow   TODO-3 should this be a model validation?
    prev = Follow.list(user_id=current_user['id'],
                       entity_id=follow_data['entity']['id'])
    if prev:
        return abort(409)

    follow, errors = follow.save()
    if errors:
        return 400, {
            'errors': errors,
            'ref': 'gKU6wgTItxpKyDs0eAlonCmi',
        }

    return 200, {'follow': follow.deliver(access='private')}
Example #37
0
    def MakeFollows(self):
        """
        # ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
        ADD FOLLOWS FOR ADMIN USERS
        # ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 
        """
        nextURL = None
        firstURL = self.request.get('nexturl')
        query = PointRoot.query().order(PointRoot.url)
        if firstURL:
            query = query.filter(PointRoot.url >= firstURL)
        pointRoots = query.fetch(11)
        if len(pointRoots) == 11:
            nextURL = pointRoots[-1].url
            pointRootsToReview = pointRoots[:10]
        else:
            pointRootsToReview = pointRoots
        
        i = 0
        for pointRoot in pointRootsToReview:
            pointRootKey = pointRoot.key
            followers = {}     
                          
            versions = pointRoot.getAllVersions()
            for point in versions:
                if point.version == 1:
                    followers[point.authorURL] = 'created'         
                elif not point.authorURL in followers:
                    followers[point.authorURL] = 'edited'  
            
            for comment in pointRoot.getComments():
                if not comment.userUrl in followers:
                    followers[comment.userUrl] = 'commented'  
                
            logging.info('ROOT: %s FOLLOWERS: %s' % (pointRoot.url, str(followers)))       
            for url in followers.iterkeys():
                followType = followers[url]
                previousNamespace = namespace_manager.get_namespace()
                if previousNamespace and previousNamespace != '':                
                    namespace_manager.set_namespace('') # DEFAULT NAMESPACE
                    usr = WhysaurusUser.getByUrl(url)
                    namespace_manager.set_namespace(previousNamespace)
                else:
                    usr = WhysaurusUser.getByUrl(url)
                logging.info('Trying to follow for U:%s, R:%s, T:%s' % (url, pointRoot.url, followType))
                f = None
                f = Follow.createFollow(usr.key, pointRootKey, followType)
                if f:
                    i = i + 1
                    logging.info('ADDED follow for U:%s, R:%s, T:%s' % (url, pointRoot.url, followType))

                       
        logging.info('Added %d follows' % i)
        if nextURL:
            t = Task(url="/MakeFollows", params={'nexturl':nextURL})
            t.add(queue_name="notifications")
            logging.info('Requeing MakeFollows task to start at url %s ' % nextURL)
Example #38
0
def delete_request(idol_id):
    identity = get_jwt_identity()
    fan = User.get(username=identity)
    idol = User.get_by_id(idol_id)
    request = Follow.get(fan=fan, idol=idol, is_approve=False)
    if request.delete_instance():
        return jsonify({'message': 'success'})
    else:
        return jsonify({'message': 'failed'})
Example #39
0
def following_list(username):
    user = User.get_or_none(username=username)
    arr = []
    followings = Follow.select().where(Follow.follower_id == user.id)

    if current_user.is_authenticated:
        for following in followings:
            following_details = User.get_or_none(id=following.followed_id)
            if Follow.get_or_none(Follow.follower == current_user.id,
                                  Follow.followed == following_details.id):
                arr.append({"profile": following_details, "status": True})

            else:
                arr.append({"profile": following_details, "status": False})
    else:
        return render_template('users/login_status.html')

    return render_template('users/following.html', followings=arr)
Example #40
0
 def follow(self, user):
     follow = Follow.query.filter_by(followed_id=user.id,
                                     follower_id=self.id).first()
     if follow:
         follow.update(enable=True)
     else:
         follow = Follow(follower_id=self.id, followed_id=user.id)
         db.session.add(follow)
         db.session.commit()
Example #41
0
    def get(self, user_name=None):
        login_user = self.get_current_user()

        if user_name is None:
            return self.redirect('/signin')

        profile = Profile.gql('WHERE nickname=:1', user_name).get()
        if not profile or not profile.is_active:
            return self.error(404)
        user = profile.get_user()
        is_self = user == login_user

        has_followed = False
        if not is_self:
            has_followed = Follow.gql('WHERE from_user = :1 AND to_user = :2',
                                      login_user, user).get() is not None            

        followers = Follow.who_subscribe_you(user)
        follower_profiles = []
        for f in followers:
            c, p = Profile.get_or_create_from_user(f.from_user)
            follower_profiles.append(p)
        followees = Follow.your_subscribers(user)
        followee_profiles = []
        for f in followees:
            c, p = Profile.get_or_create_from_user(f.to_user)
            followee_profiles.append(p)

        try:
            page = int(self.request.get('page', '1'))
        except ValueError:
            page = 1

        has_followed = Follow.gql('WHERE from_user = :1 AND to_user =:2',
                                  login_user,
                                  user).get()
        pagesize = settings.BLIP_PAGE_SIZE
        paginator = SimplePaginator(Blip.qs_for_author(user),
                                    page, pagesize)

        blips = each_profiles(paginator.object_list)
        return self.render('user_page.html', locals())
Example #42
0
 def get(self, user_name=None):
     login_user = self.get_current_user()
     target_profile = ProfileByNickView(user_name).get()
     if target_profile is None:
         return self.error(404)
     target_user = target_profile.get_user()
     follow = Follow.new(login_user, target_user)
     if follow is None:
         return self.error(404)
     follow.update_profile()
     return self.redirect('/home')
Example #43
0
 def get(self, user_name=None):
     login_user = self.get_current_user()
     target_profile = ProfileByNickView(user_name).get()
     if target_profile is None:
         return self.error(404)
     target_user = target_profile.get_user()
     follow = Follow.gql("WHERE from_user=:1 AND to_user=:2", login_user, target_user).get()
     if follow:
         follow.delete()
         follow.update_profile()
     BlipLink.delete_for_author(login_user, target_user)
     return self.redirect('/home')
Example #44
0
def test_user_id(db_conn, follows_table):
    """
    A follow should require a user_id.
    """

    follow, errors = Follow.insert({
        'entity': {
            'id': 'A',
            'kind': 'card',
        }
    })
    assert len(errors) == 1
    follow['user_id'] = 'A'
    follow, errors = follow.save()
    assert len(errors) == 0
Example #45
0
def test_entity(db_conn, follows_table):
    """
    Expect a follow to require an entity kind and id.
    """

    follow, errors = Follow.insert({
        'user_id': 'A',
    })
    assert len(errors) == 2
    follow['entity'] = {
        'id': 'A',
        'kind': 'card',
    }
    follow, errors = follow.save()
    assert len(errors) == 0
Example #46
0
def send_notices(entity_id, entity_kind, notice_kind, notice_data):
    """
    When an event occurs, send notices outs.
    """

    user_ids = Follow.get_user_ids_by_entity(entity_id=entity_id,
                                             entity_kind=entity_kind)
    for user_id in user_ids:
        notice, errors = Notice.insert({
            'user_id': user_id,
            'kind': notice_kind,
            'data': notice_data,
        })
        if errors:
            raise Exception(errors)
Example #47
0
    def AddNotification(self):
        rootKeyUrlsafe = self.request.get('rootKey')
        notifyReasonCode = self.request.get('notifyReasonCode')
        sourceUserUrlsafe = self.request.get('userKey')
        additionalText = self.request.get('additionalText')        

        pointRootKey = ndb.Key(urlsafe=rootKeyUrlsafe)
        sourceUserKey = ndb.Key(urlsafe=sourceUserUrlsafe)
        follows = Follow.getActiveFollowsForPoint(pointRootKey)
        
        for f in follows:
            if f.user != sourceUserKey:
                Notification.createNotificationFromFollow(self, 
                                                          f, pointRootKey, 
                                                          sourceUserKey, 
                                                          int(notifyReasonCode),
                                                          additionalText,
                                                           )
Example #48
0
def get_follows_route(request):
    """
    Get a list of the users follows.
    """

    db_conn = request["db_conn"]

    current_user = get_current_user(request)
    if not current_user:
        return abort(401)

    follows = Follow.list(db_conn, user_id=current_user["id"], **request["params"])

    output = {"follows": [follow.deliver(access="private") for follow in follows]}

    # TODO-3 SPLITUP should this be a different endpoint?
    if "entities" in request["params"]:
        entities = flush_entities(db_conn, [follow["entity"] for follow in follows])
        output["entities"] = [entity.deliver() if entity else None for entity in entities]

    return 200, output
Example #49
0
def get_follows_route(request):
    """
    Get a list of the users follows.
    """

    current_user = get_current_user(request)
    if not current_user:
        return abort(401)

    follows = Follow.list(user_id=current_user['id'], **request['params'])

    output = {
        'follows': [follow.deliver(access='private') for follow in follows]
    }

    # TODO-3 SPLITUP should this be a different endpoint?
    if 'entities' in request['params']:
        entities = flush_entities(follow['entity'] for follow in follows)
        output['entities'] = [entity.deliver() if entity else None
                              for entity in entities]

    return 200, output
Example #50
0
def unfollow_route(request, follow_id):
    """
    Remove a follow. Must be current user's own follow.
    """

    db_conn = request["db_conn"]

    current_user = get_current_user(request)
    if not current_user:
        return abort(401)

    follow = Follow.get(db_conn, id=follow_id)
    if not follow:
        return abort(404)

    if follow["user_id"] != current_user["id"]:
        return abort(403)

    follow, errors = follow.delete(db_conn)
    if errors:
        return 400, {"errors": errors, "ref": "iGmpx8UwoFcKNmSKq9Aocy1a"}

    return 200, {}
Example #51
0
    def get(self, meeting_key=None):
        from models.blip import Blip
        login_user = self.get_current_user()
        meeting = Meeting.get(meeting_key)
        if meeting is None or not meeting.is_active:
            return self.error(404)
        if not meeting.has_member(login_user):
            return self.error(401)
        c, p = Profile.get_or_create_from_user(meeting.creator)
        
        admin_profiles = [p]

        member_profiles = []
        members = meeting.members(include_creator=False)
        for u in members:
            c, p = Profile.get_or_create_from_user(u)
            member_profiles.append(p)

        followees = Follow.your_subscribers(login_user)
        followee_profiles = []
        for f in followees:
            if f.to_user not in members:
                c, p = Profile.get_or_create_from_user(f.to_user)
                followee_profiles.append(p)
            
        try:
            page = int(self.request.get('page', '1'))
        except ValueError:
            page = 1

        pagesize = settings.ROOM_PAGE_SIZE
        paginator = SimplePaginator(Blip.qs_for_meeting(meeting),
                                     page, pagesize)
        
        blips = each_profiles(paginator.object_list)
        return self.render('meeting_item.html', locals())
Example #52
0
def unfollow_route(request, follow_id):
    """
    Remove a follow. Must be current user's own follow.
    """

    current_user = get_current_user(request)
    if not current_user:
        return abort(401)

    follow = Follow.get(id=follow_id)
    if not follow:
        return abort(404)

    if follow['user_id'] != current_user['id']:
        return abort(403)

    follow, errors = follow.delete()
    if errors:
        return 400, {
            'errors': errors,
            'ref': 'iGmpx8UwoFcKNmSKq9Aocy1a'
        }

    return 200, {}
Example #53
0
def get_user_route(request, user_id):
    """
    Get the user by their ID.
    """

    user = User.get(id=user_id)
    current_user = get_current_user(request)
    # Posts if in request params
    # Sets if in request params and allowed
    # Follows if in request params and allowed
    if not user:
        return abort(404)

    data = {}
    data['user'] = user.deliver(access='private'
                                if current_user
                                and user['id'] == current_user['id']
                                else None)

    # TODO-2 SPLITUP create new endpoints for these instead
    if 'posts' in request['params']:
        data['posts'] = [post.deliver() for post in
                         get_posts_facade(user_id=user['id'])]
    if ('sets' in request['params']
            and user['settings']['view_sets'] == 'public'):
        u_sets = UserSets.get(user_id=user['id'])
        data['sets'] = [set_.deliver() for set_ in u_sets.list_sets()]
    if ('follows' in request['params']
            and user['settings']['view_follows'] == 'public'):
        data['follows'] = [follow.deliver() for follow in
                           Follow.list(user_id=user['id'])]
    if 'avatar' in request['params']:
        size = int(request['params']['avatar'])
        data['avatar'] = user.get_avatar(size if size else None)

    return 200, data
Example #54
0
def create_post_route(request, topic_id):
    """
    Create a new post on a given topic.
    Proposal: must include entity (card, unit, or set) information.
    Vote: must refer to a valid proposal.
    """

    current_user = get_current_user(request)
    if not current_user:
        return abort(401)

    topic = Topic.get(id=topic_id)
    if not topic:
        return 404, {
            'errors': [{
                'name': 'topic_id',
                'message': c('no_topic'),
            }],
            'ref': 'PCSFCxsJtnlP0x9WzbPoKcwM',
        }

    # ## STEP 1) Create post (and entity) instances
    post_data = request['params'].get('post')
    if not post_data:
        return 400, {
            'errors': [{
                'name': 'post',
                'message': 'Missing post data.',
            }],
            'ref': 'ykQpZwJKq54MTCxgkx0p6baW'
        }
    post_data = omit(post_data, ('id', 'created', 'modified',))
    post_data['user_id'] = current_user['id']
    post_data['topic_id'] = topic_id
    post_ = instance_post_facade(post_data)
    post_kind = post_['kind']
    if post_kind == 'proposal':
        entity = instance_new_entity(request['params'])
        entity_kind = get_kind(request['params'])
        post_['entity_version'] = {
            'id': entity['id'],
            'kind': entity_kind,
        }

    # ## STEP 2) Validate post (and entity) instances
    errors = prefix_error_names('post.', post_.validate())
    if post_kind == 'proposal':
        errors = errors + prefix_error_names('entity.', entity.validate())
    if len(errors):
        return 400, {
            'errors': errors,
            'ref': 'tux33ztgFj9ittSpS7WKIkq7'
        }

    # ## STEP 3) Save post (and entity)
    post_.save()
    if post_kind == 'proposal':
        entity.save()

    # ## STEP 4) Add author as a follower
    Follow.insert({
        'user_id': current_user['id'],
        'entity': {
            'id': topic['id'],
            'kind': 'topic',
        }
    })
    # TODO-2 also follow the entity

    # ## STEP 5) Make updates based on proposal / vote status
    if post_kind == 'proposal':
        update_entity_status(post_)
    if post_kind == 'vote':
        proposal = Proposal.get(id=post_['replies_to_id'])
        update_entity_status(proposal)

    # ## STEP 6) Return response
    return 200, {'post': post_.deliver()}
Example #55
0
def create_topic_route(request):
    """
    Create a new topic.
    The first post (or proposal) must be provided.
    """

    current_user = get_current_user(request)
    if not current_user:
        return abort(401)

    # ## STEP 1) Create post and topic (and entity) instances
    topic_data = request['params'].get('topic')
    post_data = request['params'].get('post')
    if not topic_data:
        return 400, {
            'errors': [{
                'name': 'topic',
                'message': 'Missing topic data.'
            }],
            'ref': 'zknSd46f2hRNjSjVHCg6YLwN'
        }
    if not post_data:
        return 400, {
            'errors': [{
                'name': 'post',
                'message': 'Missing post data.'
            }],
            'ref': 'Qki4oWX4nTdNAjYI8z5iNawr'
        }
    topic_data = omit(topic_data, ('id', 'created', 'modified'))
    topic_data['user_id'] = current_user['id']
    topic = Topic(topic_data)
    post_data = omit(post_data, ('id', 'created', 'modified',))
    post_data['user_id'] = current_user['id']
    post_data['topic_id'] = topic['id']
    post_ = instance_post_facade(post_data)
    post_kind = post_['kind']
    if post_kind == 'proposal':
        entity = instance_new_entity(request['params'])
        entity_kind = get_kind(request['params'])
        post_['entity_version'] = {
            'id': entity['id'],
            'kind': entity_kind,
        }

    # ## STEP 2) Validate post and topic (and entity) instances
    errors = prefix_error_names('topic.', topic.validate())
    errors = errors + prefix_error_names('post.', post_.validate())
    if post_kind == 'proposal':
        errors = errors + prefix_error_names('entity.', entity.validate())
    if len(errors):
        return 400, {
            'errors': errors,
            'ref': 'TAY5pX3ghWBkSIVGTHzpQySa'
        }

    # ## STEP 3) Save post and topic (and entity)
    topic.save()
    post_.save()
    if post_kind == 'proposal':
        entity.save()

    # ## STEP 4) Add author as a follower
    Follow.insert({
        'user_id': current_user['id'],
        'entity': {
            'id': topic['id'],
            'kind': 'topic',
        }
    })
    # TODO-2 also follow the entity automatically IF needed

    # ## STEP 5) Send out any needed notifications
    send_notices(
        entity_id=topic['entity']['id'],
        entity_kind=topic['entity']['kind'],
        notice_kind='create_topic',
        notice_data={
            'user_name': current_user['name'],
            'topic_name': topic['name'],
            'entity_kind': topic['entity']['kind'],
            'entity_name': topic['entity']['id'],
        }
    )

    # ## STEP 5) Return response
    return 200, {'topic': topic.deliver(), 'post': post_.deliver()}