A Python content management system designed for kirsle.net featuring a blog, comments and photo albums. https://rophako.kirsle.net/
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

comment.py 6.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232
  1. # -*- coding: utf-8 -*-
  2. """Commenting models."""
  3. from flask import g, url_for
  4. import time
  5. import hashlib
  6. import urllib
  7. import random
  8. import re
  9. import config
  10. import rophako.jsondb as JsonDB
  11. import rophako.model.user as User
  12. import rophako.model.emoticons as Emoticons
  13. from rophako.utils import send_email
  14. from rophako.log import logger
  15. def add_comment(thread, uid, name, subject, message, url, time, ip, image=None):
  16. """Add a comment to a comment thread.
  17. * uid is 0 if it's a guest post, otherwise the UID of the user.
  18. * name is the commenter's name (if a guest)
  19. * subject is for the e-mails that are sent out
  20. * message is self explanatory.
  21. * url is the URL where the comment can be read.
  22. * time, epoch time of comment.
  23. * ip is the IP address of the commenter.
  24. * image is a Gravatar image URL etc.
  25. """
  26. # Get the comments for this thread.
  27. comments = get_comments(thread)
  28. # Make up a unique ID for the comment.
  29. cid = random_hash()
  30. while cid in comments:
  31. cid = random_hash()
  32. # Add the comment.
  33. comments[cid] = dict(
  34. uid=uid,
  35. name=name or "Anonymous",
  36. image=image or "",
  37. message=message,
  38. time=time or int(time.time()),
  39. ip=ip,
  40. )
  41. write_comments(thread, comments)
  42. # Get info about the commenter.
  43. if uid > 0:
  44. user = User.get_user(uid=uid)
  45. if user:
  46. name = user["name"]
  47. # Send the e-mail to the site admins.
  48. send_email(
  49. to=config.NOTIFY_ADDRESS,
  50. subject="New comment: {}".format(subject),
  51. message="""{name} has left a comment on: {subject}
  52. {message}
  53. To view this comment, please go to {url}
  54. =====================
  55. This e-mail was automatically generated. Do not reply to it.""".format(
  56. name=name,
  57. subject=subject,
  58. message=message,
  59. url=url,
  60. ),
  61. )
  62. # Notify any subscribers.
  63. subs = get_subscribers(thread)
  64. for sub in subs.keys():
  65. # Make the unsubscribe link.
  66. unsub = url_for("comment.unsubscribe", thread=thread, who=sub, _external=True)
  67. send_email(
  68. to=sub,
  69. subject="New Comment: {}".format(subject),
  70. message="""Hello,
  71. You are currently subscribed to the comment thread '{thread}', and somebody has
  72. just added a new comment!
  73. {name} has left a comment on: {subject}
  74. {message}
  75. To view this comment, please go to {url}
  76. =====================
  77. This e-mail was automatically generated. Do not reply to it.
  78. If you wish to unsubscribe from this comment thread, please visit the following
  79. URL: {unsub}""".format(
  80. thread=thread,
  81. name=name,
  82. subject=subject,
  83. message=message,
  84. url=url,
  85. unsub=unsub,
  86. )
  87. )
  88. def delete_comment(thread, cid):
  89. """Delete a comment from a thread."""
  90. comments = get_comments(thread)
  91. del comments[cid]
  92. write_comments(thread, comments)
  93. def count_comments(thread):
  94. """Count the comments on a thread."""
  95. comments = get_comments(thread)
  96. return len(comments.keys())
  97. def add_subscriber(thread, email):
  98. """Add a subscriber to a thread."""
  99. if not "@" in email:
  100. return
  101. # Sanity check: only subscribe to threads that exist.
  102. if not JsonDB.exists("comments/threads/{}".format(thread)):
  103. return
  104. logger.info("Subscribe e-mail {} to thread {}".format(email, thread))
  105. subs = get_subscribers(thread)
  106. subs[email] = int(time.time())
  107. write_subscribers(thread, subs)
  108. def unsubscribe(thread, email):
  109. """Unsubscribe an e-mail address from a thread.
  110. If `thread` is `*`, the e-mail is unsubscribed from all threads."""
  111. # Which threads to unsubscribe from?
  112. threads = []
  113. if thread == "*":
  114. threads = JsonDB.list_docs("comments/subscribers")
  115. else:
  116. threads = [thread]
  117. # Remove them as a subscriber.
  118. for thread in threads:
  119. if JsonDB.exists("comments/subscribers/{}".format(thread)):
  120. logger.info("Unsubscribe e-mail address {} from comment thread {}".format(email, thread))
  121. db = get_subscribers(thread)
  122. del db[email]
  123. write_subscribers(thread, db)
  124. def format_message(message):
  125. """HTML sanitize the message and format it for display."""
  126. # We basically want to escape HTML symbols (like what Flask does for us
  127. # automatically), but we want line breaks to translate to literal <br> tags.
  128. message = re.sub(r'&', '&amp;', message)
  129. message = re.sub(r'<', '&lt;', message)
  130. message = re.sub(r'>', '&gt;', message)
  131. message = re.sub(r'"', '&quot;', message)
  132. message = re.sub(r"'", '&apos;', message)
  133. message = re.sub(r'\n', '<br>', message)
  134. message = re.sub(r'\r', '', message)
  135. # Process emoticons.
  136. message = Emoticons.render(message)
  137. return message
  138. def get_comments(thread):
  139. """Get the comment thread."""
  140. doc = "comments/threads/{}".format(thread)
  141. if JsonDB.exists(doc):
  142. return JsonDB.get(doc)
  143. return {}
  144. def write_comments(thread, comments):
  145. """Save the comments DB."""
  146. if len(comments.keys()) == 0:
  147. return JsonDB.delete("comments/threads/{}".format(thread))
  148. return JsonDB.commit("comments/threads/{}".format(thread), comments)
  149. def get_subscribers(thread):
  150. """Get the subscribers to a comment thread."""
  151. doc = "comments/subscribers/{}".format(thread)
  152. if JsonDB.exists(doc):
  153. return JsonDB.get(doc)
  154. return {}
  155. def write_subscribers(thread, subs):
  156. """Save the subscribers to the DB."""
  157. if len(subs.keys()) == 0:
  158. return JsonDB.delete("comments/subscribers/{}".format(thread))
  159. return JsonDB.commit("comments/subscribers/{}".format(thread), subs)
  160. def random_hash():
  161. """Get a short random hash to use as the ID for a comment."""
  162. md5 = hashlib.md5()
  163. md5.update(str(random.randint(0, 1000000)))
  164. return md5.hexdigest()
  165. def gravatar(email):
  166. """Generate a Gravatar link for an email address."""
  167. if "@" in email:
  168. # Default avatar?
  169. default = config.COMMENT_DEFAULT_AVATAR
  170. # Construct the URL.
  171. params = {
  172. "s": "96", # size
  173. }
  174. if default:
  175. params["d"] = default
  176. url = "http://www.gravatar.com/avatar/" + hashlib.md5(email.lower()).hexdigest() + "?"
  177. url += urllib.urlencode(params)
  178. return url
  179. return ""