def get_likes(entry_id, entry_type, owner=crawler.uid): param = { "stype": entry_type, "sourceId": entry_id, "owner": owner, "gid": "{entry_type}_{entry_id}".format(entry_type=entry_type, entry_id=entry_id), "uid": crawler.uid, } r = crawler.get_json(config.LIKE_URL, param) for like_item in r["likeList"]: save_user(like_item["id"], like_item["name"], like_item["headUrl"]) like = { "entry_id": entry_id, "entry_type": entry_type, "uid": like_item["id"] } Like.insert(**like).on_conflict("replace").execute() logger.info( " crawled {count} likes on {entry_type} {entry_id}".format( count=len(r["likeList"]), entry_type=entry_type, entry_id=entry_id)) return r["likeCount"]
def get(self, post_id): # check if logged in and get username. username = self.check_login(self.request.cookies.get('user_id')) if not username: self.redirect('/login') else: # get the post. post = db.get(db.Key.from_path('Post', int(post_id))) # if post belongs to user, show alert. if post.username == username: self.render('alerts.html', alert='You cannot like your own post', path='/%s' % post_id) else: already_like = Like.all().filter('username='******'post_id=', post_id).get() # if user hasn't liked the post, create like. if not already_like: l = Like(username=username, post_id=post_id) l.put() self.render('alerts.html', alert='Like added to post', path='/%s' % post_id) # if user has already liked the post, show alert. else: self.render('alerts.html', alert='You can only like a post once', path='/%s' % post_id)
def set_like(meme_id): if g.current_user is None: abort(FORBIDDEN) if 'score' not in request.form: abort(BAD_REQUEST) try: score = int(request.form['score']) except ValueError: abort(BAD_REQUEST) if not (-1 <= score <= 1): abort(BAD_REQUEST) user = g.current_user meme = session.query(Meme).filter(Meme.id == meme_id).first() if meme is None: abort(BAD_REQUEST) like = session.query(Like).filter( and_(Like.meme_id == meme.id, Like.user_id == user.id)).first() old_score = 0 if like is None else like.score if like is None: like = Like(meme_id=meme.id, user_id=user.id, score=score) session.add(like) else: like.score = score meme.rating = meme.rating - old_score + score session.commit() return 'OK', CREATED
def get(self, post_id): # get post content, likes and comments from id passed in the url. post = db.get(db.Key.from_path('Post', int(post_id))) likes = Like.all().filter('post_id =', post_id).count() comments = Comment.all().filter('post_id = ', post_id) # check if logged in and get username. username = self.check_login(self.request.cookies.get('user_id')) # detect if user already liked the post. already_like = Like.all().filter('username='******'post_id=', post_id).get() # if post does not exist based id, show alert. if not post: self.render('alerts.html', alert='Post does not exist', path='/blog') # show the form. else: self.render('post-page.html', post=post, likes=likes, already_like=already_like, username=username, comments=comments)
def delete_post(cls, post_id, user_id): error_msg = None posts = Post.all().order('-created').fetch(limit=10) updated_post_list = posts post = Post.get_by_id(post_id) if user_id == post.created_by: # delete comments of the post comments = Comment.all().filter('post_id =', post_id).fetch(limit=10) for c in comments: Comment.delete(c) # delete likes of the post likes = Like.all().filter('post_id =', post_id).fetch(limit=10) for l in likes: Like.delete(l) # delete the post updated_post_list = cls.update_list_on_delete( object_list=posts, object_id=post_id ) Post.delete(post) else: error_msg = 'You can delete only your own posts' return updated_post_list, error_msg
def post(self): post_id = int(self.request.get('post_id')) user_id = int(self.request.get('user_id')) post_username = self.request.get('username') message = '' u = self.current_user() if u: # check if user is not liking own post if u.username != post_username: # check if post was already liked likes = Like.all().filter('post_id =', post_id).filter( 'username ='******'/view?p=%s&u=%s&#likes' % (post_id, user_id)) else: message = 'You can only like a post once' else: message = 'You cannot like your own post' self.redirect('/view?p=%s&u=%s&m=%s&#likes' % (post_id, user_id, message)) else: self.redirect('/login')
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
def get(self, post_id): if self.good_cookie_exists(): # put the user id and post_id into the Like entity # go to success page, which will have link to home h = self.request.cookies.get('user') curusor = h.split("|")[0] # make sure user doesn't own post post_key = db.Key.from_path( 'Post', int(post_id)) # returning something, but what??? if db.get(post_key) is not None: # if post exists, continue owns = self.user_owns_post(post_key) if owns: # if user owns the post, end self.redirect("/") return else: # otherwise post exists and user is not owner likes = Like.all().filter("post_id = ", str(post_id)).filter( "user = "******"/") # UI blocks multiple liking as well return else: # new Like entity l = Like(post_id=post_id, user=curusor) l.put() # commit entry self.render("successlike.html", loul="liked") else: self.redirect("/") return else: self.redirect("/login") return
def get(self, post_id): if not self.user: return self.redirect('/login') key = ndb.Key('Post', int(post_id), parent=models.blog_key()) post = key.get() if not post: self.error(404) return like_obj = Like.query(Like.post == post.key).get() if post.author == self.user.key: self.write("You can not like your own post") else: if like_obj: authors = like_obj.author for author in authors: if (author == self.user.key): return self.redirect("/blog/%s" % str(post.key.id())) like_obj.like_count += 1 authors.append(self.user.key) like_obj.put() self.redirect('/') else: like_obj = Like(post=post.key, like_count=1) like_obj.author.append(self.user.key) like_obj.put() self.redirect('/')
def get_likes(entry_id, entry_type, owner=crawler.uid): param = { "stype": entry_type, "sourceId": entry_id, "owner": owner, "gid": '{entry_type}_{entry_id}'.format(entry_type=entry_type, entry_id=entry_id), "uid": crawler.uid } r = crawler.get_json(config.LIKE_URL, param) for l in r['likeList']: save_user(l['id'], l['name'], l['headUrl']) like = { 'entry_id': entry_id, 'entry_type': entry_type, 'uid': l['id'] } Like.insert(**like).on_conflict('replace').execute() logger.info(' crawled {count} likes on {entry_type} {entry_id}'.format( count=len(r['likeList']), entry_type=entry_type, entry_id=entry_id )) return r['likeCount']
def post(self): """ Post method to like and unlike blogs """ if self.user: if self.request.get("like_blog"): _blog_id = self.request.get("like_blog") user = self.user user_id = user.key.id() _user = User.by_id(int(user_id)) _blog = Blog.get_by_id(int(_blog_id)) like = Like(user=user.key, blog=_blog.key) like.like = 1 like_key = like.put() blog = _blog.key.get() blog.likes.append(like_key) blog.put() self.redirect('/') if self.request.get("dislike"): _blog_id = self.request.get("dislike") user = self.user user_id = user.key.id() _user = User.by_id(int(user_id)) _blog = Blog.get_by_id(int(_blog_id)) like = Like.query(Like.user == user.key, Like.blog == _blog.key).get() like_key = like.key blog = _blog.key.get() blog.likes.remove(like_key) blog.put() like_key.delete() self.redirect('/') else: self.redirect('/login')
def callback(bot: telegram.Bot, update: telegram.Update): query = update.callback_query like_type = query.data if settings.DEBUG: logger.debug('update: %s', update) chat_tg_id = query.message.chat_id message_tg_id = query.message.message_id user_tg_id = query.from_user.id try: with db: msg, created = Message.get_or_create( chat_tg_id=chat_tg_id, message_tg_id=message_tg_id, defaults={'user_tg_id': -1}, ) if created: logger.warning('missing message: chat_id = %s, msg_id = %s', chat_tg_id, message_tg_id) like = msg.likes.filter(Like.user_tg_id == user_tg_id).first() if like: if like_type == str(like.type): like.delete_instance() else: like.type = like_type like.save() else: if user_tg_id == msg.user_tg_id: like_dict = msg.get_likes_by_type() if like_type == str(Like.DISLIKE) and like_dict[ Like.LIKE] < settings.DELETE_THRESHOLD: bot.delete_message(chat_tg_id, message_tg_id) query.answer() return else: Like.create(message_id=msg.id, user_tg_id=user_tg_id, type=like_type) like_dict = msg.get_likes_by_type() if like_dict[Like.LIKE] + settings.DELETE_THRESHOLD <= like_dict[ Like.DISLIKE] + like_dict[Like.OLD]: bot.delete_message(chat_tg_id, message_tg_id) else: reply_markup = get_reply_markup(like_dict) kwargs = dict(chat_id=chat_tg_id, message_id=message_tg_id, reply_markup=reply_markup) if query.message.text: bot.edit_message_text(text=query.message.text, **kwargs) else: bot.edit_message_caption(caption=query.message.caption, **kwargs) except Exception: logger.exception('exception while adding like %s', update) query.answer()
def post(self, request, *args, **kwargs): user_liker = request.user user_liked = get_object_or_404(User, id=kwargs['id']) try: like = Like( liker =user_liker, liked =user_liked, anonymous =request.POST.get('anonym') == "true" ) like.save() response = like.serialize(user_liker) # ---------****--- PUSH ---****--------- # yg_pm = BarachielPushManager() yg_pm.set_like(like) yg_pm.send() return HttpResponse(json.dumps(response), mimetype='application/json') except IntegrityError: # TODO si ya existe pero con anonymous distinto actualizar. return HttpResponseBadRequest("Already Waved")
def post(self, post_id): # Prevent users from liking their own posts post = self.secure_interaction(post_id, error_type="like", match_user=False) if post: user_id = self.check_for_user() # Determine if the user has liked the post before like = Like.by_user_post(user_id, str(post.key().id())) # If they have liked the post before remove the like and decrease # the post likes if like: post.likes -= 1 like.delete() post.put() else: # If they have not liked the post before then add a like and # increase the post likes post.likes += 1 l = Like(parent=blog_key(), user_id=user_id, post_id=str(post.key().id())) l.put() post.put() self.redirect('/post/%s' % str(post.key().id()))
def get(self, boker_id): boker = Boker.get_by_id(int(boker_id)) if boker: deferred.defer(update_num_view, str(boker.key())) # Check post type, Video or Photo if boker.video_id and boker.video_source: self.template = 'video.html' if self.current_user is not None: user = User.get_by_key_name(self.current_user['id']) can_like = not Like.already_like(user, boker) else: can_like = False else: active_contest = Contest.active_contest() if active_contest: is_nominee = Contest.is_nominee(boker) if self.current_user is not None: user = User.get_by_key_name(self.current_user['id']) can_vote = not Vote.already_vote(user) can_like = not Like.already_like(user, boker) else: can_vote = False can_like = False querystring = self.request.GET return self.render_response(self.template, locals()) else: self.abort(404)
def get(self, topic_id): key = getKey(topic_id) likes = Like.query().filter(Like.topic == key, Like.createdBy == self.user_info['user_id']).fetch(1) if len(likes) == 0: Like(topic=key, createdBy=self.user_info['user_id'], modifiedBy=self.user_info['user_id']).put() else: likes[0].key.delete() self.redirect(self.uri_for('home'))
def get(self, action, post_id): if self.validate(action, post_id): params = {} like = Like(post=self.blog_post, liked_by=self.user) key = like.put() # get updated object params['post'] = db.get(key).post self.render("permalink.html", **params)
def post(self, post_id): post = Post.get_by_id(int(post_id)) if post and post.author.key().id() == self.user.key().id(): self.error(404) else: like = Like(post=post, user=self.user) like.put() time.sleep(1) self.redirect('/{}'.format(post_id))
def like_post(request): if request.method == 'GET': post_id = request.GET['post_id'] post = Post.objects.get(pk=post_id) like = Like(like_post=post, like_user=request.user) like.save() return HttpResponseRedirect('/ourblog/post/' + post_id) else: return HttpResponse("Request method is not a GET")
def post(self, post_id): key = db.Key.from_path('Post', int(post_id)) post = self.get_post(key) # check that # post exists, # user is not liking his own post, # user didn't like this post if post and self.user.username != post.author.username and\ not post.liked(self.user): like = Like(user = self.user, post = post) like.put() self.response.out.write(json.dumps({}))
def move_db() -> None: logging_settings = settings.LOGGING logging_settings['loggers']['peewee']['level'] = 'INFO' logging.config.dictConfig(settings.LOGGING) sqlite_db = get_db() initdb.create_tables() with peewee_db: cur = sqlite_db.execute('select count(*) AS cnt from messages') messages_count = cur.fetchone()['cnt'] cur = sqlite_db.execute('select chat_id, message_id, user_id from messages') logger.info('moving %s messages', messages_count) for index, row in enumerate(cur): if index % 100 == 0: logger.info('%s messages...', index) Message.get_or_create( chat_tg_id=row['chat_id'], message_tg_id=row['message_id'], user_tg_id=row['user_id'], ) cur = sqlite_db.execute('select count(*) AS cnt from likes') likes_count = cur.fetchone()['cnt'] cur = sqlite_db.execute('select chat_id, message_id, user_id, like_type from likes') logger.info('moving %s likes', likes_count) for index, row in enumerate(cur): if index % 100 == 0: logger.info('%s likes...', index) msg, _ = Message.get_or_create( chat_tg_id=row['chat_id'], message_tg_id=row['message_id'], defaults={'user_tg_id': -1}, ) like = Like.filter( Like.message_id == msg.id, Like.user_tg_id == row['user_id'], ).first() if like: like.type = row['like_type'] like.save() else: Like.create( message_id=msg.id, user_tg_id=row['user_id'], type=row['like_type'], )
def get(self, slug): user = User.is_logged(self) query = Koch.all().filter( 'slug =', slug).fetch(1) if len( query ): koch = query[0]; alreadylike = False alreadyfollow = False likesusers = [] koch.views += 1 koch.put() author = koch.author avatar = helpers.get_gravatar( author.email, 90 ) author_recipes_count = Koch.all().filter('author =', author).count(); for like in Like.all().filter( 'koch =', koch ): if like.user.fb_profile_url: lavatar = "https://graph.facebook.com/%s/picture" % (like.user.nickname) elif not like.user.usegravatar and like.user.avatar: lavatar = "/avatar/?user_id=%s" %(like.user.key()) else: lavatar = helpers.get_gravatar( like.user.email, 90 ) likesusers.append({ 'nickname' : like.user.nickname, 'avatar' : lavatar }) if user: alreadylike = Like.alreadylike( koch, user ) alreadyfollow = Friendship.alreadyfollow( user, author ) is_owner = True if user.key() == author.key() else False if author.fb_profile_url: avatar = "https://graph.facebook.com/%s/picture" % (author.nickname) elif not author.usegravatar and author.avatar: avatar = "/avatar/?user_id=%s" %(author.key()) else: avatar = helpers.get_gravatar( author.email, 90 ) last_kochs = Koch.all().filter('author =', author).order('-created').fetch(5); last_from_all = Koch.get_random() current = "explore" humanlikes = intcomma( int( koch.likes) ) self.response.out.write(template.render('templates/details_koch.html', locals())) else: self.error(404)
def put(self, request, pk, format=None): try: comment = Comment.objects.get(pk=pk) if request.data['type'] == 'update': if comment.user == request.user: comment_serializer = CommentsSerializer(comment, data=request.data) if comment_serializer.is_valid(): comment_serializer.save() return Response(comment_serializer.data) else: return Response(status.HTTP_400_BAD_REQUEST) else: return Response(status.HTTP_405_METHOD_NOT_ALLOWED) elif request.data['type'] == 'like': already_liked_user = comment.get_users if request.user not in already_liked_user: like = Like() like.comment = comment like.user = request.user like.save() return Response(status.HTTP_201_CREATED) else: return Response(status.HTTP_501_NOT_IMPLEMENTED) elif request.data['type'] == 'unlike': already_liked_user = comment.get_users if request.user in already_liked_user: like = Like.objects.get(user=request.user, comment=comment) like.delete() return Response(status.HTTP_201_CREATED) else: return Response(status.HTTP_501_NOT_IMPLEMENTED) except Comment.DoesNotExist: return Response(status.HTTP_404_NOT_FOUND)
def post(self, request): if not self.postobject.likes.filter(liker=self.request.user).exists(): like = Like(post=self.postobject, liker=self.request.user) like.save() else: Like.objects.filter(liker=self.request.user, post=self.postobject).delete() self.postobject.liked = Like.objects.filter( post=self.postobject).count() self.postobject.save() return HttpResponse( self.postobject.likes.filter(liker=self.request.user).exists())
def test_likes(self): c = Comment(user_id = self.uid1, game_id = self.game1_id, text="Test Text") c.id = 33 db.session.add(c) db.session.commit() test_like = Like(user_id=self.uid1, comment_id=c.id) test_like.id = 254 db.session.add(test_like) db.session.commit() like = Like.query.filter(Like.comment_id==33, Like.user_id==11).one() self.assertEqual(like.id, 254) self.assertEqual(like.user_id, 11) self.assertEqual(like.comment_id, 33)
def like_view(request): user = check_validation(request) if user and request.method == 'POST': form = Like(request.POST) if form.is_valid(): post_id = form.cleaned_data.get('post').id existing_like = Like.objects.filter(post_id=post_id, user=user).first() if not existing_like: Like.objects.create(post_id=post_id, user=user) else: existing_like.delete() return redirect('/feed/') else: return redirect('/login/')
def like_message(msg_id): """Let a user like a warbler""" if not g.user: flash("Access unauthorized.", "danger") return redirect(url_for('homepage')) new_like = Like() new_like.user_id = g.user.id new_like.message_id = msg_id db.session.add(new_like) db.session.commit() return redirect(request.referrer)
def like_update(cls, post_id, user_id): error_msg = '' post = Post.get_by_id(post_id) current_like = Like.all().filter('post_id =', post_id).filter('user_id =', int(user_id)).get() if user_id != post.created_by: if not current_like: # if there is no record, adding a record with value=True l = Like(user_id=int(user_id), post_id=int(post_id), like_value=True) l.put() return l, error_msg current_like.like_value = not current_like.like_value current_like.put() else: error_msg = 'You cannot like your own post' return current_like, error_msg
def post(self, post_id): key = db.Key.from_path('Post', int(post_id), parent=blog_key()) post = db.get(key) if not post: self.error(404) return c = "" if (self.user): if (self.request.get('like') and self.request.get('like') == "update"): likes = db.GqlQuery("select * from Like where post_id = " + post_id + " and user_id = " + str(self.user.key().id())) if self.user.key().id() == post.user_id: self.redirect("/blog/" + post_id + "?error=You cannot like your own " + "post.!!") return elif likes.count() == 0: l = Like(parent=blog_key(), user_id=self.user.key().id(), post_id=int(post_id)) l.put() if (self.request.get('comment')): c = Comment(parent=blog_key(), user_id=self.user.key().id(), post_id=int(post_id), comment=self.request.get('comment')) c.put() else: self.redirect("/login?error=You need to login before " + "performing edit, like or commenting.!!") return comments = db.GqlQuery("select * from Comment where post_id = " + post_id + "order by created desc") likes = db.GqlQuery("select * from Like where post_id=" + post_id) self.render("permalink.html", post=post, comments=comments, noOfLikes=likes.count(), new=c)
def handle_like(message_id): """ Add a like to a message when star symbol is clicked. """ """ Still need to add a button which links to this route (action/post)""" """ Should be able to unlike a warble as well by clicking on link""" if not g.user: flash("Please login.", "success") return redirect("/login") message = Message.query.get(message_id) like = Like.query.get((message_id, g.user.id)) if like: db.session.delete(like) db.session.commit() flash("Like was removed!", "success") elif g.user.id == message.user_id: flash("Sorry! You can't like your own posts.", "danger") else: like = Like(msg_id=message_id, user_id=g.user.id) db.session.add(like) db.session.commit() flash("Like was added!", "success") return redirect("/")
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
def setUp(self): ''' Set up our test client and make a new message, user and like for each test to work with ''' self.client = app.test_client() new_message = Message(id=1, text="Testing", timestamp=datetime.datetime( 2018, 1, 1, 1, 1, 1, 1), user_id=1) new_user = User(id=1, email='*****@*****.**', username='******', image_url='/static/images/default-pic.png', header_image_url='/static/images/warbler-hero.jpg', bio='Test Bio', location='Test Location', password='******') new_like = Like(user_id=1, message_id=1) db.session.add(new_message) db.session.add(new_user) db.session.add(new_like) db.session.commit()
def test_is_liked_by(self): """Does is_liked_by method return correct boolean?""" u = User(email="*****@*****.**", username="******", password="******") u2 = User(email="*****@*****.**", username="******", password="******") db.session.add(u) db.session.add(u2) db.session.commit() msg = Message(text="My dad makes margaritas!") u.messages.append(msg) db.session.commit() msg_to_like = Message.query.first() # gets the second user that was created (u2) liker = User.query.order_by(User.id.desc()).first() # gets u1 nonliker = User.query.first() new_like = Like(user_id=liker.id, message_id=msg_to_like.id) db.session.add(new_like) db.session.commit() like = Message.query.first() self.assertEqual(like.is_liked_by(liker), True) self.assertEqual(like.is_liked_by(nonliker), False)
def messages_like_toggle(message_id): """Like/unlike a message.""" #TODO: think about splitting this into two routes - one that likes, # one that unlikes. Would provide more flexibility. if not g.user: flash("Access unauthorized.", "danger") return redirect("/") if g.like_form.validate_on_submit(): like = Like.query.filter_by(message_id=message_id, user_id=g.user.id).one_or_none() if like: db.session.delete(like) else: new_like = Like(message_id=message_id, user_id=g.user.id) db.session.add(new_like) db.session.commit() ####### request.referrer puts every reload in the history ####### # when using request.referrer have a fall back (e.g. homepage) return redirect(request.referrer)
def get(self): qry = Topic.query().order(Topic.topic) topics = [] for row in qry: likes = Like.query().filter(Like.topic == row.key).count() topics.append(TOPIC(key=row.key, topic=row.topic, description=row.description, archived=row.archived, likes=likes)) self.render_template('home.html', {'topics': topics})
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)
def like_message(message_id): """Like a message.""" # if not g.user: # flash("Access unauthorized.", "danger") # return redirect("/") try: liked = Like.query.filter_by(msg_id=message_id, user_id=g.user.id).first() # import pdb; pdb.set_trace() if liked: db.session.delete(liked) db.session.commit() return jsonify({"status": "DELETED"}) else: like = Like(msg_id=message_id, user_id=g.user.id) db.session.add(like) db.session.commit() return jsonify({"status": "OK"}) # cur_message = Message.query.get(message_id) # if cur_message.user_id == g.user.id: # return redirect(request.referrer) # g_likes = [msg.id for msg in g.user.likes] except (IntegrityError, InvalidRequestError): db.session.rollback() liked_msg = Like.query.get_or_404((g.user.id, message_id)) db.session.delete(liked_msg) db.session.commit() g_likes = [msg.id for msg in g.user.likes] return redirect(request.referrer)
def like_action(request): """ 处理 like action """ assert(request.method=='POST' and request.is_ajax()==True) bid = request.POST.get('id') try: query = Like.objects.filter(user=request.user, book=bid) if len(query): query.delete() unlike_signal.send(sender=request.user, target=bid, cat='book') else: record = Like(user=request.user, book=bid) record.save() like_signal.send(sender=request.user, target=bid, cat='book') addLikeMsg(request.user, bid, "likebook") return HttpResponse('success') except: return HttpResponse('fail')
def dislike(ecocup): username = session["username"] like = Like.query.filter_by(user=username, ecocup=ecocup).first() if like is None: like = Like(user=username, ecocup=ecocup, valeur=-1) db.session.add(like) else: like.valeur = -1 ecocup = Ecocup.query.get(ecocup) if ecocup is None: return jsonify({"error": True}) db.session.commit() ecocup.appreciation = sum(map(lambda l: l.valeur, Like.query.filter_by(ecocup=ecocup.id).all())) db.session.commit() return jsonify({"appreciation": ecocup.appreciation, "error": False})
def get_like_value(self,branch): userinfo = UserInfo.get_by_username(self.username) if userinfo and self.is_user_info_current(userinfo): like_key = Like.create_key(branch.key,self.username) like = like_key.get(); if like: return like.value return 0
def like_boker(user_key, boker_key, explicitly_shared=False): """Like a boker""" user = User.get_by_key_name(user_key) boker = Boker.get(boker_key) boker_owner = boker.user if user and boker and not Like.already_like(user, boker): # Create like like = Like(user=user, boker=boker) like.put() # Update like numbers boker.num_like += 1 boker.put() if not settings.DEBUG: # Post to FB try: boker_url = "%s/boker/%s" % (settings.APP_DOMAIN, boker.key().id()) graph = facebook.GraphAPI(user.access_token) graph.request('me/og.likes', post_args={'object': boker_url, 'fb:explicitly_shared': str(explicitly_shared).lower()}) except Exception as e: print e # Notify Boker owner if user != boker_owner: try: boker_url = encode_url("/boker/%s" % boker.key().id()) graph = facebook.GraphAPI(settings.FACEBOOK_APP_ACCESS_TOKEN) graph.request('%s/notifications' % boker_owner.id, post_args={ 'href': '?to=' + boker_url, 'template': '@[%s] menyukai boker anda.' % user.id, }) except Exception as e: print e else: logging.info('Runtask: post_like_story...')
def send_like(liker_id, liked_id, message, is_anonymous=False): user_liker = User.objects.get(id=liker_id) user_liked = User.objects.get(id=liked_id) already_waved = True like = None try: like = Like.objects.get(liker=user_liker, liked=user_liked) like.anonymous = is_anonymous except ObjectDoesNotExist: already_waved = False like = Like( liker=user_liker, liked=user_liked, anonymous=is_anonymous ) like.save() if message: like.add_message(message) # ---------****--- PUSH ---****--------- # yg_pm = BarachielPushManager() yg_pm.set_like(like) yg_pm.send() response = like.serialize(user_liker) return (response, already_waved)
def likes(request): id1 = request.POST['client_id'] print request.POST loggeduserid=request.user.id myUser = get_object_or_404(User, id=loggeduserid) y = get_object_or_404(MyUser, id=int(id1)) try: likee = Like.objects.get(user = myUser, profile = y) except ObjectDoesNotExist: y.like_number += 1 likee = Like() likee.user = myUser likee.profile = y likee.save() #print like x = y.like_number y.save() response_dict = {} response_dict.update({'server_response': x}) return HttpResponse(json.dumps(response_dict), mimetype='application/javascript')
def megustas(request,lugar,recurso): gustas = '' try: gustas = Like.objects.get(actividad = int(recurso)) gustas.like += 1 gustas.save() print 'try ' + recurso except : print 'except ' + recurso gustas = Like() gustas.like=1 gustas.actividad = int(recurso) gustas.save() if(lugar == '1'): return HttpResponseRedirect('/todas') elif(lugar == '0'): return HttpResponseRedirect('/') else: return HttpResponseRedirect('/actividad/' + lugar)
def set_like(self,branch_urlsafe_key,like_value): if branch_urlsafe_key is None or branch_urlsafe_key == '': return False, ['invalid_parameters'] userinfo = self.current_user_info() if userinfo is None: return False, ['unauthenticated'] branch_key = ndb.Key(urlsafe=branch_urlsafe_key) like_key = Like.create_key(branch_key,userinfo.username) like = like_key.get() if like is None: branch = branch_key.get() like = Like(key=like_key,username=userinfo.username,branch=branch_key,branchauthorname=branch.authorname) like.value = int(like_value) like.put() return True, like
def get(self): """ Get method to render blog.html """ if self.user: user_key = self.user user_id = user_key.key.id() _user = User.by_id(int(user_id)) _blogs = Blog.query_blogs().fetch() likes = Like.query().fetch() self.render('blog.html', blogs=_blogs, user=_user, likes=likes) else: _blogs = Blog.query_blogs().fetch() self.render('blog.html', blogs=_blogs, user=None, likes=None)
def post(self): user = User.is_logged(self) if not user: self.response.out.write( simplejson.dumps({'status':'error', 'message':'In order to vote you must sign in.'}) ) return key = self.request.get('key') koch = db.get(key) vote = Like.all().filter('koch =', koch).filter('user ='******'status':'error', 'message':'Are you cheating?'}) ) return votes = Like.up( koch, user ) self.response.out.write( simplejson.dumps( { 'status' : 'success', 'message' : 'up', 'votes' : votes } ) )
def get_post_bundle(cls, post_id, user=None): user_id = int(user.key().id()) if user else None post = Post.get_by_id(post_id) comments = Comment.all().filter('post_id =', post_id).order('-created').fetch(limit=10) like = Like.all().filter('post_id =', post_id).filter('user_id =', user_id).get() if user else None # username dictionary, to show usernames instead of IDs user_ids = set([c.created_by for c in comments]) user_ids.add(post.created_by) if user_id: user_ids.add(user_id) user_objects = User.get_by_id(user_ids) username_dict = {u.key().id(): u.username for u in user_objects} return PostBundle(post, comments, like, username_dict)
def get_kochs_data(entities, author=None): kochs = [] user = User.is_logged() for koch in entities: if user: alreadylike = Like.alreadylike( koch, user ) else: alreadylike = False kochs.append({ 'koch' : koch, 'humanlikes' : intcomma( int( koch.likes) ), 'alreadylike' : alreadylike, }) return kochs
def post(self): user = User.is_logged(self) if not user: self.response.out.write( simplejson.dumps({'status':'error', 'message':'In order to vote you must sign in.'}) ) return key = self.request.get('key') koch = db.get(key) vote = Like.all().filter('koch =', koch).filter('user ='******'status' : 'success', 'message' : 'down', 'votes' : votes } ) ) return self.response.out.write( simplejson.dumps({'status':'success', 'message':'An error occurred please contact the developer'}) )
return LikePostBadRequest( "No object matching content-type %r and object PK %r exists." % \ (escape(ctype), escape(object_pk))) except (ValueError, ValidationError), e: return LikePostBadRequest( "Attempting go get content-type %r and object PK %r exists raised %s" % \ (escape(ctype), escape(object_pk), e.__class__.__name__)) request_user = request.user # Otherwise create the like like = Like.objects.filter(user=request_user, content_type=ctype, object_pk=object_pk) if like.count() > 0: like = like[0] else: like = Like() like.ip_address = request.META.get("REMOTE_ADDR", None) like.user = request_user like.content_type = ctype like.object_pk = object_pk like.likes = likes like.submit_date = datetime.datetime.now() like.site_id = settings.SITE_ID # Save the like and signal that it was saved like.save() if notification: #notify all concerned users by the object notification.send([request_user], "new_like", {'like_user': request_user,
def get(self): qs = {} page = int(self.request.get('page') or 1) limit = int(self.request.get('limit') or settings.PAGINATION_LIMIT) sort_name, sort_field = self.sorter() qs['sort'] = sort_name bokers = Boker.all().order(sort_field) # Current loggedin User current_user = None if self.current_user: current_user = User.get_by_key_name(self.current_user['id']) # Filter by user user_filter = self.request.get('username') if user_filter: qs['username'] = user_filter user = User.gql("WHERE username=:1", user_filter).get() bokers.filter('user ='******'s objects = [] for b in bokers: # Check if user can like a boker user_can_like = False if current_user: user_can_like = not Like.already_like(current_user, b) data = { 'user': { 'id': b.user.id, 'username': b.user.username, 'name': b.user.name, 'url': self.uri_for('user', username=b.user.username), }, 'current_user': { 'id': None, 'username': None, }, 'id': b.key().id(), 'key': str(b.key()), 'created': naturaltime(b.created), 'is_new': is_new(b.created), 'description': b.description, 'permalink': self.uri_for('boker_view', boker_id=b.key().id()), 'num_comment': b.num_comment, 'num_view': b.num_view, 'num_like': b.num_like, 'can_like': user_can_like, } if b.photo: data['type'] = 'photo' data['photo'] = {'key': str(b.photo.key())} if b.video_id: data['type'] = 'video' data['embed'] = {'id': b.video_id, 'url': 'http://www.youtube.com/embed/' + b.video_id} if self.current_user: data['current_user'] = { 'id': self.current_user.get('id'), 'username': self.current_user.get('username'), } objects.append(data) # metadata qs.update({'page': page+1}) next_qs = self._build_qs(qs) qs.update({'page': page-1}) previous_qs = self._build_qs(qs) meta = { 'count': len(objects), 'limit': limit, 'page': page, 'next_url': '%s?%s' % (self.uri_for('streams'), next_qs) if page < num_pages else None, 'previous_url': '%s?%s' % (self.uri_for('streams'), previous_qs) if page > 1 else None, 'pages': num_pages, } streams = dict( meta=meta, objects=objects, ) self.response.headers['Content-Type'] = 'application/json' self.response.out.write(json.dumps(streams))