commonified comments, now can be added on any generator

This commit is contained in:
Rushabh Mehta 2013-09-25 16:07:18 +05:30
parent 4b65c9d6d6
commit 491af45225
19 changed files with 198 additions and 233 deletions

View file

@ -14,6 +14,9 @@ class DocType:
webnotes.msgprint("Max Comments reached!", raise_exception=True)
def on_update(self):
import startup.event_handlers
if hasattr(startup.event_handlers, 'comment_added'):
startup.event_handlers.comment_added(self.doc)
try:
import startup.event_handlers
if hasattr(startup.event_handlers, 'comment_added'):
startup.event_handlers.comment_added(self.doc)
except ImportError, e:
pass

View file

@ -7,7 +7,6 @@ from __future__ import unicode_literals
import webnotes
import inspect, os, json, datetime, shutil
from jinja2 import Environment, FileSystemLoader
from webnotes.modules import get_doc_path, get_module_path, scrub
from webnotes.utils import get_path, get_base_path
@ -409,9 +408,7 @@ def write_docs(data, build_sitemap=None, domain=None):
if isinstance(data, basestring):
data = json.loads(data)
jenv = Environment(loader = FileSystemLoader(webnotes.utils.get_base_path()))
template = jenv.get_template("app/docs/templates/docs.html")
template = webnotes.get_template("app/docs/templates/docs.html")
data["index"] = data["docs"]
data["docs"] = None

View file

@ -508,6 +508,22 @@ def get_list(doctype, filters=None, fields=None, docstatus=None,
group_by=group_by, order_by=order_by, limit_start=limit_start, limit_page_length=limit_page_length,
as_list=as_list, debug=debug)
def get_jenv():
from jinja2 import Environment, FileSystemLoader
from webnotes.utils import get_base_path, global_date_format
from markdown2 import markdown
from json import dumps
jenv = Environment(loader = FileSystemLoader(get_base_path()))
jenv.filters["global_date_format"] = global_date_format
jenv.filters["markdown"] = markdown
jenv.filters["json"] = dumps
return jenv
def get_template(path):
return get_jenv().get_template(path)
_config = None
def get_config():
global _config

View file

@ -110,6 +110,7 @@ class LoginManager:
full_name = " ".join(filter(None, [info.first_name, info.last_name]))
webnotes.response["full_name"] = full_name
webnotes._response.set_cookie("full_name", full_name)
webnotes._response.set_cookie("user_id", self.user)
def post_login(self):
self.run_trigger()
@ -209,8 +210,10 @@ class LoginManager:
if user == webnotes.session.user:
webnotes.session.sid = ""
webnotes._response.delete_cookie("full_name")
webnotes._response.delete_cookie("user_id")
webnotes._response.delete_cookie("sid")
webnotes._response.set_cookie("full_name", "")
webnotes._response.set_cookie("user_id", "")
webnotes._response.set_cookie("sid", "")
class CookieManager:

View file

@ -18,16 +18,13 @@ def send(recipients=None, sender=None, doctype='Profile', email_field='email',
return cint(rdata.unsubscribed)
def check_bulk_limit(new_mails):
import startup
from webnotes import conf
from webnotes.utils import nowdate
this_month = webnotes.conn.sql("""select count(*) from `tabBulk Email` where
month(creation)=month(%s)""" % nowdate())[0][0]
if hasattr(startup, 'get_monthly_bulk_mail_limit'):
monthly_bulk_mail_limit = startup.get_monthly_bulk_mail_limit()
else:
monthly_bulk_mail_limit = conf.get('monthly_bulk_mail_limit') or 500
monthly_bulk_mail_limit = conf.get('monthly_bulk_mail_limit') or 500
if this_month + len(recipients) > monthly_bulk_mail_limit:
webnotes.msgprint("""Monthly Bulk Mail Limit (%s) Crossed""" % monthly_bulk_mail_limit,

View file

@ -101,12 +101,15 @@ class EMail:
self.msg_root.attach(part)
def get_footer(self, footer=None):
"""append a footer (signature)"""
import startup
"""append a footer (signature)"""
footer = footer or ""
footer += webnotes.conn.get_value('Control Panel',None,'mail_footer') or ''
footer += getattr(startup, 'mail_footer', '')
try:
import startup
footer += getattr(startup, 'mail_footer', '')
except ImportError, e:
pass
return footer

View file

@ -49,9 +49,6 @@ def render_page(page_name):
return html
def build_page(page_name):
from jinja2 import Environment, FileSystemLoader
from markdown2 import markdown
if not webnotes.conn:
webnotes.connect()
@ -101,9 +98,7 @@ def build_page(page_name):
context.update(get_website_settings())
jenv = Environment(loader = FileSystemLoader(basepath))
jenv.filters["markdown"] = markdown
jenv.filters["json"] = json.dumps
jenv = webnotes.get_jenv()
context["base_template"] = jenv.get_template(webnotes.get_config().get("base_template"))
template_name = page_options['template']

View file

@ -50,23 +50,11 @@ class DocType:
self.doc.categories = webnotes.conn.sql_list("select name from `tabBlog Category` order by name")
self.doc.texts = {
"comments": _("Comments"),
"first_comment": _("Be the first one to comment"),
"add_comment": _("Add Comment"),
"submit": _("Submit"),
"all_posts_by": _("All posts by"),
}
comment_list = webnotes.conn.sql("""\
self.doc.comment_list = webnotes.conn.sql("""\
select comment, comment_by_fullname, creation
from `tabComment` where comment_doctype="Blog Post"
and comment_docname=%s order by creation""", self.doc.name, as_dict=1)
self.doc.comment_list = comment_list or []
for comment in self.doc.comment_list:
comment['comment_date'] = webnotes.utils.global_date_format(comment['creation'])
comment['comment'] = markdown2.markdown(comment['comment'])
and comment_docname=%s order by creation""", self.doc.name, as_dict=1) or []
def clear_blog_cache():
for blog in webnotes.conn.sql_list("""select page_name from
@ -110,64 +98,3 @@ def get_blog_list(start=0, by=None, category=None):
res['content'] = res['content'][:140]
return result
@webnotes.whitelist(allow_guest=True)
def add_comment(args=None):
"""
args = {
'comment': '',
'comment_by': '',
'comment_by_fullname': '',
'comment_doctype': '',
'comment_docname': '',
'page_name': '',
}
"""
import webnotes
import webnotes.utils, markdown2
if not args: args = webnotes.form_dict
args['comment'] = unicode(markdown2.markdown(args.get('comment') or ''))
args['doctype'] = "Comment"
page_name = args.get("page_name")
if "page_name" in args:
del args["page_name"]
if "cmd" in args:
del args["cmd"]
comment = webnotes.bean(args)
comment.ignore_permissions = True
comment.insert()
# since comments are embedded in the page, clear the web cache
webnotes.webutils.clear_cache(page_name)
args['comment_date'] = webnotes.utils.global_date_format(comment.doc.creation)
template_args = { 'comment_list': [args]}
# get html of comment row
from jinja2 import Environment, FileSystemLoader
jenv = Environment(loader = FileSystemLoader(webnotes.utils.get_base_path()))
template = jenv.get_template("lib/website/doctype/blog_post/templates/includes/comment.html")
comment_html = template.render(template_args)
# notify commentors
commentors = [d[0] for d in webnotes.conn.sql("""select comment_by from tabComment where
comment_doctype='Blog Post' and comment_docname=%s and
ifnull(unsubscribed, 0)=0""", args.get('comment_docname'))]
blog = webnotes.doc("Blog Post", args.get("comment_docname"))
blogger_profile = webnotes.conn.get_value("Blogger", blog.blogger, "profile")
blogger_email = webnotes.conn.get_value("Profile", blogger_profile, "email")
from webnotes.utils.email_lib.bulk import send
send(recipients=list(set(commentors + [blogger_email])),
doctype='Comment',
email_field='comment_by',
subject='New Comment on Blog: ' + blog.title,
message='%(comment)s<p>By %(comment_by_fullname)s</p>' % args,
ref_doctype='Blog Post', ref_docname=blog.name)
return comment_html.replace("\n", "")

View file

@ -1,17 +1,5 @@
{% extends base_template %}
{% block javascript %}
<script>
{% include "lib/website/doctype/blog_post/templates/includes/blog_post.js" %}
</script>
{% endblock %}
{% block css %}
<style>
{% include "lib/website/doctype/blog_post/templates/includes/blog_post.css" %}
</style>
{% endblock %}
{% block content %}
<div class="col-md-12" itemscope itemtype="http://schema.org/BlogPost">
<h2 itemprop="name headline">{{ title }}</h2>
@ -30,33 +18,8 @@
{% include "lib/website/doctype/blog_post/templates/includes/blogger.html" %}
{% endif %}
<hr>
<h3>{{ texts.comments }}</h3><br>
<div class="blog-comments">
{% if not comment_list %}
<div class="no-comment">
<p>{{ texts.first_comment }}</p>
</div>
{% endif %}
{% include 'lib/website/doctype/blog_post/templates/includes/comment.html' %}
</div>
<div><button class="btn btn-default add-comment">{{ texts.add_comment }}</button></div>
<div style="display: none; margin-top: 10px; max-width: 400px;"
id="comment-form">
<div class="alert" style="display:none;"></div>
<form>
<fieldset>
<input class="form-control" name="comment_by_fullname" placeholder="Your Name" type="text"/><br>
<input class="form-control" name="comment_by"
placeholder="Your Email Id" type="text"/><br>
<textarea class="form-control" name="comment" rows=10
placeholder="Comment"/>
</textarea><br>
<button class="btn btn-info" id="submit-comment">{{ texts.submit }}</button>
</fieldset>
</form>
</div>
<h3>Comments</h3>
{% include 'lib/website/templates/includes/comments.html' %}
</div>
{% include 'lib/website/doctype/blog_post/templates/includes/blog_footer.html' %}
{% endblock %}

View file

@ -1,13 +0,0 @@
<style>
.comment-title {
color:#777;
}
.comment-content {
margin-left: 20px;
}
input {
width: 240px;
}
</style>

View file

@ -1,65 +0,0 @@
// Copyright (c) 2013, Web Notes Technologies Pvt. Ltd.
// MIT License. See license.txt
// js inside blog page
$(document).ready(function() {
var n_comments = $(".comment-row").length;
if(n_comments) {
$(".no_comment").toggle(false);
}
if(n_comments > 50) {
$(".add-comment").toggle(false)
.parent().append("<div class='alert alert-warning'>Comments are closed.</div>")
}
$(".add-comment").click(function() {
$(this).toggle(false);
$("#comment-form").toggle();
$("#comment-form input, #comment-form, textarea").val("");
})
$("#submit-comment").click(function() {
var args = {
comment_by_fullname: $("[name='comment_by_fullname']").val(),
comment_by: $("[name='comment_by']").val(),
comment: $("[name='comment']").val(),
cmd: "website.doctype.blog_post.blog_post.add_comment",
comment_doctype: "Blog Post",
comment_docname: "{{ name }}",
page_name: "{{ page_name }}",
_type: "POST"
}
$("#comment-form .alert").toggle(false);
if(!args.comment_by_fullname || !args.comment_by || !args.comment) {
$("#comment-form .alert")
.html("All fields are necessary to submit the comment.")
.toggle(true);
return false;
}
$.ajax({
type: "POST",
url: "server.py",
data: args,
dataType: "json",
success: function(data) {
if(data.exc) {
$("#comment-form .alert")
.html(data.exc)
.toggle(true)
} else {
$(data.message).appendTo(".blog-comments");
$(".no_comment").toggle(false);
$(".add-comment").toggle(false);
$("#comment-form")
.replaceWith("<div class='alert alert-success'>Thank you for your comment!</div>")
}
}
})
return false;
})
})

View file

@ -8,6 +8,6 @@
<h4>{{ blogger_info.full_name }}</h4>
<p style="color: #999">{{ blogger_info.bio }}</p>
<p><a href="blog?by={{ blogger_info.name }}&by_name={{ blogger_info.full_name }}">
{{ texts.all_posts_by }} {{ blogger_info.full_name }}</a></p>
All Posts By {{ blogger_info.full_name }}</a></p>
</div>
</div>

View file

@ -1,17 +0,0 @@
{#
this template generates comment rows for a blog
it is to be included in the blog/blog.html template
#}
<div itemscope itemtype="http://schema.org/UserComments">
{% for comment in comment_list %}
<div class="comment-row">
<div class="comment-title">
<span itemprop="name" class="author">{{ comment.comment_by_fullname }}</span> /
<span itemprop="commentTime">{{ comment.comment_date }}</span>:
</div>
<p class="comment-content" itemprop="commentText">{{ comment.comment }}</p>
<hr>
</div>
{% endfor %}
</div>

View file

@ -124,6 +124,10 @@ $.extend(wn, {
return modal;
},
msgprint: function(html, title) {
if(html.substr(0,1)==="[") html = JSON.parse(html);
if($.isArray(html)) {
html = html.join("<hr>")
}
return wn.get_modal(title || "Message", html).modal("show");
},
send_message: function(opts, btn) {

View file

View file

@ -0,0 +1,9 @@
<div class="comment-row">
<div class="comment-title text-muted">
<span itemprop="name" class="author">{{ comment.comment_by_fullname }}</span> /
<span itemprop="commentTime">{{ comment.creation|global_date_format }}</span>:
</div>
<p class="comment-content" itemprop="commentText"
style="margin-left: 20px;">{{ comment.comment|markdown }}</p>
<hr>
</div>

View file

@ -0,0 +1,85 @@
{% if not comment_list %}
<div class="no-comment">
<div class="alert alert-info">Start a new discussion.</div>
</div>
{% endif %}
<div itemscope itemtype="http://schema.org/UserComments" id="comment-list">
{% for comment in comment_list %}
{% include "lib/website/templates/includes/comment.html" %}
{% endfor %}
</div>
<div><button class="btn btn-default add-comment">Add Comment</button></div>
<div style="display: none; margin-top: 10px; max-width: 400px;"
id="comment-form">
<div class="alert" style="display:none;"></div>
<form>
<fieldset>
<input class="form-control" name="comment_by_fullname" placeholder="Your Name" type="text"/><br>
<input class="form-control" name="comment_by"
placeholder="Your Email Id" type="text"/><br>
<textarea class="form-control" name="comment" rows=10
placeholder="Comment"/>
</textarea><br>
<button class="btn btn-info" id="submit-comment">Submit</button>
</fieldset>
</form>
</div>
<script>
$(document).ready(function() {
var n_comments = $(".comment-row").length;
if(n_comments) {
$(".no_comment").toggle(false);
}
if(n_comments > 50) {
$(".add-comment").toggle(false)
.parent().append("<div class='alert alert-warning'>Comments are closed.</div>")
}
$(".add-comment").click(function() {
$(this).toggle(false);
$("#comment-form").toggle();
$("[name='comment_by']").val(getCookie("user_id") || "");
$("[name='comment_by_fullname']").val(getCookie("full_name") || "");
$("#comment-form textarea").val("");
})
$("#submit-comment").click(function() {
var args = {
comment_by_fullname: $("[name='comment_by_fullname']").val(),
comment_by: $("[name='comment_by']").val(),
comment: $("[name='comment']").val(),
comment_doctype: "{{ doctype }}",
comment_docname: "{{ name }}",
page_name: "{{ page_name }}",
}
if(!args.comment_by_fullname || !args.comment_by || !args.comment) {
wn.msgprint("All fields are necessary to submit the comment.")
return false;
}
wn.call({
type: "POST",
method: "website.templates.includes.comments.add_comment",
args: args,
callback: function(r) {
if(r.exc) {
if(r._server_messages)
wn.msgprint(r._server_messages);
} else {
$(r.message).appendTo("#comment-list");
$(".no-comment, .add-comment").toggle(false);
$("#comment-form")
.replaceWith("<div class='alert alert-success'>Thank you for your comment!</div>")
}
}
})
return false;
})
})
</script>

View file

@ -0,0 +1,58 @@
# Copyright (c) 2013, Web Notes Technologies Pvt. Ltd.
# MIT License. See license.txt
import webnotes
import webnotes.utils, markdown2
from webnotes import _
@webnotes.whitelist(allow_guest=True)
def add_comment(args=None):
"""
args = {
'comment': '',
'comment_by': '',
'comment_by_fullname': '',
'comment_doctype': '',
'comment_docname': '',
'page_name': '',
}
"""
if not args:
args = webnotes.local.form_dict
args['doctype'] = "Comment"
page_name = args.get("page_name")
if "page_name" in args:
del args["page_name"]
if "cmd" in args:
del args["cmd"]
comment = webnotes.bean(args)
comment.ignore_permissions = True
comment.insert()
# since comments are embedded in the page, clear the web cache
webnotes.webutils.clear_cache(page_name)
# notify commentors
commentors = [d[0] for d in webnotes.conn.sql("""select comment_by from tabComment where
comment_doctype=%s and comment_docname=%s and
ifnull(unsubscribed, 0)=0""", (comment.doc.comment_doctype, comment.doc.comment_docname))]
owner = webnotes.conn.get_value(comment.doc.comment_doctype, comment.doc.comment_docname, "owner")
from webnotes.utils.email_lib.bulk import send
send(recipients=list(set(commentors + [owner])),
doctype='Comment',
email_field='comment_by',
subject='New Comment on %s: %s' % (comment.doc.comment_doctype,
comment.doc.title or comment.doc.comment_docname),
message='%(comment)s<p>By %(comment_by_fullname)s</p>' % args,
ref_doctype=comment.doc.comment_doctype, ref_docname=comment.doc.comment_docname)
template = webnotes.get_template("lib/website/templates/includes/comment.html")
return template.render({"comment": comment.doc.fields})