Exemplo n.º 1
0
 def post(self, post_id):
     blogpost = self.get_blogpost(post_id)
     user = self.get_user_object()
     if user:
         if blogpost:
             # To detect which form is sent, the like or the comment
             if "likeBtn" in self.request.POST:
                 if blogpost.author.key().id() == user.key().id():
                     error = "You cannot like your own post!"
                     comments = self.get_comments(blogpost)
                     self.render_content(blogpost=blogpost,
                                         user=user,
                                         comments=comments,
                                         error_like=error)
                 else:
                     like = LikePost(user=user, blogpost=blogpost)
                     like.put()
                     self.redirect('/%s' % post_id)
             else:
                 content = self.request.get("comment")
                 if content:
                     comment = Comment(user=user,
                                       blogpost=blogpost,
                                       content=content)
                     comment.put()
                     self.redirect('/%s' % post_id)
                 else:
                     error = "Please write something before posting!"
                     comments = self.get_comments(blogpost)
                     self.render_content(blogpost=blogpost,
                                         user=user,
                                         comments=comments,
                                         error_comment=error)
     else:
         self.redirect("/login")
Exemplo n.º 2
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
        """
            While commenting, a comment datastore object is created and stored,
            with respect to each 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 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()

            # 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("/blog/" + post_id + "?error= Need to Login Please.")
            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,
                    no_of_likes=likes.count(),
                    new=c)
Exemplo n.º 3
0
    def post(self):
        self.options()
        username = self.request.get('username')
        post_id = self.request.get('post_id')
        content = self.request.get('content')

        if username != None and post_id != None and content != None:
            comment_post = Comment(username=username,
                                   post_id=post_id,
                                   content=content)
            comment_post.put()
            self.response.out.write("Complete")
        else:
            self.response.out.write("Fail")
Exemplo n.º 4
0
def response():
	if config.memcache.db:
		clearmem()
	action = cgi_get("action", choices=["post", "videopost", "comment", "photo", "photoset", "md"])
	if action == "md":
		for dn, dz, fz in os.walk("md"):
			succeed([f[:-3] for f in fz])
	user = cgi_get("user")
	if action == "comment":
		ent = Comment(user=user, post=cgi_get("post"), body=cgi_get("body"))
	elif action == "photo":
		pkey = cgi_get("key", required=False)
		if pkey:
			ent = Photo.query(Photo.key == pkey).get()
		else:
			ent = Photo()
		capt = cgi_get("caption", required=False) # imgs uploaded separately
		if capt:
			ent.caption = capt
	else:
		blurb = cgi_get("blurb", required=False)
		pkey = cgi_get("key", required=False)
		tags = cgi_get("tags", required=False)
		pmod = db.get_model(action)
		if pkey:
			ent = pmod.query(pmod.key == pkey).get()
		else:
			ent = pmod(user=user)
		ent.title = cgi_get("title")
		ent.live = cgi_get("live")
		if blurb:
			ent.blurb = blurb
		if tags:
			ent.tags = tags
		if action == "post":
			ent.body = cgi_get("body")
	ent.put()
	if action == "photo": # get photoset
		psk = cgi_get("photoset", required=False)
		if psk:
			ps = db.get(psk) # these are hacky -- fix list ops in ct
			if cgi_get("remove", default=False):
#				ps.photos.remove(ent.key)
				ps.photos = [p for p in ps.photos if p != ent.key]
			else:
#				ps.photos.append(ent.key)
				ps.photos = ps.photos + [ent.key]
			ps.put()
	succeed(ent.id())
Exemplo n.º 5
0
 def post(self):
     text = self.request.get('comment')
     if len(text) > 0:
         date_time = self.request.get('date_time')
         post_key = Post.query(Post.date_time == date_time).fetch()[0].key
         name = self.request.get('author_name')
         author_key = Key('User', self.session.get('user_key_id'))
         comment = Comment(author_key = author_key,
                           post_key = post_key,
                           text = text,
                           author_name = name,
                           date_time = datetime.now().strftime('%m/%d/%y/%H/%M/%S/%f'))
         comment.put()
         time.sleep(0.1)
     self.redirect('/index')
Exemplo n.º 6
0
    def post(self):
        """create a comment to related post"""
        if self.with_no_user():
            self.redirect("/")
            return

        uid = self.user.key().id()
        uname = self.user.name
        pid = long(self.request.get("pid"))
        content = self.request.get("content")

        if content:
            comment = Comment(uid=uid, uname=uname, pid=pid, content=content)
            comment.put()

        self.redirect("/post/%s" % pid)
Exemplo n.º 7
0
    def post(self, id=None):
        comment = Comment()
        user = users.get_current_user()
        key_user = ndb.Key(User, user.email())
        user_details = key_user.get()
        if self.request.get("comment").strip() != "":
            comment.commenter = user_details
            comment.commentDescription = self.request.get("comment").strip()
            comment.createdAt = datetime.now()
            comment = comment.put()
            commentedPost = Post.get_by_id(int(id))
            commentedPost.comments.append(comment.get())
            commentedPost.put()
            time.sleep(0.1)
        else:
            self.add_message("Please don't enter empty string", "danger")

        if self.request.get("ad").strip() == "postDetail":
            self.redirect('/post/' + id, abort=False)
        else:
            self.redirect('/', abort=False)
Exemplo n.º 8
0
    def post(self, photo_id=0):
        '''Adding a new comment to a photo.'''
        user_id, user = self.get_user()
        if not user:
            self.redirect('/')
            return

        photo_id = int(photo_id)
        comment = self.request.get('comment-text')
        #comment = escape(comment)

        logging.info(photo_id)

        photo = Photo.get_by_id(photo_id)
        new_comment = Comment(
            photo=photo.key,
            user=user.key,
            text=comment
        )
        new_comment.put()

        # keep track of the total number of comments
        photo.comment_count += 1
        photo.put()

        # send an email to the photographer and commentators, letting them
        # know of the new comment
        to = self._email_addresses(photo, user)

        if not to:
            # the commentator is also the photographer and there are
            # no comments from other users - no email to send.
            logging.info('Comment made, but no need to send email.')
            self.redirect(self.request.path)
            return

        body = (
            'Someone has made a comment on a photograph.'
            '\n\n'
            'From: {}\n\n'
            '{}'  # comment
            '\n\n'
            "The following link will take you to the photograph's page.\n"
            'http://prelude-hmpc.appspot.com/photo/{}'
        )
        body = body.format(user.username, comment, photo_id)

        try:
            email = mail.EmailMessage(
                sender='HMPC Bot <*****@*****.**>',
                subject='HMPC: New photograph comment',
                bcc=to,
                body=body
            )
            email.send()
        except OverQuotaError, msg:
            logging.error(msg)
            # send a message to admin (me) then I can forward to users
            new_body = body + '\n\nSend to:\n' + ', '.join(to)
            mail.send_mail_to_admins(
                sender='HMPC Bot <*****@*****.**>',
                subject='HMPC: New photograph comment (over quota)',
                body=new_body
            )
Exemplo n.º 9
0
    def post(self, post_slug=""):
        if post_slug:
            t_values = {}

            post_id = self.request.POST['post_id']
            post = Entry.get_by_id(long(post_id))
            if post:
                # ok, we find the post, try to add comment to this post
                logging.warning("find one post with post_id %s" % (post_id))
                t_values['post'] = post
                # dump(post)

                # check google recaptcha, these two fileds might not exist due to connection to reCAPTCHA
                recaptcha_challenge_field = self.request.POST.get('recaptcha_challenge_field', "")
                recaptcha_response_field = self.request.POST.get('recaptcha_response_field', "")
                remote_ip = self.request.environ['REMOTE_ADDR']
                private_key = "6LdwFdISAAAAAOYRK7ls3O-kXPTnYDEstrLM2MRo"
                antispam_flag = False
                try:
                    result = submit(recaptcha_challenge_field, recaptcha_response_field, private_key, remote_ip)
                    logging.info("google recaptcha %s, %s" % (result.is_valid, result.error_code))
                    if result.is_valid:
                        antispam_flag = True
                except:
                    e = sys.exc_info()[0]
                    logging.info(e)

                # create comment for this post
                if antispam_flag:
                    logging.info("PostManager - add comment")
                    comm_author = self.request.POST['author']
                    comm_email = self.request.POST['email']
                    comm_weburl = self.request.POST['weburl']
                    comm_content = self.request.POST['comment']
                    comment_ip = self.request.environ['REMOTE_ADDR']
                    comm = Comment(entry=post, author=comm_author, email=comm_email, weburl=comm_weburl, content=comm_content, ip=comment_ip)
                    comm.put()
                    t_values['alert_message'] = "Thanks %s for your comment!" % (comm_author)
                else:
                    logging.warning("comment ignored because antispam failed")
                    t_values['alert_message'] = "Sorry, your comment was ignored because of reCAPTCHA failure!"

                # find all comments
                comments = Comment.all().filter("entry =", post).order("date")
                logging.info("PostHandler, post, find %d comments" % (comments.count()))
                if post_id:
                    # only update commentcount when new comment is added
                    post.commentcount = comments.count()
                    post.put()
                t_values['comments'] = comments
            else:
                logging.warning("post_id %s does not exist" % (post_id))

            links = Link.all().order("date")
            t_values['links'] = links

            categories = Category.all()
            t_values['categories'] = categories
    
            pages = Entry.all().filter("is_external_page =", True).filter("entrytype =", 'page').order("date")
            t_values['pages'] = pages

            return self.response.out.write(render_template("post.html", t_values, "basic", False))
        else:
            self.redirect(uri_for("weblog.index"))
Exemplo n.º 10
0
    def post(self, nodeid, topicid):
        if self.cur_user and self.cur_user.flag > 1:
            author = self.cur_user.name
            content = self.POST['content']

            if content and len(content) <= COMMENT_MAX_S:
                int_time = int(time())

                #check spam
                mi_obj = MemberInfo.get_or_insert(author)
                if self.cur_user.flag < 99:
                    if mi_obj.replyt:
                        t_list = mi_obj.replyt.split(',')
                        if len(t_list) == MEMBER_RECENT_REPLY and (
                                int_time - int(t_list[-1])) < 3600:
                            self.write(
                                u'403:不要回复太频繁了 <a href="/t-%s-%s">请返回</a>' %
                                (nodeid, topicid))
                            return

                #check repeat
                content = textilize(content)  #safe_encode(content)
                con_md5 = md5(content.encode('utf-8')).hexdigest()
                if memcache.get('c_' + con_md5):
                    self.write(u'403:请勿灌水 <a href="/t-%s-%s">请返回</a>' %
                               (nodeid, topicid))
                    return
                else:
                    memcache.set('c_' + con_md5, '1', 36000)

                topic_key = '%s-%s' % (nodeid, topicid)
                t_obj = Topic.get_by_key_name(topic_key)
                if not t_obj:
                    self.error(404)
                    self.write('404: not found')
                    return

                if t_obj.cnum:
                    id_num = t_obj.cnum + 1
                else:
                    id_num = 1

                c_key = '%s-%d' % (topic_key, id_num)
                c_obj = Comment(key_name=c_key)
                c_obj.author = author
                c_obj.add = int_time
                c_obj.con = content
                c_obj.put()
                if c_obj.is_saved():
                    #topic commont count +1
                    t_obj.cnum = id_num
                    t_obj.reply = author
                    t_obj.edit = int_time
                    db.run_in_transaction(obj_runput, t_obj)
                    #memberinfo
                    mi_obj.replyn += 1
                    if mi_obj.replyk:
                        t_list = mi_obj.replyk.split(',')
                        if topic_key in t_list:
                            t_list.remove(topic_key)
                        t_list.insert(0, topic_key)
                        mi_obj.replyk = ','.join(t_list[:MEMBER_RECENT_REPLY])
                    else:
                        mi_obj.replyk = topic_key

                    if mi_obj.replyt:
                        t_list = mi_obj.replyt.split(',')
                        t_list.insert(0, str(int_time))
                        mi_obj.replyt = ','.join(t_list[:MEMBER_RECENT_REPLY])
                    else:
                        mi_obj.replyt = str(int_time)
                    db.run_in_transaction(obj_runput, mi_obj,
                                          ['reply_objs:' + author])
                    #recent reply +key
                    hi_obj = KeyStrValue.get_or_insert('recent-reply-topic')
                    if hi_obj.value:
                        t_list = hi_obj.value.split(',')
                        if topic_key in t_list:
                            t_list.remove(topic_key)
                        t_list.insert(0, topic_key)
                        hi_obj.value = ','.join(t_list[:RECENT_COMMENT_NUM])
                        db.run_in_transaction(
                            obj_runput, hi_obj,
                            ['get_topic_key_title:recent-reply-topic'])
                    else:
                        hi_obj.value = topic_key
                        db.run_in_transaction(
                            obj_runput, hi_obj,
                            ['get_topic_key_title:recent-reply-topic'])
                    #all reply counter +1
                    at_obj = Counter.get_or_insert('all-reply-num',
                                                   name='all-reply-num')
                    at_obj.value += 1
                    db.run_in_transaction(obj_runput, at_obj)
                    #notifications
                    if t_obj.author != author:
                        mentions = findall_mentions(
                            c_obj.con + ' @%s ' % t_obj.author, author)
                    else:
                        mentions = findall_mentions(c_obj.con, author)

                    if mentions:
                        deferred.defer(set_mentions,
                                       topic_key,
                                       ','.join(mentions),
                                       _countdown=8,
                                       _queue="default")

                    #del cache
                    cache_keys = []
                    hi_obj = KeyStrValue.get_or_insert('recent-topic-home')
                    if hi_obj.value:
                        if topic_key in hi_obj.value.split(','):
                            cache_keys.append(
                                'get_topic_objs:recent-topic-home')

                    if id_num < EACH_PAGE_COMMENT_NUM:
                        cache_keys.append('get_comments:%s:1' % topic_key)
                    else:
                        cache_keys.append('get_comments:%s:%d' % (topic_key, [
                            i for i in range(1, id_num, EACH_PAGE_COMMENT_NUM)
                        ][-1]))

                    if cache_keys:
                        memcache.delete_multi(cache_keys)

                    self.redirect('/t-%s#reply%d' % (topic_key, id_num))
                    return
            else:
                self.write('错误: 没有内容 或 内容太长了,请后退返回修改!')
        else:
            self.error(403)
            self.write('403:forbidden')
Exemplo n.º 11
0
 def post(self, nodeid, topicid):
     if self.cur_user and self.cur_user.flag>1:
         author = self.cur_user.name
         content = self.POST['content']
         
         if content and len(content)<=COMMENT_MAX_S:
             int_time = int(time())
             
             #check spam
             mi_obj = MemberInfo.get_or_insert(author)
             if mi_obj.replyt:
                 t_list = mi_obj.replyt.split(',')
                 if len(t_list) == MEMBER_RECENT_REPLY and (int_time-int(t_list[-1])) < 3600:
                     self.write(u'403:不要回复太频繁了 <a href="/t-%s-%s">请返回</a>' % (nodeid, topicid))
                     return
             
             #check repeat
             content = textilize(content)
             #content = safe_encode(content)
             con_md5 = md5(content.encode('utf-8')).hexdigest()
             if memcache.get('c_'+con_md5):
                 self.write(u'403:请勿灌水 <a href="/t-%s-%s">请返回</a>' % (nodeid, topicid))
                 return
             else:
                 memcache.set('c_'+con_md5, '1', 36000)
             
             topic_key = '%s-%s' % (nodeid, topicid)
             t_obj = Topic.get_by_key_name(topic_key)
             if not t_obj:
                 self.error(404)
                 self.write('404: not found')
                 return
             
             if t_obj.cnum:
                 id_num = t_obj.cnum + 1
             else:
                 id_num = 1
             
             c_key = '%s-%d' % (topic_key, id_num)
             c_obj = Comment(key_name=c_key)
             c_obj.author = author
             c_obj.add = int_time
             c_obj.con = content
             c_obj.put()
             if c_obj.is_saved():
                 #topic commont count +1
                 t_obj.cnum = id_num
                 t_obj.reply = author
                 t_obj.edit = int_time
                 db.run_in_transaction(obj_runput,t_obj)
                 #memberinfo
                 mi_obj.replyn += 1
                 if mi_obj.replyk:
                     t_list = mi_obj.replyk.split(',')
                     if topic_key in t_list:
                         t_list.remove(topic_key)
                     t_list.insert(0, topic_key)
                     mi_obj.replyk = ','.join(t_list[:MEMBER_RECENT_REPLY])
                 else:
                     mi_obj.replyk = topic_key
                     
                 if mi_obj.replyt:
                     t_list = mi_obj.replyt.split(',')
                     t_list.insert(0, str(int_time))
                     mi_obj.replyt = ','.join(t_list[:MEMBER_RECENT_REPLY])
                 else:
                     mi_obj.replyt = str(int_time)
                 db.run_in_transaction(obj_runput,mi_obj,['reply_objs:'+author])
                 #recent reply +key
                 hi_obj = KeyStrValue.get_or_insert('recent-reply-topic')
                 if hi_obj.value:
                     t_list = hi_obj.value.split(',')
                     if topic_key in t_list:
                         t_list.remove(topic_key)
                     t_list.insert(0, topic_key)
                     hi_obj.value = ','.join(t_list[:RECENT_COMMENT_NUM])
                     db.run_in_transaction(obj_runput,hi_obj,['get_topic_key_title:recent-reply-topic'])
                 else:
                     hi_obj.value = topic_key
                     db.run_in_transaction(obj_runput,hi_obj,['get_topic_key_title:recent-reply-topic'])
                 #all reply counter +1
                 at_obj = Counter.get_or_insert('all-reply-num', name = 'all-reply-num')
                 at_obj.value += 1
                 db.run_in_transaction(obj_runput,at_obj)
                 #notifications
                 if t_obj.author != author:
                     mentions = findall_mentions(c_obj.con+' @%s '%t_obj.author, author)
                 else:
                     mentions = findall_mentions(c_obj.con, author)
                 
                 if mentions:
                     deferred.defer(set_mentions, topic_key, ','.join(mentions), _countdown=8, _queue="default")
                 
                 #del cache
                 cache_keys = []
                 hi_obj = KeyStrValue.get_or_insert('recent-topic-home')
                 if hi_obj.value:
                     if topic_key in hi_obj.value.split(','):
                         cache_keys.append('get_topic_objs:recent-topic-home')
                 
                 if id_num<EACH_PAGE_COMMENT_NUM:
                     cache_keys.append('get_comments:%s:1' % topic_key)
                 else:
                     cache_keys.append('get_comments:%s:%d' % (topic_key, [i for i in range(1,id_num,EACH_PAGE_COMMENT_NUM)][-1]))
                 
                 if cache_keys:
                     memcache.delete_multi(cache_keys)
                 
                 
                 self.redirect('/t-%s#reply%d'%(topic_key,id_num))
                 return
         else:
             self.write('错误: 没有内容 或 内容太长了,请后退返回修改!')
     else:
         self.error(403)
         self.write('403:forbidden')