local app = require("lapis").Application() local db = require("lapis.db") local constants = require("constants") local util = require("util") local models = require("models") local Posts = models.Posts local Threads = models.Threads app:get("single_post", "/:post_id", function(self) local query = constants.FULL_POSTS_QUERY .. "WHERE posts.id = ?" local p = db.query(query, self.params.post_id) if p then self.post = p[1] self.thread = Threads:find({id = self.post.thread_id}) self.page_title = self.post.username .. "'s post in " .. self.thread.title end return {render = "post.single-post"} end) app:get("edit_post", "/:post_id/edit", function(self) local user = util.get_logged_in_user(self) if not user then return {redirect_to = self:url_for"all_topics"} end local editing_query = constants.FULL_POSTS_QUERY .. "WHERE posts.id = ?" local p = db.query(editing_query, self.params.post_id) if not p then return {redirect_to = self:url_for"all_topics"} end if p[1].user_id ~= user.id then return {redirect_to = self:url_for"all_topics"} end self.me = user self.editing_post = p[1] self.thread = Threads:find({id = self.editing_post.thread_id}) local thread_predicate = constants.FULL_POSTS_QUERY .. "WHERE posts.thread_id = ?\n" local context_prev_query = thread_predicate .. "AND posts.created_at < ? ORDER BY posts.created_at DESC LIMIT 2" local context_next_query = thread_predicate .. "AND posts.created_at > ? ORDER BY posts.created_at ASC LIMIT 2" self.prev_context = db.query(context_prev_query, self.thread.id, self.editing_post.created_at) self.next_context = db.query(context_next_query, self.thread.id, self.editing_post.created_at) return {render = "post.edit-post"} end) app:post("edit_post", "/:post_id/edit", function(self) local user = util.get_logged_in_user(self) if not user then return {redirect_to = self:url_for("all_topics")} end local post = Posts:find({id = self.params.post_id}) if not post then return {redirect_to = self:url_for("all_topics")} end if post.user_id ~= user.id then return {redirect_to = self:url_for("all_topics")} end util.update_post(post, self.params.new_content) local thread = Threads:find({id = post.thread_id}) local link = self:url_for("thread", {slug = thread.slug}, {after = post.id}) .. "#post-" .. post.id return {redirect_to = link} end) return app