Preserve original upload filenames, share upload JS, polish UI, update docs
- Adds an "uploads" SQLite table (filename → original_name) so the user's original filename is preserved and used in Content-Disposition headers and the admin listing instead of the on-disk hex name. - Extracts shared upload logic to static/upload.js (window.GlimmerUpload), deduplicating ~80 lines between the uploads page and the paste editor. - Adds size hints on upload buttons, an extension chip + original name in the uploads table, and a .ext-chip style. - Updates CLAUDE.md and README.md (route table, schema, features, project structure) to reflect the new endpoint and behaviour. Co-Authored-By: Claude Opus 4.6 <[email protected]>
This commit is contained in:
1 parent
b069027d56
commit
1b91014d1c
8 files changed
+315
-192
No files matched your search
@@ -2,7 +2,7 @@
|
||||
|
||||
## Project Overview
|
||||
|
||||
**Glimmer** is a single-binary Go URL shortener + pastebin with image upload support. It runs on a Raspberry Pi Zero (512 MB RAM, ARMv5) and compiles to a fully self-contained binary — no CGo, no external runtime, no system SQLite.
|
||||
**Glimmer** is a single-binary Go URL shortener + pastebin with image and file upload support. It runs on a Raspberry Pi Zero (512 MB RAM, ARMv5) and compiles to a fully self-contained binary — no CGo, no external runtime, no system SQLite.
|
||||
|
||||
Live at [luci.ooo](https://luci.ooo).
|
||||
|
||||
@@ -33,25 +33,27 @@ glimmer/
|
||||
├── Makefile
|
||||
├── data/
|
||||
│ ├── urls.db # SQLite DB (auto-created)
|
||||
│ └── uploads/ # Uploaded images (auto-created)
|
||||
│ └── uploads/ # Uploaded images & files (auto-created)
|
||||
└── internal/
|
||||
├── config/config.go # TOML config structs + loader
|
||||
├── db/db.go # DB open/migrate; Link + Paste CRUD
|
||||
├── db/db.go # DB open/migrate; Link + Paste + Upload CRUD
|
||||
├── slug/slug.go # Base-36 slug generation + validation
|
||||
└── server/
|
||||
├── server.go # Mux, middleware wiring, server start
|
||||
├── handlers.go # All HTTP handlers + rendering helpers
|
||||
├── middleware.go # Auth, CSRF, sessions, rate limiter
|
||||
├── templates.go # embed.FS for templates + static; initTemplates()
|
||||
├── static/style.css # Custom styles on top of Pico CSS 2
|
||||
├── static/
|
||||
│ ├── style.css # Custom styles on top of Pico CSS 2
|
||||
│ └── upload.js # Shared client-side upload helper (window.GlimmerUpload)
|
||||
└── templates/
|
||||
├── index.html # Public: URL shortener form
|
||||
├── admin_login.html # Login (dark, centered)
|
||||
├── admin.html # Dashboard: stats, tiles, links tables
|
||||
├── admin_edit.html # Edit a single link
|
||||
├── admin_bin.html # Pastes list
|
||||
├── admin_bin_edit.html # Create / edit paste (with image upload JS)
|
||||
├── admin_uploads.html # Image upload management
|
||||
├── admin_bin_edit.html # Create / edit paste (uses /static/upload.js)
|
||||
├── admin_uploads.html # Image + file upload management
|
||||
├── bin_view.html # Public paste viewer
|
||||
├── bin_token.html # Token prompt for protected pastes
|
||||
└── 404.html
|
||||
@@ -84,7 +86,7 @@ All templates receive a `pageData` struct. Add new fields there when templates n
|
||||
Templates and static files are embedded into the binary via `//go:embed` in `templates.go`. Changes to templates are compiled in; they are **not** reloaded at runtime. Always rebuild after template changes.
|
||||
|
||||
### No JS frameworks
|
||||
All JavaScript is vanilla ES5-style (`var`, not `const`/`let`) written inline in templates. No build step, no npm, no bundler.
|
||||
All JavaScript is vanilla ES5-style (`var`, not `const`/`let`). Most JS is inline in templates; shared upload logic lives in `static/upload.js` and is exposed as `window.GlimmerUpload`. No build step, no npm, no bundler.
|
||||
|
||||
### CSS framework
|
||||
[Pico CSS 2](https://picocss.com/) loaded from CDN. Custom overrides in `static/style.css`. Admin pages use `data-theme="dark"`.
|
||||
@@ -104,10 +106,20 @@ All JavaScript is vanilla ES5-style (`var`, not `const`/`let`) written inline in
|
||||
All state-changing POSTs must include `<input type="hidden" name="csrf_token" value="{{$.CSRFToken}}">` in the form. Handlers must be wrapped with `requireCSRF`. For multipart form handlers (file uploads), verify CSRF manually inside the handler *after* calling `r.ParseMultipartForm` — do not use the `requireCSRF` wrapper as it will parse with Go's default 32 MB limit before `MaxBytesReader` takes effect.
|
||||
|
||||
### File uploads
|
||||
Two endpoints, both admin-only and CSRF-protected:
|
||||
- `POST /admin/upload` — images only (PNG/JPEG/GIF/WebP), up to `upload.max_size_mb` from config (default 50 MB). MIME type validated by magic bytes via `http.DetectContentType`.
|
||||
- `POST /admin/upload-file` — any file type, hard-coded 5 MB cap. Validates only that the extension is `[a-z0-9]{1,10}`.
|
||||
|
||||
Shared upload rules:
|
||||
- Max size enforced via `http.MaxBytesReader(w, r.Body, maxBytes)` at handler start
|
||||
- MIME type validated via `http.DetectContentType` (magic bytes), not the client-supplied `Content-Type`
|
||||
- Filenames are always `[32 hex chars].[ext]` — validated by `validUploadRe` regexp before any file operation
|
||||
- Filenames written to disk are always `[32 hex chars].[ext]` — validated by `validUploadRe` regexp before any file operation. Original filenames are stored in the `uploads` table (filename → original_name) and used for `Content-Disposition` and the admin listing.
|
||||
- Per-request timeouts extended to 120s via `http.NewResponseController` — global timeouts stay at 5s/10s
|
||||
- `sanitizeDisplayFilename()` strips control chars and markdown-significant chars (`[ ] ( ) \ \` * < > " '`) before the original name is embedded in JSON responses or stored.
|
||||
|
||||
### Serving uploads (`/uploads/{filename}`)
|
||||
`handleUploadsServe` validates the filename against `validUploadRe`, then:
|
||||
- **Images** (`.png`/`.jpg`/`.gif`/`.webp`) — served inline by `http.ServeFile` so they can embed in public pastes.
|
||||
- **Everything else** — forced to download with `Content-Type: application/octet-stream` + `Content-Disposition: attachment` (with both ASCII `filename=` and RFC 5987 `filename*=UTF-8''…`). This prevents same-origin XSS from uploaded HTML/SVG/JS being rendered by the browser.
|
||||
|
||||
### Image resize
|
||||
Only PNG (`.png`) and JPEG (`.jpg`) are resizable. Resize uses a nearest-neighbour scale implemented in stdlib (`image`, `image/color`, `image/jpeg`, `image/png`) — no external image library. GIF and WebP are served and deletable but not resizable.
|
||||
|
||||
@@ -33,16 +33,19 @@ A lightweight, single-binary URL shortener and pastebin built in Go. Hosted on [
|
||||
- **Raw view:** Append `?raw=1` to any paste URL for `text/plain` output
|
||||
- **Copy button:** One-click clipboard copy in the paste viewer
|
||||
- **Image embedding:** Paste an image from clipboard or use the Upload Image button in the paste editor — image is uploaded and a markdown link is inserted at the cursor automatically
|
||||
- **File attachments:** Use the Upload File button to attach any file type (up to 5 MB); a markdown download link is inserted at the cursor
|
||||
|
||||
### Image Uploads
|
||||
- **Admin-only upload:** Images up to 50 MB via file picker or clipboard paste in the paste editor
|
||||
- **Supported formats:** PNG, JPEG, GIF, WebP (validated by magic bytes, not file extension)
|
||||
- **Uploads management tab:** View all uploaded images with thumbnails, file size, and dimensions
|
||||
- **Resize:** Downscale PNG or JPEG images in-place by setting a max dimension — re-encodes JPEG at 85% quality; no additional dependencies
|
||||
- **Delete:** Remove individual images from the admin uploads tab
|
||||
- **Copy markdown:** One-click copy of the `` link for use in any paste
|
||||
- **Public serving:** Uploaded images are served at `/uploads/{filename}` and render in public paste views
|
||||
- **Per-upload timeout:** Upload requests get a 120-second read/write deadline via `http.NewResponseController`; all other routes keep the 5s/10s defaults
|
||||
### Image & File Uploads
|
||||
- **Two upload modes:**
|
||||
- **Images** — PNG, JPEG, GIF, WebP up to 50 MB (configurable). Validated by magic bytes, not file extension.
|
||||
- **Files** — any file type up to 5 MB (hard-coded). Validated by extension regex only.
|
||||
- **Original filenames preserved:** Stored on disk as `[32 hex chars].[ext]` but the user's original filename is recorded in a SQLite `uploads` table and used in the admin listing and the `Content-Disposition` header when the file is downloaded.
|
||||
- **Uploads management tab:** View all uploaded files with thumbnails (images) or document icons (files), extension chip, original name, file size, and image dimensions.
|
||||
- **Resize:** Downscale PNG or JPEG images in-place by setting a max dimension — re-encodes JPEG at 85% quality; no additional dependencies.
|
||||
- **Delete:** Remove individual uploads from the admin uploads tab.
|
||||
- **Copy markdown:** One-click copy of the `` (images) or `[name](/uploads/...)` (files) link for use in any paste.
|
||||
- **Public serving:** Uploaded images are served inline at `/uploads/{filename}` and render in public paste views. **Non-image files are forced to download** with `Content-Disposition: attachment` to prevent same-origin XSS via uploaded HTML/SVG/JS.
|
||||
- **Per-upload timeout:** Upload requests get a 120-second read/write deadline via `http.NewResponseController`; all other routes keep the 5s/10s defaults.
|
||||
|
||||
### Security
|
||||
- CSRF protection on every state-changing POST (double-submit cookie pattern)
|
||||
@@ -69,12 +72,12 @@ glimmer/
|
||||
│ └── glimmer.init # SysV init script (Ubuntu 14.04 and older)
|
||||
├── data/
|
||||
│ ├── urls.db # SQLite database (auto-created on first run)
|
||||
│ └── uploads/ # Uploaded images (auto-created on first run)
|
||||
│ └── uploads/ # Uploaded images & files (auto-created on first run)
|
||||
└── internal/
|
||||
├── config/
|
||||
│ └── config.go # TOML config loader; Config struct (incl. UploadConfig)
|
||||
├── db/
|
||||
│ └── db.go # SQLite open/migrate; Link & Paste CRUD
|
||||
│ └── db.go # SQLite open/migrate; Link & Paste & Upload CRUD
|
||||
├── slug/
|
||||
│ └── slug.go # Base-36 slug generation and validation
|
||||
└── server/
|
||||
@@ -82,14 +85,15 @@ glimmer/
|
||||
├── handlers.go # All request handlers; template rendering helpers
|
||||
├── middleware.go # requireAuth, requireCSRF, rateLimiter, sessionStore, clientIP
|
||||
├── static/
|
||||
│ └── style.css # Custom styles on top of Pico CSS (no JS)
|
||||
│ ├── style.css # Custom styles on top of Pico CSS
|
||||
│ └── upload.js # Shared client-side upload helper (window.GlimmerUpload)
|
||||
└── templates/
|
||||
├── index.html # Public home: shorten form + QR result
|
||||
├── admin_login.html # Login form (dark, centered card)
|
||||
├── admin.html # Admin dashboard: stats bar, tiles, links tables
|
||||
├── admin_edit.html # Edit a single link
|
||||
├── admin_bin.html # Pastes list with format/token badges
|
||||
├── admin_bin_edit.html # Create / edit a paste (with image upload)
|
||||
├── admin_bin_edit.html # Create / edit a paste (with image + file upload)
|
||||
├── admin_uploads.html # Upload management: list, resize, delete
|
||||
├── bin_view.html # Public paste viewer (GitHub Gist style)
|
||||
└── 404.html # Not found page
|
||||
@@ -154,8 +158,8 @@ path = "./data/urls.db"
|
||||
length = 3 # Auto-generated slug length (characters)
|
||||
|
||||
[upload]
|
||||
dir = "./data/uploads" # Where uploaded images are stored (auto-created)
|
||||
max_size_mb = 50 # Max image upload size in MB
|
||||
dir = "./data/uploads" # Where uploaded images & files are stored (auto-created)
|
||||
max_size_mb = 50 # Max image upload size in MB (file uploads are hard-capped at 5 MB)
|
||||
```
|
||||
|
||||
### 3. Set your admin password
|
||||
@@ -402,7 +406,7 @@ If proxying through Cloudflare, `X-Forwarded-For` is safe to trust for rate limi
|
||||
| `GET` | `/{slug}` | Public | Redirect to destination |
|
||||
| `GET` | `/bin/{name}` | Public | View paste |
|
||||
| `GET` | `/bin/{name}/{token}` | Public | View token-protected paste |
|
||||
| `GET` | `/uploads/{filename}` | Public | Serve uploaded image |
|
||||
| `GET` | `/uploads/{filename}` | Public | Serve uploaded image inline; non-images forced as `attachment` |
|
||||
| `GET` | `/admin/login` | Public | Login form |
|
||||
| `POST` | `/admin/login` | Public | Submit login |
|
||||
| `POST` | `/admin/logout` | Admin | Logout (CSRF protected) |
|
||||
@@ -418,8 +422,9 @@ If proxying through Cloudflare, `X-Forwarded-For` is safe to trust for rate limi
|
||||
| `POST` | `/admin/bin/edit/{id}` | Admin | Save paste edit (CSRF) |
|
||||
| `POST` | `/admin/bin/delete/{id}` | Admin | Delete paste (CSRF) |
|
||||
| `GET` | `/admin/uploads` | Admin | Uploads management list |
|
||||
| `POST` | `/admin/upload` | Admin | Upload an image (returns JSON) |
|
||||
| `POST` | `/admin/uploads/delete/{filename}` | Admin | Delete an uploaded image (CSRF) |
|
||||
| `POST` | `/admin/upload` | Admin | Upload an image — PNG/JPEG/GIF/WebP, up to 50 MB (returns JSON) |
|
||||
| `POST` | `/admin/upload-file` | Admin | Upload any file — up to 5 MB (returns JSON) |
|
||||
| `POST` | `/admin/uploads/delete/{filename}` | Admin | Delete an uploaded file (CSRF) |
|
||||
| `POST` | `/admin/uploads/resize/{filename}` | Admin | Resize a PNG/JPEG in-place (returns JSON) |
|
||||
| `GET` | `/static/*` | Public | CSS / static assets |
|
||||
|
||||
@@ -446,9 +451,16 @@ CREATE TABLE pastes (
|
||||
content TEXT NOT NULL DEFAULT '',
|
||||
format TEXT NOT NULL DEFAULT 'markdown', -- 'markdown' | 'text'
|
||||
token TEXT, -- NULL = public; non-null = token required
|
||||
hidden INTEGER NOT NULL DEFAULT 0, -- 1 = return 404 instead of token prompt
|
||||
created_at TEXT NOT NULL DEFAULT (datetime('now')),
|
||||
updated_at TEXT NOT NULL DEFAULT (datetime('now'))
|
||||
);
|
||||
|
||||
CREATE TABLE uploads (
|
||||
filename TEXT PRIMARY KEY, -- on-disk name, e.g. "abc123…def.pdf"
|
||||
original_name TEXT NOT NULL DEFAULT '', -- sanitised original from the upload form
|
||||
created_at TEXT NOT NULL DEFAULT (datetime('now'))
|
||||
);
|
||||
```
|
||||
|
||||
To reset the database (e.g. during development):
|
||||
@@ -481,8 +493,8 @@ path = "./data/urls.db" # Path to SQLite file (directory auto-created)
|
||||
length = 3 # Length of auto-generated slugs (recommended: 3–6)
|
||||
|
||||
[upload]
|
||||
dir = "./data/uploads" # Directory for uploaded images (auto-created)
|
||||
max_size_mb = 50 # Max upload size in MB
|
||||
dir = "./data/uploads" # Directory for uploaded images & files (auto-created)
|
||||
max_size_mb = 50 # Max image upload size in MB; file uploads are hard-capped at 5 MB
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
@@ -31,6 +31,12 @@ type Link struct {
|
||||
CreatedAt time.Time
|
||||
}
|
||||
|
||||
type Upload struct {
|
||||
Filename string
|
||||
OriginalName string
|
||||
CreatedAt time.Time
|
||||
}
|
||||
|
||||
type DB struct {
|
||||
conn *sql.DB
|
||||
}
|
||||
@@ -76,6 +82,11 @@ func migrate(conn *sql.DB) error {
|
||||
created_at TEXT NOT NULL DEFAULT (datetime('now')),
|
||||
updated_at TEXT NOT NULL DEFAULT (datetime('now'))
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS uploads (
|
||||
filename TEXT PRIMARY KEY,
|
||||
original_name TEXT NOT NULL DEFAULT '',
|
||||
created_at TEXT NOT NULL DEFAULT (datetime('now'))
|
||||
);
|
||||
`)
|
||||
if err != nil {
|
||||
return fmt.Errorf("running migrations: %w", err)
|
||||
@@ -277,6 +288,47 @@ func scanPaste(row *sql.Row) (*Paste, error) {
|
||||
return &p, nil
|
||||
}
|
||||
|
||||
// ---- Upload metadata ----
|
||||
|
||||
func (d *DB) RecordUpload(filename, originalName string) error {
|
||||
_, err := d.conn.Exec(
|
||||
"INSERT OR REPLACE INTO uploads (filename, original_name) VALUES (?, ?)",
|
||||
filename, originalName,
|
||||
)
|
||||
return err
|
||||
}
|
||||
|
||||
func (d *DB) GetUploadName(filename string) (string, error) {
|
||||
var name string
|
||||
err := d.conn.QueryRow("SELECT original_name FROM uploads WHERE filename = ?", filename).Scan(&name)
|
||||
if err == sql.ErrNoRows {
|
||||
return "", nil
|
||||
}
|
||||
return name, err
|
||||
}
|
||||
|
||||
func (d *DB) ListUploadNames() (map[string]string, error) {
|
||||
rows, err := d.conn.Query("SELECT filename, original_name FROM uploads")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
names := make(map[string]string)
|
||||
for rows.Next() {
|
||||
var f, n string
|
||||
if err := rows.Scan(&f, &n); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
names[f] = n
|
||||
}
|
||||
return names, rows.Err()
|
||||
}
|
||||
|
||||
func (d *DB) DeleteUpload(filename string) error {
|
||||
_, err := d.conn.Exec("DELETE FROM uploads WHERE filename = ?", filename)
|
||||
return err
|
||||
}
|
||||
|
||||
func scanLink(row *sql.Row) (*Link, error) {
|
||||
var l Link
|
||||
var ts string
|
||||
|
||||
+58
-19
@@ -56,15 +56,17 @@ type pageData struct {
|
||||
}
|
||||
|
||||
type UploadInfo struct {
|
||||
Filename string
|
||||
SizeHuman string
|
||||
Size int64
|
||||
URL string
|
||||
Width int
|
||||
Height int
|
||||
CanResize bool
|
||||
IsImage bool
|
||||
ModTime time.Time
|
||||
Filename string
|
||||
OriginalName string
|
||||
SizeHuman string
|
||||
Size int64
|
||||
URL string
|
||||
Ext string
|
||||
Width int
|
||||
Height int
|
||||
CanResize bool
|
||||
IsImage bool
|
||||
ModTime time.Time
|
||||
}
|
||||
|
||||
var mdRenderer = goldmark.New(
|
||||
@@ -770,12 +772,38 @@ func (s *Server) handleUploadsServe(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
path := filepath.Join(s.cfg.Upload.Dir, name)
|
||||
if !isImageFile(name) {
|
||||
download := name
|
||||
if orig, _ := s.db.GetUploadName(name); orig != "" {
|
||||
download = orig
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/octet-stream")
|
||||
w.Header().Set("Content-Disposition", `attachment; filename="`+name+`"`)
|
||||
w.Header().Set("Content-Disposition", contentDispositionAttachment(download))
|
||||
}
|
||||
http.ServeFile(w, r, path)
|
||||
}
|
||||
|
||||
// contentDispositionAttachment builds a safe attachment header. The ASCII
|
||||
// filename strips characters that would break header parsing; the RFC 5987
|
||||
// filename* preserves any UTF-8 chars for clients that understand it.
|
||||
func contentDispositionAttachment(name string) string {
|
||||
var ascii strings.Builder
|
||||
for _, r := range name {
|
||||
if r < 32 || r == 127 || r == '"' || r == '\\' {
|
||||
continue
|
||||
}
|
||||
if r > 127 {
|
||||
ascii.WriteByte('_')
|
||||
continue
|
||||
}
|
||||
ascii.WriteRune(r)
|
||||
}
|
||||
a := ascii.String()
|
||||
if a == "" {
|
||||
a = "download"
|
||||
}
|
||||
return fmt.Sprintf(`attachment; filename="%s"; filename*=UTF-8''%s`, a, url.PathEscape(name))
|
||||
}
|
||||
|
||||
// ---- Upload management handlers ----
|
||||
|
||||
func (s *Server) handleAdminUploads(w http.ResponseWriter, r *http.Request) {
|
||||
@@ -785,6 +813,8 @@ func (s *Server) handleAdminUploads(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
|
||||
names, _ := s.db.ListUploadNames()
|
||||
|
||||
var uploads []UploadInfo
|
||||
for _, entry := range entries {
|
||||
if entry.IsDir() {
|
||||
@@ -798,15 +828,17 @@ func (s *Server) handleAdminUploads(w http.ResponseWriter, r *http.Request) {
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
ui := UploadInfo{
|
||||
Filename: name,
|
||||
Size: info.Size(),
|
||||
SizeHuman: formatBytes(info.Size()),
|
||||
URL: "/uploads/" + name,
|
||||
IsImage: isImageFile(name),
|
||||
ModTime: info.ModTime(),
|
||||
}
|
||||
ext := strings.ToLower(filepath.Ext(name))
|
||||
ui := UploadInfo{
|
||||
Filename: name,
|
||||
OriginalName: names[name],
|
||||
Size: info.Size(),
|
||||
SizeHuman: formatBytes(info.Size()),
|
||||
URL: "/uploads/" + name,
|
||||
Ext: strings.TrimPrefix(ext, "."),
|
||||
IsImage: isImageFile(name),
|
||||
ModTime: info.ModTime(),
|
||||
}
|
||||
if ui.IsImage {
|
||||
if f, err := os.Open(filepath.Join(s.cfg.Upload.Dir, name)); err == nil {
|
||||
if cfg, _, err := image.DecodeConfig(f); err == nil {
|
||||
@@ -838,6 +870,7 @@ func (s *Server) handleAdminUploadDelete(w http.ResponseWriter, r *http.Request)
|
||||
return
|
||||
}
|
||||
os.Remove(filepath.Join(s.cfg.Upload.Dir, filename))
|
||||
s.db.DeleteUpload(filename)
|
||||
http.Redirect(w, r, "/admin/uploads", http.StatusSeeOther)
|
||||
}
|
||||
|
||||
@@ -937,7 +970,7 @@ func (s *Server) handleUpload(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
|
||||
file, _, err := r.FormFile("file")
|
||||
file, header, err := r.FormFile("file")
|
||||
if err != nil {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
if err.Error() == "http: request body too large" {
|
||||
@@ -1003,10 +1036,14 @@ func (s *Server) handleUpload(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
|
||||
displayName := sanitizeDisplayFilename(header.Filename)
|
||||
s.db.RecordUpload(filename, displayName)
|
||||
|
||||
imgURL := "/uploads/" + filename
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
json.NewEncoder(w).Encode(map[string]string{
|
||||
"url": imgURL,
|
||||
"filename": displayName,
|
||||
"markdown": "",
|
||||
})
|
||||
}
|
||||
@@ -1074,6 +1111,8 @@ func (s *Server) handleFileUpload(w http.ResponseWriter, r *http.Request) {
|
||||
if displayName == "" {
|
||||
displayName = filename
|
||||
}
|
||||
s.db.RecordUpload(filename, displayName)
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
json.NewEncoder(w).Encode(map[string]string{
|
||||
"url": fileURL,
|
||||
|
||||
@@ -402,3 +402,18 @@ mark.badge-hidden {
|
||||
color: var(--pico-muted-color);
|
||||
font-size: 0.8rem;
|
||||
}
|
||||
|
||||
.ext-chip {
|
||||
display: inline-block;
|
||||
font-family: var(--pico-font-family-monospace);
|
||||
font-size: 0.7rem;
|
||||
font-weight: 600;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.03em;
|
||||
padding: 0.1rem 0.4rem;
|
||||
border-radius: 4px;
|
||||
background: var(--pico-primary-background);
|
||||
color: var(--pico-primary-inverse);
|
||||
min-width: 2.5rem;
|
||||
text-align: center;
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
// Shared upload helper for the admin uploads page and the paste editor.
|
||||
// Wires up an "Upload Image" and "Upload File" button pair to their hidden
|
||||
// file inputs and posts to /admin/upload (images, 50 MB) or
|
||||
// /admin/upload-file (any file, 5 MB).
|
||||
//
|
||||
// Usage: call window.GlimmerUpload.init({
|
||||
// imgBtn, fileBtn, imgInput, fileInput, statusEl,
|
||||
// onUploaded: function(data, isImage) { ... } // required
|
||||
// });
|
||||
|
||||
(function(window) {
|
||||
var IMG_MAX = 50 * 1024 * 1024;
|
||||
var FILE_MAX = 5 * 1024 * 1024;
|
||||
|
||||
function getCsrfToken() {
|
||||
var match = document.cookie.match(/(?:^|;\s*)csrf=([^;]+)/);
|
||||
return match ? match[1] : '';
|
||||
}
|
||||
|
||||
function init(opts) {
|
||||
var imgBtn = opts.imgBtn;
|
||||
var fileBtn = opts.fileBtn;
|
||||
var imgInput = opts.imgInput;
|
||||
var fileInput = opts.fileInput;
|
||||
var statusEl = opts.statusEl;
|
||||
var onUploaded = opts.onUploaded;
|
||||
|
||||
function setDisabled(v) {
|
||||
if (imgBtn) imgBtn.disabled = v;
|
||||
if (fileBtn) fileBtn.disabled = v;
|
||||
}
|
||||
|
||||
function setStatus(msg) {
|
||||
if (statusEl) statusEl.textContent = msg;
|
||||
}
|
||||
|
||||
function doUpload(file, isImage) {
|
||||
if (isImage) {
|
||||
if (!file || !file.type || file.type.indexOf('image/') !== 0) {
|
||||
setStatus('Not an image file');
|
||||
return;
|
||||
}
|
||||
if (file.size > IMG_MAX) {
|
||||
setStatus('File too large (max 50 MB)');
|
||||
return;
|
||||
}
|
||||
} else {
|
||||
if (file.size > FILE_MAX) {
|
||||
setStatus('File too large (max 5 MB)');
|
||||
return;
|
||||
}
|
||||
}
|
||||
setStatus('Uploading…');
|
||||
setDisabled(true);
|
||||
|
||||
var fd = new FormData();
|
||||
fd.append('file', file);
|
||||
fd.append('csrf_token', getCsrfToken());
|
||||
var endpoint = isImage ? '/admin/upload' : '/admin/upload-file';
|
||||
|
||||
fetch(endpoint, { method: 'POST', body: fd, credentials: 'same-origin' })
|
||||
.then(function(r) { return r.json(); })
|
||||
.then(function(data) {
|
||||
setDisabled(false);
|
||||
if (data.error) {
|
||||
setStatus('Error: ' + data.error);
|
||||
return;
|
||||
}
|
||||
onUploaded(data, isImage);
|
||||
})
|
||||
.catch(function() {
|
||||
setDisabled(false);
|
||||
setStatus('Upload failed');
|
||||
});
|
||||
}
|
||||
|
||||
if (imgBtn && imgInput) {
|
||||
imgBtn.addEventListener('click', function() { imgInput.click(); });
|
||||
imgInput.addEventListener('change', function() {
|
||||
if (imgInput.files.length > 0) doUpload(imgInput.files[0], true);
|
||||
imgInput.value = '';
|
||||
});
|
||||
}
|
||||
if (fileBtn && fileInput) {
|
||||
fileBtn.addEventListener('click', function() { fileInput.click(); });
|
||||
fileInput.addEventListener('change', function() {
|
||||
if (fileInput.files.length > 0) doUpload(fileInput.files[0], false);
|
||||
fileInput.value = '';
|
||||
});
|
||||
}
|
||||
|
||||
return { doUpload: doUpload, setStatus: setStatus };
|
||||
}
|
||||
|
||||
window.GlimmerUpload = { init: init, getCsrfToken: getCsrfToken };
|
||||
})(window);
|
||||
@@ -80,8 +80,8 @@
|
||||
|
||||
<label>Content</label>
|
||||
<div class="upload-controls">
|
||||
<button type="button" id="upload-img-btn" class="outline secondary">Upload Image</button>
|
||||
<button type="button" id="upload-file-btn" class="outline secondary">Upload File</button>
|
||||
<button type="button" id="upload-img-btn" class="outline secondary" title="PNG, JPEG, GIF, WebP — up to 50 MB">Upload Image <small style="opacity:.7">(50 MB)</small></button>
|
||||
<button type="button" id="upload-file-btn" class="outline secondary" title="Any file type — up to 5 MB">Upload File <small style="opacity:.7">(5 MB)</small></button>
|
||||
<input type="file" id="img-input" accept="image/png,image/jpeg,image/gif,image/webp" style="display:none">
|
||||
<input type="file" id="file-input" style="display:none">
|
||||
<small id="upload-status"></small>
|
||||
@@ -139,6 +139,7 @@
|
||||
{{if .Paste}}{{with .Paste}}{{end}}{{end}}
|
||||
</article>
|
||||
</main>
|
||||
<script src="/static/upload.js"></script>
|
||||
<script>
|
||||
function toggleCustomToken() {
|
||||
var wrap = document.getElementById('custom-token-wrap');
|
||||
@@ -150,64 +151,8 @@
|
||||
|
||||
(function() {
|
||||
var textarea = document.querySelector('textarea[name="content"]');
|
||||
var uploadImgBtn = document.getElementById('upload-img-btn');
|
||||
var uploadFileBtn = document.getElementById('upload-file-btn');
|
||||
var imgInput = document.getElementById('img-input');
|
||||
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 setButtonsDisabled(v) {
|
||||
uploadImgBtn.disabled = v;
|
||||
uploadFileBtn.disabled = v;
|
||||
}
|
||||
|
||||
function doUpload(file, isImage) {
|
||||
if (isImage) {
|
||||
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;
|
||||
}
|
||||
} else {
|
||||
if (file.size > 5 * 1024 * 1024) {
|
||||
status.textContent = 'File too large (max 5 MB)';
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
status.textContent = 'Uploading\u2026';
|
||||
setButtonsDisabled(true);
|
||||
var fd = new FormData();
|
||||
fd.append('file', file);
|
||||
fd.append('csrf_token', getCsrfToken());
|
||||
var endpoint = isImage ? '/admin/upload' : '/admin/upload-file';
|
||||
|
||||
fetch(endpoint, { method: 'POST', body: fd, credentials: 'same-origin' })
|
||||
.then(function(res) { return res.json(); })
|
||||
.then(function(data) {
|
||||
setButtonsDisabled(false);
|
||||
if (data.error) {
|
||||
status.textContent = 'Error: ' + data.error;
|
||||
return;
|
||||
}
|
||||
insertAtCursor(data.markdown);
|
||||
status.textContent = 'Uploaded';
|
||||
setTimeout(function() { status.textContent = ''; }, 3000);
|
||||
})
|
||||
.catch(function() {
|
||||
setButtonsDisabled(false);
|
||||
status.textContent = 'Upload failed';
|
||||
});
|
||||
}
|
||||
|
||||
function insertAtCursor(text) {
|
||||
var start = textarea.selectionStart;
|
||||
var end = textarea.selectionEnd;
|
||||
@@ -218,16 +163,17 @@
|
||||
textarea.focus();
|
||||
}
|
||||
|
||||
uploadImgBtn.addEventListener('click', function() { imgInput.click(); });
|
||||
uploadFileBtn.addEventListener('click', function() { fileInput.click(); });
|
||||
|
||||
imgInput.addEventListener('change', function() {
|
||||
if (imgInput.files.length > 0) doUpload(imgInput.files[0], true);
|
||||
imgInput.value = '';
|
||||
});
|
||||
fileInput.addEventListener('change', function() {
|
||||
if (fileInput.files.length > 0) doUpload(fileInput.files[0], false);
|
||||
fileInput.value = '';
|
||||
var uploader = window.GlimmerUpload.init({
|
||||
imgBtn: document.getElementById('upload-img-btn'),
|
||||
fileBtn: document.getElementById('upload-file-btn'),
|
||||
imgInput: document.getElementById('img-input'),
|
||||
fileInput: document.getElementById('file-input'),
|
||||
statusEl: status,
|
||||
onUploaded: function(data) {
|
||||
insertAtCursor(data.markdown);
|
||||
status.textContent = 'Uploaded';
|
||||
setTimeout(function() { status.textContent = ''; }, 3000);
|
||||
}
|
||||
});
|
||||
|
||||
textarea.addEventListener('paste', function(e) {
|
||||
@@ -235,7 +181,7 @@
|
||||
for (var i = 0; i < items.length; i++) {
|
||||
if (items[i].type.indexOf('image') !== -1) {
|
||||
e.preventDefault();
|
||||
doUpload(items[i].getAsFile(), true);
|
||||
uploader.doUpload(items[i].getAsFile(), true);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -38,8 +38,8 @@
|
||||
<p>{{len .Uploads}} files</p>
|
||||
</hgroup>
|
||||
<div class="upload-controls">
|
||||
<button type="button" id="upload-img-btn" class="btn-sm">Upload Image</button>
|
||||
<button type="button" id="upload-file-btn" class="btn-sm outline">Upload File</button>
|
||||
<button type="button" id="upload-img-btn" class="btn-sm" title="PNG, JPEG, GIF, WebP — up to 50 MB">Upload Image <small style="opacity:.7">(50 MB)</small></button>
|
||||
<button type="button" id="upload-file-btn" class="btn-sm outline" title="Any file type — up to 5 MB">Upload File <small style="opacity:.7">(5 MB)</small></button>
|
||||
<input type="file" id="img-input" accept="image/png,image/jpeg,image/gif,image/webp" style="display:none">
|
||||
<input type="file" id="file-input" style="display:none">
|
||||
<small id="upload-status"></small>
|
||||
@@ -65,13 +65,19 @@
|
||||
{{else}}<a href="{{.URL}}" target="_blank" style="font-size:1.5rem" title="Download file">📄</a>
|
||||
{{end}}
|
||||
</td>
|
||||
<td><code style="font-size:0.75rem">{{.Filename}}</code></td>
|
||||
<td>
|
||||
<div style="display:flex;align-items:center;gap:.4rem;flex-wrap:wrap">
|
||||
<span class="ext-chip">{{.Ext}}</span>
|
||||
{{if .OriginalName}}<span style="font-size:0.85rem">{{.OriginalName}}</span>{{end}}
|
||||
</div>
|
||||
<code style="font-size:0.7rem;opacity:.6">{{.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}}', {{.IsImage}}, this)">Copy</button>
|
||||
<button type="button" class="outline btn-sm" onclick="copyMarkdown('{{.Filename}}', {{.IsImage}}, {{.OriginalName}}, 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 file?')" style="margin:0">
|
||||
<input type="hidden" name="csrf_token" value="{{$.CSRFToken}}">
|
||||
@@ -115,17 +121,14 @@
|
||||
</article>
|
||||
</dialog>
|
||||
|
||||
<script src="/static/upload.js"></script>
|
||||
<script>
|
||||
var currentResizeFile = '';
|
||||
|
||||
function getCsrfToken() {
|
||||
var match = document.cookie.match(/(?:^|;\s*)csrf=([^;]+)/);
|
||||
return match ? match[1] : '';
|
||||
}
|
||||
|
||||
function copyMarkdown(filename, isImage, btn) {
|
||||
function copyMarkdown(filename, isImage, originalName, btn) {
|
||||
var url = '/uploads/' + filename;
|
||||
var md = isImage ? '' : '[' + filename + '](' + url + ')';
|
||||
var label = originalName || filename;
|
||||
var md = isImage ? '' : '[' + label + '](' + url + ')';
|
||||
navigator.clipboard.writeText(md).then(function() {
|
||||
var orig = btn.textContent;
|
||||
btn.textContent = 'Copied!';
|
||||
@@ -135,7 +138,7 @@
|
||||
|
||||
function openResize(filename, w, h) {
|
||||
currentResizeFile = filename;
|
||||
document.getElementById('resize-current').textContent = 'Current: ' + w + '\u00d7' + h;
|
||||
document.getElementById('resize-current').textContent = 'Current: ' + w + '×' + h;
|
||||
document.getElementById('resize-status').textContent = '';
|
||||
document.getElementById('resize-confirm').disabled = false;
|
||||
document.getElementById('resize-dialog').showModal();
|
||||
@@ -145,11 +148,11 @@
|
||||
var dim = document.getElementById('resize-dim').value;
|
||||
var status = document.getElementById('resize-status');
|
||||
var btn = this;
|
||||
status.textContent = 'Resizing\u2026';
|
||||
status.textContent = 'Resizing…';
|
||||
btn.disabled = true;
|
||||
|
||||
var fd = new FormData();
|
||||
fd.append('csrf_token', getCsrfToken());
|
||||
fd.append('csrf_token', window.GlimmerUpload.getCsrfToken());
|
||||
fd.append('max_dim', dim);
|
||||
|
||||
fetch('/admin/uploads/resize/' + currentResizeFile, { method: 'POST', body: fd, credentials: 'same-origin' })
|
||||
@@ -163,9 +166,8 @@
|
||||
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
|
||||
if (dimEl) dimEl.textContent = data.width + '×' + data.height;
|
||||
status.textContent = 'Done — ' + data.size_human;
|
||||
var imgs = document.querySelectorAll('img[src="/uploads/' + currentResizeFile + '"]');
|
||||
imgs.forEach(function(img) { img.src = '/uploads/' + currentResizeFile + '?t=' + Date.now(); });
|
||||
})
|
||||
@@ -175,65 +177,14 @@
|
||||
});
|
||||
});
|
||||
|
||||
// Upload buttons
|
||||
var uploadImgBtn = document.getElementById('upload-img-btn');
|
||||
var uploadFileBtn = document.getElementById('upload-file-btn');
|
||||
var imgInput = document.getElementById('img-input');
|
||||
var fileInput = document.getElementById('file-input');
|
||||
var uploadStatus = document.getElementById('upload-status');
|
||||
|
||||
uploadImgBtn.addEventListener('click', function() { imgInput.click(); });
|
||||
uploadFileBtn.addEventListener('click', function() { fileInput.click(); });
|
||||
|
||||
imgInput.addEventListener('change', function() {
|
||||
if (imgInput.files.length > 0) doUpload(imgInput.files[0], true);
|
||||
imgInput.value = '';
|
||||
window.GlimmerUpload.init({
|
||||
imgBtn: document.getElementById('upload-img-btn'),
|
||||
fileBtn: document.getElementById('upload-file-btn'),
|
||||
imgInput: document.getElementById('img-input'),
|
||||
fileInput: document.getElementById('file-input'),
|
||||
statusEl: document.getElementById('upload-status'),
|
||||
onUploaded: function() { location.reload(); }
|
||||
});
|
||||
fileInput.addEventListener('change', function() {
|
||||
if (fileInput.files.length > 0) doUpload(fileInput.files[0], false);
|
||||
fileInput.value = '';
|
||||
});
|
||||
|
||||
function doUpload(file, isImage) {
|
||||
if (isImage) {
|
||||
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;
|
||||
}
|
||||
} else {
|
||||
if (file.size > 5 * 1024 * 1024) {
|
||||
uploadStatus.textContent = 'File too large (max 5 MB)';
|
||||
return;
|
||||
}
|
||||
}
|
||||
uploadStatus.textContent = 'Uploading\u2026';
|
||||
uploadImgBtn.disabled = true;
|
||||
uploadFileBtn.disabled = true;
|
||||
var fd = new FormData();
|
||||
fd.append('file', file);
|
||||
fd.append('csrf_token', getCsrfToken());
|
||||
var endpoint = isImage ? '/admin/upload' : '/admin/upload-file';
|
||||
fetch(endpoint, { method: 'POST', body: fd, credentials: 'same-origin' })
|
||||
.then(function(r) { return r.json(); })
|
||||
.then(function(data) {
|
||||
uploadImgBtn.disabled = false;
|
||||
uploadFileBtn.disabled = false;
|
||||
if (data.error) {
|
||||
uploadStatus.textContent = 'Error: ' + data.error;
|
||||
} else {
|
||||
location.reload();
|
||||
}
|
||||
})
|
||||
.catch(function() {
|
||||
uploadImgBtn.disabled = false;
|
||||
uploadFileBtn.disabled = false;
|
||||
uploadStatus.textContent = 'Upload failed';
|
||||
});
|
||||
}
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
Reference in new issue
Block a user