Esempio n. 1
0
def view_ad(url):
    room = Room.query.filter_by(urlname=url).first()
    if not room:
        abort(404)
    if room.dead or get_days_ago(room.created_at) > OLD_DAYS.days:
        abort(404)
    occupied = Occupied.query.filter_by(space=room.occupieds).order_by("created_at").first()
    if occupied and get_days_ago(occupied.created_at) > OCCUPIED_DAYS.days:
        abort(404)
    # URL is okay. Show the ad.
    comments = Comment.query.filter_by(commentspace=room.comments, parent=None).order_by("created_at").all()
    commentform = CommentForm()
    delcommentform = DeleteCommentForm()
    if request.method == "POST":
        if request.form.get("form.id") == "newcomment" and commentform.validate():
            if commentform.edit_id.data:
                comment = Comment.query.get(int(commentform.edit_id.data))
                if comment:
                    if comment.user == g.user:
                        comment.message = commentform.message.data
                        flash("Your comment has been edited", category="info")
                    else:
                        flash("You can only edit your own comments", category="info")
                else:
                    flash("No such comment", category="error")
            else:
                comment = Comment(user=g.user, commentspace=room.comments, message=commentform.message.data)
                if commentform.parent_id.data:
                    parent = Comment.query.get(int(commentform.parent_id.data))
                    if parent and parent.commentspace == room.comments:
                        comment.parent = parent
                room.comments.count += 1
                db.session.add(comment)
                flash("Your comment has been posted", category="success")
            db.session.commit()
            # Redirect despite this being the same page because HTTP 303 is required to not break
            # the browser Back button
            return redirect(url_for("view_ad", url=room.urlname) + "#c" + str(comment.id), code=303)
        elif request.form.get("form.id") == "delcomment" and delcommentform.validate():
            comment = Comment.query.get(int(delcommentform.comment_id.data))
            if comment:
                if comment.user == g.user:
                    comment.delete()
                    room.comments.count -= 1
                    db.session.commit()
                    flash("Your comment was deleted.", category="success")
                else:
                    flash("You did not post that comment.", category="error")
            else:
                flash("No such comment.", category="error")
            return redirect(url_for("view_ad", url=room.urlname), code=303)
    return render_template(
        "room.html", room=room, comments=comments, commentform=commentform, delcommentform=delcommentform
    )
Esempio n. 2
0
def show_product_page(pid):
    # 商品詳情頁的路由
    # 取得資料庫指定pid的商品資料
    doc = db.collection('product_list').document(pid).get()
    product = doc.to_dict()
    product['created_at'] = time_format(product['created_at'])
    # 取得網頁標題
    page_title = product['title'] + '|介紹'
    # 建立留言表單
    created_comment_form = CreateCommentForm()
    # 如果表單被送出
    auth_state = check_login()['auth_state']
    if created_comment_form.validate_on_submit():
        email = auth_state['user']['email']
        new_comment = {
            'email': email,
            'content': created_comment_form.content.data,
            'created_at': time.time(),
        }
        print('新留言:', new_comment)
        # 把心留言存入product_list(集合)/pid(文件)/comment_list(集合)
        db.collection(f'product_list/{pid}/comment_list').add(new_comment)
        return redirect(f'/product/{pid}/show')
    # 取得該商品的留言
    comment_collection = db.collection(
        f'product_list/{pid}/comment_list').order_by(
            'created_at', direction='DESCENDING').get()
    # 留言列表
    comment_list = []
    for doc in comment_collection:
        comment = doc.to_dict()
        comment['id'] = pid
        # 把更新留言的表單存到留言內
        # !在多表單的情況下加入prefix參數,可以幫每個表單加上不同前綴,以防伺服器混亂
        comment['update_form'] = UpdateCommentForm(prefix=doc.id)
        comment['del_form'] = DeleteCommentForm(prefix=doc.id + '-del')
        # 如果該表單被送出且合法
        if comment['update_form'].validate_on_submit():
            updated_comment = {'content': comment['update_form'].content.data}
            # 把資料更新到資料庫內
            db.document(f'product_list/{pid}/comment_list/{doc.id}').update(
                updated_comment)
            # 重新導向
            return redirect(f'/product/{pid}/show')

        if comment['del_form'].validate_on_submit():
            db.document(f'product_list/{pid}/comment_list/{doc.id}').delete()
            return redirect(f'/product/{pid}/show')

        # 把內容放入表單內當預設值
        comment['update_form'].content.data = comment['content']
        # 格式時間
        comment['created_at'] = time_format(comment['created_at'])
        comment_list.append(comment)

    return render_template('product/show.html',
                           product=product,
                           page_title=page_title,
                           created_comment_form=created_comment_form,
                           comment_list=comment_list)
Esempio n. 3
0
def delete_comment(request):
    if request.method == "POST":
        form = DeleteCommentForm(request.POST)
        if form.is_valid():
            client = get_object_or_404(Client,
                                       pk=form.cleaned_data['client_id'])
            comment = get_object_or_404(Comment,
                                        pk=form.cleaned_data['comment_id'])
            selection = get_object_or_404(Selection,
                                          pk=form.cleaned_data['selection_id'])
            comment.delete()
            return HttpResponseRedirect(request.META.get('HTTP_REFERER'), {
                'selection': selection,
                'client': client
            })
        else:
            raise Http404("That page does not exist")
    else:
        raise Http404("That page does not exist")
Esempio n. 4
0
def delete_comment(id=None):
    form = DeleteCommentForm()

    post_id = request.args.get("id")
    if form.validate_on_submit():
        comment = Comment.query.get(id)
        if checkph(comment.hash_password, form.password.data):
            post = Post.query.get(post_id)
            post.total_comments -= 1
            db.session.delete(comment)
            db.session.commit()

            return redirect(url_for('routes.view', id=post_id))
            # Ahora debería guardar el catalogo del negocio en la db
        else:
            return redirect(
                url_for('routes.output', msg="""Contraseña errónea, bro."""))

    return render_template('user/delete.html', form=form)
Esempio n. 5
0
def viewsession(name, slug):
    space = ProposalSpace.query.filter_by(name=name).first()
    if not space:
        abort(404)
    try:
        proposal_id = int(slug.split('-')[0])
    except ValueError:
        abort(404)
    proposal = Proposal.query.get(proposal_id)
    if not proposal:
        abort(404)
    if proposal.proposal_space != space:
        return redirect(url_for('viewsession', name=proposal.proposal_space.name, slug=proposal.urlname), code=301)
    if slug != proposal.urlname:
        return redirect(url_for('viewsession', name=proposal.proposal_space.name, slug=proposal.urlname), code=301)
    # URL is okay. Show the proposal.
    comments = sorted(Comment.query.filter_by(commentspace=proposal.comments, parent=None).order_by('created_at').all(),
        key=lambda c: c.votes.count, reverse=True)
    commentform = CommentForm()
    delcommentform = DeleteCommentForm()
    if request.method == 'POST':
        if request.form.get('form.id') == 'newcomment' and commentform.validate():
            if commentform.edit_id.data:
                comment = Comment.query.get(int(commentform.edit_id.data))
                if comment:
                    if comment.user == g.user:
                        comment.message = commentform.message.data
                        comment.message_html = markdown(comment.message)
                        comment.edited_at = datetime.utcnow()
                        flash("Your comment has been edited", "info")
                    else:
                        flash("You can only edit your own comments", "info")
                else:
                    flash("No such comment", "error")
            else:
                comment = Comment(user=g.user, commentspace=proposal.comments, message=commentform.message.data)
                if commentform.parent_id.data:
                    parent = Comment.query.get(int(commentform.parent_id.data))
                    if parent and parent.commentspace == proposal.comments:
                        comment.parent = parent
                comment.message_html = markdown(comment.message)
                proposal.comments.count += 1
                comment.votes.vote(g.user)  # Vote for your own comment
                db.session.add(comment)
                flash("Your comment has been posted", "info")
            db.session.commit()
            # Redirect despite this being the same page because HTTP 303 is required to not break
            # the browser Back button
            return redirect(url_for('viewsession', name=space.name, slug=proposal.urlname) + "#c" + str(comment.id),
                code=303)
        elif request.form.get('form.id') == 'delcomment' and delcommentform.validate():
            comment = Comment.query.get(int(delcommentform.comment_id.data))
            if comment:
                if comment.user == g.user:
                    comment.delete()
                    proposal.comments.count -= 1
                    db.session.commit()
                    flash("Your comment was deleted.", "info")
                else:
                    flash("You did not post that comment.", "error")
            else:
                flash("No such comment.", "error")
            return redirect(url_for('viewsession', name=space.name, slug=proposal.urlname), code=303)
    return render_template('proposal.html', space=space, proposal=proposal,
        comments=comments, commentform=commentform, delcommentform=delcommentform,
        breadcrumbs=[(url_for('viewspace', name=space.name), space.title)])
Esempio n. 6
0
def viewsession(name, slug):
    space = ProposalSpace.query.filter_by(name=name).first()
    if not space:
        abort(404)
    try:
        proposal_id = int(slug.split('-')[0])
    except ValueError:
        abort(404)
    proposal = Proposal.query.get(proposal_id)
    if not proposal:
        abort(404)
    if proposal.proposal_space != space:
        return redirect(url_for('viewsession',
                                name=proposal.proposal_space.name,
                                slug=proposal.urlname),
                        code=301)
    if slug != proposal.urlname:
        return redirect(url_for('viewsession',
                                name=proposal.proposal_space.name,
                                slug=proposal.urlname),
                        code=301)
    # URL is okay. Show the proposal.
    comments = sorted(
        Comment.query.filter_by(commentspace=proposal.comments,
                                parent=None).order_by('created_at').all(),
        key=lambda c: c.votes.count,
        reverse=True)
    commentform = CommentForm()
    commentform.message.flags.markdown = True
    delcommentform = DeleteCommentForm()
    if request.method == 'POST':
        if request.form.get(
                'form.id') == 'newcomment' and commentform.validate():
            send_mail_info = []
            if commentform.edit_id.data:
                comment = Comment.query.get(int(commentform.edit_id.data))
                if comment:
                    if comment.user == g.user:
                        comment.message = commentform.message.data
                        comment.message_html = markdown(comment.message)
                        comment.edited_at = datetime.utcnow()
                        flash("Your comment has been edited", "info")
                    else:
                        flash("You can only edit your own comments", "info")
                else:
                    flash("No such comment", "error")
            else:
                comment = Comment(user=g.user,
                                  commentspace=proposal.comments,
                                  message=commentform.message.data)
                if commentform.parent_id.data:
                    parent = Comment.query.get(int(commentform.parent_id.data))
                    if parent.user.email:
                        if parent.user == proposal.user:  # check if parent comment & proposal owner are same
                            if not g.user == parent.user:  # check if parent comment is by proposal owner
                                send_mail_info.append({
                                    'to':
                                    proposal.user.email or proposal.email,
                                    'subject':
                                    "%s Funnel:%s" % (name, proposal.title),
                                    'template':
                                    'proposal_comment_reply_email.md'
                                })
                        else:  # send mail to parent comment owner & proposal owner
                            if not parent.user == g.user:
                                send_mail_info.append({
                                    'to':
                                    parent.user.email,
                                    'subject':
                                    "%s Funnel:%s" % (name, proposal.title),
                                    'template':
                                    'proposal_comment_to_proposer_email.md'
                                })
                            if not proposal.user == g.user:
                                send_mail_info.append({
                                    'to':
                                    proposal.user.email or proposal.email,
                                    'subject':
                                    "%s Funnel:%s" % (name, proposal.title),
                                    'template':
                                    'proposal_comment_email.md'
                                })

                    if parent and parent.commentspace == proposal.comments:
                        comment.parent = parent
                else:  # for top level comment
                    if not proposal.user == g.user:
                        send_mail_info.append({
                            'to':
                            proposal.user.email or proposal.email,
                            'subject':
                            "%s Funnel:%s" % (name, proposal.title),
                            'template':
                            'proposal_comment_email.md'
                        })
                comment.message_html = markdown(comment.message)
                proposal.comments.count += 1
                comment.votes.vote(g.user)  # Vote for your own comment
                db.session.add(comment)
                flash("Your comment has been posted", "info")
                send_comment_mail(proposal, comment)

            db.session.commit()
            to_redirect = url_for('viewsession',
                                  name=space.name,
                                  slug=proposal.urlname,
                                  _external=True) + "#c" + str(comment.id)
            for item in send_mail_info:
                email_body = render_template(item.pop('template'),
                                             proposal=proposal,
                                             comment=comment,
                                             link=to_redirect)
                send_mail(sender=None, body=email_body, **item)
            # Redirect despite this being the same page because HTTP 303 is required to not break
            # the browser Back button
            return redirect(to_redirect, code=303)
        elif request.form.get(
                'form.id') == 'delcomment' and delcommentform.validate():
            comment = Comment.query.get(int(delcommentform.comment_id.data))
            if comment:
                if comment.user == g.user:
                    comment.delete()
                    proposal.comments.count -= 1
                    db.session.commit()
                    flash("Your comment was deleted.", "info")
                else:
                    flash("You did not post that comment.", "error")
            else:
                flash("No such comment.", "error")
            return redirect(url_for('viewsession',
                                    name=space.name,
                                    slug=proposal.urlname),
                            code=303)
    links = [
        Markup(url_re.sub(urllink, unicode(escape(l))))
        for l in proposal.links.replace('\r\n', '\n').split('\n') if l
    ]
    confirmform = ConfirmSessionForm()
    return render_template('proposal.html',
                           space=space,
                           proposal=proposal,
                           comments=comments,
                           commentform=commentform,
                           delcommentform=delcommentform,
                           breadcrumbs=[(url_for('viewspace', name=space.name),
                                         space.title)],
                           links=links,
                           confirmform=confirmform)
Esempio n. 7
0
def viewsession(name, slug):
    space = ProposalSpace.query.filter_by(name=name).first()
    if not space:
        abort(404)
    try:
        proposal_id = int(slug.split('-')[0])
    except ValueError:
        abort(404)
    proposal = Proposal.query.get(proposal_id)
    if not proposal:
        abort(404)
    if proposal.proposal_space != space:
        return redirect(url_for('viewsession', name=proposal.proposal_space.name, slug=proposal.urlname), code=301)
    if slug != proposal.urlname:
        return redirect(url_for('viewsession', name=proposal.proposal_space.name, slug=proposal.urlname), code=301)
    # URL is okay. Show the proposal.
    comments = sorted(Comment.query.filter_by(commentspace=proposal.comments, parent=None).order_by('created_at').all(),
        key=lambda c: c.votes.count, reverse=True)
    commentform = CommentForm()
    commentform.message.flags.markdown = True
    delcommentform = DeleteCommentForm()
    if request.method == 'POST':
        if request.form.get('form.id') == 'newcomment' and commentform.validate():
            send_mail_info = []
            if commentform.edit_id.data:
                comment = Comment.query.get(int(commentform.edit_id.data))
                if comment:
                    if comment.user == g.user:
                        comment.message = commentform.message.data
                        comment.message_html = markdown(comment.message)
                        comment.edited_at = datetime.utcnow()
                        flash("Your comment has been edited", "info")
                    else:
                        flash("You can only edit your own comments", "info")
                else:
                    flash("No such comment", "error")
            else:
                comment = Comment(user=g.user, commentspace=proposal.comments,
                    message=commentform.message.data)
                if commentform.parent_id.data:
                    parent = Comment.query.get(int(commentform.parent_id.data))
                    if parent.user.email:
                        if parent.user == proposal.user:  # check if parent comment & proposal owner are same
                            if not g.user == parent.user:  # check if parent comment is by proposal owner
                                send_mail_info.append({'to': proposal.user.email or proposal.email,
                                    'subject': "%s Funnel:%s" % (name, proposal.title),
                                    'template': 'proposal_comment_reply_email.md'})
                        else:  # send mail to parent comment owner & proposal owner
                            if not parent.user == g.user:
                                send_mail_info.append({'to': parent.user.email,
                                    'subject': "%s Funnel:%s" % (name, proposal.title),
                                    'template': 'proposal_comment_to_proposer_email.md'})
                            if not proposal.user == g.user:
                                send_mail_info.append({'to': proposal.user.email or proposal.email,
                                    'subject': "%s Funnel:%s" % (name, proposal.title),
                                    'template': 'proposal_comment_email.md'})

                    if parent and parent.commentspace == proposal.comments:
                        comment.parent = parent
                else:  # for top level comment
                    if not proposal.user == g.user:
                        send_mail_info.append({'to': proposal.user.email or proposal.email,
                            'subject': "%s Funnel:%s" % (name, proposal.title),
                            'template': 'proposal_comment_email.md'})
                comment.message_html = markdown(comment.message)
                proposal.comments.count += 1
                comment.votes.vote(g.user)  # Vote for your own comment
                db.session.add(comment)
                flash("Your comment has been posted", "info")
            db.session.commit()
            to_redirect = url_for('viewsession', name=space.name,
                    slug=proposal.urlname, _external=True) + "#c" + str(comment.id)
            for item in send_mail_info:
                email_body = render_template(item.pop('template'), proposal=proposal, comment=comment, link=to_redirect)
                send_mail(sender=None, body=email_body, **item)
            # Redirect despite this being the same page because HTTP 303 is required to not break
            # the browser Back button
            return redirect(to_redirect, code=303)
        elif request.form.get('form.id') == 'delcomment' and delcommentform.validate():
            comment = Comment.query.get(int(delcommentform.comment_id.data))
            if comment:
                if comment.user == g.user:
                    comment.delete()
                    proposal.comments.count -= 1
                    db.session.commit()
                    flash("Your comment was deleted.", "info")
                else:
                    flash("You did not post that comment.", "error")
            else:
                flash("No such comment.", "error")
            return redirect(url_for('viewsession', name=space.name, slug=proposal.urlname), code=303)
    links = [Markup(url_re.sub(urllink, unicode(escape(l)))) for l in proposal.links.replace('\r\n', '\n').split('\n') if l]
    confirmform = ConfirmSessionForm()
    return render_template('proposal.html', space=space, proposal=proposal,
        comments=comments, commentform=commentform, delcommentform=delcommentform,
        breadcrumbs=[(url_for('viewspace', name=space.name), space.title)],
        links=links, confirmform=confirmform)