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.
 
 
 
 
 

251 lines
6.7 KiB

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