def get(self, *args, **kwargs): user = self.current_user() stype = args[0] if stype == "1": article_query = Article.get_by_username(user.username) page_size = 5 cur_page = self.get_argument("cur_page", int(math.ceil(article_query.count() / page_size))) article = pagination(count_all=article_query.count(), query=article_query, page_size=page_size, cur_page=cur_page) self.render( 'personal/manager.html', article=article, comment={}, forperson={}, page_title="文章管理", ) elif stype == "2": comment_query = Comment.get_by_username(user.username) forperson_query = Comment.get_by_foruser(user.username) page_size = 5 cur_page1 = self.get_argument("cur_page1", int(math.ceil(comment_query.count() / page_size))) cur_page2 = self.get_argument("cur_page2", int(math.ceil(forperson_query.count() / page_size))) comment = pagination(count_all=comment_query.count(), query=comment_query, page_size=page_size, cur_page=cur_page1) forperson = pagination(count_all=forperson_query.count(), query=forperson_query, page_size=page_size, cur_page=cur_page2) self.render( 'personal/manager.html', article={}, comment=comment, forperson=forperson, page_title="评论管理", ) else: return self.redirect(url_for("index"))
def post(self, rater, rating, comment_text): if comment_text: comment_text = urllib2.unquote(comment_text) if type(comment_text) == type(""): comment_text = comment_text.decode("latin1") else: comment_text = "" rater_rating = RaterRating.update(rater, int(rating), comment_text) if rater_rating is not None: if comment_text != "": Comment.create(comment_text, int(rating), rater_rating.tags) self.response.out.write( simplejson.dumps({ 'rater_id': rater_rating.rater_id, 'result': True, 'pusher_message': make_push_rating_message(rater_rating, comment_text) })) else: self.error(404) self.response.out.write( simplejson.dumps({ 'rater_id': None, 'result': False }))
def post(self, *args, **kwargs): stype = args[0] if stype == "1": article_key = self.get_argument("theKey", "") user = self.current_user() article = Article.get_by_key(article_key) if article_key != "" and(user.level == 100 or user.username == article.username): if Article.dele_by_key(article_key): Comment.dele_by_article(article_key) self.write("删除成功!") else: self.send_error(404) else: self.send_error(404) if stype == "2": comment_key = self.get_argument("theKey", "") user = self.current_user() comment = Comment.get_by_key(comment_key) if comment_key != "" and (user.level == 100 or user.username == comment.username): if Comment.dele_by_key(comment_key): self.write("删除成功!") else: self.send_error(404) else: self.send_error(404) else: self.redirect("/user/personal/manager/1")
def post(self, *args, **kwargs): comment = self.get_argument("comment", "") user_re = re.compile(r"@(\S{3,19}) (.*)") try: foruser = user_re.search(comment).group(1) if not User.exist(foruser): foruser = "" else: comment = user_re.search(comment).group(2) except Exception as e: foruser = "" article_key = self.get_argument("article_key", "") user = self.current_user() if user is not None: username = user.username else: username = "******" if user is not None and user.level == 0: self.messages.error("您暂时无法评论!") elif Comment.num_lim(username): self.messages.error("评论过多,暂时无法评论,请联系管理员!") elif comment != "": Comment.new(username, foruser, comment, article_key) self.messages.success("评论成功!") self.redirect("/spider/" + article_key)
def read_comments(self, task_id): """Read Comments for a task from service and return a dict keyed on id.""" # the easiest way to get comments from task rabbit is through the task. #path = "{}/{}".format(TASK_RABBIT.TASKS_PATH, str(task_id)) #raw_task = self._get(path) # ## extract the raw task rabbit comments from the raw task dict. #raw_comments = ( # TaskRabbitCommentTransformer.pull_tr_comments_from_task_dict( # raw_task) # ) # ## convert raw comments to Comments #comments = {} #for raw_comment in raw_comments: # comment = ( # TaskRabbitCommentTransformer.convert_dict_to_comment( # raw_comment) # ) # comments[comment.id()] = comment print "fake comment coming from task rabbit" comment = Comment(-1, -1, unicode("partnership is key.")) comments = {comment.id(): comment} return comments
def post_comment(): user_name = request.params.get('user_name', '') comment = request.params.get('comment', '') if len(user_name) == 0 or len(comment) == 0: redirect('/') Comment.add(user_name, comment) redirect('/')
def post(self, *args, **kwargs): comment_key = self.get_argument("theKey", "") user = self.current_user() comment = Comment.get_by_key(comment_key) if comment_key != "" and (user.level == 100 or user.username == comment.username): Comment.dele_by_key(comment_key) return self.write("删除成功") else: self.send_error(404)
def post(self): user = util.get_user_from_session() message = self.request.get('message') owner_email = self.request.get('owner_email') bout_id = self.request.get('bout_id') bout = Bout.get_by_id(long(bout_id)) photo = Photo.for_bout_user(bout, owner_email) Comment.create(user, photo, message) Notification.create('comment_add', photo.bout.owner, user.email, bout)
def new_form_comment(): try: data = request.form # add client IP if provided by HTTP proxy ip = "" if "X-Forwarded-For" in request.headers: ip = request.headers["X-Forwarded-For"] # log logger.info(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("captcha", "") 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", "") created = datetime.now().strftime("%Y-%m-%d %H:%M:%S") # add a row to Comment table 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, ip=ip, ) comment.save() except: logger.exception("new comment failure") abort(400) return redirect("/redirect/", code=302)
def after_insert(self, raw_post: Dict, values_lst: List[SQLValuesToWrite], records: List[DataRecord]): for record in records: statistic_add_comment(record['related_type'], record['related_id'], record['id']) post_number = Comment.select().where( Comment.related_id == record['related_id'], Comment.id <= record['id']).count() Comment.update(post_number=post_number).where( Comment.id == record['id']).execute()
def post(self, *args, **kwargs): key = self.get_argument("theKey", "") user = self.current_user() article = Article.get_by_key(key) if key != "" and(user.level == 100 or user.username == article.username): if Article.dele_by_key(key): Comment.dele_by_article(key) self.write("删除成功!") else: self.send_error(404) else: self.send_error(404)
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)
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)
def _prepare_data(self): return [ Comment("1", "qwerty 1", "qazxsw 1", "plmnko 1", "qazxsw 1", "plmnko 1"), Comment("2", "qwerty 2", "qazxsw 2", "plmnko 2", "qazxsw 1", "plmnko 1"), Comment("3", "qwerty 3", "qazxsw 3", "plmnko 3", "qazxsw 1", "plmnko 1"), Comment("4", "qwerty 4", "qazxsw 4", "plmnko 4", "qazxsw 1", "plmnko 1"), Comment("5", "qwerty 5", "qazxsw 5", "plmnko 5", "qazxsw 1", "plmnko 1"), ]
def after_insert(self, raw_post: Dict, values_lst: List[SQLValuesToWrite], records: List[DataRecord]): for record in records: statistic_add_comment(record['related_type'], record['related_id'], record['id']) post_number = Comment.select().where(Comment.related_id == record['related_id'], Comment.id <= record['id']).count() Comment.update(post_number=post_number).where(Comment.id == record['id']).execute() if self.do_mentions: self.do_mentions(record['user_id'], POST_TYPES.COMMENT, record['id'], { 'comment_info': { 'related_type': record['related_type'], 'related_id': record['related_id'], } })
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')
def do_action(self): args = self.get_args([ ('text_id', str, None), ('email', str, None), ('subject', str, None), ('comment', str, None), ]) text_id = args.get('text_id') chelper = Comment() chelper.create(args) comments = Comment().get_all(text_id) res = Blog().get_one(text_id) res['comment'] = comments self.result = res return True
def post(self): p = Post.get(self.params['post_key']) spam = self.params.get('spam_breaker', None) if not spam or spam.lower().find("purple") == -1: self.redirect('/blog/view/%s/%s' % (p.posted_on.strftime("%Y%m%d"), p.slug)) return c = Comment(post=p, author=self.params['author'], email=self.params.get('email', None), url=self.params.get('url', None), content=self.params['comment']) c.put() mailer.new_comment(p, c) self.redirect('/blog/view/%s/%s' % (p.posted_on.strftime("%Y%m%d"), p.slug))
def post(self): for row in Article.all(): row.delete() for row in Comment.all(): row.delete() self.redirect('/blog')
def comment(): article_id = request.form.get('articleId') or 0 if not article_id: return jsonify(state=False, message='文章不存在') user_id = session.get('userid') user_name = session.get('username') to_name = request.form.get('toName') or None content = request.form.get('content') or None if not content: return jsonify(state=False, message='评论内容不能为空') if not user_name or not user_id: return jsonify(state=False, message='用户未登录') user = db_session.query(User).filter(User.id == user_id).first() ## 向数据库添加一条评论 c = Comment(article_id, user.id, user.name, user.head_url, to_name, content) db_session.add(c) db_session.flush() article_url = 'http://hamilton.duapp.com/detail?articleId=' + str( article_id) bmq.send_mail(['*****@*****.**'], 'hamilton上的新回复', '<!--HTML-->\n您有一条新回复需要处理<br/>点击查看:<a href="' + article_url + '">' + article_url + '</a>') return jsonify(state=True, message='success')
def save_all_in_month(self, year, month): ''' comment 는 top level comment 만 가져옵니다. ''' query_result = list(psaw_crawler.get_all_in_month(datetime(year, month, 1))) submissions = [Submission( title=submission.title, unique_id=submission.id, author=submission.author.name if submission.author else None, selftext=submission.selftext, flair=submission.link_flair_text, created_at=datetime.utcfromtimestamp(submission.created_utc)) for submission in query_result] self.session.add_all(submissions) self.session.flush() submission_map = {submission.unique_id: submission for submission in submissions} comments = [Comment( submission_id=submission_map[elem.id].id, unique_id=com.id, author=com.author.name if com.author else None, selftext=com.body, created_at=datetime.utcfromtimestamp(com.created_utc)) for elem in query_result for com in elem.comments] self.session.add_all(comments)
def do_comment_upload(): # 新的评论信息插入 # 将密码加密 try: message = '' status = 0 insert_dict = g.params login_name = insert_dict['login_name'] #判断用户账号是邮件或者手机号 if '@' in login_name: insert_dict['comment_email'] = login_name else: insert_dict['comment_phone'] = login_name insert_dict.pop('login_name') g.db.add(Comment(**insert_dict)) g.db.commit() except Exception, e: message = repr(e) status = 1 g.db.rollback()
def submit_new_comment(): for comment in Comment.select().where(Comment.notified.is_null()): comment_list = ( 'author: %s' % comment.author_name, 'site: %s' % comment.author_site, 'date: %s' % comment.created, 'url: %s' % comment.url, '', '%s' % comment.content, '', ) comment_text = '\n'.join(comment_list) email_body = get_template('new_comment').render(url=comment.url, comment=comment_text) # send email site = Site.get(Site.id == comment.site) subject = 'STACOSYS %s: [%d:%s]' % (site.name, comment.id, site.token) if mailer.send(site.admin_email, subject, email_body): logger.debug('new comment processed ') # notify site admin and save notification datetime comment.notify_site_admin() else: logger.warn('rescheduled. send mail failure ' + subject)
def generate_site(token): site = Site.select().where(Site.token == token).get() rss_title = get_template('rss_title_message').render(site=site.name) md = markdown.Markdown() items = [] for row in (Comment.select().join(Site).where( Site.token == token, Comment.published).order_by(-Comment.published).limit(10)): item_link = '%s://%s%s' % (config.get( config.RSS_PROTO), site.url, row.url) items.append( PyRSS2Gen.RSSItem( title='%s - %s://%s%s' % (config.get( config.RSS_PROTO), row.author_name, site.url, row.url), link=item_link, description=md.convert(row.content), guid=PyRSS2Gen.Guid('%s/%d' % (item_link, row.id)), pubDate=row.published, )) rss = PyRSS2Gen.RSS2( title=rss_title, link='%s://%s' % (config.get(config.RSS_PROTO), site.url), description='Commentaires du site "%s"' % site.name, lastBuildDate=datetime.now(), items=items, ) rss.write_xml(open(config.get(config.RSS_FILE), 'w'), encoding='utf-8')
def submit_new_comment(): for comment in Comment.select().where(Comment.notified.is_null()): comment_list = ( "author: %s" % comment.author_name, "site: %s" % comment.author_site, "date: %s" % comment.created, "url: %s" % comment.url, "", "%s" % comment.content, "", ) comment_text = "\n".join(comment_list) email_body = get_template("new_comment").render( url=comment.url, comment=comment_text ) # send email site = Site.get(Site.id == comment.site) subject = "STACOSYS %s: [%d:%s]" % (site.name, comment.id, site.token) mailer.send(site.admin_email, subject, email_body) logger.debug("new comment processed ") # update comment comment.notified = datetime.now().strftime("%Y-%m-%d %H:%M:%S") comment.save()
def query_comments(): comments = [] try: token = request.args.get('token', '') url = request.args.get('url', '') logger.info('retrieve comments for url %s' % (url)) for comment in (Comment.select(Comment).join(Site).where( (Comment.url == url) & (Comment.published.is_null(False)) & (Site.token == token)).order_by(+Comment.published)): d = { 'author': comment.author_name, 'content': comment.content, 'avatar': comment.author_gravatar, 'date': comment.published.strftime('%Y-%m-%d %H:%M:%S') } if comment.author_site: d['site'] = comment.author_site logger.debug(d) comments.append(d) r = jsonify({'data': comments}) r.status_code = 200 except: logger.warn('bad request') r = jsonify({'data': []}) r.status_code = 400 return r
def get(self, **kwargs): template = jinja_env.get_template('post.html') post_id = kwargs['post_id'] post = Post.get_by_id(int(post_id)) # Retrieve all comments comments_query = Comment.query(Comment.post_id == int(post_id)).order( Comment.submitted) comments = [comment for comment in comments_query] # Discern anonymous browsers from users cookie = self.request.cookies.get('user') user = None has_liked = None if validate_user_cookie(cookie): user = cookie.split("|")[0] has_liked = user_has_liked_post(user, post_id) # If this post exists, render it (otherwise, 404) self.write( template, { 'post': post, 'comments': comments, 'current_user': user, 'has_liked': has_liked })
def query_comments(): comments = [] try: token = request.args.get('token', '') url = request.args.get('url', '') logger.info('retrieve comments for token %s, url %s' % (token, url)) for comment in Comment.select(Comment).join(Site).where( (Comment.url == url) & (Comment.published.is_null(False)) & (Site.token == token)).order_by(+Comment.published): d = {} d['author'] = comment.author_name d['content'] = comment.content if comment.author_site: d['site'] = comment.author_site d['avatar'] = comment.author_gravatar d['date'] = comment.published.strftime("%Y-%m-%d %H:%M:%S") logger.debug(d) comments.append(d) r = jsonify({'data': comments}) r.status_code = 200 except: logger.warn('bad request') r = jsonify({'data': []}) r.status_code = 400 return r
async def collect_comments(self, owner_id: int, post_id: int) -> AsyncIterator[Comment]: offset = 0 while True: comment_count = 0 async for comment in self.__session.wall.get_comments( owner_id=owner_id, post_id=post_id, offset=offset, count=self.__MAX_COMMENTS_PER_REQUEST__, need_likes=True, sort='asc'): comment_count += 1 likes = [] if comment.count_likes: likes = [ user_id async for user_id in self.collect_likes( 'comment', owner_id, comment.id, 'likes') ] yield Comment(comment_id=comment.id, owner_id=comment.from_id, text=comment.text, date=comment.date, likes=likes, reply=comment.reply_to_user) if comment_count < self.__MAX_COMMENTS_PER_REQUEST__: break offset += self.__MAX_COMMENTS_PER_REQUEST__
def generate_site(token): site = Site.select().where(Site.token == token).get() rss_title = get_template("rss_title_message").render(site=site.name) md = markdown.Markdown() items = [] for row in ( Comment.select() .join(Site) .where(Site.token == token, Comment.published) .order_by(-Comment.published) .limit(10) ): item_link = "%s://%s%s" % (config.get(config.RSS_PROTO), site.url, row.url) items.append( PyRSS2Gen.RSSItem( title="%s - %s://%s%s" % (config.get(config.RSS_PROTO), row.author_name, site.url, row.url), link=item_link, description=md.convert(row.content), guid=PyRSS2Gen.Guid("%s/%d" % (item_link, row.id)), pubDate=row.published, ) ) rss = PyRSS2Gen.RSS2( title=rss_title, link="%s://%s" % (config.get(config.RSS_PROTO), site.url), description="Commentaires du site '%s'" % site.name, lastBuildDate=datetime.now(), items=items, ) rss.write_xml(open(config.get(config.RSS_FILE), "w"), encoding="utf-8")
def post(self, **kwargs): post_id = kwargs['post_id'] user_id = kwargs['user_id'] content = self.request.POST['content'] Comment(content=content, submitter=user_id, post_id=int(post_id)).put() self.redirect('/posts/' + post_id)
def post(self, rater, rating, comment_text): if comment_text: comment_text = urllib2.unquote(comment_text) if type(comment_text) == type(""): comment_text = comment_text.decode("latin1") else: comment_text = "" rater_rating = RaterRating.update(rater, int(rating), comment_text) if rater_rating is not None: if comment_text != "": Comment.create(comment_text, int(rating), rater_rating.tags) self.response.out.write(simplejson.dumps({'rater_id': rater_rating.rater_id, 'result': True, 'pusher_message':make_push_rating_message(rater_rating, comment_text)})) else: self.error(404) self.response.out.write(simplejson.dumps({'rater_id': None, 'result': False}))
def get(self): next = self.request.get('next') owner_email = self.request.get('owner_email') bout_id = long(self.request.get('bout_id')) bout = Bout.get_by_id(bout_id) photo = Photo.for_bout_user(bout, owner_email) response = util.fetch_with_cursor(Comment.all().ancestor(photo).order("-timestamp"), limit=20, cursor=next, mapper=make_comment_dict) self.response.write(json.dumps(response))
def ordered_comments(self, dir="ASC"): # this import cannot be in the header because # it causes a circular import and blows up from model.comment import Comment comments = Comment.all().filter("post =", self) if dir == "DESC": return comments.order("-posted_at") else: return comments.order("posted_at")
def get(self, **kwargs): post_id = kwargs['post_id'] Post.get_by_id(int(post_id)).key.delete() # Cascade the delete to all comments associated with the post comments = Comment.query(Comment.post_id == int(post_id)) for comment in comments: comment.key.delete() self.redirect('/')
async def after_insert(self, raw_post: Dict, values: SQLValuesToWrite, record: DataRecord): post_stats_do_comment(record['related_type'], record['related_id'], record['id']) post_number = Comment.select().where( Comment.related_id == record['related_id'], Comment.id <= record['id']).count() Comment.update(post_number=post_number).where( Comment.id == record['id']).execute() if self.do_mentions: # 创建提醒 loc = [record['related_type'], record['related_id']] # record['related_id']: memoryview loc_title = POST_TYPES.get_post_title_by_list(loc)[ record['related_id'].tobytes()] related = [POST_TYPES.COMMENT, record['id']] self.do_mentions(record['user_id'], loc_title, loc, related)
def _prepare_expected_data(self): return [ Comment("1", self._highlighted_text, self._highlighted_text, self._highlighted_text, self._highlighted_text, self._highlighted_text), Comment("2", self._highlighted_text, self._highlighted_text, self._highlighted_text, self._highlighted_text, self._highlighted_text), Comment("3", self._highlighted_text, self._highlighted_text, self._highlighted_text, self._highlighted_text, self._highlighted_text), Comment("4", self._highlighted_text, self._highlighted_text, self._highlighted_text, self._highlighted_text, self._highlighted_text), Comment("5", self._highlighted_text, self._highlighted_text, self._highlighted_text, self._highlighted_text, self._highlighted_text), ]
def error_if_comment_does_not_exist(*args, **kwargs): self = args[0] post_id = kwargs['comment_id'] post = Comment.get_by_id(int(post_id)) if post: fn(self, **kwargs) else: self.abort(404)
def create_comment(self, params, comment_type): if comment_type == 'txt': if not params.get('content', False): raise HTTPError(403, 'there is not data') comment = Comment.new(**params) if comment_type == 'audio': audio = hqby.audio.get_temp_audio(params['audio_id']) info = hqby.audio.move_temp_audio( audio, configs['audio_base_path'], configs['audio_base_url'], hqby.audio.id_to_subdir(params['topic_id']) ) #info['src'] = info['src'].encode('utf-8') info['audio_len'] = audio['len'] info['type'] = audio['type'] params['content'] = json.dumps(info) del params['audio_id'] comment = Comment.new(**params) return comment
def post(self): book = Book.get_by_key_name("Book_" + self.request.get('book')) if not book: return body = self.request.get('body') if not body: return comment = Comment( book = book, body = body ) comment.put() Activity(type='comment', book=book).put() user = users.get_current_user() template_values = { 'comment': comment, 'user': user, } path = os.path.join(os.path.dirname(__file__), '..', 'view', 'comment/index.html') result = template.render(path, template_values) self.response.out.write(result)
def _reply_comment_email(email: Email): m = re.search(r'\[(\d+)\:(\w+)\]', email.subject) if not m: logger.warn('ignore corrupted email. No token %s' % email.subject) return comment_id = int(m.group(1)) token = m.group(2) # retrieve site and comment rows try: comment = Comment.select().where(Comment.id == comment_id).get() except: logger.warn('unknown comment %d' % comment_id) return True if comment.published: logger.warn('ignore already published email. token %d' % comment_id) return if comment.site.token != token: logger.warn('ignore corrupted email. Unknown token %d' % comment_id) return if not email.plain_text_content: logger.warn('ignore empty email') return # safe logic: no answer or unknown answer is a go for publishing if email.plain_text_content[:2].upper() in ('NO'): logger.info('discard comment: %d' % comment_id) comment.delete_instance() new_email_body = get_template('drop_comment').render( original=email.plain_text_content) if not mailer.send(email.from_addr, 'Re: ' + email.subject, new_email_body): logger.warn('minor failure. cannot send rejection mail ' + email.subject) else: # save publishing datetime comment.publish() logger.info('commit comment: %d' % comment_id) # rebuild RSS rss.generate_site(token) # send approval confirmation email to admin new_email_body = get_template('approve_comment').render( original=email.plain_text_content) if not mailer.send(email.from_addr, 'Re: ' + email.subject, new_email_body): logger.warn('minor failure. cannot send approval email ' + email.subject) return True
def post(self, **kwargs): post_id = kwargs['post_id'] comment_id = kwargs['comment_id'] content = self.request.POST['content'] # Update the comment comment = Comment.get_by_id(int(comment_id)) comment.content = content comment.put() self.redirect('/posts/' + post_id)
async def before_insert(self, values_lst: List[SQLValuesToWrite]): for values in values_lst: relate_type = values.get('related_type', None) if not (relate_type and relate_type in POST_TYPES.values()): return self.finish(RETCODE.INVALID_POSTDATA, "被评论的内容不存在") try: cid = config.POST_ID_GENERATOR(values['related_id']) post = POST_TYPES.get_post(relate_type, cid) if not post: return self.finish(RETCODE.INVALID_POSTDATA, "被评论的内容不存在") if relate_type == POST_TYPES.TOPIC: if post.state == POST_STATE.CLOSE: return self.finish(RETCODE.INVALID_POSTDATA, "无法评论指定内容") elif post.visible in (POST_VISIBLE.HIDE, ): return self.finish(RETCODE.INVALID_POSTDATA, "被评论的内容不存在") except TypeError: return self.finish(RETCODE.INVALID_POSTDATA, "被评论的内容不存在") if 'content' not in values or not values['content']: return self.finish(RETCODE.INVALID_POSTDATA, "评论内容不能为空") if 'reply_to_cmt_id' in values: try: rtid = config.POST_ID_GENERATOR(values['reply_to_cmt_id']) except TypeError: return self.finish(RETCODE.INVALID_POSTDATA, "指定被回复的内容不存在") c: Comment = Comment.get_by_pk(rtid.to_bin()) if not c: return self.finish(RETCODE.INVALID_POSTDATA, "指定被回复的内容不存在") if c.related_id != post.id: return self.finish(RETCODE.INVALID_POSTDATA, "指定被回复的内容不存在") values['reply_to_cmt_id'] = rtid.to_bin() if not isinstance(config.LONG_ID_GENERATOR, config.SQLSerialGenerator): values['id'] = config.LONG_ID_GENERATOR().to_bin() values['related_id'] = cid.to_bin() values['related_type'] = int(values['related_type']) values['user_id'] = self.current_user.id values['time'] = int(time.time()) values['content'], self.do_mentions = check_content_mention( values['content']) if relate_type == POST_TYPES.TOPIC: post: Topic await post.weight_inc()
def __trans_dict_to_comment(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() )
def _comment_data(self, comm, fields=None): """ 评论返回格式包装 """ data = Comment._comment_data(comm) user = hqby.user.get_user_info(uid=data['user_id']) data['user'] = user to_user = {} if data['to_user_id']: to_user = hqby.user.get_user_info(uid=data['to_user_id']) data['to_user'] = to_user return data
def __comment_to_bson(project_id: Union[int, str], comment: Comment) -> dict: return { "_id": ( comment.noteable_iid if comment.noteable_iid is not None else ObjectId(), comment.noteable_type, project_id, ), "project_id": project_id, }.update(comment.to_dict())
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
def post(self): media=self.getMedia(self.request.get('key')) if media: comment=Comment() comment.title=self.request.get('title') u=users.get_current_user() if u: comment.by=u.nickname() else: comment.by="Mr. I'm too good to log in" comment.text=self.request.get('text') commentkey=self.request.get('commentkey') if commentkey: comment.op=Comment.get(commentkey) else: comment.media=media comment.put() template_values = {"media":media} path = os.path.join(os.path.dirname(__file__), '../html/details.html') shared.render(self, path, template_values)
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
def make_photo_dict(photo, email): photo_dict = {} owner = User.get_by_key_name(photo.owner_email) photo_dict['image'] = photo.image_url photo_dict['owner_email'] = photo.owner_email photo_dict['owner_first_name'] = owner.first_name photo_dict['owner_last_name'] = owner.last_name photo_dict['num_votes'] = Vote.count(photo) photo_dict['num_comments'] = len(Comment.for_(photo)) photo_dict['is_voted'] = Vote.is_voted(email, photo) photo_dict['profile_picture'] = owner.profile_picture return photo_dict
def get_comments_count(): try: token = request.args.get('token', '') url = request.args.get('url', '') count = Comment.select(Comment).join(Site).where( (Comment.url == url) & (Comment.published.is_null(False)) & (Site.token == token)).count() r = jsonify({'count': count}) r.status_code = 200 except: r = jsonify({'count': 0}) r.status_code = 200 return r
def get(self, key): try: comment = Comment.get(db.Key(key)) except(Exception): comment = None if comment: template_values = { 'comment': comment, } path = os.path.join(os.path.dirname(__file__), '..', 'view', 'comment/index.html') result = template.render(path, template_values) else: path = os.path.join(os.path.dirname(__file__), '..', 'view', 'comment/not_found.html') result = template.render(path, {}) self.response.out.write(result)
def index(self): now = datetime.datetime.now() # up and coming fixtures user = users.get_current_user() comments = Comment.all() comments.order("-commented_at") self.comments = comments.fetch(10) # profile = models.Profile.load(user) # profile = web.getuserprofile(self) events = Event.all() events.order("-event_start") self.events = events.fetch(10) categorys = db.GqlQuery("SELECT * FROM Category ORDER BY type ASC") # sorted all sports self.categorys = categorys.fetch(10) # leagues = None # teams = None totalusers = db.GqlQuery("SELECT * FROM Profile") # total profiles totalusercount = totalusers.count() topusers = db.GqlQuery("SELECT * FROM Profile")
def get(self, *args): key = args[0] ar = Article.get_by_key(key) page_size = 5 comment_query = Comment.get_by_article(key) cur_page = self.get_argument("cur_page", int(math.ceil(comment_query.count() / page_size))) comment = pagination(count_all=comment_query.count(), query=comment_query, page_size=page_size, cur_page=cur_page) next_back = Article.get_next_back(key) if ar is not None: page_title = ar.header self.render( "spider.html", page_title=page_title, ar=ar, comment=comment, next_back=next_back, ) else: self.messages.error("文章链接已经更新") self.redirect(url_for("index"))
def get(self, **kwargs): uid = kwargs['uid'] mode = kwargs['mode'] item_id = int(kwargs['item_id']) user = hqby.user.get_user_info(uid=uid) if not user: raise HTTPError(403, 'can not found this user') if mode not in ['topic','comment']: raise HTTPError(400,'type not topic or comment') if mode == 'topic': #如果赞的是心得 先从缓存中找赞 没赞过的话就新建赞 key = "0"+uid+str(item_id) zan = model.like.get_zan(uid,item_id,0,key) if not zan: #更新心得里的like_num 新建赞 新建msg item = Topic.update_topic(item_id, True, False) item_data = Topic._topic_data(item) zan = {'user_id':str(uid),'item_id':item_data['topic_id'],'item_type':0} zan = model.like.create_like(zan) msg = self.create_msg('TL', user, item_data) self.write({'status':1,'type':mode,'like_num':item_data['like_num'],'uid':uid,'like_id':zan['id'],'msg':msg}) else: self.write({'status':0,'type':mode,'msg':'already liked'}) elif mode == 'comment': #如果赞的是评论 先从缓存中找赞 没赞过的话就新建赞 key = "1"+uid+str(item_id) zan = model.like.get_zan(uid,item_id,1,key) if not zan: item = Comment.update_comment(item_id,True) zan = {'user_id':str(uid),'item_id':item['id'],'item_type':1} zan = model.like.create_like(zan) msg = self.create_msg('CL', user, item) self.write({'status':1,'type':mode,'like_num':item['like_num'],'uid':uid,'like_id':zan['id'],'msg':msg}) else: self.write({'status':0,'type':mode,'msg':'already liked'}) return
post_key = ndb.Key(urlsafe=new_comment['post_id']) post = post_key.get() # Check that the post entity actually exists (key might reference a deleted entity) if post is None: raise TypeError # Respond with 404 - Not Found if we can't construct or get entity by the provided key # (Catch all errors, because it really doesn't matter what error we get when trying to construct # the key, since everything means that they provided key is invalid and fetching entity is not possible) except Exception, e: self.error(404) return # Create the comment entity comment = Anna_Comment(user_id = user.user_id(), post_id = new_comment['post_id'], content = new_comment['content']) # Push the comment to the database comment.put() # Create the list inside comments if this is the first comment if post.comments is None: post.comments = [comment.key] # Append the comment to the list if the list already exists else: post.comments.append(comment.key) # Push the comment with its list to the database post.put()
def show(self): r = Comment.get(self.params.get('id'))
def reply_comment_email(data): from_email = data["from"] subject = data["subject"] message = "" for part in data["parts"]: if part["content-type"] == "text/plain": message = part["content"] break m = re.search(r"\[(\d+)\:(\w+)\]", subject) if not m: logger.warn("ignore corrupted email. No token %s" % subject) return comment_id = int(m.group(1)) token = m.group(2) # retrieve site and comment rows try: comment = Comment.select().where(Comment.id == comment_id).get() except: logger.warn("unknown comment %d" % comment_id) return True if comment.published: logger.warn("ignore already published email. token %d" % comment_id) return if comment.site.token != token: logger.warn("ignore corrupted email. Unknown token %d" % comment_id) return if not message: logger.warn("ignore empty email") return # safe logic: no answer or unknown answer is a go for publishing if message[:2].upper() in ("NO", "SP"): # put a log to help fail2ban if message[:2].upper() == "SP": # SPAM if comment.ip: logger.info( "SPAM comment from %s: %d" % (comment.ip, comment_id) ) else: logger.info("cannot identify SPAM source: %d" % comment_id) logger.info("discard comment: %d" % comment_id) comment.delete_instance() email_body = get_template("drop_comment").render(original=message) mailer.send(from_email, "Re: " + subject, email_body) else: # update Comment row comment.published = datetime.now().strftime("%Y-%m-%d %H:%M:%S") comment.ip = None comment.save() logger.info("commit comment: %d" % comment_id) # rebuild RSS rss.generate_site(token) # send approval confirmation email to admin email_body = get_template("approve_comment").render(original=message) mailer.send(from_email, "Re: " + subject, email_body) return True
def delete(self, key): comment = Comment.get(db.Key(key)) user = users.get_current_user() if comment and user and user == comment.author: comment.delete() self.response.out.write("ok")