Implement cooldowns

This commit is contained in:
Dominic Ferrando
2025-04-19 21:50:19 -04:00
parent 10ab0edfc8
commit ae66403cea
7 changed files with 204 additions and 116 deletions
+45
View File
@@ -0,0 +1,45 @@
package util
import (
"net"
"net/http"
"strings"
"sync"
"time"
)
var (
PostCooldowns = make(map[string]time.Time)
ThreadCooldowns = make(map[string]time.Time)
)
var cooldownMutex sync.Mutex
const POST_COOLDOWN = 15 * time.Second
const THREAD_COOLDOWN = 2 * time.Minute
func IsOnCooldown(ip string, m map[string]time.Time, duration time.Duration) bool {
cooldownMutex.Lock()
defer cooldownMutex.Unlock()
last, exists := m[ip]
if !exists || time.Since(last) >= duration {
m[ip] = time.Now()
return false
}
return true
}
func GetIP(r *http.Request) string {
if xff := r.Header.Get("X-Forwarded-For"); xff != "" {
parts := strings.Split(xff, ",")
return strings.TrimSpace(parts[0])
}
// Fallback to RemoteAddr
ip, _, err := net.SplitHostPort(r.RemoteAddr)
if err != nil {
return r.RemoteAddr
}
return ip
}
+104
View File
@@ -0,0 +1,104 @@
package util
import (
"fmt"
"html/template"
"image"
"io"
"log"
"mime/multipart"
"os"
"path/filepath"
"strings"
"github.com/disintegration/imaging"
)
// 10 MB memory limit
const FILE_MEM_LIMIT int64 = 10 << 20
const POST_IMG_FULL_PATH = "web/static/img/posts/full"
const POST_IMG_THUMB_PATH = "web/static/img/posts/thumb"
func EnrichPost(body string) string {
var b strings.Builder
for _, rawLine := range strings.Split(body, "\n") {
var outLine string
for i, rawWord := range strings.Split(rawLine, " ") {
var outWord string
if strings.HasPrefix(rawWord, ">>") {
postId := strings.TrimPrefix(rawWord, ">>")
esc := template.HTMLEscapeString(rawWord)
outWord = fmt.Sprintf(
`<a onclick="onReplyLinkClick(event)"
onmouseover="highlightPost(%[1]s, event)" `+
`onmouseleave="highlightPost(%[1]s, event, false)" `+
`href="#post-%[1]s" class="reply-link">%s</a>`,
postId, esc,
)
} else {
outWord = template.HTMLEscapeString(rawWord)
}
if i != 0 {
outLine += " "
}
outLine += outWord
}
if strings.HasPrefix(rawLine, ">") && !strings.HasPrefix(rawLine, ">>") {
outLine = `<span class="greentext">` + outLine + `</span>`
}
b.WriteString(outLine)
b.WriteString("<br/>")
}
return b.String()
}
func SavePostFile(file *multipart.File, filename string) error {
dstPathFull := filepath.Join(POST_IMG_FULL_PATH, filename)
dstPathThumb := filepath.Join(POST_IMG_THUMB_PATH, filename)
// FULL
if err := os.MkdirAll(POST_IMG_FULL_PATH, 0755); err != nil {
log.Printf("MkdirAll (full): %v", err)
return err
}
dstFull, err := os.Create(dstPathFull)
if err != nil {
log.Printf("os.Create (full): %v", err)
return err
}
defer dstFull.Close()
if _, err := io.Copy(dstFull, *file); err != nil {
log.Printf("io.Copy (full): %v", err)
return err
}
if _, err := (*file).Seek(0, 0); err != nil { // rewind file
log.Printf("seek file (thumb): %v", err)
return err
}
// THUMBNAIL
if err := os.MkdirAll(POST_IMG_THUMB_PATH, 0755); err != nil {
log.Printf("MkdirAll (thumb): %v", err)
return err
}
img, _, err := image.Decode(*file)
if err != nil {
log.Printf("image.Decode: %v", err)
return err
}
thumb := imaging.Resize(img, 300, 0, imaging.Lanczos)
if err = imaging.Save(thumb, dstPathThumb); err != nil {
log.Printf("imaging.Save: %v", err)
return err
}
return nil
}
-44
View File
@@ -1,44 +0,0 @@
package util
import (
"fmt"
"html/template"
"strings"
)
func EnrichPost(body string) string {
var b strings.Builder
for _, rawLine := range strings.Split(body, "\n") {
var outLine string
for i, rawWord := range strings.Split(rawLine, " ") {
var outWord string
if strings.HasPrefix(rawWord, ">>") {
postId := strings.TrimPrefix(rawWord, ">>")
esc := template.HTMLEscapeString(rawWord)
outWord = fmt.Sprintf(
`<a onclick="onReplyLinkClick(event)"
onmouseover="highlightPost(%[1]s, event)" `+
`onmouseleave="highlightPost(%[1]s, event, false)" `+
`href="#post-%[1]s" class="reply-link">%s</a>`,
postId, esc,
)
} else {
outWord = template.HTMLEscapeString(rawWord)
}
if i != 0 {
outLine += " "
}
outLine += outWord
}
if strings.HasPrefix(rawLine, ">") && !strings.HasPrefix(rawLine, ">>") {
outLine = `<span class="greentext">` + outLine + `</span>`
}
b.WriteString(outLine)
b.WriteString("<br/>")
}
return b.String()
}
+17 -61
View File
@@ -4,78 +4,22 @@ import (
"database/sql" "database/sql"
"errors" "errors"
"fmt" "fmt"
"image"
"io"
"log" "log"
"mime/multipart"
"net/http" "net/http"
"os"
"path/filepath" "path/filepath"
"strconv" "strconv"
"time" "time"
"github.com/disintegration/imaging"
"github.com/dominicf2001/comfychan/internal/database" "github.com/dominicf2001/comfychan/internal/database"
"github.com/dominicf2001/comfychan/internal/util"
"github.com/dominicf2001/comfychan/web/views" "github.com/dominicf2001/comfychan/web/views"
"github.com/go-chi/chi/v5" "github.com/go-chi/chi/v5"
"github.com/go-chi/chi/v5/middleware" "github.com/go-chi/chi/v5/middleware"
_ "github.com/mattn/go-sqlite3" _ "github.com/mattn/go-sqlite3"
) )
// 10 MB memory limit
const FILE_MEM_LIMIT int64 = 10 << 20
const POST_IMG_FULL_PATH = "web/static/img/posts/full"
const POST_IMG_THUMB_PATH = "web/static/img/posts/thumb"
var dev = true var dev = true
func savePostFile(file *multipart.File, filename string) error {
dstPathFull := filepath.Join(POST_IMG_FULL_PATH, filename)
dstPathThumb := filepath.Join(POST_IMG_THUMB_PATH, filename)
// FULL
if err := os.MkdirAll(POST_IMG_FULL_PATH, 0755); err != nil {
log.Printf("MkdirAll (full): %v", err)
return err
}
dstFull, err := os.Create(dstPathFull)
if err != nil {
log.Printf("os.Create (full): %v", err)
return err
}
defer dstFull.Close()
if _, err := io.Copy(dstFull, *file); err != nil {
log.Printf("io.Copy (full): %v", err)
return err
}
if _, err := (*file).Seek(0, 0); err != nil { // rewind file
log.Printf("seek file (thumb): %v", err)
return err
}
// THUMBNAIL
if err := os.MkdirAll(POST_IMG_THUMB_PATH, 0755); err != nil {
log.Printf("MkdirAll (thumb): %v", err)
return err
}
img, _, err := image.Decode(*file)
if err != nil {
log.Printf("image.Decode: %v", err)
return err
}
thumb := imaging.Resize(img, 300, 0, imaging.Lanczos)
if err = imaging.Save(thumb, dstPathThumb); err != nil {
log.Printf("imaging.Save: %v", err)
return err
}
return nil
}
func disableCacheInDevMode(next http.Handler) http.Handler { func disableCacheInDevMode(next http.Handler) http.Handler {
if !dev { if !dev {
return next return next
@@ -174,12 +118,18 @@ func main() {
// CREATE THREAD // CREATE THREAD
r.Post("/{slug}/threads", func(w http.ResponseWriter, r *http.Request) { r.Post("/{slug}/threads", func(w http.ResponseWriter, r *http.Request) {
ip := util.GetIP(r)
if util.IsOnCooldown(ip, util.ThreadCooldowns, util.THREAD_COOLDOWN) {
http.Error(w, "Too many posts at once.", http.StatusTooManyRequests)
return
}
slug := chi.URLParam(r, "slug") slug := chi.URLParam(r, "slug")
subject := r.FormValue("subject") subject := r.FormValue("subject")
body := r.FormValue("body") body := r.FormValue("body")
if err := r.ParseMultipartForm(FILE_MEM_LIMIT); err != nil { if err := r.ParseMultipartForm(util.FILE_MEM_LIMIT); err != nil {
http.Error(w, "Failed to parse form", http.StatusBadRequest) http.Error(w, "Failed to parse form", http.StatusBadRequest)
log.Printf("ParseMultipartForm: %v", err) log.Printf("ParseMultipartForm: %v", err)
return return
@@ -194,7 +144,7 @@ func main() {
defer file.Close() defer file.Close()
filename := strconv.FormatInt(time.Now().UnixNano(), 10) + filepath.Ext(header.Filename) filename := strconv.FormatInt(time.Now().UnixNano(), 10) + filepath.Ext(header.Filename)
if err := savePostFile(&file, filename); err != nil { if err := util.SavePostFile(&file, filename); err != nil {
http.Error(w, "Failed to save file", http.StatusInternalServerError) http.Error(w, "Failed to save file", http.StatusInternalServerError)
log.Printf("savePostFile: %v", err) log.Printf("savePostFile: %v", err)
return return
@@ -209,6 +159,12 @@ func main() {
// CREATE POST // CREATE POST
r.Post("/{slug}/threads/{threadId}", func(w http.ResponseWriter, r *http.Request) { r.Post("/{slug}/threads/{threadId}", func(w http.ResponseWriter, r *http.Request) {
ip := util.GetIP(r)
if util.IsOnCooldown(ip, util.PostCooldowns, util.POST_COOLDOWN) {
http.Error(w, "Too many posts at once.", http.StatusTooManyRequests)
return
}
// slug := chi.URLParam(r, "slug") // slug := chi.URLParam(r, "slug")
// TODO: use relative thread_nums (see issue #1) // TODO: use relative thread_nums (see issue #1)
threadIdStr := chi.URLParam(r, "threadId") threadIdStr := chi.URLParam(r, "threadId")
@@ -221,7 +177,7 @@ func main() {
body := r.FormValue("body") body := r.FormValue("body")
mediaPath := "" mediaPath := ""
if err := r.ParseMultipartForm(FILE_MEM_LIMIT); err != nil { if err := r.ParseMultipartForm(util.FILE_MEM_LIMIT); err != nil {
http.Error(w, "Failed to parse form", http.StatusBadRequest) http.Error(w, "Failed to parse form", http.StatusBadRequest)
log.Printf("ParseMultipartForm: %v", err) log.Printf("ParseMultipartForm: %v", err)
return return
@@ -237,7 +193,7 @@ func main() {
} else { } else {
defer file.Close() defer file.Close()
filename := strconv.FormatInt(time.Now().UnixNano(), 10) + filepath.Ext(header.Filename) filename := strconv.FormatInt(time.Now().UnixNano(), 10) + filepath.Ext(header.Filename)
if err := savePostFile(&file, filename); err != nil { if err := util.SavePostFile(&file, filename); err != nil {
http.Error(w, "Failed to save file", http.StatusInternalServerError) http.Error(w, "Failed to save file", http.StatusInternalServerError)
log.Printf("savePostFile: %v", err) log.Printf("savePostFile: %v", err)
return return
+11 -1
View File
@@ -70,7 +70,6 @@ body {
.catalog-preview h1 { .catalog-preview h1 {
font-size: 14px; font-size: 14px;
color: #0F0C5D;
font-weight: bold; font-weight: bold;
} }
@@ -82,6 +81,7 @@ body {
.catalog-preview-link { .catalog-preview-link {
text-decoration: none; text-decoration: none;
cursor: pointer; cursor: pointer;
color: #0F0C5D;
} }
.catalog-preview-img { .catalog-preview-img {
@@ -251,3 +251,13 @@ body {
.box p { .box p {
padding: 10px; padding: 10px;
} }
.warning {
background: #FFAAAA;
color: #000;
border: 1px solid #000;
padding: 8px;
margin: 5px 0;
font-size: 12px;
}
+16 -7
View File
@@ -8,6 +8,9 @@ import (
) )
templ NewThreadForm(board database.Board) { templ NewThreadForm(board database.Board) {
<div style="display: none;" id="newPostWarning" class="warning">
<p>Please wait until the 2 minute cooldown is finished.</p>
</div>
<form <form
hx-encoding="multipart/form-data" hx-encoding="multipart/form-data"
style="display: none;" style="display: none;"
@@ -15,17 +18,23 @@ templ NewThreadForm(board database.Board) {
hx-swap="none" hx-swap="none"
hx-post={ fmt.Sprintf("/%s/threads", board.Slug) } hx-post={ fmt.Sprintf("/%s/threads", board.Slug) }
_="on htmx:afterRequest _="on htmx:afterRequest
hide me if event.detail.xhr.status is not 429
then show #newThreadBtn hide me
then set #newPostBody.value to '' then show #newThreadBtn
then set #newPostFile.value to '' then set #newPostBody.value to ''
then trigger refreshThreads on body" then set #newPostFile.value to ''
then set #newPostSubject.value to ''
then hide #newPostWarning
then trigger refreshThreads on body
else
show #newPostWarning
end"
> >
<table> <table>
<tbody> <tbody>
<tr class="new-post-form-field"> <tr class="new-post-form-field">
<th>Subject</th> <th>Subject</th>
<td><input name="subject"/></td> <td><input id="newPostSubject" name="subject"/></td>
</tr> </tr>
<tr class="new-post-form-field"> <tr class="new-post-form-field">
<th>Comment</th> <th>Comment</th>
@@ -82,7 +91,7 @@ templ ThreadsCatalog(previews []CatalogThreadPreview) {
/> />
</a> </a>
<h1> <h1>
<a href={ templ.URL(preview.ThreadURL) } class="thread-subject catalog-preview-link">{ preview.Subject }</a> <a href={ templ.URL(preview.ThreadURL) } class="catalog-preview-link">{ preview.Subject }</a>
</h1> </h1>
<p> <p>
@templ.Raw(util.EnrichPost(preview.Body)) @templ.Raw(util.EnrichPost(preview.Body))
+11 -3
View File
@@ -62,6 +62,9 @@ templ Thread(board database.Board, thread database.Thread, posts []database.Post
<script src="/static/thread.js" defer></script> <script src="/static/thread.js" defer></script>
@BoardHeader(board) @BoardHeader(board)
<div class="new-post-container"> <div class="new-post-container">
<div style="display: none;" id="newPostWarning" class="warning">
<p>Please wait until the 15 second cooldown is finished.</p>
</div>
<form <form
hx-encoding="multipart/form-data" hx-encoding="multipart/form-data"
id="newPostForm" id="newPostForm"
@@ -69,9 +72,14 @@ templ Thread(board database.Board, thread database.Thread, posts []database.Post
hx-post={ fmt.Sprintf("/%s/threads/%d", hx-post={ fmt.Sprintf("/%s/threads/%d",
board.Slug, thread.Id) } board.Slug, thread.Id) }
_="on htmx:afterRequest _="on htmx:afterRequest
set #newPostBody.value to '' if event.detail.xhr.status is not 429
then set #newPostFile.value to '' set #newPostBody.value to ''
then trigger refreshPosts on body" then set #newPostFile.value to ''
then hide #newPostWarning
then trigger refreshPosts on body
else
show #newPostWarning
end"
> >
<table> <table>
<tbody> <tbody>