93 lines
2.0 KiB
Go
93 lines
2.0 KiB
Go
package routes
|
|
|
|
import (
|
|
"dk/internal/components"
|
|
"dk/internal/database"
|
|
"dk/internal/models/forum"
|
|
"dk/internal/models/users"
|
|
"fmt"
|
|
"strings"
|
|
|
|
sushi "git.sharkk.net/Sharkk/Sushi"
|
|
"git.sharkk.net/Sharkk/Sushi/auth"
|
|
)
|
|
|
|
func RegisterForumRoutes(app *sushi.App) {
|
|
authed := app.Group("/forum")
|
|
authed.Use(auth.RequireAuth())
|
|
authed.Get("/", index)
|
|
authed.Get("/new", showNew)
|
|
authed.Post("/new", new)
|
|
authed.Get("/:id", showThread)
|
|
}
|
|
|
|
func index(ctx sushi.Ctx) {
|
|
threads, err := forum.Threads()
|
|
if err != nil {
|
|
threads = make([]*forum.Forum, 0)
|
|
}
|
|
fmt.Printf("\nFound %d threads\n", len(threads))
|
|
|
|
components.RenderPage(ctx, "Forum", "forum/index.html", map[string]any{
|
|
"threads": threads,
|
|
})
|
|
}
|
|
|
|
func showNew(ctx sushi.Ctx) {
|
|
components.RenderPage(ctx, "New Forum Thread", "forum/new.html", map[string]any{})
|
|
}
|
|
|
|
func new(ctx sushi.Ctx) {
|
|
sess := ctx.GetCurrentSession()
|
|
|
|
title := strings.TrimSpace(ctx.Form("title").String())
|
|
content := strings.TrimSpace(ctx.Form("content").String())
|
|
|
|
if title == "" {
|
|
sess.SetFlash("error", "Thread title cannot be empty")
|
|
ctx.Redirect("/forum/new")
|
|
return
|
|
}
|
|
|
|
if content == "" {
|
|
sess.SetFlash("error", "Thread content cannot be empty")
|
|
ctx.Redirect("/forum/new")
|
|
return
|
|
}
|
|
|
|
user := ctx.GetCurrentUser().(*users.User)
|
|
|
|
thread := forum.New()
|
|
thread.Author = user.ID
|
|
thread.Title = title
|
|
thread.Content = content
|
|
|
|
database.Transaction(func() error {
|
|
return thread.Insert()
|
|
})
|
|
|
|
ctx.Redirect(fmt.Sprintf("/forum/%d", thread.ID))
|
|
}
|
|
|
|
func showThread(ctx sushi.Ctx) {
|
|
sess := ctx.GetCurrentSession()
|
|
id := ctx.Param("id").Int()
|
|
|
|
thread, err := forum.Find(id)
|
|
if err != nil {
|
|
sess.SetFlash("error", fmt.Sprintf("Forum thread %d not found", id))
|
|
ctx.Redirect("/forum")
|
|
return
|
|
}
|
|
|
|
if thread.Parent != 0 {
|
|
sess.SetFlash("error", fmt.Sprintf("Forum post %d is not a thread", id))
|
|
ctx.Redirect("/forum")
|
|
return
|
|
}
|
|
|
|
components.RenderPage(ctx, thread.Title, "forum/thread.html", map[string]any{
|
|
"thread": thread,
|
|
})
|
|
}
|