Compare commits

...
5 Commits
Author SHA1 Message Date
puttaalu a7f2afc3ad Add a /manage page to edit, delete and restore posts
A new auth-gated web UI at /manage lists every post for inline editing of
caption, date and tags, with per-row and bulk delete and bulk tag add/remove.
It is backed by a small JSON API (all behind the same htpasswd Basic auth as
/upload, and unlinked from the public site):

  GET  /api/photos        list posts (newest first)
  POST /api/edit          rewrite one sidecar (caption, date, tags)
  POST /api/tags          bulk add/remove tags across posts
  POST /api/delete        move posts to content/.trash/ (reversible)
  GET  /api/trash         list trashed items
  POST /api/restore       move a trashed item back (409 on live-slug clash)
  POST /api/trash/empty   hard delete trashed items (id… or all=1)

Design notes:
- Editing only rewrites the .toml; the slug (and URL) never changes.
- Delete is reversible: image + sidecar move to content/.trash/ with a
  timestamp suffix, excluded from the site (loadPhotos skips dirs). The only
  hard delete is emptying the trash.
- Build now prunes: it drops the derived HTML trees (photo/ day/ album/ page/
  grid/page/) and regenerates them, and pruneRenditions removes orphaned
  images/thumbs/medium/og. Without this a deleted post would linger at its old
  URL and on stale day/album pages; this also cleans up after a hand-removed
  sidecar.
- Sidecars are written atomically (temp + rename) so a concurrent build never
  observes a half-written file.
- Slugs and trash ids are validated as bare filenames, closing path traversal
  and dotfile access.
- Every state-changing POST passes a sameOrigin (CSRF) check, since Basic-auth
  credentials are replayed by the browser on every request to the host. It
  honours Sec-Fetch-Site, falls back to Origin vs base-url/Host, and allows
  header-less non-browser clients. Ported from the independent /manage on
  plex/trunk-ng.

module.nix proxies /manage and /api/ to the app (nginx otherwise serves them
as missing static files). The apps are unchanged; the API is there for them to
adopt edit/delete later.
2026-10-18 21:52:11 +02:00
puttaalu 434d2437bf Move upload auth from nginx into the app
Add HTTP Basic auth on /upload, reading an Apache htpasswd file (bcrypt
only, `htpasswd -B`) via a new -htpasswd flag. This lets nginx drop to a
plain TLS-terminating reverse proxy with no auth of its own; the existing
bcrypt htpasswd file is reused unchanged.

auth.go:
- LoadHtpasswd parses user:hash lines, keeps bcrypt entries ($2a/$2b/$2y,
  so Apache's $2y$ works), skips MD5/SHA/crypt with a warning.
- Unknown users still pay for one bcrypt comparison against a dummy hash,
  so response timing can't enumerate valid usernames.
- Failed attempts draw from a token-bucket limiter (x/time/rate, ~1/s,
  burst 10) returning 429 once drained; successful and bulk uploads never
  touch it.

server.go guards both /upload routes (nil authenticator = passthrough for
local --serve). /health stays open. Empty -htpasswd disables auth and logs
a warning.

module.nix: new top-level services.photogallery.htpasswdFile, delivered to
the service via systemd LoadCredential (so a root-owned 0400 secret works).
Removed nginx.htpasswdFile and basic_auth from the vhost.

Both uploader apps already send Basic credentials, so no client change.

Deps: golang.org/x/crypto/bcrypt, golang.org/x/time/rate (vendorHash bump).
2026-10-18 14:45:33 +02:00
puttaalu 3291ed67d5 shorten the text for RSS feed link 2026-10-18 13:35:10 +02:00
puttaalu faa1e01c59 Add a tags field to the Android and desktop uploaders
Each photo card gains a free-text tags input, sent as a raw
comma-separated `tags` form field on upload. The server normalizes it
(parseTags), so the clients stay dumb — no tag parsing on-device.

- Android: PickedItem.tags + setTags; threaded through UploadQueue →
  UploadWorker → UploadClient's multipart.
- Desktop: a tags QLineEdit per PhotoItemWidget; UploadClient.upload sends
  it.
2026-10-08 16:19:25 +02:00
puttaalu a42abfab48 Add albums: group photos by free-text tags
An album is a tag. Photos carry lowercase free-text tags in their .toml
sidecar (`tags = [...]`), parallel to the existing day grouping — no
database, all derived at build time.

- albums.go: parseTags (lowercase/trim/dedupe, slug via sanitiseSlug),
  groupByTag mirroring groupByDay, and rendering for album pages, the
  index, and the JSON API. Slug collisions between distinct names are
  suffixed and logged.
- Routes: /album/<slug>/ (paginated square grid per tag), /albums/ (index
  with counts), /tags.json (machine-readable tag list, served statically
  like feed.xml).
- POST /upload gains a `tags` field written into the sidecar; the web
  upload form gains a tags input.
- Tags shown on each photo page linking to their album; an Albums link in
  the timeline/grid header.
2026-10-08 16:14:09 +02:00
34 changed files with 2304 additions and 40 deletions

No files matched your search

+97 -9
View File
@@ -19,13 +19,76 @@ The binary does three things at once:
- Serves a multipart upload API at `POST /upload` - Serves a multipart upload API at `POST /upload`
- In dev mode (`--serve`), also serves `public/` as static files - In dev mode (`--serve`), also serves `public/` as static files
Routes: `GET /upload` (HTML upload form), `POST /upload` (multipart), `GET /health`. Routes: `GET /upload` (HTML upload form), `POST /upload` (multipart),
`GET /manage` (edit/delete UI), the manage API under `/api/` (see Manage),
`GET /health`. Every route except `/health` is gated by HTTP Basic auth when
`-htpasswd` is set (see Auth).
In production nginx sits in front: serves `public/` directly, proxies `/upload` to localhost, htpasswd on the upload endpoint. Note `/health` is **not** proxied — nginx only forwards `location /upload`, so anything outside the box can only reach `/upload`. In production nginx sits in front: serves `public/` directly, proxies the
dynamic endpoints (`/upload`, `/manage`, `/api/`) to localhost, terminates TLS.
Auth is **no longer nginx's job** — the app checks credentials itself
(`auth.go`), so the nginx vhost just proxies. `/health` is **not** proxied, so
only `/upload`, `/manage` and `/api/` are reachable from outside the box;
anything new the app serves needs a matching `location` in `module.nix` or
nginx will 404 it as a missing static file.
## Auth
`-htpasswd <file>` points at an Apache htpasswd file — **bcrypt only**, generate
with `htpasswd -B`. Each `POST /upload` and `GET /upload` then needs HTTP Basic
credentials matching a line in that file; `GET /health` stays open. `$2y$`
(Apache) and `$2a$`/`$2b$` hashes are all accepted; non-bcrypt lines (MD5
`$apr1$`, SHA, crypt) are skipped with a warning. Empty `-htpasswd` disables
auth entirely (dev default) and logs a warning — `/upload` is then open.
Verification lives in `auth.go`: unknown users still pay for one bcrypt
comparison (against a dummy hash) so timing can't enumerate usernames, and
**failed** attempts draw from a token-bucket limiter (`golang.org/x/time/rate`,
~1/s, burst 10) that returns `429` once drained — successful and bulk uploads
never touch it. Both apps (Android, Qt desktop) already send Basic auth, so no
client change was needed. Deps: `golang.org/x/crypto/bcrypt`, `golang.org/x/time/rate`.
## Manage (edit / delete)
`GET /manage` is an auth-gated web page (`templates/manage.html`) for editing
and deleting posts; it is **not linked from the public site** (reach it by URL).
Its API, all behind the same Basic auth and handled in `manage.go`:
- `GET /api/photos` — every post as JSON (`slug, caption, date, tags, thumb, url`), newest first.
- `POST /api/edit` — rewrite one post's sidecar (`slug, caption, date, tags`). The slug (and URL) never changes; editing only touches the `.toml`.
- `POST /api/tags` — bulk add/remove tags across posts (`slugs` CSV + `add`/`remove` CSV), leaving each post's caption and date intact.
- `POST /api/delete` — move posts (`slug` repeated, or `slugs` CSV) to `content/.trash/` (timestamp-suffixed, reversible), **not** a hard delete.
- `GET /api/trash` — list trashed items (`id` = `<slug>.<stamp>`, `slug`, `deletedAt`, `image`, `hasMeta`), newest first.
- `POST /api/restore` — move a trashed item (`id`) back to `content/`, stripping the timestamp. Refuses with `409` if a live post already holds that slug.
- `POST /api/trash/empty` — **hard delete** trashed items: specific `id`s (repeated), or everything with `all=1`. The only non-reversible delete in the system.
The manage page has a Trash panel (header toggle) for restore / delete-forever /
empty. `trash.go` handles these; filenames parse as `<slug>.<stamp><ext>` (slug
is dot-free and the stamp is a fixed `20060102-150405`, so parts peel off
unambiguously), and `id`s are validated the same way to block traversal.
Each non-trash mutation triggers the same async rebuild as upload. Sidecars are written
atomically (temp + rename) so a concurrent build never sees a half-written
file. Slugs are validated (`resolveSlug`: bare filename only, must name an
existing content image) which closes path traversal and dotfile access.
Every state-changing POST (`edit`, `delete`, `tags`, `restore`, `trash/empty`)
first passes `sameOrigin` (`server.go`): because Basic-auth credentials are
replayed by the browser on every request to the host, a cross-site page could
otherwise drive a logged-in user into a delete (CSRF). The check honours
`Sec-Fetch-Site`, falls back to comparing `Origin` against `-base-url`/`Host`,
and allows header-less non-browser clients (curl). Cross-site → `403`. (Ported
from the independent `/manage` on `plex/trunk-ng`.)
**Delete relies on `Build`'s prune step** (`generator.go`): a rebuild drops the
derived HTML trees (`photo/ day/ album/ page/ grid/page/`) and regenerates them,
and `pruneRenditions` removes `images|thumbs|medium|og` files with no backing
photo. Without this a deleted post would linger at its old URL and in stale
day/album pages. This also cleans up after a sidecar removed by hand.
## Stack ## Stack
- **Go** — stdlib + `BurntSushi/toml`, `fsnotify/fsnotify`, `golang.org/x/image` - **Go** — stdlib + `BurntSushi/toml`, `fsnotify/fsnotify`, `golang.org/x/image`, `golang.org/x/crypto` (bcrypt), `golang.org/x/time` (rate)
- **Templates** — `html/template`, embedded via `embed.FS` - **Templates** — `html/template`, embedded via `embed.FS`
- **Images** — four renditions per photo: original copy, 600×600 centre-cropped square thumbnail, a 1600px-longest-side "medium" for the detail page, and a 1200px "og" for link previews. Catmull-Rom resize. Outputs are skipped when newer than the source. - **Images** — four renditions per photo: original copy, 600×600 centre-cropped square thumbnail, a 1600px-longest-side "medium" for the detail page, and a 1200px "og" for link previews. Catmull-Rom resize. Outputs are skipped when newer than the source.
- **Feed** — Atom (`encoding/xml`) - **Feed** — Atom (`encoding/xml`)
@@ -36,10 +99,15 @@ In production nginx sits in front: serves `public/` directly, proxies `/upload`
```toml ```toml
caption = "Tempelhof at sunrise" caption = "Tempelhof at sunrise"
date = "2026-06-14" date = "2026-06-14"
tags = ["berlin", "sunrise"]
``` ```
Missing sidecar → filename as caption, today as date. Photos sort newest first by that date. Missing sidecar → filename as caption, today as date. Photos sort newest first by that date.
`tags` is optional, free-text, and defines albums (see below). Tags are
normalized to lowercase on load/upload (`parseTags` in `albums.go`); a tag may
contain spaces (`"berlin trip"`), and its URL slug is derived with `sanitiseSlug`.
## Design ## Design
- Gruvbox dark hard colour scheme - Gruvbox dark hard colour scheme
@@ -51,6 +119,18 @@ Missing sidecar → filename as caption, today as date. Photos sort newest first
- Each timeline date heading links to a **single-day page** (`/day/<YYYY-MM-DD>/`) holding just that day's photos. `renderDayPages` writes one per `groupByDay` run; the ISO label doubles as the URL slug. - Each timeline date heading links to a **single-day page** (`/day/<YYYY-MM-DD>/`) holding just that day's photos. `renderDayPages` writes one per `groupByDay` run; the ISO label doubles as the URL slug.
- Single photo page with sidebar and newer/older navigation - Single photo page with sidebar and newer/older navigation
### Albums (tags)
A second grouping axis, parallel to days: an album is just a tag (`albums.go`).
`groupByTag` mirrors `groupByDay`, and `renderAlbumPages` writes a paginated
square-grid album per tag at `/album/<slug>/` (like the grid view). `/albums/`
is the index of every tag with counts; `/tags.json` is the machine-readable tag
list (`[{tag, slug, count}]`, served statically like `feed.xml`). Tags show on
each photo page and link to their album; an **Albums** link sits in the
timeline/grid header. Tags are assigned at upload via the `tags` field on
`POST /upload` (comma-separated) or by editing a sidecar's `tags`. All derived at
build time — no database.
### Link previews ### Link previews
Photo pages carry Open Graph + Twitter-card meta tags so a shared link unfurls Photo pages carry Open Graph + Twitter-card meta tags so a shared link unfurls
@@ -119,10 +199,12 @@ inputs.photogallery.nixosModules.default
services.photogallery = { services.photogallery = {
enable = true; enable = true;
baseURL = "https://photos.yourdomain.tld"; baseURL = "https://photos.yourdomain.tld";
# bcrypt htpasswd (`htpasswd -B`); handed to the service via LoadCredential,
# so a root-owned 0400 secret is fine. Omit to leave /upload open.
htpasswdFile = "/run/secrets/photogallery-htpasswd";
nginx = { nginx = {
enable = true; enable = true;
domain = "photos.yourdomain.tld"; domain = "photos.yourdomain.tld";
htpasswdFile = "/etc/nginx/.htpasswd-gallery";
}; };
}; };
``` ```
@@ -142,12 +224,19 @@ nix build # succeeds
|---|---| |---|---|
| `main.go` | Flags, wires generator + watcher + server | | `main.go` | Flags, wires generator + watcher + server |
| `generator.go` | Scans content dir, renders HTML + Atom feed, generates thumbs/mediums | | `generator.go` | Scans content dir, renders HTML + Atom feed, generates thumbs/mediums |
| `albums.go` | Tag parsing/normalization, `groupByTag`, album pages + `/albums/` + `/tags.json` |
| `server.go` | Upload API + optional static file serving | | `server.go` | Upload API + optional static file serving |
| `auth.go` | htpasswd (bcrypt) HTTP Basic auth + failed-attempt rate limit for `/upload` |
| `manage.go` | Edit/delete API (`/api/photos`, `/api/edit`, `/api/tags`, `/api/delete`) + trash move + atomic sidecar writes |
| `trash.go` | Trash API: list (`/api/trash`), `/api/restore`, `/api/trash/empty` (hard delete) |
| `templates/manage.html` | Auth-gated edit/delete web UI at `/manage`, with a Trash panel |
| `watcher.go` | fsnotify watcher with 500ms debounce | | `watcher.go` | fsnotify watcher with 500ms debounce |
| `assets.go` | `//go:embed` for templates and static | | `assets.go` | `//go:embed` for templates and static |
| `templates/timeline.html` | Site root: photos grouped by day, paginated | | `templates/timeline.html` | Site root: photos grouped by day, paginated |
| `templates/grid.html` | Flat square grid at `/grid/`, paginated | | `templates/grid.html` | Flat square grid at `/grid/`, paginated |
| `templates/day.html` | Single-day page at `/day/<date>/` | | `templates/day.html` | Single-day page at `/day/<date>/` |
| `templates/album.html` | Album (tag) page at `/album/<slug>/`, paginated |
| `templates/albums.html` | Album index at `/albums/` |
| `templates/photo.html` | Single photo page, neighbour links and prefetch | | `templates/photo.html` | Single photo page, neighbour links and prefetch |
| `static/photo-nav.js` | Arrow-key and swipe navigation | | `static/photo-nav.js` | Arrow-key and swipe navigation |
| `module.nix` | NixOS module (systemd service, tmpfiles, nginx vhost) | | `module.nix` | NixOS module (systemd service, tmpfiles, nginx vhost) |
@@ -161,8 +250,7 @@ nix build # succeeds
## What's not done yet ## What's not done yet
- ActivityPub federation (planned later — start with RSS/Atom) - ActivityPub federation (planned later — start with RSS/Atom)
- Multi-image upload - Edit/delete/trash in the Android and Qt apps (web `/manage` only so far; the `/api/` endpoints are there for the apps to adopt)
- Delete/edit via UI - Any auth beyond the app's htpasswd Basic auth (no sessions, no per-user scopes)
- Any auth beyond nginx htpasswd
- The Android app has never been run on real hardware - The Android app has never been run on real hardware
- Photo-page swipe has never been tested on a real touchscreen; the iOS Safari edge-gesture interaction is the untested part - Photo-page swipe has never been tested on a real touchscreen; the iOS Safari edge-gesture interaction is the untested part
+204
View File
@@ -0,0 +1,204 @@
package main
import (
"encoding/json"
"log"
"os"
"path/filepath"
"sort"
"strconv"
"strings"
"time"
)
// Tag is a normalized album tag: a lowercase free-text Name and its URL Slug.
type Tag struct {
Name string
Slug string
}
// Album is all photos sharing one tag, newest first.
type Album struct {
Tag Tag
Count int
Photos []Photo
}
// parseTags normalizes raw tag strings into unique Tags. Each input may itself
// be comma-separated (as typed in the upload form), so entries are split on
// commas, lowercased, trimmed, de-duplicated by name, and given a URL slug via
// sanitiseSlug. Entries that are empty or slug to nothing are dropped.
func parseTags(raw ...string) []Tag {
var tags []Tag
seen := map[string]bool{}
for _, entry := range raw {
for _, part := range strings.Split(entry, ",") {
name := strings.ToLower(strings.TrimSpace(part))
if name == "" || seen[name] {
continue
}
slug := sanitiseSlug(name)
if slug == "" {
continue
}
seen[name] = true
tags = append(tags, Tag{Name: name, Slug: slug})
}
}
return tags
}
// groupByTag collapses photos (already sorted newest first) into one Album per
// distinct tag name, preserving photo order within each album. Albums are
// returned sorted alphabetically by tag name. If two different names produce the
// same URL slug, the later one is suffixed (-2, -3, …) and a warning is logged,
// so album URLs stay unique.
func groupByTag(photos []Photo) []Album {
byName := map[string][]Photo{}
for _, p := range photos {
for _, t := range p.Tags {
byName[t.Name] = append(byName[t.Name], p)
}
}
names := make([]string, 0, len(byName))
for name := range byName {
names = append(names, name)
}
sort.Strings(names)
slugOwner := map[string]string{}
albums := make([]Album, 0, len(names))
for _, name := range names {
slug := sanitiseSlug(name)
if owner, taken := slugOwner[slug]; taken && owner != name {
base := slug
for n := 2; ; n++ {
cand := base + "-" + strconv.Itoa(n)
if _, t := slugOwner[cand]; !t {
slug = cand
break
}
}
log.Printf("album slug collision: %q and %q both slug to %q; using %q for the latter",
owner, name, base, slug)
}
slugOwner[slug] = name
ps := byName[name]
albums = append(albums, Album{
Tag: Tag{Name: name, Slug: slug},
Count: len(ps),
Photos: ps,
})
}
return albums
}
// baseData returns the profile-header and site-wide fields every page template
// expects, so the album templates stay in step with the others.
func (g *Generator) baseData() map[string]any {
return map[string]any{
"BaseURL": g.baseURL,
"Year": time.Now().Year(),
"Author": g.author,
"Handle": g.handle,
"Bio": g.bio,
"BioAlt": g.bioAlt,
"Initial": g.initial(),
"FontsURL": g.fontsURL,
"SerifFamily": g.serifFamily,
"MlFamily": g.mlFamily,
}
}
// renderAlbumPages writes one paginated album per tag under public/album/<slug>/,
// a flat square grid like the grid view. total is the site-wide photo count, for
// the profile header.
func (g *Generator) renderAlbumPages(albums []Album, total int) error {
for _, al := range albums {
albumDir := filepath.Join(g.outputDir, "album", al.Tag.Slug)
if err := os.MkdirAll(albumDir, 0755); err != nil {
return err
}
base := "/album/" + al.Tag.Slug + "/"
totalPages := (al.Count + g.pageSize - 1) / g.pageSize
if totalPages == 0 {
totalPages = 1
}
for i := 0; i < totalPages; i++ {
start := i * g.pageSize
end := start + g.pageSize
if end > al.Count {
end = al.Count
}
dst := filepath.Join(albumDir, "index.html")
if i > 0 {
dir := filepath.Join(albumDir, "page", strconv.Itoa(i+1))
if err := os.MkdirAll(dir, 0755); err != nil {
return err
}
dst = filepath.Join(dir, "index.html")
}
prev := ""
next := ""
switch i {
case 0:
// no prev
case 1:
prev = base
default:
prev = base + "page/" + strconv.Itoa(i) + "/"
}
if i+1 < totalPages {
next = base + "page/" + strconv.Itoa(i+2) + "/"
}
data := g.baseData()
data["Tag"] = al.Tag
data["Count"] = al.Count
data["Photos"] = al.Photos[start:end]
data["Total"] = total
data["Page"] = i + 1
data["TotalPages"] = totalPages
data["PrevURL"] = prev
data["NextURL"] = next
if err := g.render("album.html", dst, data); err != nil {
return err
}
}
}
return nil
}
// renderAlbumsIndex writes public/albums/index.html — every tag with its count,
// linking to each album.
func (g *Generator) renderAlbumsIndex(albums []Album, total int) error {
data := g.baseData()
data["Albums"] = albums
data["Total"] = total
return g.render("albums.html", filepath.Join(g.outputDir, "albums", "index.html"), data)
}
type tagJSON struct {
Tag string `json:"tag"`
Slug string `json:"slug"`
Count int `json:"count"`
}
// renderTagsJSON writes public/tags.json — the machine-readable tag list, served
// statically like feed.xml.
func (g *Generator) renderTagsJSON(albums []Album) error {
out := make([]tagJSON, 0, len(albums))
for _, a := range albums {
out = append(out, tagJSON{Tag: a.Tag.Name, Slug: a.Tag.Slug, Count: a.Count})
}
b, err := json.MarshalIndent(out, "", " ")
if err != nil {
return err
}
return os.WriteFile(filepath.Join(g.outputDir, "tags.json"), b, 0644)
}
@@ -81,6 +81,7 @@ class MainActivity : ComponentActivity() {
) )
}, },
onCaptionChange = viewModel::setCaption, onCaptionChange = viewModel::setCaption,
onTagsChange = viewModel::setTags,
onDateChange = viewModel::setDate, onDateChange = viewModel::setDate,
onRemove = viewModel::removeItem, onRemove = viewModel::removeItem,
onSubmit = viewModel::submit, onSubmit = viewModel::submit,
@@ -60,6 +60,7 @@ class UploadClient(
fileName: String, fileName: String,
caption: String, caption: String,
date: String, date: String,
tags: String,
): UploadOutcome { ): UploadOutcome {
val mediaType = if (fileName.endsWith(".png", ignoreCase = true)) { val mediaType = if (fileName.endsWith(".png", ignoreCase = true)) {
"image/png".toMediaType() "image/png".toMediaType()
@@ -72,6 +73,7 @@ class UploadClient(
.addFormDataPart("image", fileName, file.asRequestBody(mediaType)) .addFormDataPart("image", fileName, file.asRequestBody(mediaType))
.addFormDataPart("caption", caption) .addFormDataPart("caption", caption)
.addFormDataPart("date", date) .addFormDataPart("date", date)
.addFormDataPart("tags", tags)
.build() .build()
val request = Request.Builder() val request = Request.Builder()
@@ -51,6 +51,7 @@ fun PostScreen(
state: PostUiState, state: PostUiState,
onPickImages: () -> Unit, onPickImages: () -> Unit,
onCaptionChange: (id: String, value: String) -> Unit, onCaptionChange: (id: String, value: String) -> Unit,
onTagsChange: (id: String, value: String) -> Unit,
onDateChange: (id: String, value: LocalDate) -> Unit, onDateChange: (id: String, value: LocalDate) -> Unit,
onRemove: (id: String) -> Unit, onRemove: (id: String) -> Unit,
onSubmit: () -> Unit, onSubmit: () -> Unit,
@@ -107,6 +108,7 @@ fun PostScreen(
ItemCard( ItemCard(
item = item, item = item,
onCaptionChange = { onCaptionChange(item.id, it) }, onCaptionChange = { onCaptionChange(item.id, it) },
onTagsChange = { onTagsChange(item.id, it) },
onEditDate = { dateEditFor = item }, onEditDate = { dateEditFor = item },
onRemove = { onRemove(item.id) }, onRemove = { onRemove(item.id) },
onOpenUrl = onOpenUrl, onOpenUrl = onOpenUrl,
@@ -185,6 +187,7 @@ fun PostScreen(
private fun ItemCard( private fun ItemCard(
item: PickedItem, item: PickedItem,
onCaptionChange: (String) -> Unit, onCaptionChange: (String) -> Unit,
onTagsChange: (String) -> Unit,
onEditDate: () -> Unit, onEditDate: () -> Unit,
onRemove: () -> Unit, onRemove: () -> Unit,
onOpenUrl: (String) -> Unit, onOpenUrl: (String) -> Unit,
@@ -220,6 +223,16 @@ private fun ItemCard(
modifier = Modifier.fillMaxWidth(), modifier = Modifier.fillMaxWidth(),
) )
Spacer(Modifier.height(6.dp)) Spacer(Modifier.height(6.dp))
OutlinedTextField(
value = item.tags,
onValueChange = onTagsChange,
label = { Text("Tags") },
placeholder = { Text("comma-separated") },
singleLine = true,
enabled = item.status !is ItemStatus.Uploading,
modifier = Modifier.fillMaxWidth(),
)
Spacer(Modifier.height(6.dp))
Row(verticalAlignment = Alignment.CenterVertically) { Row(verticalAlignment = Alignment.CenterVertically) {
OutlinedButton( OutlinedButton(
onClick = onEditDate, onClick = onEditDate,
@@ -41,6 +41,7 @@ data class PickedItem(
val source: Uri, val source: Uri,
val preview: Bitmap? = null, val preview: Bitmap? = null,
val caption: String = "", val caption: String = "",
val tags: String = "", // raw comma-separated; the server normalizes
val date: LocalDate = LocalDate.now(), val date: LocalDate = LocalDate.now(),
val status: ItemStatus = ItemStatus.Pending, val status: ItemStatus = ItemStatus.Pending,
) )
@@ -114,6 +115,10 @@ class UploadViewModel(app: Application) : AndroidViewModel(app) {
updateItem(id) { it.copy(caption = value) } updateItem(id) { it.copy(caption = value) }
} }
fun setTags(id: String, value: String) {
updateItem(id) { it.copy(tags = value) }
}
fun setDate(id: String, value: LocalDate) { fun setDate(id: String, value: LocalDate) {
updateItem(id) { it.copy(date = value) } updateItem(id) { it.copy(date = value) }
} }
@@ -159,6 +164,7 @@ class UploadViewModel(app: Application) : AndroidViewModel(app) {
uri = Uri.fromFile(staged), uri = Uri.fromFile(staged),
caption = current.caption, caption = current.caption,
date = current.date, date = current.date,
tags = current.tags,
uniqueSuffix = item.id.take(6), uniqueSuffix = item.id.take(6),
) )
observe(item.id, workId) observe(item.id, workId)
@@ -34,6 +34,7 @@ object UploadQueue {
uri: Uri, uri: Uri,
caption: String, caption: String,
date: LocalDate, date: LocalDate,
tags: String,
uniqueSuffix: String, uniqueSuffix: String,
): UUID { ): UUID {
val slug = LocalDateTime.now().format(SLUG_FORMAT) + "-" + uniqueSuffix val slug = LocalDateTime.now().format(SLUG_FORMAT) + "-" + uniqueSuffix
@@ -45,6 +46,7 @@ object UploadQueue {
.putString(UploadWorker.KEY_SLUG, slug) .putString(UploadWorker.KEY_SLUG, slug)
.putString(UploadWorker.KEY_CAPTION, caption) .putString(UploadWorker.KEY_CAPTION, caption)
.putString(UploadWorker.KEY_DATE, date.format(ISO_DATE)) .putString(UploadWorker.KEY_DATE, date.format(ISO_DATE))
.putString(UploadWorker.KEY_TAGS, tags)
.build(), .build(),
) )
.setConstraints( .setConstraints(
@@ -38,6 +38,7 @@ class UploadWorker(
val slug = inputData.getString(KEY_SLUG) ?: return@withContext Result.failure() val slug = inputData.getString(KEY_SLUG) ?: return@withContext Result.failure()
val caption = inputData.getString(KEY_CAPTION).orEmpty() val caption = inputData.getString(KEY_CAPTION).orEmpty()
val date = inputData.getString(KEY_DATE).orEmpty() val date = inputData.getString(KEY_DATE).orEmpty()
val tags = inputData.getString(KEY_TAGS).orEmpty()
val settings = SettingsStore(applicationContext) val settings = SettingsStore(applicationContext)
if (!settings.isConfigured) { if (!settings.isConfigured) {
@@ -66,6 +67,7 @@ class UploadWorker(
fileName = prepared.file.name, fileName = prepared.file.name,
caption = caption, caption = caption,
date = date, date = date,
tags = tags,
) )
// Keep the staged and prepared copies only while a retry might still // Keep the staged and prepared copies only while a retry might still
@@ -147,6 +149,7 @@ class UploadWorker(
const val KEY_SLUG = "slug" const val KEY_SLUG = "slug"
const val KEY_CAPTION = "caption" const val KEY_CAPTION = "caption"
const val KEY_DATE = "date" const val KEY_DATE = "date"
const val KEY_TAGS = "tags"
const val KEY_RESULT_SLUG = "result_slug" const val KEY_RESULT_SLUG = "result_slug"
const val KEY_RESULT_URL = "result_url" const val KEY_RESULT_URL = "result_url"
+102
View File
@@ -0,0 +1,102 @@
package main
import (
"bufio"
"fmt"
"log"
"net/http"
"os"
"strings"
"golang.org/x/crypto/bcrypt"
"golang.org/x/time/rate"
)
// Authenticator checks HTTP Basic credentials against bcrypt hashes loaded from
// an Apache-style htpasswd file. Only bcrypt entries are supported — generate
// them with `htpasswd -B`. This replaces nginx's basic_auth so the app can run
// behind a plain TLS-terminating reverse proxy with no auth of its own.
type Authenticator struct {
creds map[string][]byte // username -> bcrypt hash
// A single bcrypt comparison runs on every failed lookup so that a request
// for an unknown user costs the same as one for a known user with a wrong
// password, closing a user-enumeration timing side channel.
dummyHash []byte
}
// LoadHtpasswd reads user:hash lines from path. Blank lines and #-comments are
// skipped, as is any entry whose hash is not bcrypt (with a warning). It is an
// error for the file to yield no usable entries.
func LoadHtpasswd(path string) (*Authenticator, error) {
f, err := os.Open(path)
if err != nil {
return nil, err
}
defer f.Close()
a := &Authenticator{creds: make(map[string][]byte)}
sc := bufio.NewScanner(f)
for sc.Scan() {
line := strings.TrimSpace(sc.Text())
if line == "" || strings.HasPrefix(line, "#") {
continue
}
user, hash, ok := strings.Cut(line, ":")
if !ok || user == "" {
continue
}
// bcrypt hashes start $2a$, $2b$ or $2y$; everything else (MD5 $apr1$,
// SHA {SHA}, crypt) is unsupported here.
if !strings.HasPrefix(hash, "$2") {
log.Printf("auth: skipping non-bcrypt entry for %q — regenerate with `htpasswd -B`", user)
continue
}
a.creds[user] = []byte(hash)
}
if err := sc.Err(); err != nil {
return nil, err
}
if len(a.creds) == 0 {
return nil, fmt.Errorf("no bcrypt entries in %s (use `htpasswd -B`)", path)
}
// Cost 10 matches htpasswd -B's default, keeping the dummy comparison the
// same price as a real one.
a.dummyHash, _ = bcrypt.GenerateFromPassword([]byte("dummy"), 10)
return a, nil
}
// check reports whether user/pass matches a stored credential.
func (a *Authenticator) check(user, pass string) bool {
hash, ok := a.creds[user]
if !ok {
// Spend the same time as a real comparison to avoid leaking which
// usernames exist.
bcrypt.CompareHashAndPassword(a.dummyHash, []byte(pass))
return false
}
return bcrypt.CompareHashAndPassword(hash, []byte(pass)) == nil
}
// basicAuth wraps next, demanding valid HTTP Basic credentials. On a failed
// attempt it consumes a token from limiter; once the limiter is exhausted,
// further failures get 429 instead of 401, throttling brute-force guessing.
// The limiter is only touched on failure, so legitimate (even bursty, bulk)
// uploads are never throttled.
func (a *Authenticator) basicAuth(limiter *rate.Limiter, next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
user, pass, ok := r.BasicAuth()
if ok && a.check(user, pass) {
next(w, r)
return
}
if !limiter.Allow() {
http.Error(w, "too many failed attempts", http.StatusTooManyRequests)
return
}
w.Header().Set("WWW-Authenticate", `Basic realm="photog"`)
http.Error(w, "unauthorized", http.StatusUnauthorized)
}
}
+144
View File
@@ -0,0 +1,144 @@
package main
import (
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"testing"
"time"
"golang.org/x/crypto/bcrypt"
"golang.org/x/time/rate"
)
// bcryptHash returns a cost-10 hash of pw, matching `htpasswd -B`'s default.
func bcryptHash(t *testing.T, pw string) string {
t.Helper()
h, err := bcrypt.GenerateFromPassword([]byte(pw), 10)
if err != nil {
t.Fatalf("GenerateFromPassword: %v", err)
}
return string(h)
}
func TestLoadHtpasswdAndCheck(t *testing.T) {
// alice's hash is rewritten to the $2y$ variant that Apache's htpasswd -B
// emits, to prove it is accepted. $2a$ and $2y$ are the same algorithm, so
// swapping the prefix on a valid hash yields a valid hash for the same
// password. bob keeps the $2a$ form.
aliceHash := bcryptHash(t, "s3cret")
if !strings.HasPrefix(aliceHash, "$2a$") {
t.Fatalf("expected $2a$ prefix, got %q", aliceHash[:4])
}
aliceHashY := "$2y$" + strings.TrimPrefix(aliceHash, "$2a$")
bobHash := bcryptHash(t, "hunter2")
file := filepath.Join(t.TempDir(), "htpasswd")
content := strings.Join([]string{
"# a comment",
"",
"alice:" + aliceHashY,
"bob:" + bobHash,
"legacy:$apr1$abcd$0123456789", // MD5 — must be skipped
}, "\n") + "\n"
if err := os.WriteFile(file, []byte(content), 0600); err != nil {
t.Fatal(err)
}
a, err := LoadHtpasswd(file)
if err != nil {
t.Fatalf("LoadHtpasswd: %v", err)
}
if _, ok := a.creds["legacy"]; ok {
t.Error("MD5 entry should have been skipped")
}
cases := []struct {
user, pass string
want bool
}{
{"alice", "s3cret", true}, // $2y$ accepted
{"bob", "hunter2", true}, // $2a$ accepted
{"alice", "wrong", false}, // wrong password
{"bob", "s3cret", false}, // right password, wrong user
{"nobody", "s3cret", false}, // unknown user
{"legacy", "whatever", false},
}
for _, c := range cases {
if got := a.check(c.user, c.pass); got != c.want {
t.Errorf("check(%q, %q) = %v, want %v", c.user, c.pass, got, c.want)
}
}
}
func TestBasicAuthMiddleware(t *testing.T) {
a := &Authenticator{creds: map[string][]byte{"alice": []byte(bcryptHash(t, "s3cret"))}}
a.dummyHash, _ = bcrypt.GenerateFromPassword([]byte("dummy"), 10)
var reached bool
// Burst of 2 failures before throttling, so the 429 path is reachable.
limiter := rate.NewLimiter(rate.Every(time.Hour), 2)
h := a.basicAuth(limiter, func(w http.ResponseWriter, r *http.Request) {
reached = true
w.WriteHeader(http.StatusCreated)
})
do := func(user, pass string, withCreds bool) *httptest.ResponseRecorder {
reached = false
req := httptest.NewRequest(http.MethodPost, "/upload", nil)
if withCreds {
req.SetBasicAuth(user, pass)
}
rec := httptest.NewRecorder()
h(rec, req)
return rec
}
// Good credentials pass through.
if rec := do("alice", "s3cret", true); rec.Code != http.StatusCreated || !reached {
t.Fatalf("valid creds: code=%d reached=%v", rec.Code, reached)
}
// No credentials → 401 with a challenge.
rec := do("", "", false)
if rec.Code != http.StatusUnauthorized {
t.Fatalf("missing creds: code=%d, want 401", rec.Code)
}
if !strings.HasPrefix(rec.Header().Get("WWW-Authenticate"), "Basic ") {
t.Errorf("missing WWW-Authenticate challenge: %q", rec.Header().Get("WWW-Authenticate"))
}
if reached {
t.Error("handler reached despite missing creds")
}
// Wrong password burns the limiter (burst 2: one above + this one), then
// the next failure is throttled to 429.
if rec := do("alice", "nope", true); rec.Code != http.StatusUnauthorized {
t.Fatalf("wrong pass #2: code=%d, want 401", rec.Code)
}
if rec := do("alice", "nope", true); rec.Code != http.StatusTooManyRequests {
t.Fatalf("wrong pass #3: code=%d, want 429", rec.Code)
}
// A valid request still succeeds while failures are throttled — the
// limiter only gates failures.
if rec := do("alice", "s3cret", true); rec.Code != http.StatusCreated {
t.Fatalf("valid creds under throttle: code=%d, want 201", rec.Code)
}
}
func TestLoadHtpasswdErrors(t *testing.T) {
if _, err := LoadHtpasswd(filepath.Join(t.TempDir(), "does-not-exist")); err == nil {
t.Error("expected error for missing file")
}
empty := filepath.Join(t.TempDir(), "htpasswd")
if err := os.WriteFile(empty, []byte("# only comments\n\nlegacy:$apr1$x$y\n"), 0600); err != nil {
t.Fatal(err)
}
if _, err := LoadHtpasswd(empty); err == nil {
t.Error("expected error when no bcrypt entries are usable")
}
}
+1 -1
View File
@@ -313,7 +313,7 @@ void MainWindow::startItem(PhotoItemWidget *item)
refreshPosting(); refreshPosting();
}); });
client->upload(prepared.filePath, QFileInfo(prepared.filePath).fileName(), client->upload(prepared.filePath, QFileInfo(prepared.filePath).fileName(),
caption, item->date()); caption, item->date(), item->tags());
}); });
watcher->setFuture(QtConcurrent::run([source, cacheDir, slug]() { watcher->setFuture(QtConcurrent::run([source, cacheDir, slug]() {
return ImagePrep::prepare(source, cacheDir, slug); return ImagePrep::prepare(source, cacheDir, slug);
+10
View File
@@ -47,6 +47,10 @@ PhotoItemWidget::PhotoItemWidget(QString sourcePath, QWidget *parent)
m_date->setDisplayFormat(QStringLiteral("yyyy-MM-dd")); m_date->setDisplayFormat(QStringLiteral("yyyy-MM-dd"));
fields->addWidget(m_date); fields->addWidget(m_date);
m_tags = new QLineEdit;
m_tags->setPlaceholderText(QStringLiteral("tags (comma-separated)"));
fields->addWidget(m_tags);
m_statusLabel = new QLabel; m_statusLabel = new QLabel;
m_statusLabel->setOpenExternalLinks(true); m_statusLabel->setOpenExternalLinks(true);
m_statusLabel->setWordWrap(true); m_statusLabel->setWordWrap(true);
@@ -70,6 +74,11 @@ QString PhotoItemWidget::date() const
return m_date->date().toString(QStringLiteral("yyyy-MM-dd")); return m_date->date().toString(QStringLiteral("yyyy-MM-dd"));
} }
QString PhotoItemWidget::tags() const
{
return m_tags->text();
}
void PhotoItemWidget::setStatus(Status status, const QString &message, const QString &url) void PhotoItemWidget::setStatus(Status status, const QString &message, const QString &url)
{ {
m_status = status; m_status = status;
@@ -79,6 +88,7 @@ void PhotoItemWidget::setStatus(Status status, const QString &message, const QSt
const bool editable = status == Status::Pending || status == Status::Error; const bool editable = status == Status::Pending || status == Status::Error;
m_caption->setEnabled(editable); m_caption->setEnabled(editable);
m_date->setEnabled(editable); m_date->setEnabled(editable);
m_tags->setEnabled(editable);
m_remove->setEnabled(status != Status::Preparing && status != Status::Uploading); m_remove->setEnabled(status != Status::Preparing && status != Status::Uploading);
switch (status) { switch (status) {
+2
View File
@@ -21,6 +21,7 @@ public:
QString sourcePath() const { return m_sourcePath; } QString sourcePath() const { return m_sourcePath; }
QString caption() const; QString caption() const;
QString date() const; // yyyy-MM-dd QString date() const; // yyyy-MM-dd
QString tags() const; // raw comma-separated; the server normalizes
Status status() const { return m_status; } Status status() const { return m_status; }
void setStatus(Status status, const QString &message = {}, const QString &url = {}); void setStatus(Status status, const QString &message = {}, const QString &url = {});
@@ -35,6 +36,7 @@ private:
QLabel *m_thumb = nullptr; QLabel *m_thumb = nullptr;
QLineEdit *m_caption = nullptr; QLineEdit *m_caption = nullptr;
QDateEdit *m_date = nullptr; QDateEdit *m_date = nullptr;
QLineEdit *m_tags = nullptr;
QLabel *m_statusLabel = nullptr; QLabel *m_statusLabel = nullptr;
QPushButton *m_remove = nullptr; QPushButton *m_remove = nullptr;
}; };
+2 -1
View File
@@ -26,7 +26,7 @@ QByteArray UploadClient::authHeader() const
} }
void UploadClient::upload(const QString &filePath, const QString &fileName, void UploadClient::upload(const QString &filePath, const QString &fileName,
const QString &caption, const QString &date) const QString &caption, const QString &date, const QString &tags)
{ {
auto *file = new QFile(filePath); auto *file = new QFile(filePath);
if (!file->open(QIODevice::ReadOnly)) { if (!file->open(QIODevice::ReadOnly)) {
@@ -57,6 +57,7 @@ void UploadClient::upload(const QString &filePath, const QString &fileName,
}; };
multiPart->append(textPart(QStringLiteral("caption"), caption)); multiPart->append(textPart(QStringLiteral("caption"), caption));
multiPart->append(textPart(QStringLiteral("date"), date)); multiPart->append(textPart(QStringLiteral("date"), date));
multiPart->append(textPart(QStringLiteral("tags"), tags));
QNetworkRequest request(QUrl(m_base + QStringLiteral("/upload"))); QNetworkRequest request(QUrl(m_base + QStringLiteral("/upload")));
request.setRawHeader("Authorization", authHeader()); request.setRawHeader("Authorization", authHeader());
+1 -1
View File
@@ -29,7 +29,7 @@ public:
// The filename matters: server.go derives the slug from it, so re-sending // The filename matters: server.go derives the slug from it, so re-sending
// the same name overwrites the same post instead of duplicating it. // the same name overwrites the same post instead of duplicating it.
void upload(const QString &filePath, const QString &fileName, void upload(const QString &filePath, const QString &fileName,
const QString &caption, const QString &date); const QString &caption, const QString &date, const QString &tags);
// Credential check via GET /upload (same Basic-auth gate the POST uses). // Credential check via GET /upload (same Basic-auth gate the POST uses).
// /health is not usable: nginx only proxies location /upload. // /health is not usable: nginx only proxies location /upload.
+1 -1
View File
@@ -18,7 +18,7 @@
# Run `go mod tidy` to generate go.sum, then `nix build`. # Run `go mod tidy` to generate go.sum, then `nix build`.
# Nix will fail and print the correct hash — paste it here. # Nix will fail and print the correct hash — paste it here.
vendorHash = "sha256-SxQDRProQtauWXPvPzbZZChLQd0iey9hnXFLiPYTS98="; vendorHash = "sha256-Q+VeDZX9DlZtOZrYRwZo19eyob8jIu19IRhdvChmVL4=";
meta = with pkgs.lib; { meta = with pkgs.lib; {
description = "Minimal static photo gallery"; description = "Minimal static photo gallery";
+63 -3
View File
@@ -41,8 +41,9 @@ var ogQualityLadder = []int{85, 78, 70, 62}
// PhotoMeta is the structure of a .toml sidecar file. // PhotoMeta is the structure of a .toml sidecar file.
type PhotoMeta struct { type PhotoMeta struct {
Caption string `toml:"caption"` Caption string `toml:"caption"`
Date string `toml:"date"` // YYYY-MM-DD Date string `toml:"date"` // YYYY-MM-DD
Tags []string `toml:"tags,omitempty"` // free-text, lowercased; each tag is an album
} }
// Photo is the in-memory representation of one image. // Photo is the in-memory representation of one image.
@@ -56,6 +57,7 @@ type Photo struct {
OGHeight int OGHeight int
Caption string Caption string
Date time.Time Date time.Time
Tags []Tag // albums this photo belongs to
} }
// DayGroup is a run of photos sharing the same calendar day, for the timeline. // DayGroup is a run of photos sharing the same calendar day, for the timeline.
@@ -121,12 +123,30 @@ func (g *Generator) Build() error {
return err return err
} }
for _, d := range []string{"images", "thumbs", "medium", "og", "photo", "grid", "day", "static"} { // Drop fully-derived HTML trees before regenerating them, so a deleted
// post, a retag or a changed date leaves no orphaned page behind. These are
// cheap to rewrite (no up-to-date skipping applies to HTML), unlike the
// image renditions, which are pruned by slug just below.
for _, d := range []string{"photo", "day", "album", "page"} {
if err := os.RemoveAll(filepath.Join(g.outputDir, d)); err != nil {
return err
}
}
if err := os.RemoveAll(filepath.Join(g.outputDir, "grid", "page")); err != nil {
return err
}
for _, d := range []string{"images", "thumbs", "medium", "og", "photo", "grid", "day", "album", "albums", "static"} {
if err := os.MkdirAll(filepath.Join(g.outputDir, d), 0755); err != nil { if err := os.MkdirAll(filepath.Join(g.outputDir, d), 0755); err != nil {
return err return err
} }
} }
// Remove rendition files whose source photo is gone (e.g. after a delete),
// keeping the expensive resize outputs of surviving photos in place so
// up-to-date skipping still works.
g.pruneRenditions(photos)
for i := range photos { for i := range photos {
if err := g.processImage(&photos[i]); err != nil { if err := g.processImage(&photos[i]); err != nil {
log.Printf("processImage %s: %v", photos[i].Slug, err) log.Printf("processImage %s: %v", photos[i].Slug, err)
@@ -142,6 +162,16 @@ func (g *Generator) Build() error {
if err := g.renderDayPages(photos); err != nil { if err := g.renderDayPages(photos); err != nil {
return err return err
} }
albums := groupByTag(photos)
if err := g.renderAlbumPages(albums, len(photos)); err != nil {
return err
}
if err := g.renderAlbumsIndex(albums, len(photos)); err != nil {
return err
}
if err := g.renderTagsJSON(albums); err != nil {
return err
}
for i := range photos { for i := range photos {
var newer, older *Photo var newer, older *Photo
if i > 0 { if i > 0 {
@@ -209,6 +239,7 @@ func (g *Generator) loadPhotos() ([]Photo, error) {
OG: "og/" + slug + ".jpg", OG: "og/" + slug + ".jpg",
Caption: meta.Caption, Caption: meta.Caption,
Date: date, Date: date,
Tags: parseTags(meta.Tags...),
}) })
} }
@@ -218,6 +249,35 @@ func (g *Generator) loadPhotos() ([]Photo, error) {
return photos, nil return photos, nil
} }
// pruneRenditions deletes files in the image output directories that no longer
// have a backing photo in content/. Called on every build, it is what makes a
// delete (and the stale sidecar left by any removed source) actually disappear
// from public/ rather than linger as an orphan reachable by direct URL.
func (g *Generator) pruneRenditions(photos []Photo) {
valid := make(map[string]bool, len(photos))
for _, p := range photos {
valid[p.Slug] = true
}
for _, d := range []string{"images", "thumbs", "medium", "og"} {
full := filepath.Join(g.outputDir, d)
entries, err := os.ReadDir(full)
if err != nil {
continue
}
for _, e := range entries {
if e.IsDir() {
continue
}
slug := strings.TrimSuffix(e.Name(), filepath.Ext(e.Name()))
if !valid[slug] {
if err := os.Remove(filepath.Join(full, e.Name())); err != nil {
log.Printf("prune %s/%s: %v", d, e.Name(), err)
}
}
}
}
}
// processImage copies the original to public/images/ and writes a square // processImage copies the original to public/images/ and writes a square
// thumbnail to public/thumbs/ plus an aspect-preserved medium image to // thumbnail to public/thumbs/ plus an aspect-preserved medium image to
// public/medium/. Outputs are skipped when already newer than the source. // public/medium/. Outputs are skipped when already newer than the source.
+4 -2
View File
@@ -1,11 +1,13 @@
module photogallery module photogallery
go 1.22 go 1.26.0
require ( require (
github.com/BurntSushi/toml v1.4.0 github.com/BurntSushi/toml v1.4.0
github.com/fsnotify/fsnotify v1.7.0 github.com/fsnotify/fsnotify v1.7.0
golang.org/x/crypto v0.58.0
golang.org/x/image v0.21.0 golang.org/x/image v0.21.0
golang.org/x/time v0.16.0
) )
require golang.org/x/sys v0.4.0 // indirect require golang.org/x/sys v0.49.0 // indirect
+6 -2
View File
@@ -2,7 +2,11 @@ github.com/BurntSushi/toml v1.4.0 h1:kuoIxZQy2WRRk1pttg9asf+WVv6tWQuBNVmK8+nqPr0
github.com/BurntSushi/toml v1.4.0/go.mod h1:ukJfTF/6rtPPRCnwkur4qwRxa8vTRFBF0uk2lLoLwho= github.com/BurntSushi/toml v1.4.0/go.mod h1:ukJfTF/6rtPPRCnwkur4qwRxa8vTRFBF0uk2lLoLwho=
github.com/fsnotify/fsnotify v1.7.0 h1:8JEhPFa5W2WU7YfeZzPNqzMP6Lwt7L2715Ggo0nosvA= github.com/fsnotify/fsnotify v1.7.0 h1:8JEhPFa5W2WU7YfeZzPNqzMP6Lwt7L2715Ggo0nosvA=
github.com/fsnotify/fsnotify v1.7.0/go.mod h1:40Bi/Hjc2AVfZrqy+aj+yEI+/bRxZnMJyTJwOpGvigM= github.com/fsnotify/fsnotify v1.7.0/go.mod h1:40Bi/Hjc2AVfZrqy+aj+yEI+/bRxZnMJyTJwOpGvigM=
golang.org/x/crypto v0.58.0 h1:COkYLr4k7nDI4r6QtMML2AfzeIswWHAJthLS6K/M/54=
golang.org/x/crypto v0.58.0/go.mod h1:Xh+kl5A+M0gMiWDytH2Hhr5Z7WbNCpv/eB/EFgfSk+w=
golang.org/x/image v0.21.0 h1:c5qV36ajHpdj4Qi0GnE0jUc/yuo33OLFaa0d+crTD5s= golang.org/x/image v0.21.0 h1:c5qV36ajHpdj4Qi0GnE0jUc/yuo33OLFaa0d+crTD5s=
golang.org/x/image v0.21.0/go.mod h1:vUbsLavqK/W303ZroQQVKQ+Af3Yl6Uz1Ppu5J/cLz78= golang.org/x/image v0.21.0/go.mod h1:vUbsLavqK/W303ZroQQVKQ+Af3Yl6Uz1Ppu5J/cLz78=
golang.org/x/sys v0.4.0 h1:Zr2JFtRQNX3BCZ8YtxRE9hNJYC8J6I1MVbMg6owUp18= golang.org/x/sys v0.49.0 h1:XbzkgYJHdqh/8m2Uu0W/dQv8nktxx4BFHp1M0gROTXA=
golang.org/x/sys v0.4.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.49.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og=
golang.org/x/time v0.16.0 h1:vMb6ptszcQMkcwiRTAuNNU50gom6++Q/6gY2hDM6VDE=
golang.org/x/time v0.16.0/go.mod h1:rVKOqvZeKvrDKTQiAHJ7wmwP0RzleSphoEA9RcdLA0s=
+13 -1
View File
@@ -20,6 +20,7 @@ func main() {
serifFamily := flag.String("serif-family", "Crimson Pro", "CSS font-family for the primary serif text") serifFamily := flag.String("serif-family", "Crimson Pro", "CSS font-family for the primary serif text")
mlFamily := flag.String("ml-family", "Manjari", "CSS font-family for the alt-script (Malayalam) bio line") mlFamily := flag.String("ml-family", "Manjari", "CSS font-family for the alt-script (Malayalam) bio line")
pageSize := flag.Int("page-size", 60, "photos per page on the timeline and grid views (timeline packs whole days, so pages vary slightly around this)") pageSize := flag.Int("page-size", 60, "photos per page on the timeline and grid views (timeline packs whole days, so pages vary slightly around this)")
htpasswd := flag.String("htpasswd", "", "path to an htpasswd file (bcrypt, `htpasswd -B`) guarding /upload; empty disables auth")
flag.Parse() flag.Parse()
for _, d := range []string{*contentDir, *outputDir} { for _, d := range []string{*contentDir, *outputDir} {
@@ -41,6 +42,17 @@ func main() {
defer w.Close() defer w.Close()
go w.Watch() go w.Watch()
s := NewServer(*port, *contentDir, *outputDir, *serve, g) var auth *Authenticator
if *htpasswd != "" {
auth, err = LoadHtpasswd(*htpasswd)
if err != nil {
log.Fatalf("htpasswd: %v", err)
}
log.Printf("upload auth: enabled (%s)", *htpasswd)
} else {
log.Print("upload auth: DISABLED (no -htpasswd); /upload is open")
}
s := NewServer(*port, *contentDir, *outputDir, *serve, g, auth)
log.Fatal(s.Listen()) log.Fatal(s.Listen())
} }
+318
View File
@@ -0,0 +1,318 @@
package main
import (
"encoding/json"
"log"
"net/http"
"os"
"path/filepath"
"strings"
"time"
"github.com/BurntSushi/toml"
)
// contentExts are the image extensions a post may use; the sidecar is always
// <slug>.toml alongside.
var contentExts = []string{".jpg", ".jpeg", ".png"}
// photoJSON is one row of GET /api/photos, consumed by the manage page.
type photoJSON struct {
Slug string `json:"slug"`
Caption string `json:"caption"`
Date string `json:"date"` // YYYY-MM-DD
Tags []string `json:"tags"`
Thumb string `json:"thumb"`
URL string `json:"url"`
}
// handleManagePage serves the (auth-gated) edit/delete UI.
func (s *Server) handleManagePage(w http.ResponseWriter, r *http.Request) {
data, err := assets.ReadFile("templates/manage.html")
if err != nil {
http.Error(w, "not found", http.StatusNotFound)
return
}
w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.Write(data)
}
// handleListPhotos returns every post as JSON, newest first, for the manage UI.
func (s *Server) handleListPhotos(w http.ResponseWriter, r *http.Request) {
photos, err := s.generator.loadPhotos()
if err != nil {
http.Error(w, "could not list photos", http.StatusInternalServerError)
return
}
out := make([]photoJSON, 0, len(photos))
for _, p := range photos {
tags := make([]string, 0, len(p.Tags))
for _, t := range p.Tags {
tags = append(tags, t.Name)
}
out = append(out, photoJSON{
Slug: p.Slug,
Caption: p.Caption,
Date: p.Date.Format("2006-01-02"),
Tags: tags,
Thumb: "/" + p.Thumb,
URL: "/photo/" + p.Slug + "/",
})
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(out)
}
// handleEdit rewrites one post's sidecar (caption, date, tags). The slug — and
// therefore the URL — never changes.
func (s *Server) handleEdit(w http.ResponseWriter, r *http.Request) {
if s.rejectCrossSite(w, r) {
return
}
if err := r.ParseForm(); err != nil {
http.Error(w, "bad request", http.StatusBadRequest)
return
}
slug := r.FormValue("slug")
if _, ok := s.resolveSlug(slug); !ok {
http.Error(w, "unknown post", http.StatusNotFound)
return
}
date := r.FormValue("date")
if date == "" {
date = time.Now().Format("2006-01-02")
}
if _, err := time.Parse("2006-01-02", date); err != nil {
http.Error(w, "date must be YYYY-MM-DD", http.StatusBadRequest)
return
}
caption := r.FormValue("caption")
if caption == "" {
caption = slug
}
var tags []string
for _, t := range parseTags(r.FormValue("tags")) {
tags = append(tags, t.Name)
}
if err := s.writeSidecar(slug, PhotoMeta{Caption: caption, Date: date, Tags: tags}); err != nil {
log.Printf("edit %s: %v", slug, err)
http.Error(w, "could not save", http.StatusInternalServerError)
return
}
s.rebuild()
w.WriteHeader(http.StatusOK)
}
// handleDelete moves one or more posts (image + sidecar) to content/.trash/.
// Slugs come as repeated `slug` fields or a comma-separated `slugs` field.
func (s *Server) handleDelete(w http.ResponseWriter, r *http.Request) {
if s.rejectCrossSite(w, r) {
return
}
slugs, err := s.formSlugs(r)
if err != nil {
http.Error(w, "bad request", http.StatusBadRequest)
return
}
deleted := 0
for _, slug := range slugs {
if _, ok := s.resolveSlug(slug); !ok {
continue
}
if err := s.moveToTrash(slug); err != nil {
log.Printf("delete %s: %v", slug, err)
continue
}
deleted++
}
if deleted > 0 {
s.rebuild()
}
writeJSON(w, map[string]int{"deleted": deleted})
}
// handleBulkTags adds and/or removes tags across the given posts, leaving each
// post's caption and date untouched. `add` and `remove` are comma-separated.
func (s *Server) handleBulkTags(w http.ResponseWriter, r *http.Request) {
if s.rejectCrossSite(w, r) {
return
}
slugs, err := s.formSlugs(r)
if err != nil {
http.Error(w, "bad request", http.StatusBadRequest)
return
}
add := parseTags(r.FormValue("add"))
remove := make(map[string]bool)
for _, t := range parseTags(r.FormValue("remove")) {
remove[t.Name] = true
}
if len(add) == 0 && len(remove) == 0 {
http.Error(w, "nothing to add or remove", http.StatusBadRequest)
return
}
updated := 0
for _, slug := range slugs {
if _, ok := s.resolveSlug(slug); !ok {
continue
}
meta := s.readSidecar(slug)
// Start from the current tags, append the additions, drop the removals,
// then let parseTags normalise and dedupe the result.
names := append([]string{}, meta.Tags...)
for _, t := range add {
names = append(names, t.Name)
}
var kept []string
for _, t := range parseTags(strings.Join(names, ",")) {
if !remove[t.Name] {
kept = append(kept, t.Name)
}
}
meta.Tags = kept
if err := s.writeSidecar(slug, meta); err != nil {
log.Printf("bulk tags %s: %v", slug, err)
continue
}
updated++
}
if updated > 0 {
s.rebuild()
}
writeJSON(w, map[string]int{"updated": updated})
}
// ── helpers ────────────────────────────────────────────────────────────────
// resolveSlug reports whether slug names an existing post and returns the image
// path. It rejects anything that is not a bare, safe filename, closing path
// traversal and access to dotfiles such as the .trash directory.
func (s *Server) resolveSlug(slug string) (string, bool) {
if slug == "" || slug != filepath.Base(slug) || strings.HasPrefix(slug, ".") {
return "", false
}
for _, ext := range contentExts {
p := filepath.Join(s.contentDir, slug+ext)
if fi, err := os.Stat(p); err == nil && !fi.IsDir() {
return p, true
}
}
return "", false
}
// formSlugs collects slugs from repeated `slug` fields and/or a comma-separated
// `slugs` field, de-duplicated.
func (s *Server) formSlugs(r *http.Request) ([]string, error) {
if err := r.ParseForm(); err != nil {
return nil, err
}
seen := make(map[string]bool)
var out []string
add := func(v string) {
v = strings.TrimSpace(v)
if v != "" && !seen[v] {
seen[v] = true
out = append(out, v)
}
}
for _, v := range r.Form["slug"] {
add(v)
}
for _, v := range strings.Split(r.FormValue("slugs"), ",") {
add(v)
}
return out, nil
}
// readSidecar loads a post's existing metadata, falling back to the same
// defaults loadPhotos uses when the sidecar is missing or unreadable.
func (s *Server) readSidecar(slug string) PhotoMeta {
meta := PhotoMeta{Caption: slug, Date: time.Now().Format("2006-01-02")}
path := filepath.Join(s.contentDir, slug+".toml")
if _, err := os.Stat(path); err == nil {
if _, err := toml.DecodeFile(path, &meta); err != nil {
log.Printf("read sidecar %s: %v", path, err)
}
}
return meta
}
// writeSidecar writes <slug>.toml atomically (temp file + rename) so a
// concurrent build can never observe a half-written sidecar.
func (s *Server) writeSidecar(slug string, meta PhotoMeta) error {
path := filepath.Join(s.contentDir, slug+".toml")
tmp, err := os.CreateTemp(s.contentDir, ".tmp-sidecar-*")
if err != nil {
return err
}
tmpName := tmp.Name()
defer os.Remove(tmpName) // no-op once the rename below succeeds
if err := toml.NewEncoder(tmp).Encode(meta); err != nil {
tmp.Close()
return err
}
if err := tmp.Close(); err != nil {
return err
}
return os.Rename(tmpName, path)
}
// moveToTrash relocates a post's image and sidecar into content/.trash/, so a
// delete is reversible. A timestamp keeps re-deleted slugs from colliding.
func (s *Server) moveToTrash(slug string) error {
trash := filepath.Join(s.contentDir, ".trash")
if err := os.MkdirAll(trash, 0755); err != nil {
return err
}
stamp := time.Now().Format("20060102-150405")
// Move every file the post owns: its image (whichever extension) and its
// sidecar. Missing pieces are not an error.
var names []string
for _, ext := range contentExts {
names = append(names, slug+ext)
}
names = append(names, slug+".toml")
for _, name := range names {
src := filepath.Join(s.contentDir, name)
if _, err := os.Stat(src); err != nil {
continue
}
ext := filepath.Ext(name)
base := strings.TrimSuffix(name, ext)
dst := filepath.Join(trash, base+"."+stamp+ext)
if err := os.Rename(src, dst); err != nil {
return err
}
}
return nil
}
// rebuild kicks off an asynchronous site rebuild, matching the upload handler.
// Build is mutex-guarded, so overlapping calls are safe. Tests may install a
// rebuildHook to make this deterministic.
func (s *Server) rebuild() {
if s.rebuildHook != nil {
s.rebuildHook()
return
}
go func() {
if err := s.generator.Build(); err != nil {
log.Printf("rebuild after manage op: %v", err)
}
}()
}
func writeJSON(w http.ResponseWriter, v any) {
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(v)
}
+285
View File
@@ -0,0 +1,285 @@
package main
import (
"encoding/json"
"image"
"image/png"
"net/http"
"net/http/httptest"
"net/url"
"os"
"path/filepath"
"strings"
"testing"
"github.com/BurntSushi/toml"
)
// newTestServer builds a Server over fresh temp content/output dirs with a
// couple of posts, runs one build, and returns it.
func newTestServer(t *testing.T) (*Server, string, string) {
t.Helper()
content := t.TempDir()
output := t.TempDir()
writePNG(t, filepath.Join(content, "foo.png"))
if err := os.WriteFile(filepath.Join(content, "foo.toml"),
[]byte("caption = \"Foo\"\ndate = \"2026-01-02\"\ntags = [\"berlin\", \"street\"]\n"), 0600); err != nil {
t.Fatal(err)
}
writePNG(t, filepath.Join(content, "bar.png")) // no sidecar
g := NewGenerator(content, output, "http://x", "A", "@a", "bio", "", "f", "s", "m", 60)
if err := g.Build(); err != nil {
t.Fatalf("initial build: %v", err)
}
s := NewServer("0", content, output, false, g, nil)
// Make rebuilds a no-op; tests call Build explicitly when they need to
// assert on generated output, so no background goroutine races teardown.
s.rebuildHook = func() {}
return s, content, output
}
func writePNG(t *testing.T, path string) {
t.Helper()
f, err := os.Create(path)
if err != nil {
t.Fatal(err)
}
defer f.Close()
if err := png.Encode(f, image.NewRGBA(image.Rect(0, 0, 2, 2))); err != nil {
t.Fatal(err)
}
}
func form(v url.Values) *http.Request {
r := httptest.NewRequest(http.MethodPost, "/", strings.NewReader(v.Encode()))
r.Header.Set("Content-Type", "application/x-www-form-urlencoded")
return r
}
func readMeta(t *testing.T, content, slug string) PhotoMeta {
t.Helper()
var m PhotoMeta
if _, err := toml.DecodeFile(filepath.Join(content, slug+".toml"), &m); err != nil {
t.Fatalf("decode %s: %v", slug, err)
}
return m
}
func TestResolveSlug(t *testing.T) {
s, _, _ := newTestServer(t)
cases := map[string]bool{
"foo": true,
"bar": true,
"nope": false,
"../server": false,
"foo/../foo": false,
".trash": false,
"": false,
"sub/foo": false,
}
for slug, want := range cases {
if _, ok := s.resolveSlug(slug); ok != want {
t.Errorf("resolveSlug(%q) = %v, want %v", slug, ok, want)
}
}
}
func TestHandleEdit(t *testing.T) {
s, content, _ := newTestServer(t)
rec := httptest.NewRecorder()
s.handleEdit(rec, form(url.Values{
"slug": {"foo"},
"caption": {"New caption"},
"date": {"2020-05-06"},
"tags": {"Paris, , night"},
}))
if rec.Code != http.StatusOK {
t.Fatalf("edit: code=%d body=%s", rec.Code, rec.Body)
}
m := readMeta(t, content, "foo")
if m.Caption != "New caption" || m.Date != "2020-05-06" {
t.Errorf("caption/date not saved: %+v", m)
}
if strings.Join(m.Tags, ",") != "paris,night" { // lowercased, empty dropped
t.Errorf("tags = %v, want [paris night]", m.Tags)
}
// Bad date rejected.
rec = httptest.NewRecorder()
s.handleEdit(rec, form(url.Values{"slug": {"foo"}, "date": {"06-05-2020"}}))
if rec.Code != http.StatusBadRequest {
t.Errorf("bad date: code=%d, want 400", rec.Code)
}
// Unknown slug rejected (and cannot escape content dir).
rec = httptest.NewRecorder()
s.handleEdit(rec, form(url.Values{"slug": {"../evil"}, "date": {"2020-01-01"}}))
if rec.Code != http.StatusNotFound {
t.Errorf("unknown slug: code=%d, want 404", rec.Code)
}
}
func TestHandleBulkTags(t *testing.T) {
s, content, _ := newTestServer(t)
// Add to bar (no sidecar yet) and foo (already has tags).
rec := httptest.NewRecorder()
s.handleBulkTags(rec, form(url.Values{"slugs": {"foo,bar"}, "add": {"aqua, berlin"}}))
if rec.Code != http.StatusOK {
t.Fatalf("bulk add: code=%d body=%s", rec.Code, rec.Body)
}
foo := readMeta(t, content, "foo")
// berlin already present → not duplicated; aqua appended.
if got := strings.Join(foo.Tags, ","); got != "berlin,street,aqua" {
t.Errorf("foo tags = %q, want berlin,street,aqua", got)
}
if got := strings.Join(readMeta(t, content, "bar").Tags, ","); got != "aqua,berlin" {
t.Errorf("bar tags = %q, want aqua,berlin", got)
}
// Remove across both.
rec = httptest.NewRecorder()
s.handleBulkTags(rec, form(url.Values{"slugs": {"foo,bar"}, "remove": {"berlin"}}))
if rec.Code != http.StatusOK {
t.Fatalf("bulk remove: code=%d", rec.Code)
}
if got := strings.Join(readMeta(t, content, "foo").Tags, ","); got != "street,aqua" {
t.Errorf("foo tags after remove = %q, want street,aqua", got)
}
// Empty add+remove is a 400.
rec = httptest.NewRecorder()
s.handleBulkTags(rec, form(url.Values{"slugs": {"foo"}}))
if rec.Code != http.StatusBadRequest {
t.Errorf("empty bulk: code=%d, want 400", rec.Code)
}
}
func TestHandleDeleteMovesToTrashAndPrunes(t *testing.T) {
s, content, output := newTestServer(t)
// Pre-condition: foo's rendition and page exist.
for _, p := range []string{"thumbs/foo.jpg", "images/foo.png", "photo/foo/index.html"} {
if _, err := os.Stat(filepath.Join(output, p)); err != nil {
t.Fatalf("expected %s before delete: %v", p, err)
}
}
rec := httptest.NewRecorder()
s.handleDelete(rec, form(url.Values{"slug": {"foo"}}))
if rec.Code != http.StatusOK {
t.Fatalf("delete: code=%d", rec.Code)
}
var res map[string]int
json.Unmarshal(rec.Body.Bytes(), &res)
if res["deleted"] != 1 {
t.Errorf("deleted = %d, want 1", res["deleted"])
}
// Source files moved out of content/ ...
if _, err := os.Stat(filepath.Join(content, "foo.png")); !os.IsNotExist(err) {
t.Error("foo.png should be gone from content")
}
// ... and into .trash/ (timestamp-suffixed).
trash, _ := os.ReadDir(filepath.Join(content, ".trash"))
var png, tml bool
for _, e := range trash {
if strings.HasPrefix(e.Name(), "foo.") && strings.HasSuffix(e.Name(), ".png") {
png = true
}
if strings.HasPrefix(e.Name(), "foo.") && strings.HasSuffix(e.Name(), ".toml") {
tml = true
}
}
if !png || !tml {
t.Errorf("trash missing files: png=%v toml=%v entries=%v", png, tml, trash)
}
// The handler rebuilds asynchronously; run a deterministic build, then
// confirm the prune removed foo's output and kept bar's.
if err := s.generator.Build(); err != nil {
t.Fatal(err)
}
for _, p := range []string{"thumbs/foo.jpg", "images/foo.png", "photo/foo"} {
if _, err := os.Stat(filepath.Join(output, p)); !os.IsNotExist(err) {
t.Errorf("%s should have been pruned", p)
}
}
if _, err := os.Stat(filepath.Join(output, "thumbs/bar.jpg")); err != nil {
t.Errorf("bar's thumb should survive: %v", err)
}
}
func TestCSRFGuard(t *testing.T) {
s, _, _ := newTestServer(t) // generator.baseURL == "http://x"
// A cross-site Origin is refused before any mutation runs.
r := form(url.Values{"slug": {"foo"}})
r.Header.Set("Origin", "http://evil.example")
rec := httptest.NewRecorder()
s.handleDelete(rec, r)
if rec.Code != http.StatusForbidden {
t.Errorf("cross-site Origin: code=%d, want 403", rec.Code)
}
// Sec-Fetch-Site: cross-site is likewise refused.
r = form(url.Values{"slug": {"foo"}})
r.Header.Set("Sec-Fetch-Site", "cross-site")
rec = httptest.NewRecorder()
s.handleDelete(rec, r)
if rec.Code != http.StatusForbidden {
t.Errorf("Sec-Fetch cross-site: code=%d, want 403", rec.Code)
}
// Same-origin is allowed through (no slugs → deletes nothing, 200).
r = form(url.Values{})
r.Header.Set("Sec-Fetch-Site", "same-origin")
rec = httptest.NewRecorder()
s.handleDelete(rec, r)
if rec.Code != http.StatusOK {
t.Errorf("same-origin: code=%d, want 200", rec.Code)
}
// A matching Origin is allowed.
r = form(url.Values{})
r.Header.Set("Origin", "http://x")
rec = httptest.NewRecorder()
s.handleDelete(rec, r)
if rec.Code != http.StatusOK {
t.Errorf("matching Origin: code=%d, want 200", rec.Code)
}
}
func TestHandleListPhotos(t *testing.T) {
s, _, _ := newTestServer(t)
rec := httptest.NewRecorder()
s.handleListPhotos(rec, httptest.NewRequest(http.MethodGet, "/api/photos", nil))
if rec.Code != http.StatusOK {
t.Fatalf("list: code=%d", rec.Code)
}
var photos []photoJSON
if err := json.Unmarshal(rec.Body.Bytes(), &photos); err != nil {
t.Fatalf("decode: %v", err)
}
if len(photos) != 2 {
t.Fatalf("got %d photos, want 2", len(photos))
}
var foo *photoJSON
for i := range photos {
if photos[i].Slug == "foo" {
foo = &photos[i]
}
}
if foo == nil {
t.Fatal("foo not in list")
}
if foo.Thumb != "/thumbs/foo.jpg" || foo.URL != "/photo/foo/" {
t.Errorf("foo paths wrong: %+v", foo)
}
if strings.Join(foo.Tags, ",") != "berlin,street" {
t.Errorf("foo tags = %v", foo.Tags)
}
}
+38 -12
View File
@@ -82,6 +82,20 @@ in {
description = "Photos per page on the timeline and grid views. The timeline packs whole days, so pages vary slightly around this."; description = "Photos per page on the timeline and grid views. The timeline packs whole days, so pages vary slightly around this.";
}; };
htpasswdFile = lib.mkOption {
type = lib.types.nullOr lib.types.path;
default = null;
example = "/run/secrets/photogallery-htpasswd";
description = ''
Path to an Apache htpasswd file (bcrypt only — generate with
`htpasswd -B`) guarding the /upload endpoint. The app performs the
auth itself, so nginx no longer needs basic_auth. The file is handed
to the service via systemd LoadCredential, so it may be root-owned and
0400 (e.g. an agenix/sops secret). Leave null to disable auth entirely
— then /upload is open and anyone who can reach it can post.
'';
};
nginx = { nginx = {
enable = lib.mkEnableOption "nginx virtual host for photogallery"; enable = lib.mkEnableOption "nginx virtual host for photogallery";
@@ -91,12 +105,6 @@ in {
description = "Domain for the nginx virtual host."; description = "Domain for the nginx virtual host.";
}; };
htpasswdFile = lib.mkOption {
type = lib.types.path;
example = "/etc/nginx/.htpasswd-gallery";
description = "Path to htpasswd file protecting the /upload endpoint.";
};
enableACME = lib.mkOption { enableACME = lib.mkOption {
type = lib.types.bool; type = lib.types.bool;
default = true; default = true;
@@ -134,7 +142,7 @@ in {
User = "photogallery"; User = "photogallery";
Group = "photogallery"; Group = "photogallery";
ExecStart = lib.escapeShellArgs [ ExecStart = lib.escapeShellArgs ([
"${pkg}/bin/photogallery" "${pkg}/bin/photogallery"
"--content" cfg.contentDir "--content" cfg.contentDir
"--output" cfg.outputDir "--output" cfg.outputDir
@@ -148,7 +156,14 @@ in {
"--serif-family" cfg.serifFamily "--serif-family" cfg.serifFamily
"--ml-family" cfg.mlFamily "--ml-family" cfg.mlFamily
"--page-size" (toString cfg.pageSize) "--page-size" (toString cfg.pageSize)
]; ] ++ lib.optionals (cfg.htpasswdFile != null) [
# %d is systemd's credentials directory; LoadCredential below drops
# the htpasswd file there, readable only by this service.
"--htpasswd" "%d/htpasswd"
]);
LoadCredential = lib.optional (cfg.htpasswdFile != null)
"htpasswd:${cfg.htpasswdFile}";
Restart = "on-failure"; Restart = "on-failure";
RestartSec = "5s"; RestartSec = "5s";
@@ -178,11 +193,22 @@ in {
tryFiles = "$uri $uri/ =404"; tryFiles = "$uri $uri/ =404";
}; };
# Auth is handled by the app (see services.photogallery.htpasswdFile),
# so nginx just proxies the dynamic endpoints: the upload form/API,
# the manage (edit/delete) page and its JSON API. Everything else is
# the static site served from root above.
locations."/upload" = { locations."/upload" = {
proxyPass = "http://127.0.0.1:${toString cfg.port}"; proxyPass = "http://127.0.0.1:${toString cfg.port}";
basicAuth = "gallery"; extraConfig = "client_max_body_size 20M;";
basicAuthFile = cfg.nginx.htpasswdFile; };
extraConfig = "client_max_body_size 20M;";
locations."/manage" = {
proxyPass = "http://127.0.0.1:${toString cfg.port}";
};
locations."/api/" = {
proxyPass = "http://127.0.0.1:${toString cfg.port}";
extraConfig = "client_max_body_size 20M;";
}; };
}; };
}; };
+82 -5
View File
@@ -5,12 +5,14 @@ import (
"io" "io"
"log" "log"
"net/http" "net/http"
"net/url"
"os" "os"
"path/filepath" "path/filepath"
"strings" "strings"
"time" "time"
"github.com/BurntSushi/toml" "github.com/BurntSushi/toml"
"golang.org/x/time/rate"
) )
type Server struct { type Server struct {
@@ -19,22 +21,89 @@ type Server struct {
outputDir string outputDir string
serve bool serve bool
generator *Generator generator *Generator
auth *Authenticator // nil disables auth (dev only)
authLimit *rate.Limiter
// rebuildHook overrides how a mutation triggers a rebuild. nil means the
// default asynchronous Build; tests set it to run synchronously (or not at
// all) so no background goroutine outlives the test.
rebuildHook func()
} }
func NewServer(port, contentDir, outputDir string, serve bool, g *Generator) *Server { func NewServer(port, contentDir, outputDir string, serve bool, g *Generator, auth *Authenticator) *Server {
return &Server{ return &Server{
port: port, port: port,
contentDir: contentDir, contentDir: contentDir,
outputDir: outputDir, outputDir: outputDir,
serve: serve, serve: serve,
generator: g, generator: g,
auth: auth,
// Brute-force throttle: ~1 failed auth/sec steady, burst of 10. Only
// failures draw from it, so legitimate bulk uploads are never slowed.
authLimit: rate.NewLimiter(rate.Every(time.Second), 10),
} }
} }
// guard applies HTTP Basic auth to h when an Authenticator is configured, and
// passes it through untouched otherwise (local --serve development).
func (s *Server) guard(h http.HandlerFunc) http.HandlerFunc {
if s.auth == nil {
return h
}
return s.auth.basicAuth(s.authLimit, h)
}
// sameOrigin reports whether a form/API post came from the gallery's own pages.
// Basic-auth credentials are replayed by the browser on every request to the
// host, so without this check any other website could drive a logged-in user's
// browser into submitting an edit, delete or retag on their behalf (CSRF).
//
// Sec-Fetch-Site is preferred; where it is absent the Origin header is compared
// against -base-url and the request Host (behind nginx the Host reaching this
// server is the proxy upstream, not the public name). A request with neither
// header is a non-browser client such as curl, which cannot be driven
// cross-site, so it is allowed.
func (s *Server) sameOrigin(r *http.Request) bool {
if site := r.Header.Get("Sec-Fetch-Site"); site != "" {
return site == "same-origin" || site == "none"
}
origin := r.Header.Get("Origin")
if origin == "" {
return true
}
if origin == s.generator.baseURL {
return true
}
u, err := url.Parse(origin)
return err == nil && u.Host == r.Host
}
// rejectCrossSite writes a 403 and returns true when r is a cross-site request.
// State-changing handlers call it first: `if s.rejectCrossSite(w, r) { return }`.
func (s *Server) rejectCrossSite(w http.ResponseWriter, r *http.Request) bool {
if s.sameOrigin(r) {
return false
}
http.Error(w, "cross-site request refused", http.StatusForbidden)
return true
}
func (s *Server) Listen() error { func (s *Server) Listen() error {
mux := http.NewServeMux() mux := http.NewServeMux()
mux.HandleFunc("GET /upload", s.handleUploadPage) mux.HandleFunc("GET /upload", s.guard(s.handleUploadPage))
mux.HandleFunc("POST /upload", s.handleUpload) mux.HandleFunc("POST /upload", s.guard(s.handleUpload))
// Edit/delete UI and its API. All auth-gated like /upload; destructive
// endpoints (delete) move posts to content/.trash/ rather than erasing.
mux.HandleFunc("GET /manage", s.guard(s.handleManagePage))
mux.HandleFunc("GET /api/photos", s.guard(s.handleListPhotos))
mux.HandleFunc("POST /api/edit", s.guard(s.handleEdit))
mux.HandleFunc("POST /api/delete", s.guard(s.handleDelete))
mux.HandleFunc("POST /api/tags", s.guard(s.handleBulkTags))
mux.HandleFunc("GET /api/trash", s.guard(s.handleListTrash))
mux.HandleFunc("POST /api/restore", s.guard(s.handleRestore))
mux.HandleFunc("POST /api/trash/empty", s.guard(s.handleEmptyTrash))
mux.HandleFunc("GET /health", func(w http.ResponseWriter, r *http.Request) { mux.HandleFunc("GET /health", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "ok") fmt.Fprintln(w, "ok")
}) })
@@ -67,6 +136,7 @@ func (s *Server) handleUploadPage(w http.ResponseWriter, r *http.Request) {
// image — the image file (jpg or png) // image — the image file (jpg or png)
// caption — human-readable caption (optional, defaults to filename) // caption — human-readable caption (optional, defaults to filename)
// date — YYYY-MM-DD (optional, defaults to today) // date — YYYY-MM-DD (optional, defaults to today)
// tags — comma-separated album tags (optional; lowercased, deduped)
func (s *Server) handleUpload(w http.ResponseWriter, r *http.Request) { func (s *Server) handleUpload(w http.ResponseWriter, r *http.Request) {
if err := r.ParseMultipartForm(32 << 20); err != nil { if err := r.ParseMultipartForm(32 << 20); err != nil {
http.Error(w, "bad request", http.StatusBadRequest) http.Error(w, "bad request", http.StatusBadRequest)
@@ -95,11 +165,18 @@ func (s *Server) handleUpload(w http.ResponseWriter, r *http.Request) {
caption = strings.TrimSuffix(header.Filename, ext) caption = strings.TrimSuffix(header.Filename, ext)
} }
// Normalize the tags once here so the sidecar stores clean lowercase names;
// the generator derives album slugs from them at build time.
var tags []string
for _, t := range parseTags(r.FormValue("tags")) {
tags = append(tags, t.Name)
}
slug := sanitiseSlug(strings.TrimSuffix(header.Filename, ext)) slug := sanitiseSlug(strings.TrimSuffix(header.Filename, ext))
if slug == "" { if slug == "" {
slug = fmt.Sprintf("photo-%d", time.Now().UnixMilli()) slug = fmt.Sprintf("photo-%d", time.Now().UnixMilli())
} }
imgPath := filepath.Join(s.contentDir, slug+ext) imgPath := filepath.Join(s.contentDir, slug+ext)
tomlPath := filepath.Join(s.contentDir, slug+".toml") tomlPath := filepath.Join(s.contentDir, slug+".toml")
out, err := os.Create(imgPath) out, err := os.Create(imgPath)
@@ -121,7 +198,7 @@ func (s *Server) handleUpload(w http.ResponseWriter, r *http.Request) {
return return
} }
defer tf.Close() defer tf.Close()
if err := toml.NewEncoder(tf).Encode(PhotoMeta{Caption: caption, Date: dateStr}); err != nil { if err := toml.NewEncoder(tf).Encode(PhotoMeta{Caption: caption, Date: dateStr, Tags: tags}); err != nil {
http.Error(w, "could not write metadata", http.StatusInternalServerError) http.Error(w, "could not write metadata", http.StatusInternalServerError)
return return
} }
+54
View File
@@ -422,3 +422,57 @@ body {
.dlayout { flex-direction: column; } .dlayout { flex-direction: column; }
.dsidebar { width: 100%; border-left: none; border-top: 1px solid var(--line); } .dsidebar { width: 100%; border-left: none; border-top: 1px solid var(--line); }
} }
/* ── Tags / albums ─────────────────────────────────────────── */
.dtags {
display: flex;
flex-wrap: wrap;
gap: 6px;
margin: 10px 0 14px;
}
.tag,
.album-chip {
display: inline-flex;
align-items: center;
gap: 6px;
padding: 3px 10px;
background: var(--bg0);
border: 1px solid var(--bg2);
color: var(--fg3);
font-family: monospace;
font-size: 12px;
text-decoration: none;
border-radius: 2px;
transition: color 0.15s, border-color 0.15s;
}
.tag:hover,
.album-chip:hover {
color: var(--aqua);
border-color: var(--fg4);
}
.album-list {
display: flex;
flex-wrap: wrap;
gap: 10px;
margin-top: 16px;
}
.album-chip {
font-size: 14px;
padding: 7px 14px;
}
.album-chip-count {
color: var(--fg4);
font-size: 11px;
}
.album-empty {
color: var(--fg4);
font-family: var(--serif);
margin-top: 16px;
}
+96
View File
@@ -0,0 +1,96 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{{.Tag.Name}} · Photo Gallery</title>
<link rel="stylesheet" href="{{.FontsURL}}">
<link rel="stylesheet" href="/static/style.css">
<link rel="icon" href="/static/favicon.ico" sizes="any">
<link rel="icon" type="image/png" href="/static/web-32.png" sizes="32x32">
<link rel="apple-touch-icon" href="/static/web-192.png">
<style>:root { --serif: '{{.SerifFamily}}', Georgia, serif; --mj: '{{.MlFamily}}', sans-serif; }</style>
<link rel="alternate" type="application/atom+xml" href="/feed.xml" title="Photo Feed">
</head>
<body>
<header class="profile-hdr">
<div class="profile-inner">
<div class="avatar-ring">
<span class="avatar-initials">{{.Initial}}</span>
</div>
<div class="pinfo">
<h1>{{.Author}}</h1>
<p class="handle">{{.Handle}}</p>
<p class="pcount"><strong>{{.Total}}</strong> posts</p>
<p class="pbio">{{.Bio}}{{if .BioAlt}}<br><span class="ml">{{.BioAlt}}</span>{{end}}</p>
<a href="/" class="rss-a">Timeline</a>
<a href="/albums/" class="rss-a">← Albums</a>
</div>
</div>
</header>
<main>
<div class="grid-wrap">
<section class="tl-day">
<h2 class="tl-date">{{.Tag.Name}}<span class="tl-count">{{.Count}}</span></h2>
<div class="pgrid">
{{range .Photos}}
<a href="/photo/{{.Slug}}/" class="ptile">
<img src="/{{.Thumb}}" alt="{{.Caption}}" loading="lazy">
</a>
{{end}}
</div>
</section>
{{if or .PrevURL .NextURL}}
<nav class="pager">
{{if .PrevURL}}<a class="pager-newer" href="{{.PrevURL}}">← Newer</a>{{end}}
{{if .NextURL}}<a class="pager-older" href="{{.NextURL}}" data-load-more>Older →</a>{{end}}
</nav>
{{end}}
</div>
</main>
<footer class="site-footer">
© 2000–{{.Year}} {{.Author}}. All rights reserved.
</footer>
<script>
(function () {
const btn = document.querySelector('[data-load-more]');
if (!btn) return;
const grid = document.querySelector('.pgrid');
let loading = false;
async function loadMore(url) {
if (loading) return;
loading = true;
try {
const res = await fetch(url);
if (!res.ok) return;
const html = await res.text();
const doc = new DOMParser().parseFromString(html, 'text/html');
doc.querySelectorAll('.pgrid > a').forEach(t => grid.appendChild(t));
const nextBtn = doc.querySelector('[data-load-more]');
if (nextBtn) btn.href = nextBtn.getAttribute('href');
else btn.remove();
} finally {
loading = false;
}
}
btn.addEventListener('click', (e) => {
e.preventDefault();
loadMore(btn.href);
});
const io = new IntersectionObserver((entries) => {
if (entries[0].isIntersecting && document.body.contains(btn)) {
loadMore(btn.href);
}
}, { rootMargin: '400px' });
io.observe(btn);
})();
</script>
</body>
</html>
+54
View File
@@ -0,0 +1,54 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Albums · Photo Gallery</title>
<link rel="stylesheet" href="{{.FontsURL}}">
<link rel="stylesheet" href="/static/style.css">
<link rel="icon" href="/static/favicon.ico" sizes="any">
<link rel="icon" type="image/png" href="/static/web-32.png" sizes="32x32">
<link rel="apple-touch-icon" href="/static/web-192.png">
<style>:root { --serif: '{{.SerifFamily}}', Georgia, serif; --mj: '{{.MlFamily}}', sans-serif; }</style>
<link rel="alternate" type="application/atom+xml" href="/feed.xml" title="Photo Feed">
</head>
<body>
<header class="profile-hdr">
<div class="profile-inner">
<div class="avatar-ring">
<span class="avatar-initials">{{.Initial}}</span>
</div>
<div class="pinfo">
<h1>{{.Author}}</h1>
<p class="handle">{{.Handle}}</p>
<p class="pcount"><strong>{{.Total}}</strong> posts</p>
<p class="pbio">{{.Bio}}{{if .BioAlt}}<br><span class="ml">{{.BioAlt}}</span>{{end}}</p>
<a href="/" class="rss-a">← Timeline</a>
</div>
</div>
</header>
<main>
<div class="grid-wrap">
<section class="tl-day">
<h2 class="tl-date">Albums<span class="tl-count">{{len .Albums}}</span></h2>
{{if .Albums}}
<div class="album-list">
{{range .Albums}}
<a href="/album/{{.Tag.Slug}}/" class="album-chip">
{{.Tag.Name}}<span class="album-chip-count">{{.Count}}</span>
</a>
{{end}}
</div>
{{else}}
<p class="album-empty">No albums yet — add tags to a photo to create one.</p>
{{end}}
</section>
</div>
</main>
<footer class="site-footer">
© 2000–{{.Year}} {{.Author}}. All rights reserved.
</footer>
</body>
</html>
+2 -1
View File
@@ -24,13 +24,14 @@
<p class="pcount"><strong>{{.Total}}</strong> posts</p> <p class="pcount"><strong>{{.Total}}</strong> posts</p>
<p class="pbio">{{.Bio}}{{if .BioAlt}}<br><span class="ml">{{.BioAlt}}</span>{{end}}</p> <p class="pbio">{{.Bio}}{{if .BioAlt}}<br><span class="ml">{{.BioAlt}}</span>{{end}}</p>
<a href="/" class="rss-a">Timeline</a> <a href="/" class="rss-a">Timeline</a>
<a href="/albums/" class="rss-a">Albums</a>
<a href="/feed.xml" class="rss-a"> <a href="/feed.xml" class="rss-a">
<svg width="14" height="14" viewBox="0 0 14 14" fill="currentColor" aria-hidden="true"> <svg width="14" height="14" viewBox="0 0 14 14" fill="currentColor" aria-hidden="true">
<circle cx="2.5" cy="11.5" r="1.5"/> <circle cx="2.5" cy="11.5" r="1.5"/>
<path d="M1.5 7.5A5 5 0 0 1 6.5 12.5H8A6.5 6.5 0 0 0 1.5 6V7.5z"/> <path d="M1.5 7.5A5 5 0 0 1 6.5 12.5H8A6.5 6.5 0 0 0 1.5 6V7.5z"/>
<path d="M1.5 4A8.5 8.5 0 0 1 10 12.5h1.5A10 10 0 0 0 1.5 2.5V4z"/> <path d="M1.5 4A8.5 8.5 0 0 1 10 12.5h1.5A10 10 0 0 0 1.5 2.5V4z"/>
</svg> </svg>
RSS feed Feed
</a> </a>
<a href="https://git.inflo.ws/aashiks/photog" class="rss-a" target="_blank" rel="noopener"> <a href="https://git.inflo.ws/aashiks/photog" class="rss-a" target="_blank" rel="noopener">
<svg width="14" height="14" viewBox="0 0 16 16" fill="currentColor" aria-hidden="true"> <svg width="14" height="14" viewBox="0 0 16 16" fill="currentColor" aria-hidden="true">
+339
View File
@@ -0,0 +1,339 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Manage — Photo Gallery</title>
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Crimson+Pro:ital,wght@0,400;0,600;0,700;1,400&family=Manjari:wght@100;400;700&display=swap">
<link rel="stylesheet" href="/static/style.css">
<link rel="icon" href="/static/favicon.ico" sizes="any">
<link rel="icon" type="image/png" href="/static/web-32.png" sizes="32x32">
<link rel="apple-touch-icon" href="/static/web-192.png">
<style>
.manage-page { max-width: 760px; margin: 0 auto; padding: 28px 20px 80px; }
.manage-head { display: flex; align-items: baseline; justify-content: space-between; gap: 12px; margin-bottom: 8px; }
.manage-head h2 { font-family: var(--serif); font-size: 22px; font-weight: 600; color: var(--fg); }
.manage-head a { font-family: monospace; font-size: 13px; color: var(--fg4); text-decoration: none; }
.manage-head a:hover { color: var(--fg2); }
#count { font-family: monospace; font-size: 12px; color: var(--fg4); margin-bottom: 20px; }
/* Bulk action bar, sticky at the top once posts are selected. */
.bulkbar {
position: sticky; top: 0; z-index: 5;
display: none; flex-wrap: wrap; align-items: center; gap: 10px;
background: var(--bg1); border: 1px solid var(--bg2);
padding: 12px 14px; margin-bottom: 20px;
}
.bulkbar.show { display: flex; }
.bulkbar .sel { font-family: monospace; font-size: 12px; color: var(--fg2); margin-right: auto; }
.bulkbar input[type="text"] {
background: var(--bg0); border: 1px solid var(--bg2); color: var(--fg);
font-family: var(--serif); font-size: 14px; padding: 7px 9px; width: 150px; outline: none;
}
.bulkbar input:focus { border-color: var(--fg4); }
.btn {
background: var(--bg1); border: 1px solid var(--bg2); color: var(--fg2);
font-family: var(--serif); font-size: 14px; padding: 7px 12px; cursor: pointer;
transition: background .2s, color .2s;
}
.btn:hover:not(:disabled) { background: var(--bg2); color: var(--fg); }
.btn:disabled { opacity: .35; cursor: not-allowed; }
.btn.danger { color: #fb4934; border-color: #5a2828; }
.btn.danger:hover:not(:disabled) { background: #2e1d1d; color: #fb4934; }
.row {
display: grid; grid-template-columns: 22px 72px 1fr auto; gap: 14px;
align-items: start; padding: 16px 0; border-top: 1px solid var(--bg1);
}
.row input[type="checkbox"] { margin-top: 28px; width: 16px; height: 16px; accent-color: var(--aqua, #8ec07c); }
.row .thumb { width: 72px; height: 72px; object-fit: cover; background: var(--bg1); display: block; }
.fields { display: flex; flex-direction: column; gap: 8px; min-width: 0; }
.fields label { font-size: 11px; color: var(--fg4); font-family: monospace; text-transform: uppercase; letter-spacing: .06em; }
.fields input {
width: 100%; background: var(--bg0); border: 1px solid var(--bg2); color: var(--fg);
font-size: 15px; padding: 8px 10px; outline: none; box-sizing: border-box;
}
.fields input[type="text"] { font-family: var(--serif); }
.fields input[type="date"] { font-family: monospace; font-size: 13px; color-scheme: dark; width: auto; }
.fields input:focus { border-color: var(--fg4); }
.rowactions { display: flex; flex-direction: column; gap: 8px; }
@media (max-width: 560px) {
.row { grid-template-columns: 22px 56px 1fr; }
.row .rowactions { grid-column: 2 / 4; flex-direction: row; }
.row input[type="checkbox"] { margin-top: 20px; }
}
.trashpanel { display: none; border: 1px solid var(--bg2); background: var(--bg0); padding: 14px; margin-bottom: 24px; }
.trashpanel.show { display: block; }
.trashhead { display: flex; align-items: center; gap: 12px; margin-bottom: 10px; }
.trashhead strong { font-family: var(--serif); color: var(--fg); }
.trashhead #trash-count { font-family: monospace; font-size: 12px; color: var(--fg4); margin-right: auto; }
.trashrow { display: flex; align-items: center; gap: 12px; padding: 8px 0; border-top: 1px solid var(--bg1); }
.trashrow .meta { margin-right: auto; min-width: 0; }
.trashrow .slug { font-family: var(--serif); color: var(--fg2); }
.trashrow .when { font-family: monospace; font-size: 11px; color: var(--fg4); }
#trash-empty-msg { color: var(--fg4); font-family: var(--serif); padding: 8px 0; }
#toast {
position: fixed; left: 50%; bottom: 24px; transform: translateX(-50%);
display: none; font-family: monospace; font-size: 13px; padding: 10px 16px; max-width: 90%;
}
#toast.ok { display: block; background: #1d2e1d; color: #b8bb26; border: 1px solid #344d28; }
#toast.err { display: block; background: #2e1d1d; color: #fb4934; border: 1px solid #5a2828; }
#empty { color: var(--fg4); font-family: var(--serif); padding: 40px 0; }
</style>
</head>
<body>
<div class="manage-page">
<div class="manage-head">
<h2>Manage posts</h2>
<span><a href="/upload">+ Upload</a> &nbsp; <a href="#" id="trash-toggle">Trash</a> &nbsp; <a href="/">← Gallery</a></span>
</div>
<div id="count">Loading…</div>
<div class="trashpanel" id="trashpanel">
<div class="trashhead">
<strong>Trash</strong>
<span id="trash-count"></span>
<button class="btn danger" id="btn-empty-all">Empty trash</button>
</div>
<div id="trashlist"></div>
<div id="trash-empty-msg" style="display:none">Trash is empty.</div>
</div>
<div class="bulkbar" id="bulkbar">
<span class="sel" id="sel">0 selected</span>
<input type="text" id="bulk-add" placeholder="add tags" autocomplete="off">
<button class="btn" id="btn-add">Add</button>
<input type="text" id="bulk-remove" placeholder="remove tags" autocomplete="off">
<button class="btn" id="btn-remove">Remove</button>
<button class="btn danger" id="btn-del-sel">Delete selected</button>
</div>
<div id="list"></div>
<div id="empty" style="display:none">No posts yet.</div>
</div>
<div id="toast"></div>
<script>
const list = document.getElementById('list');
const countEl = document.getElementById('count');
const emptyEl = document.getElementById('empty');
const bulkbar = document.getElementById('bulkbar');
const selEl = document.getElementById('sel');
const toast = document.getElementById('toast');
let toastTimer;
function flash(msg, ok) {
toast.textContent = msg;
toast.className = ok ? 'ok' : 'err';
clearTimeout(toastTimer);
toastTimer = setTimeout(() => { toast.className = ''; }, 3500);
}
function selectedSlugs() {
return [...list.querySelectorAll('input.pick:checked')].map(c => c.dataset.slug);
}
function refreshBulk() {
const n = selectedSlugs().length;
selEl.textContent = n + ' selected';
bulkbar.classList.toggle('show', n > 0);
}
function row(p) {
const el = document.createElement('div');
el.className = 'row';
el.dataset.slug = p.slug;
el.innerHTML = `
<input type="checkbox" class="pick" data-slug="${p.slug}" aria-label="Select">
<a href="${p.url}" target="_blank" rel="noopener"><img class="thumb" src="${p.thumb}" alt=""></a>
<div class="fields">
<label>Caption</label>
<input type="text" class="f-caption" value="">
<label>Date</label>
<input type="date" class="f-date" value="${p.date}">
<label>Tags (comma-separated)</label>
<input type="text" class="f-tags" value="">
</div>
<div class="rowactions">
<button class="btn f-save">Save</button>
<button class="btn danger f-del">Delete</button>
</div>`;
// Set values via property to avoid HTML-escaping issues in attributes.
el.querySelector('.f-caption').value = p.caption;
el.querySelector('.f-tags').value = (p.tags || []).join(', ');
el.querySelector('.pick').addEventListener('change', refreshBulk);
el.querySelector('.f-save').addEventListener('click', () => save(el, p.slug));
el.querySelector('.f-del').addEventListener('click', () => delOne(el, p.slug));
return el;
}
async function load() {
try {
const res = await fetch('/api/photos', { headers: { 'Accept': 'application/json' } });
if (!res.ok) throw new Error('HTTP ' + res.status);
const photos = await res.json();
list.innerHTML = '';
photos.forEach(p => list.appendChild(row(p)));
countEl.textContent = photos.length + (photos.length === 1 ? ' post' : ' posts');
emptyEl.style.display = photos.length ? 'none' : 'block';
refreshBulk();
} catch (err) {
countEl.textContent = '';
flash('Could not load posts: ' + err.message, false);
}
}
async function post(url, body) {
const res = await fetch(url, { method: 'POST', body });
if (!res.ok) throw new Error((await res.text()).trim() || ('HTTP ' + res.status));
return res;
}
async function save(el, slug) {
const form = new FormData();
form.append('slug', slug);
form.append('caption', el.querySelector('.f-caption').value);
form.append('date', el.querySelector('.f-date').value);
form.append('tags', el.querySelector('.f-tags').value);
try {
await post('/api/edit', form);
flash('Saved ' + slug, true);
} catch (err) { flash('Save failed: ' + err.message, false); }
}
async function delOne(el, slug) {
if (!confirm('Move "' + slug + '" to trash?')) return;
const form = new FormData();
form.append('slug', slug);
try {
await post('/api/delete', form);
el.remove();
flash('Moved ' + slug + ' to trash', true);
refreshBulk();
updateCount();
} catch (err) { flash('Delete failed: ' + err.message, false); }
}
function updateCount() {
const n = list.querySelectorAll('.row').length;
countEl.textContent = n + (n === 1 ? ' post' : ' posts');
emptyEl.style.display = n ? 'none' : 'block';
}
document.getElementById('btn-del-sel').addEventListener('click', async () => {
const slugs = selectedSlugs();
if (!slugs.length) return;
if (!confirm('Move ' + slugs.length + ' post(s) to trash?')) return;
const form = new FormData();
form.append('slugs', slugs.join(','));
try {
await post('/api/delete', form);
flash('Moved ' + slugs.length + ' to trash', true);
await load();
} catch (err) { flash('Delete failed: ' + err.message, false); }
});
async function bulkTags(field, label) {
const slugs = selectedSlugs();
const val = document.getElementById(field).value.trim();
if (!slugs.length || !val) return;
const form = new FormData();
form.append('slugs', slugs.join(','));
form.append(label, val);
try {
await post('/api/tags', form);
document.getElementById(field).value = '';
flash('Updated tags on ' + slugs.length + ' post(s)', true);
await load();
} catch (err) { flash('Tag update failed: ' + err.message, false); }
}
document.getElementById('btn-add').addEventListener('click', () => bulkTags('bulk-add', 'add'));
document.getElementById('btn-remove').addEventListener('click', () => bulkTags('bulk-remove', 'remove'));
// ── Trash ────────────────────────────────────────────────────────────────
const trashpanel = document.getElementById('trashpanel');
const trashlist = document.getElementById('trashlist');
const trashCount = document.getElementById('trash-count');
const trashEmpty = document.getElementById('trash-empty-msg');
function trashRow(it) {
const el = document.createElement('div');
el.className = 'trashrow';
const parts = [];
if (it.image) parts.push('image');
if (it.hasMeta) parts.push('caption/tags');
el.innerHTML = `
<div class="meta">
<div class="slug"></div>
<div class="when">deleted ${it.deletedAt} · ${parts.join(' + ') || 'empty'}</div>
</div>
<button class="btn t-restore">Restore</button>
<button class="btn danger t-del">Delete forever</button>`;
el.querySelector('.slug').textContent = it.slug;
el.querySelector('.t-restore').addEventListener('click', () => restore(it));
el.querySelector('.t-del').addEventListener('click', () => deleteForever(it));
return el;
}
async function loadTrash() {
try {
const res = await fetch('/api/trash', { headers: { 'Accept': 'application/json' } });
if (!res.ok) throw new Error('HTTP ' + res.status);
const items = await res.json();
trashlist.innerHTML = '';
items.forEach(it => trashlist.appendChild(trashRow(it)));
trashCount.textContent = items.length + (items.length === 1 ? ' item' : ' items');
trashEmpty.style.display = items.length ? 'none' : 'block';
} catch (err) {
flash('Could not load trash: ' + err.message, false);
}
}
async function restore(it) {
const form = new FormData();
form.append('id', it.id);
try {
await post('/api/restore', form);
flash('Restored ' + it.slug, true);
await Promise.all([load(), loadTrash()]);
} catch (err) { flash('Restore failed: ' + err.message, false); }
}
async function deleteForever(it) {
if (!confirm('Permanently delete "' + it.slug + '"? This cannot be undone.')) return;
const form = new FormData();
form.append('id', it.id);
try {
await post('/api/trash/empty', form);
flash('Deleted ' + it.slug + ' forever', true);
await loadTrash();
} catch (err) { flash('Delete failed: ' + err.message, false); }
}
document.getElementById('trash-toggle').addEventListener('click', (e) => {
e.preventDefault();
const showing = trashpanel.classList.toggle('show');
if (showing) loadTrash();
});
document.getElementById('btn-empty-all').addEventListener('click', async () => {
if (!confirm('Permanently delete everything in the trash? This cannot be undone.')) return;
const form = new FormData();
form.append('all', '1');
try {
await post('/api/trash/empty', form);
flash('Trash emptied', true);
await loadTrash();
} catch (err) { flash('Empty failed: ' + err.message, false); }
});
load();
</script>
</body>
</html>
+5
View File
@@ -58,6 +58,11 @@
</div> </div>
<p class="dcaption">{{.Photo.Caption}}</p> <p class="dcaption">{{.Photo.Caption}}</p>
<p class="ddate">{{.Photo.Date.Format "Jan 02, 2006"}}</p> <p class="ddate">{{.Photo.Date.Format "Jan 02, 2006"}}</p>
{{if .Photo.Tags}}
<div class="dtags">
{{range .Photo.Tags}}<a href="/album/{{.Slug}}/" class="tag">{{.Name}}</a>{{end}}
</div>
{{end}}
<p class="dfull"><a href="/{{.Photo.File}}" download>↓ Full size</a></p> <p class="dfull"><a href="/{{.Photo.File}}" download>↓ Full size</a></p>
</div> </div>
</div> </div>
+2 -1
View File
@@ -24,13 +24,14 @@
<p class="pcount"><strong>{{.Total}}</strong> posts</p> <p class="pcount"><strong>{{.Total}}</strong> posts</p>
<p class="pbio">{{.Bio}}{{if .BioAlt}}<br><span class="ml">{{.BioAlt}}</span>{{end}}</p> <p class="pbio">{{.Bio}}{{if .BioAlt}}<br><span class="ml">{{.BioAlt}}</span>{{end}}</p>
<a href="/grid/" class="rss-a">Grid</a> <a href="/grid/" class="rss-a">Grid</a>
<a href="/albums/" class="rss-a">Albums</a>
<a href="/feed.xml" class="rss-a"> <a href="/feed.xml" class="rss-a">
<svg width="14" height="14" viewBox="0 0 14 14" fill="currentColor" aria-hidden="true"> <svg width="14" height="14" viewBox="0 0 14 14" fill="currentColor" aria-hidden="true">
<circle cx="2.5" cy="11.5" r="1.5"/> <circle cx="2.5" cy="11.5" r="1.5"/>
<path d="M1.5 7.5A5 5 0 0 1 6.5 12.5H8A6.5 6.5 0 0 0 1.5 6V7.5z"/> <path d="M1.5 7.5A5 5 0 0 1 6.5 12.5H8A6.5 6.5 0 0 0 1.5 6V7.5z"/>
<path d="M1.5 4A8.5 8.5 0 0 1 10 12.5h1.5A10 10 0 0 0 1.5 2.5V4z"/> <path d="M1.5 4A8.5 8.5 0 0 1 10 12.5h1.5A10 10 0 0 0 1.5 2.5V4z"/>
</svg> </svg>
RSS feed Feed
</a> </a>
<a href="https://git.inflo.ws/aashiks/photog" class="rss-a" target="_blank" rel="noopener"> <a href="https://git.inflo.ws/aashiks/photog" class="rss-a" target="_blank" rel="noopener">
<svg width="14" height="14" viewBox="0 0 16 16" fill="currentColor" aria-hidden="true"> <svg width="14" height="14" viewBox="0 0 16 16" fill="currentColor" aria-hidden="true">
+7
View File
@@ -161,6 +161,11 @@
<input type="date" id="date"> <input type="date" id="date">
</div> </div>
<div class="field">
<label for="tags">Tags</label>
<input type="text" id="tags" placeholder="comma-separated, lowercase" autocomplete="off">
</div>
<button class="submit-btn" id="submit-btn" disabled>Upload photo</button> <button class="submit-btn" id="submit-btn" disabled>Upload photo</button>
<div id="feedback"></div> <div id="feedback"></div>
</div> </div>
@@ -256,6 +261,7 @@
form.append('image', file); form.append('image', file);
form.append('caption', document.getElementById('caption').value); form.append('caption', document.getElementById('caption').value);
form.append('date', dateInput.value); form.append('date', dateInput.value);
form.append('tags', document.getElementById('tags').value);
try { try {
const res = await fetch('/upload', { method: 'POST', body: form }); const res = await fetch('/upload', { method: 'POST', body: form });
@@ -268,6 +274,7 @@
prompt.style.display = 'flex'; prompt.style.display = 'flex';
dropZone.classList.remove('has-image'); dropZone.classList.remove('has-image');
document.getElementById('caption').value = ''; document.getElementById('caption').value = '';
document.getElementById('tags').value = '';
submitBtn.disabled = true; submitBtn.disabled = true;
} else { } else {
feedback.className = 'err'; feedback.className = 'err';
+206
View File
@@ -0,0 +1,206 @@
package main
import (
"log"
"net/http"
"os"
"path/filepath"
"regexp"
"sort"
"strings"
"time"
)
// trashStamp is the timestamp moveToTrash appends: 20060102-150405.
var trashStamp = regexp.MustCompile(`^\d{8}-\d{6}$`)
// trashItem is one recoverable post in content/.trash/, grouping the image and
// its sidecar that were trashed together (same slug, same timestamp).
type trashItem struct {
ID string `json:"id"` // "<slug>.<stamp>", the restore/empty handle
Slug string `json:"slug"` // original slug it would restore to
DeletedAt string `json:"deletedAt"`
Image string `json:"image"` // trash filename of the image, "" if only a sidecar
HasMeta bool `json:"hasMeta"` // whether a sidecar is present
}
func (s *Server) trashDir() string { return filepath.Join(s.contentDir, ".trash") }
// parseTrashName splits a trash filename "<slug>.<stamp><ext>" into its parts.
// slug is a bare sanitised name (no dots) and stamp is a fixed timestamp, so
// the extension and the stamp peel off unambiguously from the right.
func parseTrashName(name string) (slug, stamp, ext string, ok bool) {
ext = filepath.Ext(name)
rest := strings.TrimSuffix(name, ext) // "<slug>.<stamp>"
i := strings.LastIndex(rest, ".")
if i < 0 {
return "", "", "", false
}
slug, stamp = rest[:i], rest[i+1:]
if slug == "" || slug != filepath.Base(slug) || strings.Contains(slug, ".") {
return "", "", "", false
}
if !trashStamp.MatchString(stamp) {
return "", "", "", false
}
return slug, stamp, ext, true
}
func isImageExt(ext string) bool {
for _, e := range contentExts {
if ext == e {
return true
}
}
return false
}
// handleListTrash returns trashed items, newest first.
func (s *Server) handleListTrash(w http.ResponseWriter, r *http.Request) {
entries, err := os.ReadDir(s.trashDir())
if err != nil {
// No trash dir yet → empty list, not an error.
writeJSON(w, []trashItem{})
return
}
byID := make(map[string]*trashItem)
for _, e := range entries {
if e.IsDir() {
continue
}
slug, stamp, ext, ok := parseTrashName(e.Name())
if !ok {
continue
}
id := slug + "." + stamp
it := byID[id]
if it == nil {
when := stamp
if t, err := time.ParseInLocation("20060102-150405", stamp, time.Local); err == nil {
when = t.Format("2006-01-02 15:04")
}
it = &trashItem{ID: id, Slug: slug, DeletedAt: when}
byID[id] = it
}
if ext == ".toml" {
it.HasMeta = true
} else if isImageExt(ext) {
it.Image = e.Name()
}
}
items := make([]trashItem, 0, len(byID))
for _, it := range byID {
items = append(items, *it)
}
// Newest first: the stamp sorts lexically in time order, and it is the tail
// of the ID.
sort.Slice(items, func(i, j int) bool { return items[i].ID > items[j].ID })
writeJSON(w, items)
}
// splitTrashID validates a "<slug>.<stamp>" handle and returns its parts.
func splitTrashID(id string) (slug, stamp string, ok bool) {
i := strings.LastIndex(id, ".")
if i < 0 {
return "", "", false
}
slug, stamp = id[:i], id[i+1:]
if slug == "" || slug != filepath.Base(slug) || strings.Contains(slug, ".") {
return "", "", false
}
if !trashStamp.MatchString(stamp) {
return "", "", false
}
return slug, stamp, true
}
// trashFiles returns the files in .trash belonging to one id (image + sidecar).
func (s *Server) trashFiles(slug, stamp string) []string {
var out []string
prefix := slug + "." + stamp
for _, ext := range append(append([]string{}, contentExts...), ".toml") {
p := filepath.Join(s.trashDir(), prefix+ext)
if _, err := os.Stat(p); err == nil {
out = append(out, p)
}
}
return out
}
// handleRestore moves a trashed post back into content/, stripping the
// timestamp. It refuses to overwrite a live post with the same slug.
func (s *Server) handleRestore(w http.ResponseWriter, r *http.Request) {
if s.rejectCrossSite(w, r) {
return
}
if err := r.ParseForm(); err != nil {
http.Error(w, "bad request", http.StatusBadRequest)
return
}
slug, stamp, ok := splitTrashID(r.FormValue("id"))
if !ok {
http.Error(w, "bad id", http.StatusBadRequest)
return
}
if _, live := s.resolveSlug(slug); live {
http.Error(w, "a post with that slug already exists", http.StatusConflict)
return
}
files := s.trashFiles(slug, stamp)
if len(files) == 0 {
http.Error(w, "not in trash", http.StatusNotFound)
return
}
for _, src := range files {
name := filepath.Base(src)
trashPrefix := slug + "." + stamp // "<slug>.<stamp>"
// "<slug>.<stamp>.png" → "<slug>.png"; "<slug>.<stamp>.toml" → "<slug>.toml"
dstName := slug + strings.TrimPrefix(name, trashPrefix)
if err := os.Rename(src, filepath.Join(s.contentDir, dstName)); err != nil {
log.Printf("restore %s: %v", name, err)
http.Error(w, "could not restore", http.StatusInternalServerError)
return
}
}
s.rebuild()
w.WriteHeader(http.StatusOK)
}
// handleEmptyTrash permanently deletes trashed items — specific ids (repeated
// `id` fields), or everything with `all=1`. This is the only hard delete.
func (s *Server) handleEmptyTrash(w http.ResponseWriter, r *http.Request) {
if s.rejectCrossSite(w, r) {
return
}
if err := r.ParseForm(); err != nil {
http.Error(w, "bad request", http.StatusBadRequest)
return
}
if r.FormValue("all") == "1" {
if err := os.RemoveAll(s.trashDir()); err != nil {
log.Printf("empty trash: %v", err)
http.Error(w, "could not empty trash", http.StatusInternalServerError)
return
}
writeJSON(w, map[string]string{"emptied": "all"})
return
}
removed := 0
for _, id := range r.Form["id"] {
slug, stamp, ok := splitTrashID(id)
if !ok {
continue
}
for _, p := range s.trashFiles(slug, stamp) {
if err := os.Remove(p); err == nil {
removed++
}
}
}
writeJSON(w, map[string]int{"removed": removed})
}
+139
View File
@@ -0,0 +1,139 @@
package main
import (
"encoding/json"
"net/http"
"net/http/httptest"
"net/url"
"os"
"path/filepath"
"testing"
)
func listTrash(t *testing.T, s *Server) []trashItem {
t.Helper()
rec := httptest.NewRecorder()
s.handleListTrash(rec, httptest.NewRequest(http.MethodGet, "/api/trash", nil))
if rec.Code != http.StatusOK {
t.Fatalf("list trash: code=%d", rec.Code)
}
var items []trashItem
if err := json.Unmarshal(rec.Body.Bytes(), &items); err != nil {
t.Fatalf("decode trash: %v", err)
}
return items
}
func TestTrashListAndRestore(t *testing.T) {
s, content, _ := newTestServer(t)
// Delete foo, then it should show up in the trash.
rec := httptest.NewRecorder()
s.handleDelete(rec, form(url.Values{"slug": {"foo"}}))
if rec.Code != http.StatusOK {
t.Fatalf("delete: %d", rec.Code)
}
items := listTrash(t, s)
if len(items) != 1 {
t.Fatalf("trash has %d items, want 1", len(items))
}
it := items[0]
if it.Slug != "foo" || !it.HasMeta || it.Image == "" {
t.Errorf("trash item wrong: %+v", it)
}
// Restore it.
rec = httptest.NewRecorder()
s.handleRestore(rec, form(url.Values{"id": {it.ID}}))
if rec.Code != http.StatusOK {
t.Fatalf("restore: code=%d body=%s", rec.Code, rec.Body)
}
for _, p := range []string{"foo.png", "foo.toml"} {
if _, err := os.Stat(filepath.Join(content, p)); err != nil {
t.Errorf("restored %s missing: %v", p, err)
}
}
if items := listTrash(t, s); len(items) != 0 {
t.Errorf("trash not empty after restore: %+v", items)
}
// Caption survived the round trip.
if readMeta(t, content, "foo").Caption != "Foo" {
t.Error("restored sidecar lost its caption")
}
}
func TestRestoreRefusesLiveCollision(t *testing.T) {
s, content, _ := newTestServer(t)
rec := httptest.NewRecorder()
s.handleDelete(rec, form(url.Values{"slug": {"foo"}}))
if rec.Code != http.StatusOK {
t.Fatalf("delete: %d", rec.Code)
}
id := listTrash(t, s)[0].ID
// A new live post now occupies the slug.
writePNG(t, filepath.Join(content, "foo.png"))
rec = httptest.NewRecorder()
s.handleRestore(rec, form(url.Values{"id": {id}}))
if rec.Code != http.StatusConflict {
t.Errorf("restore over live post: code=%d, want 409", rec.Code)
}
// The trashed copy is left intact for a manual decision.
if len(listTrash(t, s)) != 1 {
t.Error("trashed item should remain after refused restore")
}
}
func TestEmptyTrash(t *testing.T) {
s, _, _ := newTestServer(t)
// Trash both posts.
rec := httptest.NewRecorder()
s.handleDelete(rec, form(url.Values{"slugs": {"foo,bar"}}))
if rec.Code != http.StatusOK {
t.Fatalf("delete: %d", rec.Code)
}
items := listTrash(t, s)
if len(items) != 2 {
t.Fatalf("trash has %d, want 2", len(items))
}
// Empty one by id.
rec = httptest.NewRecorder()
s.handleEmptyTrash(rec, form(url.Values{"id": {items[0].ID}}))
if rec.Code != http.StatusOK {
t.Fatalf("empty one: %d", rec.Code)
}
if len(listTrash(t, s)) != 1 {
t.Error("expected 1 item left after deleting one")
}
// Empty all.
rec = httptest.NewRecorder()
s.handleEmptyTrash(rec, form(url.Values{"all": {"1"}}))
if rec.Code != http.StatusOK {
t.Fatalf("empty all: %d", rec.Code)
}
if len(listTrash(t, s)) != 0 {
t.Error("trash not empty after all")
}
}
func TestSplitTrashIDRejectsJunk(t *testing.T) {
cases := map[string]bool{
"foo.20260102-150405": true,
"foo.bar.20260102-150405": false, // slug "foo.bar" has a dot → rejected
"../x.20260102-150405": false, // traversal
"foo.2026": false, // malformed stamp
"foo": false, // no stamp
"": false,
}
for id, want := range cases {
if _, _, ok := splitTrashID(id); ok != want {
t.Errorf("splitTrashID(%q) = %v, want %v", id, ok, want)
}
}
}