Ejemplo n.º 1
0
    def get(self, post_id):
        """
        get:   Get
        Args:
                self:   This object
                post_id:    Post ID
        """
        if not self.user:
            return self.redirect('/login')

        key = db.Key.from_path('Post', int(post_id), parent=blog_key())
        b = db.get(key)

        if not b:
            self.render('notfound.html')
            return
#
#       Check that user IDs do not match
#
        user_id = self.user.key().id()
        if b.user_id == user_id:
            return self.redirect('/blog/%s' % str(b.key().id()))

        if b.is_liked_by_user(user_id) == 'Liked':
            return self.redirect('/blog/%s' % str(b.key().id()))

        l = Likes(parent=blog_key(),
                  post_id=int(post_id),
                  user_id=int(user_id))
        l.put()
        self.redirect('/blog/%s' % str(b.key().id()))
Ejemplo n.º 2
0
 def get(self):
     login = self.read_cookie('login')
     uid = None
     if login:
         uid = int(login)
         user = Users.get_by_id(uid)
     post_id = self.request.get("p")
     if post_id:
         if uid:
             post = Post.get_by_id(int(post_id))
             if int(uid) == int(post.user.key().id()):
                 #your own post
                 self.redirect("/blog/" + post_id + "?e=like_own")
             else:
                 likes = db.GqlQuery(
                     "select * from Likes where user = :1 and post = :2",
                     user.key(), post.key())
                 if likes.count() == 0:
                     new_like = Likes(post=post, user=user)
                     new_like.put()
                     self.redirect("/blog/" + str(post.key().id()))
                 else:
                     self.redirect("/blog/" + post_id + "?e=like_alrd")
         else:
             self.redirect("/blog/" + post_id + "?e=like_permission")
     else:
         self.redirect("/blog")
Ejemplo n.º 3
0
    def setUp(self):
        """Create test client, add sample data."""

        db.drop_all()
        db.create_all()

        user = User.signup(username="******",
                           email="*****@*****.**",
                           password="******",
                           image_url=None)
        user.id = 1000
        self.user_id = user.id

        db.session.commit()

        message = Message(text="Test Message", user_id=1000)
        message.id = 2000
        self.message_id = message.id
        db.session.add(message)
        db.session.commit()

        self.user1 = User.query.get(self.user_id)

        like = Likes(user_id=self.user1.id, message_id=self.message_id)
        like.id = 2000
        self.like_id = like.id
        db.session.add(like)
        db.session.commit()

        self.client = app.test_client()
Ejemplo n.º 4
0
    def post(self):
        cookie_user = self.get_user_from_cookie()
        if cookie_user:
            postID = self.request.get('postID')
            post_obj = Post.get_by_id(int(postID))
            like_obj = Likes.query(Likes.post == post_obj.key).get()

            if post_obj.user == cookie_user.key:
                self.write(json.dumps(({'like_count': -1})))
            else:
                if like_obj:
                    liked_by = like_obj.user_id
                    for u_id in liked_by:
                        if u_id == cookie_user.key.id():
                            self.write(json.dumps(({'like_count': -2})))
                            return
                    like_obj.like_count += 1
                    liked_by.append(cookie_user.key.id())
                    like_obj.put()
                    self.write(
                        json.dumps(({
                            'like_count': like_obj.like_count
                        })))
                else:
                    like_obj = Likes(post=post_obj.key, like_count=1)
                    like_obj.user_id.append(cookie_user.key.id())
                    like_obj.put()
                    time.sleep(0.2)
                    self.write(
                        json.dumps(({
                            'like_count': like_obj.like_count
                        })))
        else:
            return None
Ejemplo n.º 5
0
 def set_up_likes(self):
     """set up likes"""
     like = Likes(user_id=self.user_id, message_id=self.message_id)
     like.id = 4000
     self.like_id = like.id
     db.session.add(like)
     db.session.commit()
Ejemplo n.º 6
0
    def post(self):
        cookie_user = self.get_user_from_cookie()
        if cookie_user:
            postID = self.request.get('postID')
            post_obj = Post.get_by_id(int(postID))
            like_obj = Likes.query(Likes.post == post_obj.key).get()

            if post_obj.user == cookie_user.key:
                self.write(json.dumps(({'like_count': -1})))
            else:
                if like_obj:
                    liked_by = like_obj.user_id
                    for u_id in liked_by:
                        if u_id == cookie_user.key.id():
                            self.write(json.dumps(({'like_count': -2})))
                            return
                    like_obj.like_count += 1
                    liked_by.append(cookie_user.key.id())
                    like_obj.put()
                    self.write(json.dumps(({'like_count': like_obj.like_count})))
                else:
                    like_obj = Likes(post=post_obj.key, like_count=1)
                    like_obj.user_id.append(cookie_user.key.id())
                    like_obj.put()
                    time.sleep(0.2)
                    self.write(json.dumps(({'like_count' : like_obj.like_count})))
        else:
            return None
Ejemplo n.º 7
0
 def test_message_model(self):
     """Create a user with a message to test"""
     hashed_pwd1 = bcrypt.generate_password_hash("HASHED_PASSWORD1").decode('UTF-8')
     user1 = User(email="*****@*****.**", username="******", password=hashed_pwd1)
     db.session.add(user1)
     db.session.commit()
     message1 = Message(text="TestMessage", user_id=user1.id)
     db.session.add(message1)
     db.session.commit()
     """Test get_message_by_id"""
     testmessage = Message.get_message_by_id(message1.id)
     self.assertEqual(user1.id, testmessage.user_id)
     
     """Test add_like"""
     hashed_pwd2 = bcrypt.generate_password_hash("HASHED_PASSWORD2").decode('UTF-8')
     user2 = User(email="*****@*****.**", username="******", password=hashed_pwd2)
     db.session.add(user2)
     db.session.commit()
     Likes.add_like(user2.id, message1.id)
     db.session.commit()
     self.assertEqual(user2.likes[0].id, message1.id)
     
     """Test delete_like"""
     before = len(user2.likes)
     Likes.delete_like(user2.id, message1.id)
     db.session.commit()
     after = len(user2.likes)        
     self.assertEqual(before - 1, after)
Ejemplo n.º 8
0
def do_like():
    """Handle likes from javascript"""    
    message_id = request.form["message_id"]    
    if int(message_id) in [x.id for x in g.user.likes]:        
        Likes.delete_like(g.user.id, message_id)
    else:
        Likes.add_like(g.user.id, message_id)        
    db.session.commit()
    return 'None'
Ejemplo n.º 9
0
def delete_like(message_id):
    """Delete a like from a post for the logged in user"""

    if not g.user:
        flash("Access unauthorized.", "danger")
        return redirect("/")

    Likes.delete_like(g.user.id, message_id)

    return "Unliked!"
Ejemplo n.º 10
0
def add_like(message_id):
    """Add a like to a post for the logged in user"""

    if not g.user:
        flash("Access unauthorized.", "danger")
        return redirect("/")

    Likes.add_like(g.user.id, message_id)

    return "Liked"
Ejemplo n.º 11
0
def like_click(word, translation):
    value = list(Likes.select().where((Likes.word == word)
                                      & (Likes.translation == translation) & (Likes.user == session["mail"])))
    if len(value) == 0:
        Likes.insert(word=word,
                     translation=translation,
                     user=session["mail"]).execute()
    else:
        like = value[0]
        like.delete_instance()
    return redirect(f"/search?word={word}")
Ejemplo n.º 12
0
def createLikes():

    try:
        if not request.json:
            abort(400)
        else:
            likes = Likes(request.json['feeds_id'],
                          request.json['no_of_likes'])
            session.add(likes)
            session.commit()
            return jsonify(likes.serialize())

    except Exception as e:
        return (str(e))
Ejemplo n.º 13
0
def anadir_megusta(request, identificador):
    usu_id = request.user.id
    if usu_id == None:
        usu_id = request.COOKIES['sessionid']
    aloj = Alojamiento.objects.get(id=int(identificador))
    try:
        d = Likes.objects.get(hotel=aloj, usuario=usu_id)
        #no hay que hacer nada, una misma persona no puede poner mas de un me gusta en un mismo alojamiento
    except:
        megusta = Likes(hotel=aloj, usuario=usu_id)
        megusta.save()

    direccion = '/alojamientos/' + identificador
    return HttpResponseRedirect(direccion)
Ejemplo n.º 14
0
	def add_like(self, thelike, type=u'facebook'):
		""" Adds the like to the current user. """
		if self.current_user:
			logging.info("add_like: %s %s"%(str(self.current_user),str(thelike)))
			new_like = Likes(user=self.current_user,
				source=u'facebook',
				category=thelike[u'category'],
				name=thelike[u'name'],
				likeid=thelike[u'id'])
			# Check for duplicates
			if db.GqlQuery("SELECT __key__ FROM Likes WHERE user = :1 AND name = :2",
				new_like.user, new_like.name).count(1) == 0:
				new_like.put() # Does not exist so put it in the data store
		else:
			return
Ejemplo n.º 15
0
 def post(self, slug):
     user = self.current_user
     likes = Likes.select().where(Likes.post_id == slug)
     if likes:
         # Do not allow more than one like for one post
         likes = Likes.select().where(Likes.post_id == slug).get()
         if likes.user_id == user.id:
             return self.redirect("/post/{}".format(slug))
     # If you are creator of post, can not like it
     post = Posts.select().where(Posts.id == slug).get()
     if post.user_id == user.id:
         return self.redirect("/post/{}".format(slug))
     # Create like
     Likes.create(user_id=user.id, post_id=slug)
     return self.redirect("/post/{}".format(slug))
Ejemplo n.º 16
0
    def setUp(self):
        """Create test client, add sample data"""

        User.query.delete()
        Message.query.delete()
        Follows.query.delete()
        Likes.query.delete()

        # OR
        # db.drop_all()
        # db.create_all()

        self.client = app.test_client()

        self.testuser_1 = User.signup(username="******",
                                      email="*****@*****.**",
                                      password="******",
                                      image_url=None)

        self.testuser_2 = User.signup(username="******",
                                      email="*****@*****.**",
                                      password="******",
                                      image_url=None)

        db.session.commit()

        self.testuser_1.following.append(self.testuser_2)

        self.testmessage_1 = Message(text="This is the first test message!",
                                     user_id=self.testuser_1.id)

        self.testmessage_2 = Message(text="This is the second test message!",
                                     user_id=self.testuser_2.id)

        db.session.add(self.testmessage_1)
        db.session.add(self.testmessage_2)

        db.session.commit()

        like_1 = Likes(user_id=self.testuser_1.id,
                       message_id=self.testmessage_2.id)

        like_2 = Likes(user_id=self.testuser_2.id,
                       message_id=self.testmessage_1.id)

        db.session.add(like_1)
        db.session.add(like_2)
        db.session.commit()
Ejemplo n.º 17
0
def messages_add_like(message_id):
    """Add like to a message"""

    if not g.user:
        flash("Access unauthorized.", "danger")
        return redirect("/")

    msg = Message.query.get_or_404(message_id)

    if g.user.id == msg.user_id:
        flash("Can not like your own message!" , "danger")
        return redirect('/')

    if g.user.is_like(msg):
        # alrealy like this message, unlike it
        Likes.query.filter(Likes.user_id==g.user.id , Likes.message_id==msg.id).delete()
        db.session.commit()

        return redirect('/')

    # like this message
    like = Likes(user_id = g.user.id , message_id=message_id)

    db.session.add(like)
    db.session.commit()

    return redirect('/')
Ejemplo n.º 18
0
def add_remove_like(message_id):
    """Add/Remove liked Warble to/from "likes" table"""

    like_ids = [like.id for like in g.user.likes]

    # Get the user_id from message_id
    user = db.session.query(
        Message.user_id).filter(Message.id == message_id).first()

    # un-like a warble
    if message_id in like_ids:
        like = Likes.query.filter_by(message_id=message_id,
                                     user_id=g.user.id).first()
        db.session.delete(like)
        db.session.commit()

        return redirect("/")

    # add a "like"
    else:
        # (a user may not "like" their own post)
        if user.user_id != g.user.id:
            like = Likes(user_id=g.user.id, message_id=message_id)

            db.session.add(like)
            db.session.commit()

        return redirect("/")
Ejemplo n.º 19
0
    def test_message_like_logged_in_already_liked(self):
        """A logged in user should be able to stop liking a message."""

        user1 = User(username="******", password="******", email="*****@*****.**")
        db.session.add(user1)
        db.session.commit()

        message = Message(text='Like me.', user_id=user1.id)
        db.session.add(message)
        db.session.commit()

        follow = Follows(user_being_followed_id=user1.id, user_following_id=self.testuser.id)
        db.session.add(follow)
        db.session.commit()

        like = Likes(user_id=self.testuser.id, message_id=message.id)
        db.session.add(like)
        db.session.commit()

        message_id = message.id
        with self.client as c:
            with c.session_transaction() as sess:
                sess[CURR_USER_KEY] = self.testuser.id

            resp = c.post(f'/users/add_like/{message_id}', follow_redirects=True)
            html = resp.get_data(as_text=True)

            self.assertEqual(resp.status_code, 200)
            self.assertNotIn('btn-primary', html)
def create_like(current_user, post_id):
    userID = current_user.userID
    postID = post_id
    like = Likes(userID = userID, postID = postID)
    db.session.add(like)
    db.session.commit(like)
    return jsonify ({'message': 'You liked a user post'})
Ejemplo n.º 21
0
def add_like_message(message_id):
    # If user is logged in:
    #   If user_id & message_id is not in liked table (i.e., not already marked as liked)
    #   Add entry into Like_table
    #   Add flash message to indicate "Message was liked"

    # Else:
    #   remove entry from the Like table

    # Notes:  - Add logic to '/' template to reflect if message has been liked
    #         - In profile view run query to get count total of likes and pass that value to profile template view for display

    if not g.user:
        flash("Access unauthorized.", "danger")
        return redirect("/")
    else:
        like = Likes.query.filter_by(user_id=g.user.id,
                                     message_id=message_id).first()
        if like == None:
            print('The value returnded for Likes search whas none')
            like = Likes(user_id=g.user.id, message_id=message_id)
            db.session.add(like)
            db.session.commit()
        else:  # Record was unliked so remove entry in Likes table
            db.session.delete(like)
            db.session.commit()
    return redirect('/')
Ejemplo n.º 22
0
 def get(self, postID):
     if self.session.get("username"):
         user = db.GqlQuery("SELECT * FROM User WHERE username='******'"
                            % self.session.get("username"))
         userID = user.get().key().id()
         key = db.Key.from_path('Posts', int(postID))
         post = db.get(key)
         if int(post.author) != int(userID):
             new_post_like = Likes(postID=int(postID), userID=int(userID),
                                   likesCount=1)
             new_post_like.put()
             self.redirect("/")
         else:
             self.redirect("/")
     else:
         self.redirect("/")
    def test_message_model(self):
        """test the Message model"""

        u1 = User.signup("test1", "*****@*****.**", "password", None)

        u2 = User.signup("test2", "*****@*****.**", "password", None)

        db.session.commit()

        u1_id = u1.id
        u2_id = u2.id

        msg1 = Message(text="msgtext", timestamp=None, user_id=u1_id)

        db.session.add(msg1)
        db.session.commit()

        msg1_id = msg1.id

        self.assertEqual(msg1.user, u1)
        self.assertEqual(len(u1.messages), 1)
        self.assertEqual(u1.messages[0].text, "msgtext")

        # test Likes model
        like = Likes(user_id=u2_id, message_id=msg1_id)

        db.session.add(like)
        db.session.commit()

        self.assertEqual(len(u2.likes), 1)
        self.assertEqual(u2.likes[0], msg1)

        # test function is_liked_by for User model
        self.assertEqual(msg1.is_liked_by(u2), True)
    def setUp(self):
        db.drop_all()
        db.create_all()
        self.client = app.test_client()
        user_1 = User.signup("user1",'*****@*****.**','password')
        user_2 = User.signup("user2",'*****@*****.**','password')
        user_3 = User.signup("user3",'*****@*****.**','password')

        db.session.add_all([user_1,user_2,user_3])
        db.session.commit()
        self.user_1 = user_1
        self.user_2 = user_2
        self.user_3 = user_3

        area_1 = Area(city="Irvine", state="CA")
        self.user_2.areas.append(area_1)
        db.session.commit()
        self.area_1 = area_1

        area_2 = Area(city="Irvine", state="CA")
        self.user_3.areas.append(area_2)
        db.session.commit()
        self.area_2 = area_2

        d = {"googlePlaceId":"ChIJ9f9zhYDb3IARfXSrxrDSdq4","name":"Lazy Dog Restaurant & Bar","address":"address"}
        rest_1 = Restaurant(name=d['name'],address=d['address'], google_place_id=d['googlePlaceId'],user_id=self.user_3.id, area_id=self.area_2.id)
        db.session.add(rest_1)
        db.session.commit()
        self.rest_1 = rest_1
        like = Likes(user_id=user_3.id, restaurant_id=rest_1.id)
        db.session.add(like)
        db.session.commit()
Ejemplo n.º 25
0
def like_msg(message_id):
    """Like another users post."""

    if not g.user:
        flash("Access unauthorized.", "danger")
        return redirect("/")

    try:
        message = Message.query.get(message_id)

        if message.user_id == g.user.id:
            return redirect(request.referrer)

        like = Likes(user_id=g.user.id, message_id=message_id)
        db.session.add(like)
        db.session.commit()

        return redirect(request.referrer)

    except (IntegrityError, InvalidRequestError):
        db.session.rollback()
        liked_msg = Likes.query.get(message_id)
        db.session.delete(liked_msg)
        db.session.commit()

        return redirect(request.referrer)
Ejemplo n.º 26
0
def likepost(post_id):
    if request.method=="POST":
        like=Likes(current_user.id,post_id)
        db.session.add(like)
        db.session.commit()
        count=countlikes(post_id)
        return jsonify(response=[{'message':'Post Liked','Likes':count}])
Ejemplo n.º 27
0
def like_or_unlike_message(message_id):
    """ like or unlike a message """

    if not g.user:
        flash("Access unauthorized.", "danger")
        return redirect("/")

    message = Message.query.get_or_404(message_id)

    if g.user.id == message.user_id:

        return redirect(request.referrer)

    else:

        like = Likes.query.filter_by(message_id=message_id).filter_by(
            user_id=g.user.id).first()

        if like:
            db.session.delete(like)

        else:
            new_like = Likes(user_id=g.user.id, message_id=message_id)
            db.session.add(new_like)

    db.session.commit()

    return redirect(request.referrer)
Ejemplo n.º 28
0
 def test_show_likes(self):
     with self.client as c:
         with c.session_transaction() as sess:
             sess[CURR_USER_KEY] = self.testuser.id
         
         """Create user and message to like"""
         tempuser = User.signup(username="******",
                                 email="*****@*****.**",
                                 password="******",
                                 image_url=None)
         db.session.add(tempuser)
         db.session.commit()
         user = db.session.query(User).filter_by(username="******").first()
         message = Message(text="Testmessage",user_id=user.id)
         db.session.add(message)
         db.session.commit()
         testmessage = db.session.query(Message).first()
         user = db.session.query(User).filter_by(username="******").first()
         templike = Likes(user_id=self.testuser.id, message_id=testmessage.id)
         db.session.add(templike)
         db.session.commit()
         testuser = db.session.query(User).filter_by(username='******').first()
         self.assertEqual(testuser.likes[0].id, message.id)
         resp = c.get(f"/users/{self.testuser.id}/likes")
         self.assertEqual(resp.status_code, 200) 
         html = resp.get_data(as_text=True)            
         self.assertIn('<div class="message-area">', html)
Ejemplo n.º 29
0
def like_message(review_id):
    """Like/"cheers" a message."""


    if not g.user:
        flash("Access unauthorized.", "danger")
        return redirect("/")

    #prevent user from liking their own message
    # m = Message.query.get(message_id)
    # if m in g.user.messages:
    #     flash("You cannot like your own message.", "danger")
    #     return redirect ("/")
    
    #logic to unlike if the liked message is already an instance of the Likes class
    if Likes.query.filter_by(user_id=g.user.id, reviews_id=review_id).all():
        liked_msg=Likes.query.filter_by(user_id=g.user.id, reviews_id=review_id).one()
        db.session.delete(liked_msg)
        db.session.commit()
        return redirect('/')

    #like the message otherwise
    liked_msg=Likes(user_id=g.user.id, reviews_id=review_id)
    db.session.add(liked_msg)
    db.session.commit()

    return redirect("/")
Ejemplo n.º 30
0
    def get(self):
        posts = []
        cookie_user = self.get_user_from_cookie()
        if cookie_user:
            loggedin_user = cookie_user
        else:
            loggedin_user = None

        posts = Post.query(Post.is_draft == False).order(-Post.created)
        all_users = User.query()
        likes = Likes.query()

        list_dict = []

        for p in posts:
            p_dict = {}
            for u in all_users:
                if p.user == u.key:
                    p_dict['p_id'] = p.key.id()
                    p_dict['p_title'] = p.title
                    p_dict['p_content'] = p.content
                    p_dict['p_created'] = p.created
                    p_dict['a_name'] = u.fullname
                    p_dict['a_key'] = u.key
                    p_dict['a_id'] = u.key.id()
            for l in likes:
                if l.post == p.key:
                    p_dict['like_count'] = l.like_count
            comment_count = Comments.query(Comments.post == p.key).count()
            p_dict['c_count'] = comment_count
            list_dict.append(p_dict)

        return self.render('home.html', user=loggedin_user,
                           list_dict=list_dict)
Ejemplo n.º 31
0
    def test_delete_messages_likes(self):
        """test if message got deleted by the user and it deletes from likes table"""
        u = User(email="*****@*****.**",
                 username="******",
                 password="******")
        db.session.add(u)
        db.session.commit()
        u2 = User(email="*****@*****.**",
                  username="******",
                  password="******")
        db.session.add(u2)
        db.session.commit()
        follow = Follows(user_being_followed_id=u.id, user_following_id=u2.id)
        db.session.add(follow)
        db.session.commit()

        m = Message(text="warblewarble", user_id=u.id)
        db.session.add(m)
        db.session.commit()
        l = Likes(user_that_liked=u2.id, message_liked=m.id)
        db.session.add(l)
        db.session.commit()
        self.assertEqual(len(u2.likes), 1)
        db.session.delete(m)
        db.session.commit()
        self.assertEqual(len(u2.likes), 0)
        self.assertEqual(len(u.messages), 0)
Ejemplo n.º 32
0
def add_like():
    ret = {"error": 0}
    try:
        report_id = int(request.form['report_id'])
        user_id = int(request.form['user_id'])
        value = int(request.form['value'])
        flag_value = int(request.form["flag_value"])

        # check if like for same report exists by this user
        like = Likes.query.filter_by(user=user_id).\
            filter_by(report=report_id).first()
        if like:
            print "[add_like] User already had liked/disliked this report"
            like.value = value
        else:
            like = Likes(report_id, user_id, value, flag_value)

        db.session.add(like)
        db.session.commit()
        ret["msg"] = "The Like and flag is added successfully"
    except Exception as exp:
        print("add_like() :: exp: %s" % exp)
        print(traceback.format_exc())
        ret["error"] = 1
        ret["msg"] = "Got exception: %s" % exp
    return json.dumps(ret)
Ejemplo n.º 33
0
def add_like(message_id):
    """ Add like to "likes" table"""

    if not g.user:
        flash("Access unauthorized.", "danger")
        return redirect("/")
    # query for record in "likes" table that matches user id and message id of
    # tweet the user just clicked on the thumbs up icon. if record found returns
    # that record, if record not found returns None.
    like_rec_test = Likes.query.filter(Likes.user_id == g.user.id,
                                       Likes.message_id == message_id).first()
    # if record found, user clicked on icon for messaged already "liked", therefore
    # user wants to "unlike" message so remove record from likes table. If none, this
    # is a new "like"
    if like_rec_test:
        db.session.delete(like_rec_test)
        db.session.commit()
        return redirect("/")
    # if matching record not found in likes table create new
    # entry in likes table
    like = Likes(user_id=g.user.id, message_id=message_id)
    db.session.add(like)
    db.session.commit()

    return redirect("/")
Ejemplo n.º 34
0
    def test_is_liked_by(self):
        """Does the is_liked_by work"""

        u = self.user
        u2 = User(email="*****@*****.**",
                  username="******",
                  password="******")

        m = Message(user_id=u.id, text='test content')

        db.session.add_all([u2, m])
        db.session.commit()

        #not like
        self.assertEqual(len(u2.likes), 0)
        self.assertEqual(len(m.likes_users), 0)
        self.assertEqual(u2.is_like(m), False)
        self.assertEqual(m.is_liked_by(u2), False)

        like = Likes(user_id=u2.id, message_id=m.id)
        db.session.add(like)
        db.session.commit()

        self.assertEqual(len(u2.likes), 1)
        self.assertEqual(len(m.likes_users), 1)
        self.assertEqual(u2.is_like(m), True)
        self.assertEqual(m.is_liked_by(u2), True)
Ejemplo n.º 35
0
    def test_users_likes_logged_in(self):
        """A logged in user should be able to see any user's liked warbles"""

        user1_id = self.user1.id
        user2_id = self.user2.id

        message = Message(text="Test warble to like",
                          timestamp=None,
                          user_id=user1_id)
        db.session.add(message)
        db.session.commit()

        like = Likes(user_id=user2_id, message_id=message.id)
        db.session.add(like)
        db.session.commit()

        with self.client as c:
            with c.session_transaction() as sess:
                sess[CURR_USER_KEY] = user1_id

            resp = c.get(f'/users/{user2_id}/likes')
            html = resp.get_data(as_text=True)

            self.assertEqual(resp.status_code, 200)
            self.assertIn("Test warble to like", html)
Ejemplo n.º 36
0
    def post(self):
        loggedin_user = self.get_user_from_cookie()
        all_users = User.query()
        posts = Post.query()

        post_id = self.request.get('post_id')
        like_count = self.request.get('like_count')

        post = Post.get_by_id(int(post_id))

        if post:
            new_like_object = Likes(post=post.key, like_count=int(like_count))
            key = new_like_object.put()
            time.sleep(0.1)
            new_like = key.get()
            post_key = new_like.post
            post = post_key.get()
            self.write("Like Count: " + str(new_like.like_count) + "Post Title:" + post.Title)
Ejemplo n.º 37
0
def login(request, provider_name):
    # We we need the response object for the adapter.
    response = HttpResponse()
    
    # Start the login procedure.
    result = authomatic.login(DjangoAdapter(request, response), provider_name)
     
    # If there is no result, the login procedure is still pending.
    # Don't write anything to the response if there is no result!
    if result:
        # If there is result, the login procedure is over and we can write to response.
                
        if result.error:
            # Login procedure finished with an error.
            response.write('<h2>Erro: {0}</h2>'.format(result.error.message))
        
        elif result.user:
            # Hooray, we have the user!
            
            # OAuth 2.0 and OAuth 1.0a provide only limited user data on login,
            # We need to update the user to get more info.
            if not (result.user.name and result.user.id):
                result.user.update()
                url = 'https://graph.facebook.com/v2.2/{0}?fields=likes,id&locale=pt_BR'
                url = url.format(result.user.id)
                
                access_response = result.provider.access(url)
                if access_response.status == 200:
                    likes=access_response.data.get('likes').get('data')
                    profile=Profile.objects.get(user=request.user)
                    Likes.objects.filter(profile=profile).delete()
                    for l in likes:
                        category=l.get('category')
                        name=l.get('name')
                        like=Likes(profile=profile,category=category,name=name)
                        like.save()
                    response.write('<script type="text/javascript">window.close()</script>') 
     

    return response
Ejemplo n.º 38
0
def like(req):
	#import pdb  
	#pdb.set_trace() 
	tip = req.POST.get('type')
	idQuestion = req.POST.get('id')
	currentQuestion = Question.objects.get(id = idQuestion)
	new_rating = currentQuestion.rating
	idUser = req.user.profile.id
	try:
		temp = Likes.objects.get(author_id = idUser, question_id = idQuestion)
	except ObjectDoesNotExist:
		new_rating = new_rating + int(tip)
		currentQuestion.rating = new_rating;
		currentQuestion.save()
		newLikes = Likes(author_id = idUser, question_id = idQuestion, tip = tip)
		newLikes.save()
		import json
		content = json.dumps({'status': True, 'new_rating':	new_rating})
		return HttpResponse(content,content_type='application/json')
	import json
	content = json.dumps({'status': False, 'new_rating': new_rating})
	return HttpResponse(content,content_type='application/json')
Ejemplo n.º 39
0
    def post(self):
        cookie_user = self.get_user_from_cookie()
        if cookie_user:
            content = self.request.get('content')
            title = self.request.get('post-title')
            is_draft = self.request.get('draft')

            if is_draft == 'on':
                is_draft = True
            else:
                is_draft = False

            if title != 'Click here to give a Title!' and \
             content != '<p>Start writing here...</p>':
                new_post = Post(
                    title=title,
                    content=content,
                    user=cookie_user.key,
                    is_draft=is_draft
                    )
                new_post_key = new_post.put()
                time.sleep(0.3)
                like_obj = Likes(post=new_post_key, like_count=0)
                like_key = like_obj.put()
                time.sleep(0.1)

                if is_draft:
                    self.redirect('/user/%s/drafts' % str(cookie_user.key.id()))
                else:
                    self.redirect('/blog/%s' % str(new_post_key.id()))
            else:
                empty_post = "Both Title and Content needed for the Blog!"
                self.render('newpost.html', user=cookie_user,
                            title=title, content=content, empty_post=empty_post)
        else:
            cookie_error = "Your session has expired please login again to continue!"
            self.render('login.html', cookie_error=cookie_error)
Ejemplo n.º 40
0
    def get(self, post_id):
        # user_id = check_for_valid_cookie(self)
        # cookie_user = User.get_by_id(int(user_id))
        cookie_user = self.get_user_from_cookie()

        post = Post.get_by_id(int(post_id))
        if post:
            comments = Comments.query(Comments.post == post.key).order(-Comments.comment_date)
            likes = Likes.query(Likes.post == post.key).get()

            list_dict = []

            comment_count = comments.count()

            if likes:
                no_of_likes = likes.like_count
            else:
                no_of_likes = 0

            for c in comments:
                c_dict = {}
                if c.post == post.key:
                    c_dict['c_id'] = c.key.id()
                    c_dict['c_comment'] = c.comment
                    c_dict['c_date'] = c.comment_date
                    user = User.query(User.key == c.user).get()
                    c_dict['c_u_name'] = user.fullname
                    c_dict['c_u_key'] = user.key
                    c_dict['c_u_id'] = user.key.id()
                    list_dict.append(c_dict)
            if cookie_user:
                if not post:
                    self.error(404)
                    return
                if cookie_user.key == post.user:
                    self.render("blog.html",
                                post=post,
                                user=cookie_user,
                                comments=list_dict,
                                like_count=no_of_likes,
                                comment_count=comment_count,
                                is_author=True)
                else:
                    self.render("blog.html",
                                post=post,
                                user=cookie_user,
                                comments=list_dict,
                                like_count=no_of_likes,
                                comment_count=comment_count,
                                is_author=False)
            else:
                self.render("blog.html",
                            post=post,
                            user=None,
                            comments=list_dict,
                            like_count=no_of_likes,
                            comment_count=comment_count,
                            is_author=False)
        else:
            self.error(404)
            return
Ejemplo n.º 41
0
def showCount(post_key):
    like_obj = Likes.query(Likes.post == post_key).get()
    if like_obj:
        return like_obj.like_count
    else:
        return "0"