Files
minibin/internal/pages/pages.go
T
whoswhip c5636c9160 max total storage usage implemented!
code may be a bit messy but....

also implemented a storage usage stat (that can be toggled in .env) that
shows on the home page, you can also enable the total limit to show as
well

eventually i need to implement clearing old unfinished uploads both on
startup, admin actions, and cleaning up on upload failure
2026-12-05 16:24:57 -05:00

158 lines
4.0 KiB
Go

package pages
import (
"errors"
"fmt"
"html/template"
"log"
"math/rand/v2"
"net/http"
"net/url"
"os"
"path/filepath"
"strings"
"sync/atomic"
"git.whoswhip.dev/whoswhip/minibin/internal/config"
"github.com/dustin/go-humanize"
)
type Pages struct {
Templates *template.Template
Qts []string
Placeholders []string
QuotaUsage *atomic.Int64
}
func (pages *Pages) Render(w http.ResponseWriter, name string, data any) {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
if err := pages.Templates.ExecuteTemplate(w, name, data); err != nil {
log.Printf("render %s: %v", name, err)
}
}
func StaticPage(pages *Pages, name string) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
pages.Render(w, name, GetRandomQt(pages.Qts))
}
}
func ResultPage(pages *Pages, title string, message string, statusCode ...int) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
code := 200
if len(statusCode) > 0 {
code = statusCode[0]
}
w.WriteHeader(code)
pages.Render(w, "result.html", map[string]any{
"Qt": GetRandomQt(pages.Qts),
"Title": title,
"Message": message,
})
}
}
func GetRandomQt(qts []string) string {
if len(qts) > 0 {
return qts[rand.IntN(len(qts))]
}
return ""
}
func LoadPages(usage *atomic.Int64) (*Pages, error) {
templates, err := template.New("").Funcs(template.FuncMap{
"hasPrefix": strings.HasPrefix,
}).ParseGlob("web/templates/*.html")
if err != nil {
return nil, err
}
pages := &Pages{
Templates: templates,
Placeholders: []string{"cmon, paste something already!"},
QuotaUsage: usage,
}
qtFiles, err := os.ReadDir("qts")
if err != nil && !errors.Is(err, os.ErrNotExist) {
return nil, err
}
for _, qt := range qtFiles {
if qt.IsDir() {
continue
}
switch strings.ToLower(filepath.Ext(qt.Name())) {
case ".jpeg", ".jpg", ".jxl", ".png", ".webp", ".avif", ".gif":
pages.Qts = append(pages.Qts, "/qts/"+url.PathEscape(qt.Name()))
}
}
pastePlaceholders, err := os.ReadFile("paste-placeholders.txt")
if err != nil && !errors.Is(err, os.ErrNotExist) {
return nil, err
}
placeholders := strings.TrimSpace(strings.ReplaceAll(string(pastePlaceholders), "\r\n", "\n"))
if placeholders != "" {
pages.Placeholders = strings.Split(placeholders, "\n")
}
return pages, nil
}
func HomeHandler(pages *Pages, cfg config.Config) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
data := map[string]any{
"Expiries": cfg.Expiries,
"FileMaxSize": humanize.Bytes(uint64(cfg.MaxFileBytes)),
"FileMaxSizeBytes": cfg.MaxFileBytes,
"PasteMaxSize": humanize.Bytes(uint64(cfg.MaxPasteBytes)),
"PasteMaxSizeBytes": cfg.MaxPasteBytes,
"Qt": GetRandomQt(pages.Qts),
}
if len(pages.Placeholders) > 0 {
data["PastePlaceholder"] = pages.Placeholders[rand.IntN(len(pages.Placeholders))]
}
if cfg.DisplayStorageLimit {
data["StorageLimit"] = humanize.Bytes(uint64(cfg.MaxStorageUsage))
}
if cfg.DisplayStorageUsage {
data["StorageUsage"] = humanize.Bytes(uint64(pages.QuotaUsage.Load()))
}
pages.Render(w, "home.html", data)
}
}
func FaqHandler(pages *Pages, cfg config.Config) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
pages.Render(w, "faq.html", map[string]any{
"Expiries": cfg.Expiries,
"Host": cfg.Host,
"NormalizeMIMETypes": cfg.NormalizeMIMETypes,
"Qt": GetRandomQt(pages.Qts),
})
}
}
func (pages *Pages) HTTPError(w http.ResponseWriter, r *http.Request, message string, status int, title ...string) {
if strings.Contains(r.Header.Get("Accept"), "text/html") {
t := fmt.Sprintf("errror %d", status)
if len(title) > 0 {
t = title[0]
}
w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.WriteHeader(status)
_ = pages.Templates.ExecuteTemplate(w, "result.html", map[string]any{
"Title": t,
"Message": message,
"Qt": GetRandomQt(pages.Qts),
})
return
}
http.Error(w, message, status)
}