Esempio n. 1
0
 def __trans_dict_to_object(self, commentDict):
     return Comment(
             cid = hashUtil.uid(),
             whoId = commentDict["whoId"],
             whoName = commentDict["whoName"],
             what = commentDict["what"],
             when = commentDict["when"],
             like = commentDict["like"],
             create = datetime.datetime.now(),
             modified = datetime.datetime.now()
         )
Esempio n. 2
0
 def do_action(self):
     args = self.get_args([
         ('text_id', str, None),
     ])
     text_id = args.get('text_id')
     res = Blog().get_one(text_id)
     comment = Comment().get_all(text_id)
     res['comment'] = comment
     read = res['read'] + 1
     Blog().update_read(text_id, read)
     self.result = res
     return True
Esempio n. 3
0
def new_form_comment():

    try:
        data = request.form
        logger.info('form data ' + str(data))

        # validate token: retrieve site entity
        token = data.get('token', '')
        site = Site.select().where(Site.token == token).get()
        if site is None:
            logger.warn('Unknown site %s' % token)
            abort(400)

        # honeypot for spammers
        captcha = data.get('remarque', '')
        if captcha:
            logger.warn('discard spam: data %s' % data)
            abort(400)

        url = data.get('url', '')
        author_name = data.get('author', '').strip()
        author_gravatar = data.get('email', '').strip()
        author_site = data.get('site', '').lower().strip()
        if author_site and author_site[:4] != 'http':
            author_site = 'http://' + author_site
        message = data.get('message', '')

        # anti-spam again
        if not url or not author_name or not message:
            logger.warn('empty field: data %s' % data)
            abort(400)
        check_form_data(data)

        # add a row to Comment table
        created = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        comment = Comment(
            site=site,
            url=url,
            author_name=author_name,
            author_site=author_site,
            author_gravatar=author_gravatar,
            content=message,
            created=created,
            notified=None,
            published=None,
        )
        comment.save()

    except:
        logger.exception('new comment failure')
        abort(400)

    return redirect('/redirect/', code=302)
Esempio n. 4
0
def create_comment():
    try:
        r = request.json
        comment = Comment(content=r['content'],
                          user_email=r['user_email'],
                          cat_id=r['cat_id'])
        db.session.add(comment)
        db.session.commit()
    except Exception as e:
        print(e)
        return jsonify({'err': 'oops'}), 444
    return jsonify(comment.json), 201
Esempio n. 5
0
    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
        """
            On posting comment, new comment tuple is created and stored,
            with relationship data of user and post.
        """
        c = ""
        if (self.user):
            # On clicking like, post-like value increases.
            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 " + "post.!!")
                    return
                elif likes.count() == 0:
                    l = Like(parent=blog_key(),
                             user_id=self.user.key().id(),
                             post_id=int(post_id))
                    l.put()

            # On commenting, it creates new comment tuple
            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)
Esempio n. 6
0
    def redirect_if_not_author(*args, **kwargs):
        self = args[0]
        user_id = kwargs['user_id']
        comment_id = kwargs['comment_id']
        comment = Comment().get_by_id(int(comment_id))

        if comment and comment.submitter == user_id:
            # Call the decorated function
            fn(*args, **kwargs)
        elif comment:
            self.redirect('/posts/' + kwargs['post_id'])
        else:
            self.abort(404)
Esempio n. 7
0
def create_comment():
    user = g.current_user
    data = request.get_json()
    order = user.orders.filter_by(id=data['order_id']).first()
    if order is None:
        return {'errmsg': '无权执行操作', 'errcode': 400}, 400
    if order.state != '已确认收货':
        return {'errmsg': '确认收货后才可评论哦', 'errcode': 400}, 400
    if order.comment.first() is not None:
        return {'errmsg': '已经评论过了哦', 'errcode': 400}, 400
    comment = Comment(order=order, user=user, content=data['content'])
    db.session.add(comment)
    db.session.commit()
    return {'errmsg': '发表评论成功', 'errcode': 200}, 200
Esempio n. 8
0
 def do_action(self):
     args = self.get_args([
         ('user_id', str, None),
     ])
     user_id = args.get('user_id')
     res = Blog().get_list(user_id)
     for item in res:
         if 'ctime' in item:
             ctime = item['ctime']
             item['date']=ctime[:4] + '年' + ctime[5:7] + '月' + ctime[8:10] +'日'
         cres = Comment().get_all(item['text_id'])
         item['ccount'] = len(cres)
     self.result = res
     return True
Esempio n. 9
0
    def post(self, post_id):
        if self.user:
            if 'main' in self.request.POST:
                self.redirect('/blog/%s' % str(post_id))
            elif 'sub' in self.request.POST:
                comment_text = self.request.get('comment')
                comment_elem = Comment(comment=comment_text,
                                       post_id=post_id,
                                       made_by=self.user.name)
                comment_elem.put()

                self.redirect('/blog/%s' % str(post_id))
        else:
            self.redirect('/blog/login')
Esempio n. 10
0
def establish_users_and_post_with_comments():

    User(id="Test_User_01", password="******").put()
    User(id="Test_User_02", password="******").put()
    User(id="Test_User_03", password="******").put()

    post_key = Post(title="Test", submitter="Test_User_01",
                    content="Test").put()

    comment_01 = Comment(content="Test content 01",
                         submitter="Test_User_01",
                         post_id=post_key.integer_id()).put()
    comment_02 = Comment(content="Test content 02",
                         submitter="Test_User_02",
                         post_id=post_key.integer_id()).put()
    comment_03 = Comment(content="Test content 03",
                         submitter="Test_User_03",
                         post_id=post_key.integer_id()).put()

    return (post_key.integer_id(), [
        comment_01.integer_id(),
        comment_02.integer_id(),
        comment_03.integer_id()
    ])
Esempio n. 11
0
def comment_post():
    if request.method == 'POST':
        username = request.form['username']
        content = request.form['content']
        tweet_id = request.form['tweet_id']
        if username:
            user = User.query.filter_by(username=username).first()
            tweet = Tweet.query.filter_by(id=tweet_id).first()
            if user and tweet:
                comment = Comment(user.id, content)
                db.session.add(comment)
                db.session.flush()
                tweet.add_comment(comment.id)
                db.session.commit()
                return jsonify(message="200 OK")
            else:
                return jsonify(error="No such user: %s or no such tweet" %
                               username)
        else:
            return jsonify(error="Error param")
Esempio n. 12
0
def add_new_comment_service(post_id, body):
    # Find logged user
    current_user = get_user_id(get_jwt_identity())

    # Find a post
    post = Post.objects(id=post_id).first()

    if post and current_user is not None:

        # Create a new comment
        comment = Comment(body=body, user=current_user)

        # Add to comments list and save
        post.comments.append(comment)
        post.save()

        return jsonify(comment)

    else:
        if post is None:
            return Response("Post does not exist", 404)
        if current_user is None:
            return Response("User does not exist", 404)
Esempio n. 13
0
def post(id):
    post = Post.query.get_or_404(id)
    form = CommentForm()
    if form.validate_on_submit():
        comment = Comment(
            body=form.body.data,
            post=post,
            author=current_user._get_current_object(),
        )
        db.session.add(comment)
        db.session.commit()
        return redirect(url_for('blog.post', id=post.id, page=-1))
    page = request.args.get('page', 1, type=int)
    if page == -1:
        page = (post.comments.count() - 1) / 10 + 1
    pagination = post.comments.order_by(Comment.timestamp.asc()).paginate(
        page, per_page=10, error_out=False)
    comments = pagination.items
    return render_template('post.html',
                           posts=[post],
                           form=form,
                           comments=comments,
                           pagination=pagination)
Esempio n. 14
0
def send_comment():
    data = request.get_json()
    print(data)
    if is_user_login(request):
        user_id = get_user_id_by_cookie(request)
    else:
        return jsonify({'code': 208, 'msg': "登录信息已经过期"})
    article_id = data['article_id']
    comment_id = data['comment_id']
    be_comment_user_id = data['be_comment_user_id']
    com_content = data['com_content']
    redis = get_redis_cli()
    user = User.query.filter(User.id == user_id).first()
    user_name = user.nick_name
    if exist_user(user_id) and exist_article(article_id):
        print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
        comment_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
        if be_comment_user_id == "null":
            comment = Comment(None, user_id,
                              comment_id, article_id, comment_time, com_content, None)
            db.session.add(comment)
            # 评论文章,个人+1积分
            user = User.query.filter(User.id == user_id).first()
            user.effect += 1
            db.session.commit()
            result = Article.query.filter(Article.article_id == article_id).first()
            result.heat = int(result.heat) + int(5)
            # 找出作者的id
            author_user_id = result.user_id
            notice_content = str(user_name) + "评论了你的文章:" + str(result.title)
            notice_title = "你收到了一条评论"
            n1 = Notice(None, author_user_id, notice_title, notice_content, 0, comment_time, -1, 2, user_id)
            db.session.add(n1)
            # 有人评论,作者积分+2
            author = User.query.filter(User.id == author_user_id).first()
            author.effect += 3
            db.session.commit()
            status_key = "status:" + "comment:" + str(author_user_id)
            if redis.keys(status_key):
                print(redis.keys(status_key))
            else:
                redis.set(status_key, 1)
        else:
            if exist_user(be_comment_user_id):
                comment = Comment(None, user_id,
                                  comment_id, article_id, comment_time, com_content, be_comment_user_id)
                db.session.add(comment)
                db.session.commit()
                notice_title = "你收到了一条回复"
                notice_content = str(user_name) + "回复了你的评论"
                n1 = Notice(None, be_comment_user_id, notice_title, notice_content, 0, comment_time, -1, 2, user_id)
                db.session.add(comment)
                db.session.add(n1)
                db.session.commit()
                status_key = "status:" + "comment:" + str(be_comment_user_id)
                if redis.keys(status_key):
                    print(redis.keys(status_key))
                else:
                    redis.set(status_key, 1)
            else:
                return jsonify({"code": "203", "msg": "被评论用户不存在,无法发表此评论"})
        # 评论数加1,并更新到redis
        result = db.session.query(Article).get(article_id)
        result.comment_num = result.comment_num + 1
        db.session.commit()
        return jsonify({"code": "200", "msg": "评论成功"})
    else:
        return jsonify({"code": "203", "msg": "用户不存在,无法发表此评论"})
Esempio n. 15
0
 def get(self, **kwargs):
     comment_id = kwargs['comment_id']
     post_id = kwargs['post_id']
     Comment().get_by_id(int(comment_id)).key.delete()
     self.redirect('/posts/' + post_id)
 def get_model(self):
     """
     :rtype: model.comment.Comment
     """
     return Comment()