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.

526 lines
16KB

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