Add image upload functionality with management interface
This commit is contained in:
1 parent
f80903c7eb
commit
b45c837c1a
8 files changed
+666
-8
No files matched your search
@@ -13,6 +13,7 @@ type Config struct {
|
||||
Admin AdminConfig `toml:"admin"`
|
||||
Database DatabaseConfig `toml:"database"`
|
||||
Slugs SlugConfig `toml:"slugs"`
|
||||
Upload UploadConfig `toml:"upload"`
|
||||
}
|
||||
|
||||
type ServerConfig struct {
|
||||
@@ -36,6 +37,11 @@ type SlugConfig struct {
|
||||
Length int `toml:"length"`
|
||||
}
|
||||
|
||||
type UploadConfig struct {
|
||||
Dir string `toml:"dir"`
|
||||
MaxSize int64 `toml:"max_size_mb"`
|
||||
}
|
||||
|
||||
func (c *ServerConfig) ReadTimeoutDuration() time.Duration {
|
||||
d, err := time.ParseDuration(c.ReadTimeout)
|
||||
if err != nil {
|
||||
@@ -70,6 +76,10 @@ func Load(path string) (*Config, error) {
|
||||
Slugs: SlugConfig{
|
||||
Length: 3,
|
||||
},
|
||||
Upload: UploadConfig{
|
||||
Dir: "./data/uploads",
|
||||
MaxSize: 50,
|
||||
},
|
||||
}
|
||||
|
||||
data, err := os.ReadFile(path)
|
||||
|
||||
@@ -2,12 +2,26 @@ package server
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/rand"
|
||||
"crypto/subtle"
|
||||
"database/sql"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"html/template"
|
||||
"image"
|
||||
"image/color"
|
||||
_ "image/gif"
|
||||
"image/jpeg"
|
||||
"image/png"
|
||||
"io"
|
||||
"math"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
@@ -36,10 +50,22 @@ type pageData struct {
|
||||
Paste any
|
||||
Pastes any
|
||||
PasteBody template.HTML
|
||||
Uploads any
|
||||
LoggedIn bool
|
||||
CSRFToken string
|
||||
}
|
||||
|
||||
type UploadInfo struct {
|
||||
Filename string
|
||||
SizeHuman string
|
||||
Size int64
|
||||
URL string
|
||||
Width int
|
||||
Height int
|
||||
CanResize bool
|
||||
ModTime time.Time
|
||||
}
|
||||
|
||||
var mdRenderer = goldmark.New(
|
||||
goldmark.WithExtensions(extension.GFM, extension.Table),
|
||||
goldmark.WithRendererOptions(html.WithUnsafe()),
|
||||
@@ -659,6 +685,302 @@ func (s *Server) handleAdminBinDelete(w http.ResponseWriter, r *http.Request) {
|
||||
http.Redirect(w, r, "/admin/bin", http.StatusSeeOther)
|
||||
}
|
||||
|
||||
// ---- Upload helpers ----
|
||||
|
||||
var validUploadRe = regexp.MustCompile(`^[0-9a-f]{32}\.(png|jpg|gif|webp)$`)
|
||||
|
||||
func validUploadFilename(name string) bool {
|
||||
return validUploadRe.MatchString(name)
|
||||
}
|
||||
|
||||
func formatBytes(n int64) string {
|
||||
switch {
|
||||
case n >= 1024*1024:
|
||||
return fmt.Sprintf("%.1f MB", float64(n)/(1024*1024))
|
||||
case n >= 1024:
|
||||
return fmt.Sprintf("%.1f KB", float64(n)/1024)
|
||||
default:
|
||||
return fmt.Sprintf("%d B", n)
|
||||
}
|
||||
}
|
||||
|
||||
func jsonError(w http.ResponseWriter, msg string, code int) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(code)
|
||||
json.NewEncoder(w).Encode(map[string]string{"error": msg})
|
||||
}
|
||||
|
||||
func scaleImage(src image.Image, maxDim int) image.Image {
|
||||
b := src.Bounds()
|
||||
w, h := b.Dx(), b.Dy()
|
||||
if w <= maxDim && h <= maxDim {
|
||||
return src
|
||||
}
|
||||
var newW, newH int
|
||||
if w >= h {
|
||||
newW = maxDim
|
||||
newH = int(math.Round(float64(h) * float64(maxDim) / float64(w)))
|
||||
} else {
|
||||
newH = maxDim
|
||||
newW = int(math.Round(float64(w) * float64(maxDim) / float64(h)))
|
||||
}
|
||||
if newW < 1 {
|
||||
newW = 1
|
||||
}
|
||||
if newH < 1 {
|
||||
newH = 1
|
||||
}
|
||||
dst := image.NewNRGBA(image.Rect(0, 0, newW, newH))
|
||||
scaleX := float64(w) / float64(newW)
|
||||
scaleY := float64(h) / float64(newH)
|
||||
for y := 0; y < newH; y++ {
|
||||
for x := 0; x < newW; x++ {
|
||||
srcX := int(float64(x)*scaleX) + b.Min.X
|
||||
srcY := int(float64(y)*scaleY) + b.Min.Y
|
||||
r, g, bl, a := src.At(srcX, srcY).RGBA()
|
||||
dst.SetNRGBA(x, y, color.NRGBA{
|
||||
R: uint8(r >> 8),
|
||||
G: uint8(g >> 8),
|
||||
B: uint8(bl >> 8),
|
||||
A: uint8(a >> 8),
|
||||
})
|
||||
}
|
||||
}
|
||||
return dst
|
||||
}
|
||||
|
||||
// ---- Upload management handlers ----
|
||||
|
||||
func (s *Server) handleAdminUploads(w http.ResponseWriter, r *http.Request) {
|
||||
entries, err := os.ReadDir(s.cfg.Upload.Dir)
|
||||
if err != nil && !os.IsNotExist(err) {
|
||||
http.Error(w, "Failed to read uploads", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
var uploads []UploadInfo
|
||||
for _, entry := range entries {
|
||||
if entry.IsDir() {
|
||||
continue
|
||||
}
|
||||
name := entry.Name()
|
||||
if !validUploadFilename(name) {
|
||||
continue
|
||||
}
|
||||
info, err := entry.Info()
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
ui := UploadInfo{
|
||||
Filename: name,
|
||||
Size: info.Size(),
|
||||
SizeHuman: formatBytes(info.Size()),
|
||||
URL: "/uploads/" + name,
|
||||
ModTime: info.ModTime(),
|
||||
}
|
||||
ext := strings.ToLower(filepath.Ext(name))
|
||||
if f, err := os.Open(filepath.Join(s.cfg.Upload.Dir, name)); err == nil {
|
||||
if cfg, _, err := image.DecodeConfig(f); err == nil {
|
||||
ui.Width = cfg.Width
|
||||
ui.Height = cfg.Height
|
||||
}
|
||||
f.Close()
|
||||
}
|
||||
if ext == ".png" || ext == ".jpg" {
|
||||
ui.CanResize = true
|
||||
}
|
||||
uploads = append(uploads, ui)
|
||||
}
|
||||
|
||||
sort.Slice(uploads, func(i, j int) bool {
|
||||
return uploads[i].ModTime.After(uploads[j].ModTime)
|
||||
})
|
||||
|
||||
d := s.adminPage(w, r)
|
||||
d.Uploads = uploads
|
||||
renderTemplate(w, "admin_uploads.html", d)
|
||||
}
|
||||
|
||||
func (s *Server) handleAdminUploadDelete(w http.ResponseWriter, r *http.Request) {
|
||||
filename := r.PathValue("filename")
|
||||
if !validUploadFilename(filename) {
|
||||
http.Error(w, "Invalid filename", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
os.Remove(filepath.Join(s.cfg.Upload.Dir, filename))
|
||||
http.Redirect(w, r, "/admin/uploads", http.StatusSeeOther)
|
||||
}
|
||||
|
||||
func (s *Server) handleAdminUploadResize(w http.ResponseWriter, r *http.Request) {
|
||||
filename := r.PathValue("filename")
|
||||
if !validUploadFilename(filename) {
|
||||
jsonError(w, "Invalid filename", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
ext := strings.ToLower(filepath.Ext(filename))
|
||||
if ext != ".png" && ext != ".jpg" {
|
||||
jsonError(w, "Only PNG and JPEG can be resized", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
maxDim, err := strconv.Atoi(r.FormValue("max_dim"))
|
||||
if err != nil || maxDim < 64 || maxDim > 8192 {
|
||||
jsonError(w, "max_dim must be between 64 and 8192", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
path := filepath.Join(s.cfg.Upload.Dir, filename)
|
||||
f, err := os.Open(path)
|
||||
if err != nil {
|
||||
jsonError(w, "File not found", http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
src, _, err := image.Decode(f)
|
||||
f.Close()
|
||||
if err != nil {
|
||||
jsonError(w, "Failed to decode image", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
dst := scaleImage(src, maxDim)
|
||||
|
||||
tmpPath := path + ".tmp"
|
||||
out, err := os.Create(tmpPath)
|
||||
if err != nil {
|
||||
jsonError(w, "Failed to write file", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
var encErr error
|
||||
if ext == ".jpg" {
|
||||
encErr = jpeg.Encode(out, dst, &jpeg.Options{Quality: 85})
|
||||
} else {
|
||||
encErr = png.Encode(out, dst)
|
||||
}
|
||||
out.Close()
|
||||
if encErr != nil {
|
||||
os.Remove(tmpPath)
|
||||
jsonError(w, "Failed to encode image", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
if err := os.Rename(tmpPath, path); err != nil {
|
||||
os.Remove(tmpPath)
|
||||
jsonError(w, "Failed to save resized image", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
info, _ := os.Stat(path)
|
||||
var newSize int64
|
||||
if info != nil {
|
||||
newSize = info.Size()
|
||||
}
|
||||
b := dst.Bounds()
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
json.NewEncoder(w).Encode(map[string]any{
|
||||
"size_human": formatBytes(newSize),
|
||||
"width": b.Dx(),
|
||||
"height": b.Dy(),
|
||||
})
|
||||
}
|
||||
|
||||
// ---- Image upload handler ----
|
||||
|
||||
var allowedMIME = map[string]string{
|
||||
"image/png": ".png",
|
||||
"image/jpeg": ".jpg",
|
||||
"image/gif": ".gif",
|
||||
"image/webp": ".webp",
|
||||
}
|
||||
|
||||
func (s *Server) handleUpload(w http.ResponseWriter, r *http.Request) {
|
||||
maxBytes := s.cfg.Upload.MaxSize * 1024 * 1024
|
||||
r.Body = http.MaxBytesReader(w, r.Body, maxBytes)
|
||||
|
||||
// Extend per-request deadlines for large uploads
|
||||
rc := http.NewResponseController(w)
|
||||
rc.SetReadDeadline(time.Now().Add(120 * time.Second))
|
||||
rc.SetWriteDeadline(time.Now().Add(120 * time.Second))
|
||||
|
||||
// Verify CSRF manually (must happen after MaxBytesReader is set)
|
||||
if !verifyCSRF(r) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusForbidden)
|
||||
json.NewEncoder(w).Encode(map[string]string{"error": "Invalid CSRF token"})
|
||||
return
|
||||
}
|
||||
|
||||
file, _, err := r.FormFile("file")
|
||||
if err != nil {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
if err.Error() == "http: request body too large" {
|
||||
w.WriteHeader(http.StatusRequestEntityTooLarge)
|
||||
json.NewEncoder(w).Encode(map[string]string{"error": fmt.Sprintf("File too large (max %d MB)", s.cfg.Upload.MaxSize)})
|
||||
} else {
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
json.NewEncoder(w).Encode(map[string]string{"error": "No file provided"})
|
||||
}
|
||||
return
|
||||
}
|
||||
defer file.Close()
|
||||
|
||||
// Read first 512 bytes to detect MIME type
|
||||
head := make([]byte, 512)
|
||||
n, err := file.Read(head)
|
||||
if err != nil && err != io.EOF {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
json.NewEncoder(w).Encode(map[string]string{"error": "Failed to read file"})
|
||||
return
|
||||
}
|
||||
head = head[:n]
|
||||
|
||||
mimeType := http.DetectContentType(head)
|
||||
ext, ok := allowedMIME[mimeType]
|
||||
if !ok {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusUnsupportedMediaType)
|
||||
json.NewEncoder(w).Encode(map[string]string{"error": "Only PNG, JPEG, GIF, and WebP images are allowed"})
|
||||
return
|
||||
}
|
||||
|
||||
// Generate random filename
|
||||
randBytes := make([]byte, 16)
|
||||
rand.Read(randBytes)
|
||||
filename := hex.EncodeToString(randBytes) + ext
|
||||
|
||||
// Write file to disk
|
||||
destPath := filepath.Join(s.cfg.Upload.Dir, filename)
|
||||
out, err := os.Create(destPath)
|
||||
if err != nil {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
json.NewEncoder(w).Encode(map[string]string{"error": "Failed to save file"})
|
||||
return
|
||||
}
|
||||
defer out.Close()
|
||||
|
||||
// Write the head bytes we already read, then copy the rest
|
||||
if _, err := out.Write(head); err != nil {
|
||||
os.Remove(destPath)
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
json.NewEncoder(w).Encode(map[string]string{"error": "Failed to save file"})
|
||||
return
|
||||
}
|
||||
if _, err := io.Copy(out, file); err != nil {
|
||||
os.Remove(destPath)
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
json.NewEncoder(w).Encode(map[string]string{"error": "Failed to save file"})
|
||||
return
|
||||
}
|
||||
|
||||
imgURL := "/uploads/" + filename
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
json.NewEncoder(w).Encode(map[string]string{
|
||||
"url": imgURL,
|
||||
"markdown": "",
|
||||
})
|
||||
}
|
||||
|
||||
var validPasteNameRe = strings.NewReplacer() // placeholder — use inline check below
|
||||
func validPasteName(name string) bool {
|
||||
if len(name) == 0 || len(name) > 64 {
|
||||
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
"io/fs"
|
||||
"log"
|
||||
"net/http"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
@@ -44,7 +45,7 @@ func securityHeaders(next http.Handler) http.Handler {
|
||||
func lowercasePath(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
lower := strings.ToLower(r.URL.Path)
|
||||
if lower != r.URL.Path && !strings.HasPrefix(r.URL.Path, "/static/") && !strings.HasPrefix(lower, "/admin") {
|
||||
if lower != r.URL.Path && !strings.HasPrefix(r.URL.Path, "/static/") && !strings.HasPrefix(lower, "/admin") && !strings.HasPrefix(r.URL.Path, "/uploads/") {
|
||||
r.URL.Path = lower
|
||||
http.Redirect(w, r, r.URL.String(), http.StatusMovedPermanently)
|
||||
return
|
||||
@@ -56,12 +57,20 @@ func lowercasePath(next http.Handler) http.Handler {
|
||||
func (s *Server) Start() error {
|
||||
initTemplates()
|
||||
|
||||
// Ensure upload directory exists
|
||||
if err := os.MkdirAll(s.cfg.Upload.Dir, 0755); err != nil {
|
||||
return fmt.Errorf("creating upload directory: %w", err)
|
||||
}
|
||||
|
||||
mux := http.NewServeMux()
|
||||
|
||||
// Static files
|
||||
staticSub, _ := fs.Sub(staticFS, "static")
|
||||
mux.Handle("GET /static/", http.StripPrefix("/static/", http.FileServer(http.FS(staticSub))))
|
||||
|
||||
// Uploaded images (public — images appear in public pastes)
|
||||
mux.Handle("GET /uploads/", http.StripPrefix("/uploads/", http.FileServer(http.Dir(s.cfg.Upload.Dir))))
|
||||
|
||||
// Public routes
|
||||
mux.HandleFunc("GET /{$}", s.handleIndex)
|
||||
mux.HandleFunc("POST /shorten", s.handleShorten)
|
||||
@@ -86,6 +95,10 @@ func (s *Server) Start() error {
|
||||
mux.HandleFunc("POST /admin/bin/edit/{id}", s.requireAuth(s.requireCSRF(s.handleAdminBinSave)))
|
||||
mux.HandleFunc("POST /admin/bin/delete/{id}", s.requireAuth(s.requireCSRF(s.handleAdminBinDelete)))
|
||||
mux.HandleFunc("GET /admin/bin/qr/{name}", s.requireAuth(s.handleBinQR))
|
||||
mux.HandleFunc("POST /admin/upload", s.requireAuth(s.handleUpload))
|
||||
mux.HandleFunc("GET /admin/uploads", s.requireAuth(s.handleAdminUploads))
|
||||
mux.HandleFunc("POST /admin/uploads/delete/{filename}", s.requireAuth(s.requireCSRF(s.handleAdminUploadDelete)))
|
||||
mux.HandleFunc("POST /admin/uploads/resize/{filename}", s.requireAuth(s.handleAdminUploadResize))
|
||||
|
||||
// Pastebin public routes (before catch-all)
|
||||
mux.HandleFunc("GET /bin/{name}", s.handleBinView)
|
||||
|
||||
@@ -382,3 +382,23 @@ mark.badge-hidden {
|
||||
padding: 0.25rem 0.75rem;
|
||||
font-size: 0.85rem;
|
||||
}
|
||||
|
||||
/* Image upload controls */
|
||||
.upload-controls {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
margin-bottom: 0.25rem;
|
||||
}
|
||||
|
||||
.upload-controls button {
|
||||
width: auto;
|
||||
margin: 0;
|
||||
padding: 0.3rem 0.75rem;
|
||||
font-size: 0.85rem;
|
||||
}
|
||||
|
||||
#upload-status {
|
||||
color: var(--pico-muted-color);
|
||||
font-size: 0.8rem;
|
||||
}
|
||||
@@ -23,6 +23,7 @@
|
||||
<div class="admin-tabs">
|
||||
<a href="/admin" class="tab-link active">Links</a>
|
||||
<a href="/admin/bin" class="tab-link">Pastes</a>
|
||||
<a href="/admin/uploads" class="tab-link">Uploads</a>
|
||||
</div>
|
||||
<main class="container" style="max-width:960px">
|
||||
|
||||
|
||||
@@ -24,6 +24,7 @@
|
||||
<div class="admin-tabs">
|
||||
<a href="/admin" class="tab-link">Links</a>
|
||||
<a href="/admin/bin" class="tab-link active">Pastes</a>
|
||||
<a href="/admin/uploads" class="tab-link">Uploads</a>
|
||||
</div>
|
||||
<main class="container" style="max-width:960px">
|
||||
{{if .Error}}
|
||||
|
||||
@@ -24,6 +24,7 @@
|
||||
<div class="admin-tabs">
|
||||
<a href="/admin" class="tab-link">Links</a>
|
||||
<a href="/admin/bin" class="tab-link active">Pastes</a>
|
||||
<a href="/admin/uploads" class="tab-link">Uploads</a>
|
||||
</div>
|
||||
<main class="container" style="max-width:860px">
|
||||
<article>
|
||||
@@ -77,13 +78,17 @@
|
||||
</select>
|
||||
</label>
|
||||
|
||||
<label>Content
|
||||
{{if .Paste}}
|
||||
{{with .Paste}}<textarea name="content" rows="20" style="font-family:monospace;font-size:0.9rem">{{.Content}}</textarea>{{end}}
|
||||
{{else}}
|
||||
<textarea name="content" rows="20" style="font-family:monospace;font-size:0.9rem" placeholder="# Hello Write your markdown here..."></textarea>
|
||||
{{end}}
|
||||
</label>
|
||||
<label>Content</label>
|
||||
<div class="upload-controls">
|
||||
<button type="button" id="upload-btn" class="outline secondary">Upload Image</button>
|
||||
<input type="file" id="file-input" accept="image/png,image/jpeg,image/gif,image/webp" style="display:none">
|
||||
<small id="upload-status"></small>
|
||||
</div>
|
||||
{{if .Paste}}
|
||||
{{with .Paste}}<textarea name="content" rows="20" style="font-family:monospace;font-size:0.9rem">{{.Content}}</textarea>{{end}}
|
||||
{{else}}
|
||||
<textarea name="content" rows="20" style="font-family:monospace;font-size:0.9rem" placeholder="# Hello Write your markdown here..."></textarea>
|
||||
{{end}}
|
||||
|
||||
<fieldset>
|
||||
<legend>Access Token</legend>
|
||||
@@ -140,6 +145,79 @@
|
||||
document.querySelector('input[name="enable_token"][value="custom"]:checked');
|
||||
wrap.style.display = checked ? 'block' : 'none';
|
||||
}
|
||||
|
||||
(function() {
|
||||
var textarea = document.querySelector('textarea[name="content"]');
|
||||
var uploadBtn = document.getElementById('upload-btn');
|
||||
var fileInput = document.getElementById('file-input');
|
||||
var status = document.getElementById('upload-status');
|
||||
|
||||
function getCsrfToken() {
|
||||
var match = document.cookie.match(/(?:^|;\s*)csrf=([^;]+)/);
|
||||
return match ? match[1] : '';
|
||||
}
|
||||
|
||||
function uploadFile(file) {
|
||||
if (!file || !file.type.startsWith('image/')) {
|
||||
status.textContent = 'Not an image file';
|
||||
return;
|
||||
}
|
||||
if (file.size > 50 * 1024 * 1024) {
|
||||
status.textContent = 'File too large (max 50 MB)';
|
||||
return;
|
||||
}
|
||||
|
||||
status.textContent = 'Uploading\u2026';
|
||||
uploadBtn.disabled = true;
|
||||
var fd = new FormData();
|
||||
fd.append('file', file);
|
||||
fd.append('csrf_token', getCsrfToken());
|
||||
|
||||
fetch('/admin/upload', { method: 'POST', body: fd, credentials: 'same-origin' })
|
||||
.then(function(res) { return res.json(); })
|
||||
.then(function(data) {
|
||||
uploadBtn.disabled = false;
|
||||
if (data.error) {
|
||||
status.textContent = 'Error: ' + data.error;
|
||||
return;
|
||||
}
|
||||
insertAtCursor(data.markdown);
|
||||
status.textContent = 'Uploaded';
|
||||
setTimeout(function() { status.textContent = ''; }, 3000);
|
||||
})
|
||||
.catch(function() {
|
||||
uploadBtn.disabled = false;
|
||||
status.textContent = 'Upload failed';
|
||||
});
|
||||
}
|
||||
|
||||
function insertAtCursor(text) {
|
||||
var start = textarea.selectionStart;
|
||||
var end = textarea.selectionEnd;
|
||||
var before = textarea.value.substring(0, start);
|
||||
var after = textarea.value.substring(end);
|
||||
textarea.value = before + text + '\n' + after;
|
||||
textarea.selectionStart = textarea.selectionEnd = start + text.length + 1;
|
||||
textarea.focus();
|
||||
}
|
||||
|
||||
uploadBtn.addEventListener('click', function() { fileInput.click(); });
|
||||
fileInput.addEventListener('change', function() {
|
||||
if (fileInput.files.length > 0) uploadFile(fileInput.files[0]);
|
||||
fileInput.value = '';
|
||||
});
|
||||
|
||||
textarea.addEventListener('paste', function(e) {
|
||||
var items = (e.clipboardData || {}).items || [];
|
||||
for (var i = 0; i < items.length; i++) {
|
||||
if (items[i].type.indexOf('image') !== -1) {
|
||||
e.preventDefault();
|
||||
uploadFile(items[i].getAsFile());
|
||||
return;
|
||||
}
|
||||
}
|
||||
});
|
||||
})();
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,213 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en" data-theme="dark">
|
||||
<head>
|
||||
<link rel="icon" type="image/x-icon" href="/static/favicon.ico">
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>Uploads — Admin</title>
|
||||
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@picocss/pico@2/css/pico.min.css">
|
||||
<link rel="stylesheet" href="/static/style.css">
|
||||
</head>
|
||||
<body>
|
||||
<nav>
|
||||
<ul><li><strong><a href="/">Glimmer</a></strong></li></ul>
|
||||
<ul>
|
||||
<li><a href="/">Home</a></li>
|
||||
<li>
|
||||
<form method="post" action="/admin/logout" style="margin:0">
|
||||
<input type="hidden" name="csrf_token" value="{{$.CSRFToken}}">
|
||||
<button type="submit" class="outline secondary btn-sm">Logout</button>
|
||||
</form>
|
||||
</li>
|
||||
</ul>
|
||||
</nav>
|
||||
<div class="admin-tabs">
|
||||
<a href="/admin" class="tab-link">Links</a>
|
||||
<a href="/admin/bin" class="tab-link">Pastes</a>
|
||||
<a href="/admin/uploads" class="tab-link active">Uploads</a>
|
||||
</div>
|
||||
<main class="container" style="max-width:960px">
|
||||
{{if .Error}}
|
||||
<article aria-label="error" class="alert-error">{{.Error}}</article>
|
||||
{{end}}
|
||||
|
||||
<article class="card-table">
|
||||
<div class="section-header">
|
||||
<hgroup>
|
||||
<h2>Uploads</h2>
|
||||
<p>{{len .Uploads}} images</p>
|
||||
</hgroup>
|
||||
<div class="upload-controls">
|
||||
<button type="button" id="upload-btn" class="btn-sm">Upload Image</button>
|
||||
<input type="file" id="file-input" accept="image/png,image/jpeg,image/gif,image/webp" style="display:none">
|
||||
<small id="upload-status"></small>
|
||||
</div>
|
||||
</div>
|
||||
<figure>
|
||||
<table role="grid">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Preview</th>
|
||||
<th>File</th>
|
||||
<th>Size</th>
|
||||
<th>Dimensions</th>
|
||||
<th>Uploaded</th>
|
||||
<th>Actions</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{{range .Uploads}}
|
||||
<tr>
|
||||
<td><a href="{{.URL}}" target="_blank"><img src="{{.URL}}" style="max-width:72px;max-height:52px;object-fit:contain;border-radius:4px"></a></td>
|
||||
<td><code style="font-size:0.75rem">{{.Filename}}</code></td>
|
||||
<td id="size-{{.Filename}}">{{.SizeHuman}}</td>
|
||||
<td id="dim-{{.Filename}}">{{if .Width}}{{.Width}}×{{.Height}}{{else}}—{{end}}</td>
|
||||
<td>{{.ModTime.Format "2006-01-02 15:04"}}</td>
|
||||
<td>
|
||||
<div role="group">
|
||||
<button type="button" class="outline btn-sm" onclick="copyMarkdown('{{.Filename}}', this)">Copy</button>
|
||||
{{if .CanResize}}<button type="button" class="outline btn-sm" onclick="openResize('{{.Filename}}', {{.Width}}, {{.Height}})">Resize</button>{{end}}
|
||||
<form method="post" action="/admin/uploads/delete/{{.Filename}}" onsubmit="return confirm('Delete this image?')" style="margin:0">
|
||||
<input type="hidden" name="csrf_token" value="{{$.CSRFToken}}">
|
||||
<button type="submit" class="outline secondary btn-sm">Del</button>
|
||||
</form>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
{{else}}
|
||||
<tr>
|
||||
<td colspan="6">
|
||||
<div class="empty-state">
|
||||
<span class="empty-icon">🖼</span>
|
||||
<p>No uploads yet. Use the button above to upload an image.</p>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
{{end}}
|
||||
</tbody>
|
||||
</table>
|
||||
</figure>
|
||||
</article>
|
||||
</main>
|
||||
|
||||
<dialog id="resize-dialog">
|
||||
<article>
|
||||
<header>
|
||||
<button aria-label="Close" rel="prev" onclick="document.getElementById('resize-dialog').close()"></button>
|
||||
<h3>Resize Image</h3>
|
||||
</header>
|
||||
<p id="resize-current" style="color:var(--pico-muted-color)"></p>
|
||||
<label>
|
||||
Max dimension (px)
|
||||
<input type="number" id="resize-dim" value="1200" min="64" max="8192" step="1">
|
||||
</label>
|
||||
<small id="resize-status" style="color:var(--pico-muted-color)"></small>
|
||||
<footer>
|
||||
<button type="button" class="secondary outline" onclick="document.getElementById('resize-dialog').close()">Cancel</button>
|
||||
<button type="button" id="resize-confirm">Resize</button>
|
||||
</footer>
|
||||
</article>
|
||||
</dialog>
|
||||
|
||||
<script>
|
||||
var currentResizeFile = '';
|
||||
|
||||
function getCsrfToken() {
|
||||
var match = document.cookie.match(/(?:^|;\s*)csrf=([^;]+)/);
|
||||
return match ? match[1] : '';
|
||||
}
|
||||
|
||||
function copyMarkdown(filename, btn) {
|
||||
var md = '';
|
||||
navigator.clipboard.writeText(md).then(function() {
|
||||
var orig = btn.textContent;
|
||||
btn.textContent = 'Copied!';
|
||||
setTimeout(function() { btn.textContent = orig; }, 1500);
|
||||
});
|
||||
}
|
||||
|
||||
function openResize(filename, w, h) {
|
||||
currentResizeFile = filename;
|
||||
document.getElementById('resize-current').textContent = 'Current: ' + w + '\u00d7' + h;
|
||||
document.getElementById('resize-status').textContent = '';
|
||||
document.getElementById('resize-confirm').disabled = false;
|
||||
document.getElementById('resize-dialog').showModal();
|
||||
}
|
||||
|
||||
document.getElementById('resize-confirm').addEventListener('click', function() {
|
||||
var dim = document.getElementById('resize-dim').value;
|
||||
var status = document.getElementById('resize-status');
|
||||
var btn = this;
|
||||
status.textContent = 'Resizing\u2026';
|
||||
btn.disabled = true;
|
||||
|
||||
var fd = new FormData();
|
||||
fd.append('csrf_token', getCsrfToken());
|
||||
fd.append('max_dim', dim);
|
||||
|
||||
fetch('/admin/uploads/resize/' + currentResizeFile, { method: 'POST', body: fd, credentials: 'same-origin' })
|
||||
.then(function(r) { return r.json(); })
|
||||
.then(function(data) {
|
||||
btn.disabled = false;
|
||||
if (data.error) {
|
||||
status.textContent = 'Error: ' + data.error;
|
||||
return;
|
||||
}
|
||||
var sizeEl = document.getElementById('size-' + currentResizeFile);
|
||||
var dimEl = document.getElementById('dim-' + currentResizeFile);
|
||||
if (sizeEl) sizeEl.textContent = data.size_human;
|
||||
if (dimEl) dimEl.textContent = data.width + '\u00d7' + data.height;
|
||||
status.textContent = 'Done \u2014 ' + data.size_human;
|
||||
// Bust the image cache
|
||||
var imgs = document.querySelectorAll('img[src="/uploads/' + currentResizeFile + '"]');
|
||||
imgs.forEach(function(img) { img.src = '/uploads/' + currentResizeFile + '?t=' + Date.now(); });
|
||||
})
|
||||
.catch(function() {
|
||||
btn.disabled = false;
|
||||
status.textContent = 'Failed';
|
||||
});
|
||||
});
|
||||
|
||||
// Upload button
|
||||
var uploadBtn = document.getElementById('upload-btn');
|
||||
var fileInput = document.getElementById('file-input');
|
||||
var uploadStatus = document.getElementById('upload-status');
|
||||
|
||||
uploadBtn.addEventListener('click', function() { fileInput.click(); });
|
||||
fileInput.addEventListener('change', function() {
|
||||
if (fileInput.files.length > 0) doUpload(fileInput.files[0]);
|
||||
fileInput.value = '';
|
||||
});
|
||||
|
||||
function doUpload(file) {
|
||||
if (!file || !file.type.startsWith('image/')) {
|
||||
uploadStatus.textContent = 'Not an image file';
|
||||
return;
|
||||
}
|
||||
if (file.size > 50 * 1024 * 1024) {
|
||||
uploadStatus.textContent = 'File too large (max 50 MB)';
|
||||
return;
|
||||
}
|
||||
uploadStatus.textContent = 'Uploading\u2026';
|
||||
uploadBtn.disabled = true;
|
||||
var fd = new FormData();
|
||||
fd.append('file', file);
|
||||
fd.append('csrf_token', getCsrfToken());
|
||||
fetch('/admin/upload', { method: 'POST', body: fd, credentials: 'same-origin' })
|
||||
.then(function(r) { return r.json(); })
|
||||
.then(function(data) {
|
||||
uploadBtn.disabled = false;
|
||||
if (data.error) {
|
||||
uploadStatus.textContent = 'Error: ' + data.error;
|
||||
} else {
|
||||
location.reload();
|
||||
}
|
||||
})
|
||||
.catch(function() {
|
||||
uploadBtn.disabled = false;
|
||||
uploadStatus.textContent = 'Upload failed';
|
||||
});
|
||||
}
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
Reference in new issue
Block a user