From 491af45225d12e44bbf8020fc91f3db8b4689d0f Mon Sep 17 00:00:00 2001
From: Rushabh Mehta
Date: Wed, 25 Sep 2013 16:07:18 +0530
Subject: [PATCH] commonified comments, now can be added on any generator
---
core/doctype/comment/comment.py | 9 +-
.../documentation_tool/documentation_tool.py | 5 +-
webnotes/__init__.py | 16 ++++
webnotes/auth.py | 3 +
webnotes/utils/email_lib/bulk.py | 7 +-
webnotes/utils/email_lib/smtp.py | 11 ++-
webnotes/webutils.py | 7 +-
website/doctype/blog_post/blog_post.py | 79 +----------------
.../templates/generators/blog_post.html | 41 +--------
.../blog_post/templates/includes/__init__.py | 0
.../templates/includes/blog_post.css | 13 ---
.../blog_post/templates/includes/blog_post.js | 65 --------------
.../blog_post/templates/includes/blogger.html | 2 +-
.../blog_post/templates/includes/comment.html | 17 ----
website/js/website.js | 4 +
website/templates/includes/__init__.py | 0
website/templates/includes/comment.html | 9 ++
website/templates/includes/comments.html | 85 +++++++++++++++++++
website/templates/includes/comments.py | 58 +++++++++++++
19 files changed, 198 insertions(+), 233 deletions(-)
create mode 100644 website/doctype/blog_post/templates/includes/__init__.py
delete mode 100644 website/doctype/blog_post/templates/includes/blog_post.css
delete mode 100644 website/doctype/blog_post/templates/includes/blog_post.js
delete mode 100644 website/doctype/blog_post/templates/includes/comment.html
create mode 100644 website/templates/includes/__init__.py
create mode 100644 website/templates/includes/comment.html
create mode 100644 website/templates/includes/comments.html
create mode 100644 website/templates/includes/comments.py
diff --git a/core/doctype/comment/comment.py b/core/doctype/comment/comment.py
index 3b9509e459..3aaea2e831 100644
--- a/core/doctype/comment/comment.py
+++ b/core/doctype/comment/comment.py
@@ -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
diff --git a/core/doctype/documentation_tool/documentation_tool.py b/core/doctype/documentation_tool/documentation_tool.py
index 5c6525a790..02e4b639a9 100644
--- a/core/doctype/documentation_tool/documentation_tool.py
+++ b/core/doctype/documentation_tool/documentation_tool.py
@@ -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
diff --git a/webnotes/__init__.py b/webnotes/__init__.py
index cdca5067b1..b8bfb0adb9 100644
--- a/webnotes/__init__.py
+++ b/webnotes/__init__.py
@@ -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
diff --git a/webnotes/auth.py b/webnotes/auth.py
index 46b8fd9a6d..4af30850af 100644
--- a/webnotes/auth.py
+++ b/webnotes/auth.py
@@ -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:
diff --git a/webnotes/utils/email_lib/bulk.py b/webnotes/utils/email_lib/bulk.py
index e11caeecde..f4e2e9ca2a 100644
--- a/webnotes/utils/email_lib/bulk.py
+++ b/webnotes/utils/email_lib/bulk.py
@@ -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,
diff --git a/webnotes/utils/email_lib/smtp.py b/webnotes/utils/email_lib/smtp.py
index bb316495f4..707d9a0603 100644
--- a/webnotes/utils/email_lib/smtp.py
+++ b/webnotes/utils/email_lib/smtp.py
@@ -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
diff --git a/webnotes/webutils.py b/webnotes/webutils.py
index 3ae7c93996..88f4cd1ff5 100644
--- a/webnotes/webutils.py
+++ b/webnotes/webutils.py
@@ -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']
diff --git a/website/doctype/blog_post/blog_post.py b/website/doctype/blog_post/blog_post.py
index dca36b7aa0..fa9bb14f72 100644
--- a/website/doctype/blog_post/blog_post.py
+++ b/website/doctype/blog_post/blog_post.py
@@ -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)sBy %(comment_by_fullname)s
' % args,
- ref_doctype='Blog Post', ref_docname=blog.name)
-
- return comment_html.replace("\n", "")
\ No newline at end of file
diff --git a/website/doctype/blog_post/templates/generators/blog_post.html b/website/doctype/blog_post/templates/generators/blog_post.html
index 0337afaf7d..28df98759c 100644
--- a/website/doctype/blog_post/templates/generators/blog_post.html
+++ b/website/doctype/blog_post/templates/generators/blog_post.html
@@ -1,17 +1,5 @@
{% extends base_template %}
-{% block javascript %}
-
-{% endblock %}
-
-{% block css %}
-
-{% endblock %}
-
{% block content %}
{{ title }}
@@ -30,33 +18,8 @@
{% include "lib/website/doctype/blog_post/templates/includes/blogger.html" %}
{% endif %}
-
{{ texts.comments }}
-
-
-
+
Comments
+ {% include 'lib/website/templates/includes/comments.html' %}
{% include 'lib/website/doctype/blog_post/templates/includes/blog_footer.html' %}
{% endblock %}
\ No newline at end of file
diff --git a/website/doctype/blog_post/templates/includes/__init__.py b/website/doctype/blog_post/templates/includes/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/website/doctype/blog_post/templates/includes/blog_post.css b/website/doctype/blog_post/templates/includes/blog_post.css
deleted file mode 100644
index 8f56cd2fec..0000000000
--- a/website/doctype/blog_post/templates/includes/blog_post.css
+++ /dev/null
@@ -1,13 +0,0 @@
-
\ No newline at end of file
diff --git a/website/doctype/blog_post/templates/includes/blog_post.js b/website/doctype/blog_post/templates/includes/blog_post.js
deleted file mode 100644
index 572216af65..0000000000
--- a/website/doctype/blog_post/templates/includes/blog_post.js
+++ /dev/null
@@ -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("Comments are closed.
")
- }
- $(".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("Thank you for your comment!
")
- }
- }
- })
-
- return false;
- })
-})
\ No newline at end of file
diff --git a/website/doctype/blog_post/templates/includes/blogger.html b/website/doctype/blog_post/templates/includes/blogger.html
index 90c3571e7b..ec35c42e95 100644
--- a/website/doctype/blog_post/templates/includes/blogger.html
+++ b/website/doctype/blog_post/templates/includes/blogger.html
@@ -8,6 +8,6 @@
{{ blogger_info.full_name }}
{{ blogger_info.bio }}
- {{ texts.all_posts_by }} {{ blogger_info.full_name }}
+ All Posts By {{ blogger_info.full_name }}
\ No newline at end of file
diff --git a/website/doctype/blog_post/templates/includes/comment.html b/website/doctype/blog_post/templates/includes/comment.html
deleted file mode 100644
index 27baaad54d..0000000000
--- a/website/doctype/blog_post/templates/includes/comment.html
+++ /dev/null
@@ -1,17 +0,0 @@
-{#
- this template generates comment rows for a blog
- it is to be included in the blog/blog.html template
-#}
-
-
- {% for comment in comment_list %}
-
- {% endfor %}
-
\ No newline at end of file
diff --git a/website/js/website.js b/website/js/website.js
index b7f708440d..160e4e7cb7 100644
--- a/website/js/website.js
+++ b/website/js/website.js
@@ -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("
")
+ }
return wn.get_modal(title || "Message", html).modal("show");
},
send_message: function(opts, btn) {
diff --git a/website/templates/includes/__init__.py b/website/templates/includes/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/website/templates/includes/comment.html b/website/templates/includes/comment.html
new file mode 100644
index 0000000000..04773ab551
--- /dev/null
+++ b/website/templates/includes/comment.html
@@ -0,0 +1,9 @@
+
\ No newline at end of file
diff --git a/website/templates/includes/comments.html b/website/templates/includes/comments.html
new file mode 100644
index 0000000000..4535880132
--- /dev/null
+++ b/website/templates/includes/comments.html
@@ -0,0 +1,85 @@
+{% if not comment_list %}
+
+{% endif %}
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/website/templates/includes/comments.py b/website/templates/includes/comments.py
new file mode 100644
index 0000000000..513522508f
--- /dev/null
+++ b/website/templates/includes/comments.py
@@ -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)sBy %(comment_by_fullname)s
' % 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})
+
\ No newline at end of file
{{ texts.first_comment }}
-