add subscribing and unsubscribing to threads

This commit is contained in:
2025-06-02 20:54:36 +03:00
parent 1e23959e52
commit bd1ba6c087
6 changed files with 94 additions and 22 deletions

View File

@ -9,6 +9,7 @@ local models = require("models")
local Topics = models.Topics
local Threads = models.Threads
local Posts = models.Posts
local Subscriptions = models.Subscriptions
local POSTS_PER_PAGE = 10
@ -97,7 +98,18 @@ app:get("thread", "/:slug", function(self)
self.other_topics = db.query("SELECT topics.id, topics.name FROM topics")
self.me = util.get_logged_in_user_or_transient(self)
self.posts = posts
if self.me:is_logged_in() then
self.is_subscribed = false
local subscription = Subscriptions:find({user_id = self.me.id, thread_id = thread.id})
if subscription then
self.is_subscribed = true
if posts[#posts].created_at > subscription.last_seen then
subscription:update({last_seen = os.time()})
end
end
end
self.page_title = thread.title
return {render = "threads.thread"}
@ -133,6 +145,10 @@ app:post("thread", "/:slug", function(self)
return {redirect_to = self:url_for("thread", {slug = thread.slug}, {page = last_page}) .. "#latest-post"}
end
if self.params.subscribe == "on" then
Subscriptions:create({user_id = user.id, thread_id = thread.id, last_seen = os.time()})
end
return {redirect_to = self:url_for("thread", {slug = thread.slug}, {page = last_page}) .. "#latest-post"}
end)
@ -206,4 +222,32 @@ app:post("thread_move", "/:slug/move", function(self)
return {redirect_to = self:url_for("thread", {slug = self.params.slug})}
end)
app:post("thread_subscribe", "/:slug/subscribe", function(self)
local user = util.get_logged_in_user(self)
if not user then
return {status = 403}
end
local thread = Threads:find({slug = self.params.slug})
if not thread then
return {status = 404}
end
local subscription = Subscriptions:find({user_id = user.id, thread_id = thread.id})
if self.params.subscribe == "subscribe" then
local now = os.time()
if subscription then
subscription:delete()
end
Subscriptions:create({user_id = user.id, thread_id = thread.id, last_seen = now})
return {redirect_to = self:url_for("thread", {slug = thread.slug}, {after = self.params.first_visible_post})}
elseif self.params.subscribe == "unsubscribe" then
if not subscription then
return {status = 404}
end
subscription:delete()
return {redirect_to = self:url_for("thread", {slug = thread.slug}, {after = self.params.first_visible_post})}
end
return {status = 400}
end)
return app