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.

536 lines
17KB

  1. # -*- coding: utf-8 -*-
  2. from __future__ import unicode_literals, absolute_import
  3. """Endpoints for the web blog."""
  4. from flask import Blueprint, g, request, redirect, url_for, flash, make_response
  5. import datetime
  6. import time
  7. import re
  8. from xml.dom.minidom import Document
  9. import rophako.model.user as User
  10. import rophako.model.blog as Blog
  11. import rophako.model.comment as Comment
  12. import rophako.model.emoticons as Emoticons
  13. from rophako.utils import (template, render_markdown, pretty_time,
  14. login_required, remote_addr)
  15. from rophako.plugin import load_plugin
  16. from rophako.settings import Config
  17. from rophako.log import logger
  18. mod = Blueprint("blog", __name__, url_prefix="/blog")
  19. load_plugin("rophako.modules.comment")
  20. @mod.route("/")
  21. def index():
  22. return template("blog/index.html")
  23. @mod.route("/archive")
  24. def archive():
  25. """List all blog posts over time on one page."""
  26. index = Blog.get_index()
  27. # Group by calendar month, and keep track of friendly versions of months.
  28. groups = dict()
  29. friendly_months = dict()
  30. for post_id, data in index.items():
  31. ts = datetime.datetime.fromtimestamp(data["time"])
  32. date = ts.strftime("%Y-%m")
  33. if not date in groups:
  34. groups[date] = dict()
  35. friendly = ts.strftime("%B %Y")
  36. friendly_months[date] = friendly
  37. # Get author's profile && Pretty-print the time.
  38. data["profile"] = User.get_user(uid=data["author"])
  39. data["pretty_time"] = pretty_time(Config.blog.time_format, data["time"])
  40. groups[date][post_id] = data
  41. # Sort by calendar month.
  42. sort_months = sorted(groups.keys(), reverse=True)
  43. # Prepare the results.
  44. result = list()
  45. for month in sort_months:
  46. data = dict(
  47. month=month,
  48. month_friendly=friendly_months[month],
  49. posts=list()
  50. )
  51. # Sort the posts by time created, descending.
  52. for post_id in sorted(groups[month].keys(), key=lambda x: groups[month][x]["time"], reverse=True):
  53. data["posts"].append(groups[month][post_id])
  54. result.append(data)
  55. g.info["archive"] = result
  56. return template("blog/archive.html")
  57. @mod.route("/category/<category>")
  58. def category(category):
  59. g.info["url_category"] = category
  60. return template("blog/index.html")
  61. @mod.route("/entry/<fid>")
  62. def entry(fid):
  63. """Endpoint to view a specific blog entry."""
  64. # Resolve the friendly ID to a real ID.
  65. post_id = Blog.resolve_id(fid)
  66. if not post_id:
  67. flash("That blog post wasn't found.")
  68. return redirect(url_for(".index"))
  69. # Look up the post.
  70. post = Blog.get_entry(post_id)
  71. post["post_id"] = post_id
  72. # Body has a snipped section?
  73. if "<snip>" in post["body"]:
  74. post["body"] = re.sub(r'\s*<snip>\s*', '\n\n', post["body"])
  75. # Render the body.
  76. if post["format"] == "markdown":
  77. post["rendered_body"] = render_markdown(post["body"])
  78. else:
  79. post["rendered_body"] = post["body"]
  80. # Render emoticons.
  81. if post["emoticons"]:
  82. post["rendered_body"] = Emoticons.render(post["rendered_body"])
  83. # Get the author's information.
  84. post["profile"] = User.get_user(uid=post["author"])
  85. post["photo"] = User.get_picture(uid=post["author"])
  86. post["photo_url"] = Config.photo.root_public
  87. # Pretty-print the time.
  88. post["pretty_time"] = pretty_time(Config.blog.time_format, post["time"])
  89. # Count the comments for this post
  90. post["comment_count"] = Comment.count_comments("blog-{}".format(post_id))
  91. # Inject information about this post's siblings.
  92. index = Blog.get_index()
  93. siblings = [None, None] # previous, next
  94. sorted_ids = list(map(lambda y: int(y), sorted(index.keys(), key=lambda x: index[x]["time"], reverse=True)))
  95. for i in range(0, len(sorted_ids)):
  96. if sorted_ids[i] == post_id:
  97. # Found us!
  98. if i > 0:
  99. # We have an older post.
  100. siblings[0] = index[ str(sorted_ids[i-1]) ]
  101. if i < len(sorted_ids) - 1:
  102. # We have a newer post.
  103. siblings[1] = index[ str(sorted_ids[i+1]) ]
  104. post["siblings"] = siblings
  105. g.info["post"] = post
  106. return template("blog/entry.html")
  107. @mod.route("/entry")
  108. @mod.route("/index")
  109. def dummy():
  110. return redirect(url_for(".index"))
  111. @mod.route("/update", methods=["GET", "POST"])
  112. @login_required
  113. def update():
  114. """Post/edit a blog entry."""
  115. # Get our available avatars.
  116. g.info["avatars"] = Blog.list_avatars()
  117. g.info["userpic"] = User.get_picture(uid=g.info["session"]["uid"])
  118. # Default vars.
  119. g.info.update(dict(
  120. post_id="",
  121. fid="",
  122. author=g.info["session"]["uid"],
  123. subject="",
  124. body="",
  125. format="markdown",
  126. avatar="",
  127. categories="",
  128. privacy=Config.blog.default_privacy,
  129. emoticons=True,
  130. comments=Config.blog.allow_comments,
  131. month="",
  132. day="",
  133. year="",
  134. hour="",
  135. min="",
  136. sec="",
  137. preview=False,
  138. ))
  139. # Editing an existing post?
  140. post_id = request.args.get("id", None)
  141. if post_id:
  142. post_id = Blog.resolve_id(post_id)
  143. if post_id:
  144. logger.info("Editing existing blog post {}".format(post_id))
  145. post = Blog.get_entry(post_id)
  146. g.info["post_id"] = post_id
  147. g.info["post"] = post
  148. # Copy fields.
  149. for field in ["author", "fid", "subject", "format", "format",
  150. "body", "avatar", "categories", "privacy",
  151. "emoticons", "comments"]:
  152. g.info[field] = post[field]
  153. # Dissect the time.
  154. date = datetime.datetime.fromtimestamp(post["time"])
  155. g.info.update(dict(
  156. month="{:02d}".format(date.month),
  157. day="{:02d}".format(date.day),
  158. year=date.year,
  159. hour="{:02d}".format(date.hour),
  160. min="{:02d}".format(date.minute),
  161. sec="{:02d}".format(date.second),
  162. ))
  163. # Are we SUBMITTING the form?
  164. if request.method == "POST":
  165. action = request.form.get("action")
  166. # Get all the fields from the posted params.
  167. g.info["post_id"] = request.form.get("id")
  168. for field in ["fid", "subject", "format", "body", "avatar", "categories", "privacy"]:
  169. g.info[field] = request.form.get(field)
  170. for boolean in ["emoticons", "comments"]:
  171. g.info[boolean] = True if request.form.get(boolean, None) == "true" else False
  172. for number in ["author", "month", "day", "year", "hour", "min", "sec"]:
  173. g.info[number] = int(request.form.get(number, 0))
  174. # What action are they doing?
  175. if action == "preview":
  176. g.info["preview"] = True
  177. # Render markdown?
  178. if g.info["format"] == "markdown":
  179. g.info["rendered_body"] = render_markdown(g.info["body"])
  180. else:
  181. g.info["rendered_body"] = g.info["body"]
  182. # Render emoticons.
  183. if g.info["emoticons"]:
  184. g.info["rendered_body"] = Emoticons.render(g.info["rendered_body"])
  185. elif action == "publish":
  186. # Publishing! Validate inputs first.
  187. invalid = False
  188. if len(g.info["body"]) == 0:
  189. invalid = True
  190. flash("You must enter a body for your blog post.")
  191. if len(g.info["subject"]) == 0:
  192. invalid = True
  193. flash("You must enter a subject for your blog post.")
  194. # Make sure the times are valid.
  195. date = None
  196. try:
  197. date = datetime.datetime(
  198. g.info["year"],
  199. g.info["month"],
  200. g.info["day"],
  201. g.info["hour"],
  202. g.info["min"],
  203. g.info["sec"],
  204. )
  205. except ValueError as e:
  206. invalid = True
  207. flash("Invalid date/time: " + str(e))
  208. # Format the categories.
  209. tags = []
  210. for tag in g.info["categories"].split(","):
  211. tags.append(tag.strip())
  212. # Okay to update?
  213. if invalid is False:
  214. # Convert the date into a Unix time stamp.
  215. epoch = float(date.strftime("%s"))
  216. new_id, new_fid = Blog.post_entry(
  217. post_id = g.info["post_id"],
  218. epoch = epoch,
  219. author = g.info["author"],
  220. subject = g.info["subject"],
  221. fid = g.info["fid"],
  222. avatar = g.info["avatar"],
  223. categories = tags,
  224. privacy = g.info["privacy"],
  225. ip = remote_addr(),
  226. emoticons = g.info["emoticons"],
  227. comments = g.info["comments"],
  228. format = g.info["format"],
  229. body = g.info["body"],
  230. )
  231. return redirect(url_for(".entry", fid=new_fid))
  232. if type(g.info["categories"]) is list:
  233. g.info["categories"] = ", ".join(g.info["categories"])
  234. return template("blog/update.html")
  235. @mod.route("/delete", methods=["GET", "POST"])
  236. @login_required
  237. def delete():
  238. """Delete a blog post."""
  239. post_id = request.args.get("id")
  240. # Resolve the post ID.
  241. post_id = Blog.resolve_id(post_id)
  242. if not post_id:
  243. flash("That blog post wasn't found.")
  244. return redirect(url_for(".index"))
  245. if request.method == "POST":
  246. confirm = request.form.get("confirm")
  247. if confirm == "true":
  248. Blog.delete_entry(post_id)
  249. flash("The blog entry has been deleted.")
  250. return redirect(url_for(".index"))
  251. # Get the entry's subject.
  252. post = Blog.get_entry(post_id)
  253. g.info["subject"] = post["subject"]
  254. g.info["post_id"] = post_id
  255. return template("blog/delete.html")
  256. @mod.route("/rss")
  257. def rss():
  258. """RSS feed for the blog."""
  259. doc = Document()
  260. rss = doc.createElement("rss")
  261. rss.setAttribute("version", "2.0")
  262. rss.setAttribute("xmlns:blogChannel", "http://backend.userland.com/blogChannelModule")
  263. doc.appendChild(rss)
  264. channel = doc.createElement("channel")
  265. rss.appendChild(channel)
  266. rss_time = "%a, %d %b %Y %H:%M:%S GMT"
  267. ######
  268. ## Channel Information
  269. ######
  270. today = time.strftime(rss_time, time.gmtime())
  271. xml_add_text_tags(doc, channel, [
  272. ["title", Config.blog.title],
  273. ["link", Config.blog.link],
  274. ["description", Config.blog.description],
  275. ["language", Config.blog.language],
  276. ["copyright", Config.blog.copyright],
  277. ["pubDate", today],
  278. ["lastBuildDate", today],
  279. ["webmaster", Config.blog.webmaster],
  280. ])
  281. ######
  282. ## Image Information
  283. ######
  284. image = doc.createElement("image")
  285. channel.appendChild(image)
  286. xml_add_text_tags(doc, image, [
  287. ["title", Config.blog.image_title],
  288. ["url", Config.blog.image_url],
  289. ["link", Config.blog.link],
  290. ["width", Config.blog.image_width],
  291. ["height", Config.blog.image_height],
  292. ["description", Config.blog.image_description],
  293. ])
  294. ######
  295. ## Add the blog posts
  296. ######
  297. index = Blog.get_index()
  298. posts = get_index_posts(index)
  299. for post_id in posts[:int(Config.blog.entries_per_feed)]:
  300. post = Blog.get_entry(post_id)
  301. item = doc.createElement("item")
  302. channel.appendChild(item)
  303. # Render the body.
  304. if post["format"] == "markdown":
  305. post["rendered_body"] = render_markdown(post["body"])
  306. else:
  307. post["rendered_body"] = post["body"]
  308. # Render emoticons.
  309. if post["emoticons"]:
  310. post["rendered_body"] = Emoticons.render(post["rendered_body"])
  311. xml_add_text_tags(doc, item, [
  312. ["title", post["subject"]],
  313. ["link", url_for("blog.entry", fid=post["fid"], _external=True)],
  314. ["description", post["rendered_body"]],
  315. ["pubDate", time.strftime(rss_time, time.gmtime(post["time"]))],
  316. ])
  317. resp = make_response(doc.toprettyxml(encoding="utf-8"))
  318. resp.headers["Content-Type"] = "application/rss+xml; charset=utf-8"
  319. return resp
  320. def xml_add_text_tags(doc, root_node, tags):
  321. """RSS feed helper function.
  322. Add a collection of simple tag/text pairs to a root XML element."""
  323. for pair in tags:
  324. name, value = pair
  325. channelTag = doc.createElement(name)
  326. channelTag.appendChild(doc.createTextNode(unicode(value)))
  327. root_node.appendChild(channelTag)
  328. def partial_index(template_name="blog/index.inc.html"):
  329. """Partial template for including the index view of the blog."""
  330. # Get the blog index.
  331. index = Blog.get_index()
  332. pool = {} # The set of blog posts to show.
  333. category = g.info.get("url_category", None)
  334. # Are we narrowing by category?
  335. if category:
  336. # Narrow down the index to just those that match the category.
  337. for post_id, data in index.items():
  338. if not category in data["categories"]:
  339. continue
  340. pool[post_id] = data
  341. # No such category?
  342. if len(pool) == 0:
  343. flash("There are no posts with that category.")
  344. return redirect(url_for(".index"))
  345. else:
  346. pool = index
  347. # Get the posts we want.
  348. posts = get_index_posts(pool)
  349. # Handle pagination.
  350. offset = request.args.get("skip", 0)
  351. try: offset = int(offset)
  352. except: offset = 0
  353. # Handle the offsets, and get those for the "older" and "earlier" posts.
  354. # "earlier" posts count down (towards index 0), "older" counts up.
  355. g.info["offset"] = offset
  356. g.info["earlier"] = offset - int(Config.blog.entries_per_page) if offset > 0 else 0
  357. g.info["older"] = offset + int(Config.blog.entries_per_page)
  358. if g.info["earlier"] < 0:
  359. g.info["earlier"] = 0
  360. if g.info["older"] < 0 or g.info["older"] > len(posts):
  361. g.info["older"] = 0
  362. g.info["count"] = 0
  363. # Can we go to other pages?
  364. g.info["can_earlier"] = True if offset > 0 else False
  365. g.info["can_older"] = False if g.info["older"] == 0 else True
  366. # Load the selected posts.
  367. selected = []
  368. stop = offset + int(Config.blog.entries_per_page)
  369. if stop > len(posts): stop = len(posts)
  370. index = 1 # Let each post know its position on-page.
  371. for i in range(offset, stop):
  372. post_id = posts[i]
  373. post = Blog.get_entry(post_id)
  374. post["post_id"] = post_id
  375. # Body has a snipped section?
  376. if "<snip>" in post["body"]:
  377. post["body"] = post["body"].split("<snip>")[0]
  378. post["snipped"] = True
  379. # Render the body.
  380. if post["format"] == "markdown":
  381. post["rendered_body"] = render_markdown(post["body"])
  382. else:
  383. post["rendered_body"] = post["body"]
  384. # Render emoticons.
  385. if post["emoticons"]:
  386. post["rendered_body"] = Emoticons.render(post["rendered_body"])
  387. # Get the author's information.
  388. post["profile"] = User.get_user(uid=post["author"])
  389. post["photo"] = User.get_picture(uid=post["author"])
  390. post["photo_url"] = Config.photo.root_public
  391. post["pretty_time"] = pretty_time(Config.blog.time_format, post["time"])
  392. # Count the comments for this post
  393. post["comment_count"] = Comment.count_comments("blog-{}".format(post_id))
  394. post["position_index"] = index
  395. index += 1
  396. selected.append(post)
  397. g.info["count"] += 1
  398. g.info["category"] = category
  399. g.info["posts"] = selected
  400. return template(template_name)
  401. def get_index_posts(index):
  402. """Helper function to get data for the blog index page."""
  403. # Separate the sticky posts from the normal ones.
  404. sticky, normal = set(), set()
  405. for post_id, data in index.items():
  406. if data["sticky"]:
  407. sticky.add(post_id)
  408. else:
  409. normal.add(post_id)
  410. # Sort the blog IDs by published time.
  411. posts = []
  412. posts.extend(sorted(sticky, key=lambda x: index[x]["time"], reverse=True))
  413. posts.extend(sorted(normal, key=lambda x: index[x]["time"], reverse=True))
  414. return posts
  415. def partial_tags():
  416. """Get a listing of tags and their quantities for the nav bar."""
  417. tags = Blog.get_categories()
  418. # Sort the tags by popularity.
  419. sort_tags = [ tag for tag in sorted(tags.keys(), key=lambda y: tags[y], reverse=True) ]
  420. result = []
  421. has_small = False
  422. for tag in sort_tags:
  423. result.append(dict(
  424. category=tag,
  425. count=tags[tag],
  426. small=tags[tag] < 3, # TODO: make this configurable
  427. ))
  428. if tags[tag] < 3:
  429. has_small = True
  430. g.info["tags"] = result
  431. g.info["has_small"] = has_small
  432. return template("blog/categories.inc.html")