Compare commits
19
Commits
a7f2afc3ad
...
trunk-ng
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
431ac2e610 | ||
|
|
504b96ed31 | ||
|
|
bb8c7109fa | ||
|
|
f1e946228a | ||
|
|
3614cfe1f8 | ||
|
|
2143b95657 | ||
|
|
125b6b5241 | ||
|
|
003a4057bf | ||
|
|
c21ddc5b7e | ||
|
|
225bdc9b4f | ||
|
|
e67d25b191 | ||
|
|
94859fb0d6 | ||
|
|
c4aa345914 | ||
|
|
bf75c9fe8e | ||
|
|
25384d3f3b | ||
|
|
8fa1aa4cd4 | ||
|
|
43075f00d4 | ||
|
|
3f719359de | ||
|
|
f1abd45f24 |
No files matched your search
@@ -19,7 +19,9 @@ The binary does three things at once:
|
||||
- Serves a multipart upload API at `POST /upload`
|
||||
- In dev mode (`--serve`), also serves `public/` as static files
|
||||
|
||||
Routes: `GET /upload` (HTML upload form), `POST /upload` (multipart),
|
||||
Routes: `GET /upload` (HTML upload form — multi-photo: the page posts one
|
||||
`POST /upload` per selected photo, each with its own caption/date/tags),
|
||||
`POST /upload` (multipart, one image per request),
|
||||
`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).
|
||||
@@ -41,6 +43,18 @@ credentials matching a line in that file; `GET /health` stays open. `$2y$`
|
||||
`$apr1$`, SHA, crypt) are skipped with a warning. Empty `-htpasswd` disables
|
||||
auth entirely (dev default) and logs a warning — `/upload` is then open.
|
||||
|
||||
`GET /api/session` is a deliberately **unguarded** probe (`handleSession`): it
|
||||
reads `r.BasicAuth()`, returns `200 {"authenticated":bool}` and never sends
|
||||
`WWW-Authenticate`, so a public page can ask without triggering the browser's
|
||||
login dialog. To stop it becoming a password oracle that sidesteps the limiter,
|
||||
a request with no credentials is answered cheaply as `false`, while one with
|
||||
*wrong* credentials runs through the same failed-attempt limiter (429 once
|
||||
drained). `static/session.js` (loaded by every page template) calls it and, when
|
||||
authenticated, builds a fixed toolbar with Upload / Manage / "Edit this"
|
||||
(`/manage?edit=<slug>`, from the photo pages' `data-slug`) links and a
|
||||
signed-in indicator. "Log out" is best-effort only — HTTP Basic has no reliable
|
||||
sign-out; a dependable one would need cookie sessions.
|
||||
|
||||
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`,
|
||||
@@ -55,6 +69,8 @@ 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.
|
||||
- `GET /api/thumb/{slug}` — serves that post's thumbnail JPEG from `public/thumbs/`. **Unguarded**: thumbnails are the same public data as the static `/thumbs/`, so nothing is protected, and keeping it off the auth path means it can never 401 and so can never trip the fail2ban auth jail over a per-row thumbnail load. Non-browser clients (the Android app) use it instead of the static `/thumbs/<slug>.jpg` path, because a front-door botwall on `location /` can block a non-browser client from the static site while `/api/` is proxied straight to the app.
|
||||
- `GET /api/tags.json` — serves the generated `public/tags.json` for the Android app's tag autocomplete. **Unguarded** (like `/api/session`): the tag list is the same public data as the static `/tags.json`, so nothing is protected, and keeping it off the auth path means it can never return 401 — otherwise an nginx auth-fail jail (fail2ban) would ban the app over a mere autocomplete poll. It lives under `/api/` only so nginx proxies it past a botwall; browsers read the static `/tags.json`.
|
||||
- `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.
|
||||
@@ -113,9 +129,9 @@ contain spaces (`"berlin trip"`), and its URL slug is derived with `sanitiseSlug
|
||||
- Gruvbox dark hard colour scheme
|
||||
- Crimson Pro (serif) for headings and captions — configurable via `-serif-family` / `-fonts-url`
|
||||
- Manjari for Malayalam text (bio line), via `-ml-family`
|
||||
- Two views of the same photos, both 3-column square grid → 2-column on mobile, both with infinite-scroll load-more. Page size is configurable via `-page-size` (default 60; NixOS `services.photogallery.pageSize`):
|
||||
- **Timeline is the site root** (`/`, `/page/2/`, …). Photos grouped by calendar day: one ISO date heading (`2026-06-14`) + count per day, then the square grid. `groupByDay` collapses the newest-first list into consecutive same-day runs; `chunkDayGroups` packs whole days into pages targeting `pageSize`, never splitting a day across a page boundary (so appended pages never duplicate a heading — the load-more JS relies on this).
|
||||
- **Grid** (`/grid/`, `/grid/page/2/`, …) is the flat square grid, linked from the profile header.
|
||||
- Two views of the same photos, both 3-column square grid → 2-column on mobile, both with infinite-scroll load-more. Page size is configurable via `-page-size` (default 60; NixOS `services.photogallery.pageSize`). Which view sits at the site root is chosen by `-default-view` (`timeline` or `grid`, default `timeline`; NixOS `services.photogallery.defaultView`): the chosen one owns `/` (`/`, `/page/2/`, …) and the other is published under `/<name>/`. `viewBase`/`pageURL` (`generator.go`) derive every page path, pager link and the Timeline↔Grid cross-links (`TimelineURL`/`GridURL` in the template data) from that one setting; `Build` removes both `timeline/` and `grid/` each run so a flipped default leaves no stale root behind.
|
||||
- **Timeline** (the default root): photos grouped by calendar day — one ISO date heading (`2026-06-14`) + count per day, then the square grid. `groupByDay` collapses the newest-first list into consecutive same-day runs; `chunkDayGroups` packs whole days into pages targeting `pageSize`, never splitting a day across a page boundary (so appended pages never duplicate a heading — the load-more JS relies on this).
|
||||
- **Grid** is the flat square grid. At `/grid/` by default, or at the root when `-default-view grid`.
|
||||
- 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
|
||||
|
||||
@@ -177,7 +193,7 @@ go run . --serve
|
||||
|
||||
## Android app
|
||||
|
||||
Kotlin + Jetpack Compose uploader: pick or share a photo, add caption and date, post. Credentials (HTTP Basic) are sealed with an Android Keystore AES-GCM key. See `android/README.md` for the detail.
|
||||
Kotlin + Jetpack Compose uploader: pick or share one or many photos, add caption/date/tags, post via a durable WorkManager queue. It also has a **Manage screen** (from the Post screen's "Manage" button) that lists published posts with thumbnails and edits caption/date/tags or deletes (to trash) via the same `/api/photos`, `/api/edit`, `/api/delete` endpoints the web `/manage` uses. The manage calls go through `UploadClient` (OkHttp + `org.json`, no extra deps); sending no `Origin`/`Sec-Fetch-Site` header, the app passes the server's same-origin CSRF check as a non-browser client. Thumbnails are fetched from `/api/thumb/<slug>` (unguarded public data, app-served) rather than the static `/thumbs/` path, so a botwall on `location /` doesn't blank them. Both tag fields (post and edit) autocomplete from the known tag list, fetched from `/api/tags.json` (unguarded public data, proxied past the botwall); suggestions filter on the token after the last comma and tapping one completes it. The multi-photo picker is constructed with an explicit `maxItems` so it reliably opens in multi-select mode. Credentials (HTTP Basic) are sealed with an Android Keystore AES-GCM key. See `android/README.md` for the detail.
|
||||
|
||||
Its own flake, deliberately separate from the root one so NixOS consumers of `nixosModules.default` don't pull the Android SDK into their lock:
|
||||
|
||||
@@ -250,7 +266,7 @@ nix build # succeeds
|
||||
## What's not done yet
|
||||
|
||||
- ActivityPub federation (planned later — start with RSS/Atom)
|
||||
- Edit/delete/trash in the Android and Qt apps (web `/manage` only so far; the `/api/` endpoints are there for the apps to adopt)
|
||||
- Restoring from trash is still web-only: the `/manage` page has it, but neither the Android nor the Qt desktop app exposes `/api/restore` or `/api/trash` yet. (Edit/delete and tag autocomplete now exist in all three clients.)
|
||||
- Any auth beyond the app's htpasswd Basic auth (no sessions, no per-user scopes)
|
||||
- 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
|
||||
@@ -1,12 +1,50 @@
|
||||
# photogallery
|
||||
|
||||
A minimal static photo gallery with an Atom feed and an upload API.
|
||||
A single-user static photo gallery: a Go binary watches a directory of images +
|
||||
`.toml` sidecars and regenerates a static site, with an Atom feed, albums, an
|
||||
authenticated upload/manage API, and Android + desktop apps. No
|
||||
database, no framework.
|
||||
|
||||
## Contributors
|
||||
|
||||
- **[Santhosh Raju](https://git.planet-express.in/fox)** — originated the ideas for the edit/delete ("manage")
|
||||
capability and the configurable default view (`-default-view`, timeline or
|
||||
grid as the site root). Both landed here as independent implementations
|
||||
building on that work.
|
||||
|
||||
## Features
|
||||
|
||||
**Gallery**
|
||||
- Two views of the same photos — a day-grouped **timeline** and a flat **grid** — either one as the site root (`-default-view`); the other lives under `/timeline/` or `/grid/`. 3-column square grid (2 on mobile) with infinite-scroll pagination.
|
||||
- **Single-day pages** (`/day/<date>/`) linked from each timeline date heading.
|
||||
- **Albums**: tag photos with free-text, lowercase tags; each tag is an album at `/album/<tag>/`, indexed at `/albums/`, plus a machine-readable `/tags.json`.
|
||||
- **Single photo pages** with newer/older navigation (arrow keys + touch swipe) and a link to the original.
|
||||
- **Open Graph / Twitter-card link previews** so shared photo links unfurl.
|
||||
- **Atom feed** at `/feed.xml`. Gruvbox-dark theme; configurable fonts and identity.
|
||||
|
||||
**Content & management (no database)**
|
||||
- `.toml` sidecars are the source of truth; the binary watches the content dir and rebuilds on any change. Four renditions per photo (original, 600² thumbnail, 1600px medium, 1200px OG), each skipped when already up to date.
|
||||
- **Web upload** (`/upload`): pick one or many photos, each with its own EXIF-prefilled date, caption and tag-autocompleting tags field; posted with per-photo status and retry.
|
||||
- **Manage UI** (`/manage`): edit caption/date/tags, bulk tag add/remove, and delete — delete is reversible (moves to `content/.trash/`, with restore / empty).
|
||||
- Tag autocomplete across the upload and manage forms, fed by `/tags.json`.
|
||||
|
||||
**Auth & security**
|
||||
- App-side **HTTP Basic auth** (bcrypt htpasswd, `-htpasswd`) on every write endpoint; nginx just terminates TLS and proxies. Failed attempts are rate-limited; state-changing requests get a same-origin (CSRF) check.
|
||||
- A **signed-in indicator** + management toolbar (Upload / Manage / Edit this) appear on every page when authenticated, via a silent `/api/session` probe (no login dialog for anonymous visitors).
|
||||
|
||||
**Clients**
|
||||
- The web upload + manage UI.
|
||||
- **Android** uploader/manager (Kotlin/Compose, `android/`): pick or share photos, multi-photo bulk upload with captions/dates/tags, plus a Manage screen to edit or delete published posts.
|
||||
- **Qt desktop** uploader (`desktop/`): bulk upload with configurable concurrency, HEIC support, credentials in the system keychain.
|
||||
|
||||
**Deployment**
|
||||
- One Go binary. NixOS flake + module (systemd service, tmpfiles, optional nginx vhost with ACME).
|
||||
|
||||
## How it works
|
||||
|
||||
1. Drop `photo.jpg` + `photo.toml` into the content directory (or upload via the web UI at `/upload`).
|
||||
2. The binary watches the directory and rebuilds the static site on any change.
|
||||
3. nginx serves `public/` and proxies `/upload` to the local API, secured with htpasswd.
|
||||
1. Drop `photo.jpg` + `photo.toml` into the content directory (or upload via the web UI at `/upload`, the manage UI, or an app).
|
||||
2. The binary watches the directory and rebuilds the static site on any change (and on every upload/edit/delete).
|
||||
3. nginx terminates TLS, serves `public/`, and proxies the dynamic endpoints (`/upload`, `/manage`, `/api/`) to the local API. **Auth is the app's job** now (bcrypt htpasswd via `-htpasswd`), not nginx's.
|
||||
|
||||
For each photo the generator produces a 600×600 square thumbnail for the grid
|
||||
and an aspect-preserved medium JPEG (longest side 1600) for the detail page.
|
||||
@@ -23,9 +61,13 @@ editable before submitting.
|
||||
```toml
|
||||
caption = "Tempelhof at sunrise"
|
||||
date = "2026-06-14"
|
||||
tags = ["berlin", "sunrise"]
|
||||
```
|
||||
|
||||
If no `.toml` is present the filename is used as the caption and today's date as the date.
|
||||
If no `.toml` is present the filename is used as the caption and today's date as
|
||||
the date. `tags` is optional, free-text and lowercased; each tag becomes an
|
||||
album. A tag may contain spaces (`"berlin trip"`); its URL slug is derived
|
||||
automatically.
|
||||
|
||||
---
|
||||
|
||||
@@ -58,6 +100,14 @@ services.photogallery = {
|
||||
enable = true;
|
||||
baseURL = "https://photos.yourdomain.tld";
|
||||
|
||||
# Auth for the upload/manage endpoints: a bcrypt htpasswd file. Handed to the
|
||||
# service via systemd LoadCredential, so a root-owned 0400 secret is fine.
|
||||
# Omit to leave /upload and /manage open.
|
||||
htpasswdFile = "/run/secrets/photogallery-htpasswd";
|
||||
|
||||
# Optional: which view is the site root ("timeline" or "grid")
|
||||
defaultView = "timeline";
|
||||
|
||||
# Optional: identity shown on the header and copyright footer
|
||||
author = "Ada Lovelace";
|
||||
handle = "@ada@example.com";
|
||||
@@ -69,20 +119,19 @@ services.photogallery = {
|
||||
serifFamily = "EB Garamond";
|
||||
mlFamily = "Manjari";
|
||||
|
||||
# Optional: built-in nginx vhost
|
||||
# Optional: built-in nginx vhost (TLS + proxy only; auth is app-side above)
|
||||
nginx = {
|
||||
enable = true;
|
||||
domain = "photos.yourdomain.tld";
|
||||
htpasswdFile = "/etc/nginx/.htpasswd-gallery";
|
||||
};
|
||||
};
|
||||
```
|
||||
|
||||
Create the htpasswd file:
|
||||
Create the htpasswd file (**bcrypt** — the app only accepts `-B` entries):
|
||||
|
||||
```bash
|
||||
nix-shell -p apacheHttpd --run \
|
||||
"htpasswd -c /etc/nginx/.htpasswd-gallery youruser"
|
||||
"htpasswd -B -c /run/secrets/photogallery-htpasswd youruser"
|
||||
```
|
||||
|
||||
### Available options
|
||||
@@ -94,6 +143,9 @@ nix-shell -p apacheHttpd --run \
|
||||
| `contentDir` | `/var/lib/photogallery/content` | Images and .toml sidecars |
|
||||
| `outputDir` | `/var/lib/photogallery/public` | Generated site output |
|
||||
| `port` | `8080` | Upload API port (localhost only) |
|
||||
| `htpasswdFile` | `null` | bcrypt htpasswd guarding write endpoints (null = open) |
|
||||
| `defaultView` | `timeline` | Site-root view: `timeline` or `grid` |
|
||||
| `pageSize` | `60` | Photos per page (timeline/grid) |
|
||||
| `author` | `Ashik Salahudeen` | Name shown on the header, photo pages and copyright footer |
|
||||
| `handle` | `@puttaalu@inflo.ws` | Handle line under the author name |
|
||||
| `bio` | `Personal photo journal.` | Primary bio line |
|
||||
@@ -101,9 +153,8 @@ nix-shell -p apacheHttpd --run \
|
||||
| `fontsURL` | Crimson Pro + Manjari | Stylesheet URL loading both web fonts |
|
||||
| `serifFamily` | `Crimson Pro` | CSS font-family for the primary serif |
|
||||
| `mlFamily` | `Manjari` | CSS font-family for the alt-script bio |
|
||||
| `nginx.enable` | `false` | Configure an nginx vhost |
|
||||
| `nginx.enable` | `false` | Configure an nginx vhost (TLS + proxy) |
|
||||
| `nginx.domain` | — | Domain for the vhost |
|
||||
| `nginx.htpasswdFile` | — | htpasswd file for `/upload` |
|
||||
| `nginx.enableACME` | `true` | Enable Let's Encrypt |
|
||||
|
||||
---
|
||||
@@ -134,7 +185,23 @@ curl -u user:password \
|
||||
-F "image=@photo.jpg" \
|
||||
-F "caption=Tempelhof at sunrise" \
|
||||
-F "date=2026-06-14" \
|
||||
-F "tags=berlin, sunrise" \
|
||||
https://photos.yourdomain.tld/upload
|
||||
```
|
||||
|
||||
Or open `https://photos.yourdomain.tld/upload` in a browser.
|
||||
Or open `https://photos.yourdomain.tld/upload` in a browser, manage existing
|
||||
posts at `/manage`, or use one of the apps below.
|
||||
|
||||
## Apps
|
||||
|
||||
Both use the same API (HTTP Basic auth) and need no server change.
|
||||
|
||||
- **Android** (`android/`) — Kotlin/Compose. Pick or share one or many photos,
|
||||
set caption/date/tags, uploads run in a durable background queue. A Manage
|
||||
screen lists published posts (with thumbnails) and edits their
|
||||
caption/date/tags or deletes them to the server's trash, over the same
|
||||
`/api/*` endpoints the web `/manage` uses. Has its own flake;
|
||||
`cd android && nix develop && ./gradlew assembleRelease`.
|
||||
- **Qt desktop** (`desktop/`) — Qt6/C++. Bulk upload with configurable
|
||||
concurrency, HEIC support, credentials stored in the system keychain. Builds
|
||||
via its own flake in `desktop/`.
|
||||
@@ -108,6 +108,8 @@ func (g *Generator) baseData() map[string]any {
|
||||
"FontsURL": g.fontsURL,
|
||||
"SerifFamily": g.serifFamily,
|
||||
"MlFamily": g.mlFamily,
|
||||
"TimelineURL": g.timelineURL(),
|
||||
"GridURL": g.gridURL(),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+10
-4
@@ -1,11 +1,17 @@
|
||||
# Gallery Upload — Android client
|
||||
|
||||
Native uploader for the photogallery `POST /upload` endpoint. Pick or share a
|
||||
photo, add a caption and date, post. Credentials are entered once and sealed
|
||||
with a key held in the Android Keystore.
|
||||
Native uploader and manager for the photogallery server. Pick or share one or
|
||||
many photos, add caption/date/tags, and post. A **Manage** screen lists the
|
||||
published posts and edits their caption/date/tags or deletes them (to the
|
||||
server's trash) over the same `/api/*` endpoints the web `/manage` uses.
|
||||
Both tag fields autocomplete from the existing tags (fetched from
|
||||
`/api/tags.json`, unguarded public data proxied past the botwall), filtering on
|
||||
the token after the last comma.
|
||||
Credentials are entered once and sealed with a key held in the Android Keystore.
|
||||
|
||||
The server is not modified by this app. Everything it needs, it does client
|
||||
side.
|
||||
side; the management calls send no browser headers, so they pass the server's
|
||||
same-origin (CSRF) check as a non-browser client.
|
||||
|
||||
## Build
|
||||
|
||||
|
||||
@@ -20,6 +20,7 @@ import androidx.compose.runtime.setValue
|
||||
import androidx.compose.runtime.saveable.rememberSaveable
|
||||
import androidx.core.content.ContextCompat
|
||||
import androidx.core.net.toUri
|
||||
import ws.inflo.photogallery.ui.ManageScreen
|
||||
import ws.inflo.photogallery.ui.PhotoGalleryTheme
|
||||
import ws.inflo.photogallery.ui.PostScreen
|
||||
import ws.inflo.photogallery.ui.SettingsScreen
|
||||
@@ -37,9 +38,13 @@ class MainActivity : ComponentActivity() {
|
||||
PhotoGalleryTheme {
|
||||
// Land on settings until there is somewhere to post to.
|
||||
var showSettings by rememberSaveable { mutableStateOf(!viewModel.isConfigured) }
|
||||
var showManage by rememberSaveable { mutableStateOf(false) }
|
||||
|
||||
// Explicit maxItems so the system photo picker reliably opens in
|
||||
// multi-select mode (the no-arg default has been seen to present
|
||||
// single-select on some devices).
|
||||
val picker = rememberLauncherForActivityResult(
|
||||
ActivityResultContracts.PickMultipleVisualMedia(),
|
||||
ActivityResultContracts.PickMultipleVisualMedia(maxItems = 50),
|
||||
) { uris -> if (uris.isNotEmpty()) viewModel.selectImages(uris) }
|
||||
|
||||
val notificationPermission = rememberLauncherForActivityResult(
|
||||
@@ -57,8 +62,8 @@ class MainActivity : ComponentActivity() {
|
||||
}
|
||||
}
|
||||
|
||||
if (showSettings) {
|
||||
SettingsScreen(
|
||||
when {
|
||||
showSettings -> SettingsScreen(
|
||||
state = viewModel.config,
|
||||
onBaseUrlChange = viewModel::setBaseUrl,
|
||||
onUsernameChange = viewModel::setUsername,
|
||||
@@ -70,9 +75,20 @@ class MainActivity : ComponentActivity() {
|
||||
null
|
||||
},
|
||||
)
|
||||
} else {
|
||||
PostScreen(
|
||||
|
||||
showManage -> ManageScreen(
|
||||
state = viewModel.manage,
|
||||
tagSuggestions = viewModel.tagSuggestions,
|
||||
onBack = { showManage = false },
|
||||
onRefresh = viewModel::loadManage,
|
||||
onSave = viewModel::saveEdit,
|
||||
onDelete = viewModel::deletePost,
|
||||
onDismissNotice = viewModel::clearManageNotice,
|
||||
)
|
||||
|
||||
else -> PostScreen(
|
||||
state = viewModel.post,
|
||||
tagSuggestions = viewModel.tagSuggestions,
|
||||
onPickImages = {
|
||||
picker.launch(
|
||||
PickVisualMediaRequest(
|
||||
@@ -87,6 +103,10 @@ class MainActivity : ComponentActivity() {
|
||||
onSubmit = viewModel::submit,
|
||||
onReset = viewModel::clear,
|
||||
onOpenSettings = { showSettings = true },
|
||||
onOpenManage = {
|
||||
viewModel.loadManage()
|
||||
showManage = true
|
||||
},
|
||||
onOpenUrl = ::openUrl,
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
package ws.inflo.photogallery.net
|
||||
|
||||
import android.graphics.Bitmap
|
||||
import android.graphics.BitmapFactory
|
||||
import okhttp3.Credentials
|
||||
import okhttp3.FormBody
|
||||
import okhttp3.Interceptor
|
||||
import okhttp3.MediaType.Companion.toMediaType
|
||||
import okhttp3.MultipartBody
|
||||
@@ -8,6 +11,8 @@ import okhttp3.OkHttpClient
|
||||
import okhttp3.Request
|
||||
import okhttp3.RequestBody.Companion.asRequestBody
|
||||
import okhttp3.Response
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONException
|
||||
import java.io.File
|
||||
import java.io.IOException
|
||||
import java.util.concurrent.TimeUnit
|
||||
@@ -25,6 +30,22 @@ sealed interface UploadOutcome {
|
||||
data class Transient(val message: String) : UploadOutcome
|
||||
}
|
||||
|
||||
/** One published post, as returned by GET /api/photos. */
|
||||
data class RemotePhoto(
|
||||
val slug: String,
|
||||
val caption: String,
|
||||
val date: String, // YYYY-MM-DD
|
||||
val tags: List<String>,
|
||||
val thumb: String, // site-relative, e.g. "/thumbs/foo.jpg"
|
||||
val url: String, // site-relative, e.g. "/photo/foo/"
|
||||
)
|
||||
|
||||
/** Result of listing posts for the manage screen. */
|
||||
sealed interface ListResult {
|
||||
data class Ok(val photos: List<RemotePhoto>) : ListResult
|
||||
data class Err(val message: String) : ListResult
|
||||
}
|
||||
|
||||
/**
|
||||
* Talks to the gallery's POST /upload endpoint.
|
||||
*
|
||||
@@ -122,6 +143,153 @@ class UploadClient(
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Lists every published post for the manage screen. The manage endpoints
|
||||
* sit behind the same Basic auth as /upload; the app sends no Origin or
|
||||
* Sec-Fetch-Site header, so it passes the server's same-origin (CSRF) check
|
||||
* as a non-browser client.
|
||||
*/
|
||||
fun listPhotos(): ListResult {
|
||||
val request = Request.Builder().url("$base/api/photos").get().build()
|
||||
return try {
|
||||
client.newCall(request).execute().use { response ->
|
||||
val text = response.body?.string().orEmpty()
|
||||
when {
|
||||
response.isSuccessful -> parsePhotos(text)
|
||||
response.code == 401 || response.code == 403 ->
|
||||
ListResult.Err("Wrong username or password")
|
||||
else -> ListResult.Err("Server returned ${response.code}")
|
||||
}
|
||||
}
|
||||
} catch (e: IOException) {
|
||||
ListResult.Err(e.message ?: "Network error")
|
||||
} catch (e: JSONException) {
|
||||
ListResult.Err("Could not read the server's response")
|
||||
}
|
||||
}
|
||||
|
||||
private fun parsePhotos(body: String): ListResult {
|
||||
val arr = JSONArray(body)
|
||||
val out = ArrayList<RemotePhoto>(arr.length())
|
||||
for (i in 0 until arr.length()) {
|
||||
val o = arr.getJSONObject(i)
|
||||
val tagsArr = o.optJSONArray("tags")
|
||||
val tags = ArrayList<String>()
|
||||
if (tagsArr != null) {
|
||||
for (j in 0 until tagsArr.length()) tags.add(tagsArr.getString(j))
|
||||
}
|
||||
out.add(
|
||||
RemotePhoto(
|
||||
slug = o.getString("slug"),
|
||||
caption = o.optString("caption"),
|
||||
date = o.optString("date"),
|
||||
tags = tags,
|
||||
thumb = o.optString("thumb"),
|
||||
url = o.optString("url"),
|
||||
),
|
||||
)
|
||||
}
|
||||
return ListResult.Ok(out)
|
||||
}
|
||||
|
||||
/**
|
||||
* Rewrites a post's sidecar. The slug (and its URL) never changes. Returns
|
||||
* null on success, or a human-readable error.
|
||||
*/
|
||||
fun editPost(slug: String, caption: String, date: String, tags: String): String? {
|
||||
val form = FormBody.Builder()
|
||||
.add("slug", slug)
|
||||
.add("caption", caption)
|
||||
.add("date", date)
|
||||
.add("tags", tags)
|
||||
.build()
|
||||
val request = Request.Builder().url("$base/api/edit").post(form).build()
|
||||
return simpleResult(request)
|
||||
}
|
||||
|
||||
/**
|
||||
* Moves a post to the server's trash (reversible there). Returns null on
|
||||
* success, or a human-readable error — including the case where the server
|
||||
* reports that nothing was deleted.
|
||||
*/
|
||||
fun deletePost(slug: String): String? {
|
||||
val form = FormBody.Builder().add("slug", slug).build()
|
||||
val request = Request.Builder().url("$base/api/delete").post(form).build()
|
||||
return try {
|
||||
client.newCall(request).execute().use { response ->
|
||||
val text = response.body?.string().orEmpty()
|
||||
when {
|
||||
response.isSuccessful -> {
|
||||
val deleted = runCatching {
|
||||
org.json.JSONObject(text).optInt("deleted", 0)
|
||||
}.getOrDefault(0)
|
||||
if (deleted > 0) null else "Nothing deleted — not found on the server"
|
||||
}
|
||||
response.code == 401 || response.code == 403 -> "Wrong username or password"
|
||||
else -> text.trim().ifEmpty { "Server returned ${response.code}" }
|
||||
}
|
||||
}
|
||||
} catch (e: IOException) {
|
||||
e.message ?: "Network error"
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetches the known tag names for autocomplete, alphabetical. Reads
|
||||
* /api/tags.json (not the static /tags.json) so a front-door botwall on
|
||||
* `location /` can't blank it for this non-browser client, mirroring how
|
||||
* thumbnails go through /api/thumb/. That endpoint is unguarded on the
|
||||
* server (public tag data), so it never 401s and can't get the app banned
|
||||
* by an auth-fail jail; the Basic header still rides along harmlessly.
|
||||
* Returns an empty list on any failure — autocomplete is a convenience,
|
||||
* never a hard dependency.
|
||||
*/
|
||||
fun fetchTags(): List<String> {
|
||||
val request = Request.Builder().url("$base/api/tags.json").get().build()
|
||||
return try {
|
||||
client.newCall(request).execute().use { response ->
|
||||
if (!response.isSuccessful) return emptyList()
|
||||
val arr = JSONArray(response.body?.string().orEmpty())
|
||||
val out = ArrayList<String>(arr.length())
|
||||
for (i in 0 until arr.length()) {
|
||||
val name = arr.getJSONObject(i).optString("tag")
|
||||
if (name.isNotEmpty()) out.add(name)
|
||||
}
|
||||
out
|
||||
}
|
||||
} catch (e: IOException) {
|
||||
emptyList()
|
||||
} catch (e: JSONException) {
|
||||
emptyList()
|
||||
}
|
||||
}
|
||||
|
||||
/** Fetches a thumbnail by its site-relative [path], or null on any failure. */
|
||||
fun fetchThumbnail(path: String): Bitmap? {
|
||||
val request = Request.Builder().url("$base$path").get().build()
|
||||
return try {
|
||||
client.newCall(request).execute().use { response ->
|
||||
if (!response.isSuccessful) return null
|
||||
response.body?.byteStream()?.let { BitmapFactory.decodeStream(it) }
|
||||
}
|
||||
} catch (e: IOException) {
|
||||
null
|
||||
}
|
||||
}
|
||||
|
||||
private fun simpleResult(request: Request): String? = try {
|
||||
client.newCall(request).execute().use { response ->
|
||||
val text = response.body?.string().orEmpty()
|
||||
when {
|
||||
response.isSuccessful -> null
|
||||
response.code == 401 || response.code == 403 -> "Wrong username or password"
|
||||
else -> text.trim().ifEmpty { "Server returned ${response.code}" }
|
||||
}
|
||||
}
|
||||
} catch (e: IOException) {
|
||||
e.message ?: "Network error"
|
||||
}
|
||||
|
||||
/** Server replies "uploaded <slug>.<ext>"; recover the slug from that. */
|
||||
private fun parseSlug(responseBody: String, fallback: String): String {
|
||||
val name = responseBody.trim().removePrefix("uploaded ").trim()
|
||||
|
||||
@@ -0,0 +1,309 @@
|
||||
package ws.inflo.photogallery.ui
|
||||
|
||||
import androidx.compose.foundation.Image
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.lazy.LazyColumn
|
||||
import androidx.compose.foundation.lazy.items
|
||||
import androidx.compose.material3.AlertDialog
|
||||
import androidx.compose.material3.Button
|
||||
import androidx.compose.material3.CircularProgressIndicator
|
||||
import androidx.compose.material3.DatePicker
|
||||
import androidx.compose.material3.DatePickerDialog
|
||||
import androidx.compose.material3.ExperimentalMaterial3Api
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.OutlinedButton
|
||||
import androidx.compose.material3.OutlinedTextField
|
||||
import androidx.compose.material3.Surface
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.material3.rememberDatePickerState
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.graphics.asImageBitmap
|
||||
import androidx.compose.ui.layout.ContentScale
|
||||
import androidx.compose.ui.text.font.FontFamily
|
||||
import androidx.compose.ui.unit.dp
|
||||
import java.time.Instant
|
||||
import java.time.LocalDate
|
||||
import java.time.ZoneId
|
||||
import java.time.format.DateTimeFormatter
|
||||
|
||||
private val DISPLAY_DATE: DateTimeFormatter = DateTimeFormatter.ofPattern("d MMM yyyy")
|
||||
|
||||
@Composable
|
||||
fun ManageScreen(
|
||||
state: ManageUiState,
|
||||
tagSuggestions: List<String>,
|
||||
onBack: () -> Unit,
|
||||
onRefresh: () -> Unit,
|
||||
onSave: (slug: String, caption: String, date: LocalDate, tags: String) -> Unit,
|
||||
onDelete: (slug: String) -> Unit,
|
||||
onDismissNotice: () -> Unit,
|
||||
) {
|
||||
var editing by remember { mutableStateOf<ManagePost?>(null) }
|
||||
var deleting by remember { mutableStateOf<ManagePost?>(null) }
|
||||
|
||||
Surface(color = MaterialTheme.colorScheme.background, modifier = Modifier.fillMaxSize()) {
|
||||
LazyColumn(
|
||||
modifier = Modifier
|
||||
.fillMaxSize()
|
||||
.padding(20.dp),
|
||||
) {
|
||||
item {
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
horizontalArrangement = Arrangement.SpaceBetween,
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Text("Manage posts", style = MaterialTheme.typography.headlineSmall, color = GruvGreen)
|
||||
Row {
|
||||
TextButton(onClick = onRefresh) { Text("Refresh") }
|
||||
TextButton(onClick = onBack) { Text("Back") }
|
||||
}
|
||||
}
|
||||
Spacer(Modifier.height(8.dp))
|
||||
}
|
||||
|
||||
state.error?.let { msg ->
|
||||
item { Notice(msg, GruvRed, onDismissNotice) }
|
||||
}
|
||||
state.message?.let { msg ->
|
||||
item { Notice(msg, GruvAqua, onDismissNotice) }
|
||||
}
|
||||
|
||||
if (state.loading) {
|
||||
item {
|
||||
Box(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.height(120.dp),
|
||||
contentAlignment = Alignment.Center,
|
||||
) { CircularProgressIndicator(color = GruvAqua) }
|
||||
}
|
||||
} else if (state.items.isEmpty()) {
|
||||
item {
|
||||
Box(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.height(120.dp),
|
||||
contentAlignment = Alignment.Center,
|
||||
) { Text("No posts.", color = GruvFg4) }
|
||||
}
|
||||
}
|
||||
|
||||
items(state.items, key = { it.slug }) { post ->
|
||||
PostRow(
|
||||
post = post,
|
||||
onEdit = { editing = post },
|
||||
onDelete = { deleting = post },
|
||||
)
|
||||
Spacer(Modifier.height(12.dp))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
editing?.let { post ->
|
||||
EditDialog(
|
||||
post = post,
|
||||
tagSuggestions = tagSuggestions,
|
||||
onDismiss = { editing = null },
|
||||
onSave = { caption, date, tags ->
|
||||
onSave(post.slug, caption, date, tags)
|
||||
editing = null
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
deleting?.let { post ->
|
||||
AlertDialog(
|
||||
onDismissRequest = { deleting = null },
|
||||
title = { Text("Move to trash?") },
|
||||
text = { Text("\"${post.caption.ifBlank { post.slug }}\" will be moved to the server's trash.") },
|
||||
confirmButton = {
|
||||
TextButton(onClick = {
|
||||
onDelete(post.slug)
|
||||
deleting = null
|
||||
}) { Text("Delete", color = GruvRed) }
|
||||
},
|
||||
dismissButton = { TextButton(onClick = { deleting = null }) { Text("Cancel") } },
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun Notice(message: String, color: androidx.compose.ui.graphics.Color, onDismiss: () -> Unit) {
|
||||
Row(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.background(GruvBg1)
|
||||
.padding(12.dp),
|
||||
horizontalArrangement = Arrangement.SpaceBetween,
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Text(message, color = color, style = MaterialTheme.typography.bodyMedium)
|
||||
TextButton(onClick = onDismiss) { Text("Dismiss") }
|
||||
}
|
||||
Spacer(Modifier.height(12.dp))
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun PostRow(post: ManagePost, onEdit: () -> Unit, onDelete: () -> Unit) {
|
||||
Row(modifier = Modifier.fillMaxWidth()) {
|
||||
Box(
|
||||
modifier = Modifier
|
||||
.size(72.dp)
|
||||
.background(GruvBg1),
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
val preview = post.preview
|
||||
if (preview != null) {
|
||||
Image(
|
||||
bitmap = preview.asImageBitmap(),
|
||||
contentDescription = null,
|
||||
contentScale = ContentScale.Crop,
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
Spacer(Modifier.width(12.dp))
|
||||
|
||||
Column(modifier = Modifier.weight(1f)) {
|
||||
Text(
|
||||
post.caption.ifBlank { post.slug },
|
||||
color = GruvFg,
|
||||
style = MaterialTheme.typography.bodyLarge,
|
||||
)
|
||||
Text(post.date.format(DISPLAY_DATE), color = GruvFg4, fontFamily = FontFamily.Monospace, style = MaterialTheme.typography.bodySmall)
|
||||
if (post.tags.isNotEmpty()) {
|
||||
Text(post.tags.joinToString(" · "), color = GruvAqua, style = MaterialTheme.typography.bodySmall)
|
||||
}
|
||||
Spacer(Modifier.height(4.dp))
|
||||
Row {
|
||||
if (post.busy) {
|
||||
CircularProgressIndicator(color = GruvAqua, modifier = Modifier.size(18.dp))
|
||||
} else {
|
||||
OutlinedButton(onClick = onEdit) { Text("Edit") }
|
||||
Spacer(Modifier.width(8.dp))
|
||||
TextButton(onClick = onDelete) { Text("Delete", color = GruvRed) }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun EditDialog(
|
||||
post: ManagePost,
|
||||
tagSuggestions: List<String>,
|
||||
onDismiss: () -> Unit,
|
||||
onSave: (caption: String, date: LocalDate, tags: String) -> Unit,
|
||||
) {
|
||||
var caption by remember { mutableStateOf(post.caption) }
|
||||
var tags by remember { mutableStateOf(post.tags.joinToString(", ")) }
|
||||
var date by remember { mutableStateOf(post.date) }
|
||||
var pickingDate by remember { mutableStateOf(false) }
|
||||
|
||||
AlertDialog(
|
||||
onDismissRequest = onDismiss,
|
||||
title = { Text("Edit ${post.slug}") },
|
||||
text = {
|
||||
Column {
|
||||
val preview = post.preview
|
||||
if (preview != null) {
|
||||
Image(
|
||||
bitmap = preview.asImageBitmap(),
|
||||
contentDescription = null,
|
||||
contentScale = ContentScale.Crop,
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.height(160.dp)
|
||||
.background(GruvBg1),
|
||||
)
|
||||
Spacer(Modifier.height(10.dp))
|
||||
}
|
||||
OutlinedTextField(
|
||||
value = caption,
|
||||
onValueChange = { caption = it },
|
||||
label = { Text("Caption") },
|
||||
singleLine = true,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
)
|
||||
Spacer(Modifier.height(8.dp))
|
||||
TagField(
|
||||
value = tags,
|
||||
onValueChange = { tags = it },
|
||||
suggestions = tagSuggestions,
|
||||
enabled = true,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
)
|
||||
Spacer(Modifier.height(8.dp))
|
||||
OutlinedButton(onClick = { pickingDate = true }) {
|
||||
Text(date.format(DISPLAY_DATE))
|
||||
}
|
||||
}
|
||||
},
|
||||
confirmButton = {
|
||||
TextButton(onClick = { onSave(caption, date, tags) }) { Text("Save") }
|
||||
},
|
||||
dismissButton = { TextButton(onClick = onDismiss) { Text("Cancel") } },
|
||||
)
|
||||
|
||||
if (pickingDate) {
|
||||
DatePickerModal(
|
||||
initial = date,
|
||||
onDismiss = { pickingDate = false },
|
||||
onConfirm = {
|
||||
date = it
|
||||
pickingDate = false
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
private fun DatePickerModal(
|
||||
initial: LocalDate,
|
||||
onDismiss: () -> Unit,
|
||||
onConfirm: (LocalDate) -> Unit,
|
||||
) {
|
||||
val pickerState = rememberDatePickerState(
|
||||
initialSelectedDateMillis = initial
|
||||
.atStartOfDay(ZoneId.systemDefault())
|
||||
.toInstant()
|
||||
.toEpochMilli(),
|
||||
)
|
||||
DatePickerDialog(
|
||||
onDismissRequest = onDismiss,
|
||||
confirmButton = {
|
||||
TextButton(onClick = {
|
||||
val millis = pickerState.selectedDateMillis
|
||||
if (millis != null) {
|
||||
onConfirm(Instant.ofEpochMilli(millis).atZone(ZoneId.systemDefault()).toLocalDate())
|
||||
} else {
|
||||
onDismiss()
|
||||
}
|
||||
}) { Text("OK") }
|
||||
},
|
||||
dismissButton = { TextButton(onClick = onDismiss) { Text("Cancel") } },
|
||||
) {
|
||||
DatePicker(state = pickerState)
|
||||
}
|
||||
}
|
||||
@@ -49,6 +49,7 @@ private val DISPLAY_DATE: DateTimeFormatter = DateTimeFormatter.ofPattern("d MMM
|
||||
@Composable
|
||||
fun PostScreen(
|
||||
state: PostUiState,
|
||||
tagSuggestions: List<String>,
|
||||
onPickImages: () -> Unit,
|
||||
onCaptionChange: (id: String, value: String) -> Unit,
|
||||
onTagsChange: (id: String, value: String) -> Unit,
|
||||
@@ -57,6 +58,7 @@ fun PostScreen(
|
||||
onSubmit: () -> Unit,
|
||||
onReset: () -> Unit,
|
||||
onOpenSettings: () -> Unit,
|
||||
onOpenManage: () -> Unit,
|
||||
onOpenUrl: (String) -> Unit,
|
||||
) {
|
||||
// Which item's date is being edited, if any.
|
||||
@@ -78,8 +80,11 @@ fun PostScreen(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Text("Post photos", style = MaterialTheme.typography.headlineSmall, color = GruvGreen)
|
||||
Row {
|
||||
TextButton(onClick = onOpenManage) { Text("Manage") }
|
||||
TextButton(onClick = onOpenSettings) { Text("Settings") }
|
||||
}
|
||||
}
|
||||
Spacer(Modifier.height(12.dp))
|
||||
}
|
||||
|
||||
@@ -107,6 +112,7 @@ fun PostScreen(
|
||||
items(state.items, key = { it.id }) { item ->
|
||||
ItemCard(
|
||||
item = item,
|
||||
tagSuggestions = tagSuggestions,
|
||||
onCaptionChange = { onCaptionChange(item.id, it) },
|
||||
onTagsChange = { onTagsChange(item.id, it) },
|
||||
onEditDate = { dateEditFor = item },
|
||||
@@ -186,6 +192,7 @@ fun PostScreen(
|
||||
@Composable
|
||||
private fun ItemCard(
|
||||
item: PickedItem,
|
||||
tagSuggestions: List<String>,
|
||||
onCaptionChange: (String) -> Unit,
|
||||
onTagsChange: (String) -> Unit,
|
||||
onEditDate: () -> Unit,
|
||||
@@ -223,12 +230,10 @@ private fun ItemCard(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
)
|
||||
Spacer(Modifier.height(6.dp))
|
||||
OutlinedTextField(
|
||||
TagField(
|
||||
value = item.tags,
|
||||
onValueChange = onTagsChange,
|
||||
label = { Text("Tags") },
|
||||
placeholder = { Text("comma-separated") },
|
||||
singleLine = true,
|
||||
suggestions = tagSuggestions,
|
||||
enabled = item.status !is ItemStatus.Uploading,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
)
|
||||
|
||||
@@ -0,0 +1,101 @@
|
||||
package ws.inflo.photogallery.ui
|
||||
|
||||
import androidx.compose.foundation.horizontalScroll
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.material3.OutlinedTextField
|
||||
import androidx.compose.material3.SuggestionChip
|
||||
import androidx.compose.material3.SuggestionChipDefaults
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.focus.onFocusChanged
|
||||
import androidx.compose.ui.unit.dp
|
||||
|
||||
private const val MAX_SUGGESTIONS = 8
|
||||
|
||||
/**
|
||||
* A comma-separated tags input with inline autocomplete. Suggestions filter on
|
||||
* the token currently being typed (the text after the last comma) and exclude
|
||||
* tags already entered; tapping one completes that token and starts the next.
|
||||
* The raw string is passed straight through — the server normalizes it.
|
||||
*/
|
||||
@Composable
|
||||
fun TagField(
|
||||
value: String,
|
||||
onValueChange: (String) -> Unit,
|
||||
suggestions: List<String>,
|
||||
enabled: Boolean,
|
||||
modifier: Modifier = Modifier,
|
||||
) {
|
||||
var focused by remember { mutableStateOf(false) }
|
||||
|
||||
val already = remember(value) {
|
||||
value.split(',').map { it.trim().lowercase() }.filter { it.isNotEmpty() }.toSet()
|
||||
}
|
||||
val token = value.substringAfterLast(',').trim()
|
||||
val matches = remember(token, suggestions, already) {
|
||||
if (token.isEmpty()) {
|
||||
emptyList()
|
||||
} else {
|
||||
suggestions.asSequence()
|
||||
.filter { it.lowercase().contains(token.lowercase()) }
|
||||
.filter { it.lowercase() !in already }
|
||||
.distinct()
|
||||
.take(MAX_SUGGESTIONS)
|
||||
.toList()
|
||||
}
|
||||
}
|
||||
|
||||
Column(modifier = modifier) {
|
||||
OutlinedTextField(
|
||||
value = value,
|
||||
onValueChange = onValueChange,
|
||||
label = { Text("Tags") },
|
||||
placeholder = { Text("comma-separated") },
|
||||
singleLine = true,
|
||||
enabled = enabled,
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.onFocusChanged { focused = it.isFocused },
|
||||
)
|
||||
if (enabled && focused && matches.isNotEmpty()) {
|
||||
Spacer(Modifier.height(6.dp))
|
||||
Row(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.horizontalScroll(rememberScrollState()),
|
||||
horizontalArrangement = Arrangement.spacedBy(6.dp),
|
||||
) {
|
||||
for (tag in matches) {
|
||||
SuggestionChip(
|
||||
onClick = { onValueChange(completeToken(value, tag)) },
|
||||
label = { Text(tag) },
|
||||
colors = SuggestionChipDefaults.suggestionChipColors(
|
||||
labelColor = GruvAqua,
|
||||
containerColor = GruvBg1,
|
||||
),
|
||||
)
|
||||
}
|
||||
Spacer(Modifier.width(2.dp))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Replaces the in-progress token (after the last comma) with [chosen] + ", ". */
|
||||
private fun completeToken(current: String, chosen: String): String {
|
||||
val lastComma = current.lastIndexOf(',')
|
||||
val head = if (lastComma >= 0) current.substring(0, lastComma + 1) + " " else ""
|
||||
return head + chosen + ", "
|
||||
}
|
||||
@@ -17,11 +17,14 @@ import kotlinx.coroutines.withContext
|
||||
import ws.inflo.photogallery.data.LastPost
|
||||
import ws.inflo.photogallery.data.SettingsStore
|
||||
import ws.inflo.photogallery.image.ImagePrep
|
||||
import ws.inflo.photogallery.net.ListResult
|
||||
import ws.inflo.photogallery.net.RemotePhoto
|
||||
import ws.inflo.photogallery.net.UploadClient
|
||||
import ws.inflo.photogallery.work.UploadQueue
|
||||
import ws.inflo.photogallery.work.UploadWorker
|
||||
import java.io.File
|
||||
import java.time.LocalDate
|
||||
import java.time.format.DateTimeFormatter
|
||||
import java.util.UUID
|
||||
|
||||
/** Per-photo status within a batch. */
|
||||
@@ -60,6 +63,25 @@ data class PostUiState(
|
||||
items.all { it.status is ItemStatus.Success || it.status is ItemStatus.Error }
|
||||
}
|
||||
|
||||
/** One published post on the manage screen. */
|
||||
data class ManagePost(
|
||||
val slug: String,
|
||||
val caption: String,
|
||||
val date: LocalDate,
|
||||
val tags: List<String>,
|
||||
val thumb: String, // site-relative path
|
||||
val url: String, // site-relative path
|
||||
val preview: Bitmap? = null,
|
||||
val busy: Boolean = false, // a save/delete is in flight
|
||||
)
|
||||
|
||||
data class ManageUiState(
|
||||
val loading: Boolean = false,
|
||||
val items: List<ManagePost> = emptyList(),
|
||||
val error: String? = null,
|
||||
val message: String? = null,
|
||||
)
|
||||
|
||||
data class SettingsUiState(
|
||||
val baseUrl: String = "",
|
||||
val username: String = "",
|
||||
@@ -87,11 +109,30 @@ class UploadViewModel(app: Application) : AndroidViewModel(app) {
|
||||
|
||||
val isConfigured: Boolean get() = settings.isConfigured
|
||||
|
||||
// Known tag names for autocomplete, shared by the Post and Manage screens.
|
||||
// Best-effort: fetched from /api/tags.json, empty until it arrives.
|
||||
var tagSuggestions by mutableStateOf<List<String>>(emptyList())
|
||||
private set
|
||||
|
||||
init {
|
||||
refreshTags()
|
||||
}
|
||||
|
||||
/** Refreshes the autocomplete tag list; silent on any failure. */
|
||||
fun refreshTags() {
|
||||
if (!settings.isConfigured) return
|
||||
viewModelScope.launch {
|
||||
val tags = withContext(Dispatchers.IO) { client().fetchTags() }
|
||||
if (tags.isNotEmpty()) tagSuggestions = tags
|
||||
}
|
||||
}
|
||||
|
||||
// ── Post screen ─────────────────────────────────────────────────────────
|
||||
|
||||
/** Replaces the current selection with [uris] and loads each preview. */
|
||||
fun selectImages(uris: List<Uri>) {
|
||||
if (uris.isEmpty()) return
|
||||
refreshTags()
|
||||
val items = uris.map { PickedItem(source = it) }
|
||||
post = post.copy(items = items)
|
||||
|
||||
@@ -225,6 +266,110 @@ class UploadViewModel(app: Application) : AndroidViewModel(app) {
|
||||
post = post.copy(items = post.items.map { if (it.id == id) transform(it) else it })
|
||||
}
|
||||
|
||||
// ── Manage screen ───────────────────────────────────────────────────────
|
||||
|
||||
var manage by mutableStateOf(ManageUiState())
|
||||
private set
|
||||
|
||||
private val isoDate: DateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd")
|
||||
|
||||
private fun client(): UploadClient =
|
||||
UploadClient(settings.baseUrl, settings.username, settings.password)
|
||||
|
||||
/** Loads the post list, then fills in thumbnails in the background. */
|
||||
fun loadManage() {
|
||||
if (!settings.isConfigured) {
|
||||
manage = manage.copy(error = "Set the server URL and credentials first")
|
||||
return
|
||||
}
|
||||
manage = manage.copy(loading = true, error = null, message = null)
|
||||
refreshTags()
|
||||
viewModelScope.launch {
|
||||
val result = withContext(Dispatchers.IO) { client().listPhotos() }
|
||||
when (result) {
|
||||
is ListResult.Ok -> {
|
||||
manage = manage.copy(
|
||||
loading = false,
|
||||
items = result.photos.map { it.toPost() },
|
||||
)
|
||||
loadThumbnails(result.photos)
|
||||
}
|
||||
is ListResult.Err ->
|
||||
manage = manage.copy(loading = false, error = result.message)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun loadThumbnails(photos: List<RemotePhoto>) {
|
||||
for (p in photos) {
|
||||
viewModelScope.launch {
|
||||
// Fetch via the /api/thumb/<slug> endpoint, not the static
|
||||
// /thumbs/ path: a front-door botwall can block this non-browser
|
||||
// client from the static site while /api/ is proxied to the app.
|
||||
// The endpoint is unguarded (public image data), so it never
|
||||
// 401s and can't get the app banned by an auth-fail jail.
|
||||
val bmp = withContext(Dispatchers.IO) { client().fetchThumbnail("/api/thumb/" + p.slug) }
|
||||
if (bmp != null) updateManage(p.slug) { it.copy(preview = bmp) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun saveEdit(slug: String, caption: String, date: LocalDate, tags: String) {
|
||||
updateManage(slug) { it.copy(busy = true) }
|
||||
viewModelScope.launch {
|
||||
val err = withContext(Dispatchers.IO) {
|
||||
client().editPost(slug, caption, date.format(isoDate), tags)
|
||||
}
|
||||
if (err == null) {
|
||||
updateManage(slug) {
|
||||
it.copy(
|
||||
busy = false,
|
||||
caption = caption,
|
||||
date = date,
|
||||
tags = parseTagList(tags),
|
||||
)
|
||||
}
|
||||
manage = manage.copy(message = "Saved")
|
||||
} else {
|
||||
updateManage(slug) { it.copy(busy = false) }
|
||||
manage = manage.copy(error = err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun deletePost(slug: String) {
|
||||
updateManage(slug) { it.copy(busy = true) }
|
||||
viewModelScope.launch {
|
||||
val err = withContext(Dispatchers.IO) { client().deletePost(slug) }
|
||||
if (err == null) {
|
||||
manage = manage.copy(
|
||||
items = manage.items.filterNot { it.slug == slug },
|
||||
message = "Moved to trash",
|
||||
)
|
||||
} else {
|
||||
updateManage(slug) { it.copy(busy = false) }
|
||||
manage = manage.copy(error = err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun clearManageNotice() {
|
||||
manage = manage.copy(error = null, message = null)
|
||||
}
|
||||
|
||||
private fun RemotePhoto.toPost(): ManagePost {
|
||||
val d = runCatching { LocalDate.parse(date, isoDate) }.getOrDefault(LocalDate.now())
|
||||
return ManagePost(slug = slug, caption = caption, date = d, tags = tags, thumb = thumb, url = url)
|
||||
}
|
||||
|
||||
// Local split for optimistic UI only; the server normalizes authoritatively.
|
||||
private fun parseTagList(raw: String): List<String> =
|
||||
raw.split(",").map { it.trim() }.filter { it.isNotEmpty() }
|
||||
|
||||
private inline fun updateManage(slug: String, transform: (ManagePost) -> ManagePost) {
|
||||
manage = manage.copy(items = manage.items.map { if (it.slug == slug) transform(it) else it })
|
||||
}
|
||||
|
||||
// ── Settings screen ─────────────────────────────────────────────────────
|
||||
|
||||
fun setBaseUrl(value: String) {
|
||||
|
||||
@@ -0,0 +1,108 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// buildWithView builds a two-photo site with the given default view and returns
|
||||
// the output dir.
|
||||
func buildWithView(t *testing.T, view string) string {
|
||||
t.Helper()
|
||||
content := t.TempDir()
|
||||
output := t.TempDir()
|
||||
writePNG(t, filepath.Join(content, "a.png"))
|
||||
writePNG(t, filepath.Join(content, "b.png"))
|
||||
|
||||
g := NewGenerator(content, output, "http://x", "A", "@a", "bio", "", "f", "s", "m", 60, view)
|
||||
if err := g.Build(); err != nil {
|
||||
t.Fatalf("build (%s): %v", view, err)
|
||||
}
|
||||
return output
|
||||
}
|
||||
|
||||
func exists(p string) bool { _, err := os.Stat(p); return err == nil }
|
||||
|
||||
func TestDefaultViewTimeline(t *testing.T) {
|
||||
out := buildWithView(t, viewTimeline)
|
||||
|
||||
// Timeline owns the root; grid is the secondary under /grid/.
|
||||
if !exists(filepath.Join(out, "index.html")) {
|
||||
t.Error("root index.html missing")
|
||||
}
|
||||
if !exists(filepath.Join(out, "grid", "index.html")) {
|
||||
t.Error("/grid/ should exist as the secondary view")
|
||||
}
|
||||
// No /timeline/ dir — timeline is at the root, not under its own name.
|
||||
if exists(filepath.Join(out, "timeline")) {
|
||||
t.Error("/timeline/ should not exist when timeline is the default")
|
||||
}
|
||||
|
||||
// The root (timeline) links to grid at /grid/.
|
||||
root := readFile(t, filepath.Join(out, "index.html"))
|
||||
if !strings.Contains(root, `href="/grid/"`) {
|
||||
t.Error("timeline root should link to /grid/")
|
||||
}
|
||||
}
|
||||
|
||||
func TestDefaultViewGrid(t *testing.T) {
|
||||
out := buildWithView(t, viewGrid)
|
||||
|
||||
// Grid owns the root; timeline is the secondary under /timeline/.
|
||||
if !exists(filepath.Join(out, "index.html")) {
|
||||
t.Error("root index.html missing")
|
||||
}
|
||||
if !exists(filepath.Join(out, "timeline", "index.html")) {
|
||||
t.Error("/timeline/ should exist as the secondary view")
|
||||
}
|
||||
// No /grid/ dir — grid is at the root now.
|
||||
if exists(filepath.Join(out, "grid")) {
|
||||
t.Error("/grid/ should not exist when grid is the default")
|
||||
}
|
||||
|
||||
// The root (grid) links back to the timeline at /timeline/.
|
||||
root := readFile(t, filepath.Join(out, "index.html"))
|
||||
if !strings.Contains(root, `href="/timeline/"`) {
|
||||
t.Error("grid root should link to /timeline/")
|
||||
}
|
||||
}
|
||||
|
||||
// TestDefaultViewSwitchCleansUp confirms that flipping the default view does not
|
||||
// leave the previous root's view directory behind.
|
||||
func TestDefaultViewSwitchCleansUp(t *testing.T) {
|
||||
content := t.TempDir()
|
||||
output := t.TempDir()
|
||||
writePNG(t, filepath.Join(content, "a.png"))
|
||||
|
||||
// First build with grid as root → creates /timeline/.
|
||||
g1 := NewGenerator(content, output, "http://x", "A", "@a", "b", "", "f", "s", "m", 60, viewGrid)
|
||||
if err := g1.Build(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !exists(filepath.Join(output, "timeline")) {
|
||||
t.Fatal("expected /timeline/ after grid-default build")
|
||||
}
|
||||
|
||||
// Rebuild with timeline as root → /timeline/ must be gone, /grid/ present.
|
||||
g2 := NewGenerator(content, output, "http://x", "A", "@a", "b", "", "f", "s", "m", 60, viewTimeline)
|
||||
if err := g2.Build(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if exists(filepath.Join(output, "timeline")) {
|
||||
t.Error("/timeline/ left over after switching default to timeline")
|
||||
}
|
||||
if !exists(filepath.Join(output, "grid", "index.html")) {
|
||||
t.Error("/grid/ should exist after switching default to timeline")
|
||||
}
|
||||
}
|
||||
|
||||
func readFile(t *testing.T, p string) string {
|
||||
t.Helper()
|
||||
b, err := os.ReadFile(p)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return string(b)
|
||||
}
|
||||
@@ -13,6 +13,8 @@ add_executable(uploader
|
||||
main.cpp
|
||||
mainwindow.cpp
|
||||
photoitemwidget.cpp
|
||||
managepostwidget.cpp
|
||||
tagcompleter.cpp
|
||||
settings.cpp
|
||||
uploadclient.cpp
|
||||
imageprep.cpp
|
||||
|
||||
+241
-1
@@ -1,17 +1,25 @@
|
||||
#include "mainwindow.h"
|
||||
|
||||
#include "imageprep.h"
|
||||
#include "managepostwidget.h"
|
||||
#include "photoitemwidget.h"
|
||||
#include "tagcompleter.h"
|
||||
#include "uploadclient.h"
|
||||
|
||||
#include <QDate>
|
||||
#include <QDateEdit>
|
||||
#include <QDateTime>
|
||||
#include <QDialog>
|
||||
#include <QDialogButtonBox>
|
||||
#include <QFileDialog>
|
||||
#include <QFileInfo>
|
||||
#include <QFormLayout>
|
||||
#include <QFuture>
|
||||
#include <QFutureWatcher>
|
||||
#include <QHBoxLayout>
|
||||
#include <QLabel>
|
||||
#include <QLineEdit>
|
||||
#include <QMessageBox>
|
||||
#include <QPushButton>
|
||||
#include <QScrollArea>
|
||||
#include <QSpinBox>
|
||||
@@ -29,6 +37,7 @@ MainWindow::MainWindow(QWidget *parent)
|
||||
m_stack = new QStackedWidget(this);
|
||||
m_stack->addWidget(buildSettingsPage()); // index 0
|
||||
m_stack->addWidget(buildPostPage()); // index 1
|
||||
m_stack->addWidget(buildManagePage()); // index 2
|
||||
setCentralWidget(m_stack);
|
||||
|
||||
if (m_settings.isConfigured())
|
||||
@@ -112,9 +121,51 @@ QWidget *MainWindow::buildPostPage()
|
||||
m_lastPost->setWordWrap(true);
|
||||
outer->addWidget(m_lastPost);
|
||||
|
||||
auto *bottomRow = new QHBoxLayout;
|
||||
auto *manageButton = new QPushButton(QStringLiteral("Manage"));
|
||||
connect(manageButton, &QPushButton::clicked, this, &MainWindow::showManage);
|
||||
bottomRow->addWidget(manageButton);
|
||||
|
||||
auto *settingsButton = new QPushButton(QStringLiteral("Settings"));
|
||||
connect(settingsButton, &QPushButton::clicked, this, &MainWindow::showSettings);
|
||||
outer->addWidget(settingsButton);
|
||||
bottomRow->addWidget(settingsButton);
|
||||
outer->addLayout(bottomRow);
|
||||
|
||||
return page;
|
||||
}
|
||||
|
||||
QWidget *MainWindow::buildManagePage()
|
||||
{
|
||||
auto *page = new QWidget;
|
||||
auto *outer = new QVBoxLayout(page);
|
||||
outer->setContentsMargins(24, 24, 24, 24);
|
||||
|
||||
auto *header = new QHBoxLayout;
|
||||
auto *title = new QLabel(QStringLiteral("<b>Manage posts</b>"));
|
||||
header->addWidget(title);
|
||||
header->addStretch();
|
||||
m_manageRefresh = new QPushButton(QStringLiteral("Refresh"));
|
||||
connect(m_manageRefresh, &QPushButton::clicked, this, &MainWindow::loadManage);
|
||||
header->addWidget(m_manageRefresh);
|
||||
auto *back = new QPushButton(QStringLiteral("Back"));
|
||||
connect(back, &QPushButton::clicked, this, &MainWindow::showPost);
|
||||
header->addWidget(back);
|
||||
outer->addLayout(header);
|
||||
|
||||
m_manageStatus = new QLabel;
|
||||
m_manageStatus->setWordWrap(true);
|
||||
outer->addWidget(m_manageStatus);
|
||||
|
||||
auto *scroll = new QScrollArea;
|
||||
scroll->setWidgetResizable(true);
|
||||
auto *container = new QWidget;
|
||||
m_manageLayout = new QVBoxLayout(container);
|
||||
m_manageLayout->setAlignment(Qt::AlignTop);
|
||||
m_manageEmptyHint = new QLabel(QStringLiteral("No posts."));
|
||||
m_manageEmptyHint->setAlignment(Qt::AlignCenter);
|
||||
m_manageLayout->addWidget(m_manageEmptyHint);
|
||||
scroll->setWidget(container);
|
||||
outer->addWidget(scroll, 1);
|
||||
|
||||
return page;
|
||||
}
|
||||
@@ -139,9 +190,21 @@ void MainWindow::showPost()
|
||||
} else {
|
||||
m_lastPost->clear();
|
||||
}
|
||||
refreshTags();
|
||||
m_stack->setCurrentIndex(1);
|
||||
}
|
||||
|
||||
void MainWindow::showManage()
|
||||
{
|
||||
if (!m_settings.isConfigured()) {
|
||||
showSettings();
|
||||
return;
|
||||
}
|
||||
m_stack->setCurrentIndex(2);
|
||||
refreshTags();
|
||||
loadManage();
|
||||
}
|
||||
|
||||
void MainWindow::saveAndTest()
|
||||
{
|
||||
// Concurrency is not a credential; persist it regardless of URL validity.
|
||||
@@ -162,6 +225,13 @@ void MainWindow::saveAndTest()
|
||||
m_settings.writePassword(m_password->text());
|
||||
m_baseUrl->setText(m_settings.baseUrl());
|
||||
|
||||
// The manage client caches the credentials it was built with; drop it so
|
||||
// the next manage action rebuilds with the ones just saved.
|
||||
if (m_manageClient) {
|
||||
m_manageClient->deleteLater();
|
||||
m_manageClient = nullptr;
|
||||
}
|
||||
|
||||
m_saveButton->setEnabled(false);
|
||||
m_settingsStatus->setText(QStringLiteral("Testing…"));
|
||||
|
||||
@@ -192,6 +262,7 @@ void MainWindow::addItem(const QString &path)
|
||||
{
|
||||
m_emptyHint->hide();
|
||||
auto *item = new PhotoItemWidget(path);
|
||||
item->setTagSuggestions(m_tagSuggestions);
|
||||
connect(item, &PhotoItemWidget::removeRequested, this, &MainWindow::removeItem);
|
||||
m_items.append(item);
|
||||
m_itemsLayout->addWidget(item);
|
||||
@@ -359,3 +430,172 @@ void MainWindow::refreshPosting()
|
||||
m_postSummary->setText(summary);
|
||||
}
|
||||
}
|
||||
|
||||
// --- Manage page -----------------------------------------------------------
|
||||
|
||||
UploadClient *MainWindow::manageClient()
|
||||
{
|
||||
if (!m_manageClient) {
|
||||
m_manageClient = new UploadClient(m_settings.baseUrl(), m_settings.username(),
|
||||
m_settings.readPassword(), this);
|
||||
|
||||
// Thumbnails arrive one per request; route each to its row by slug.
|
||||
connect(m_manageClient, &UploadClient::thumbnailReady, this,
|
||||
[this](const QString &slug, const QImage &image) {
|
||||
for (ManagePostWidget *w : std::as_const(m_manageItems))
|
||||
if (w->slug() == slug)
|
||||
w->setThumbnail(image);
|
||||
});
|
||||
|
||||
// The tag list feeds both the post cards and the edit dialog.
|
||||
connect(m_manageClient, &UploadClient::tagsFetched, this,
|
||||
[this](const QStringList &tags) {
|
||||
if (tags.isEmpty())
|
||||
return; // best-effort; keep whatever we had
|
||||
m_tagSuggestions = tags;
|
||||
applyTagSuggestions();
|
||||
});
|
||||
}
|
||||
return m_manageClient;
|
||||
}
|
||||
|
||||
void MainWindow::refreshTags()
|
||||
{
|
||||
if (m_settings.isConfigured())
|
||||
manageClient()->fetchTags();
|
||||
}
|
||||
|
||||
void MainWindow::applyTagSuggestions()
|
||||
{
|
||||
for (PhotoItemWidget *item : std::as_const(m_items))
|
||||
item->setTagSuggestions(m_tagSuggestions);
|
||||
}
|
||||
|
||||
void MainWindow::clearManageItems()
|
||||
{
|
||||
for (ManagePostWidget *item : std::as_const(m_manageItems))
|
||||
item->deleteLater();
|
||||
m_manageItems.clear();
|
||||
m_manageEmptyHint->show();
|
||||
}
|
||||
|
||||
void MainWindow::loadManage()
|
||||
{
|
||||
if (!m_settings.isConfigured()) {
|
||||
m_manageStatus->setText(QStringLiteral("Set the server URL and credentials first"));
|
||||
return;
|
||||
}
|
||||
m_manageStatus->setText(QStringLiteral("Loading…"));
|
||||
m_manageRefresh->setEnabled(false);
|
||||
|
||||
connect(
|
||||
manageClient(), &UploadClient::photosListed, this,
|
||||
[this](const QList<RemotePhoto> &photos, const QString &error) {
|
||||
m_manageRefresh->setEnabled(true);
|
||||
clearManageItems();
|
||||
if (!error.isEmpty()) {
|
||||
m_manageStatus->setText(error);
|
||||
return;
|
||||
}
|
||||
m_manageStatus->clear();
|
||||
if (photos.isEmpty())
|
||||
return;
|
||||
m_manageEmptyHint->hide();
|
||||
for (const RemotePhoto &p : photos) {
|
||||
auto *item = new ManagePostWidget(p.slug, p.caption, p.date, p.tags,
|
||||
m_settings.baseUrl() + p.url);
|
||||
connect(item, &ManagePostWidget::editRequested, this, &MainWindow::editItem);
|
||||
connect(item, &ManagePostWidget::deleteRequested, this, &MainWindow::deleteItem);
|
||||
m_manageItems.append(item);
|
||||
m_manageLayout->addWidget(item);
|
||||
manageClient()->fetchThumbnail(p.slug);
|
||||
}
|
||||
},
|
||||
Qt::SingleShotConnection);
|
||||
manageClient()->listPhotos();
|
||||
}
|
||||
|
||||
void MainWindow::editItem(ManagePostWidget *item)
|
||||
{
|
||||
QDialog dialog(this);
|
||||
dialog.setWindowTitle(QStringLiteral("Edit %1").arg(item->slug()));
|
||||
auto *layout = new QVBoxLayout(&dialog);
|
||||
|
||||
auto *form = new QFormLayout;
|
||||
auto *caption = new QLineEdit(item->caption());
|
||||
auto *date = new QDateEdit(QDate::fromString(item->date(), QStringLiteral("yyyy-MM-dd")));
|
||||
date->setCalendarPopup(true);
|
||||
date->setDisplayFormat(QStringLiteral("yyyy-MM-dd"));
|
||||
if (!date->date().isValid())
|
||||
date->setDate(QDate::currentDate());
|
||||
auto *tags = new QLineEdit(item->tags().join(QStringLiteral(", ")));
|
||||
auto *completer = new TagCompleter(&dialog);
|
||||
completer->setSuggestions(m_tagSuggestions);
|
||||
tags->setCompleter(completer);
|
||||
form->addRow(QStringLiteral("Caption"), caption);
|
||||
form->addRow(QStringLiteral("Date"), date);
|
||||
form->addRow(QStringLiteral("Tags"), tags);
|
||||
layout->addLayout(form);
|
||||
|
||||
auto *buttons = new QDialogButtonBox(QDialogButtonBox::Save | QDialogButtonBox::Cancel);
|
||||
connect(buttons, &QDialogButtonBox::accepted, &dialog, &QDialog::accept);
|
||||
connect(buttons, &QDialogButtonBox::rejected, &dialog, &QDialog::reject);
|
||||
layout->addWidget(buttons);
|
||||
|
||||
if (dialog.exec() != QDialog::Accepted)
|
||||
return;
|
||||
|
||||
const QString newCaption = caption->text();
|
||||
const QString newDate = date->date().toString(QStringLiteral("yyyy-MM-dd"));
|
||||
const QString newTags = tags->text();
|
||||
|
||||
item->setBusy(true);
|
||||
connect(
|
||||
manageClient(), &UploadClient::editFinished, this,
|
||||
[this, item, newCaption, newDate, newTags](const QString &slug, const QString &error) {
|
||||
item->setBusy(false);
|
||||
if (!error.isEmpty()) {
|
||||
m_manageStatus->setText(QStringLiteral("Edit failed: %1").arg(error));
|
||||
return;
|
||||
}
|
||||
QStringList tagList;
|
||||
const auto parts = newTags.split(QLatin1Char(','), Qt::SkipEmptyParts);
|
||||
for (const QString &t : parts) {
|
||||
const QString trimmed = t.trimmed();
|
||||
if (!trimmed.isEmpty())
|
||||
tagList << trimmed;
|
||||
}
|
||||
item->applyEdit(newCaption, newDate, tagList);
|
||||
m_manageStatus->setText(QStringLiteral("Saved %1").arg(slug));
|
||||
},
|
||||
Qt::SingleShotConnection);
|
||||
manageClient()->editPost(item->slug(), newCaption, newDate, newTags);
|
||||
}
|
||||
|
||||
void MainWindow::deleteItem(ManagePostWidget *item)
|
||||
{
|
||||
const QString name = item->caption().isEmpty() ? item->slug() : item->caption();
|
||||
const auto choice = QMessageBox::question(
|
||||
this, QStringLiteral("Move to trash?"),
|
||||
QStringLiteral("\"%1\" will be moved to the server's trash.").arg(name));
|
||||
if (choice != QMessageBox::Yes)
|
||||
return;
|
||||
|
||||
item->setBusy(true);
|
||||
connect(
|
||||
manageClient(), &UploadClient::deleteFinished, this,
|
||||
[this, item](const QString &, const QString &error) {
|
||||
if (!error.isEmpty()) {
|
||||
item->setBusy(false);
|
||||
m_manageStatus->setText(QStringLiteral("Delete failed: %1").arg(error));
|
||||
return;
|
||||
}
|
||||
m_manageItems.removeOne(item);
|
||||
item->deleteLater();
|
||||
m_manageStatus->setText(QStringLiteral("Moved to trash"));
|
||||
if (m_manageItems.isEmpty())
|
||||
m_manageEmptyHint->show();
|
||||
},
|
||||
Qt::SingleShotConnection);
|
||||
manageClient()->deletePost(item->slug());
|
||||
}
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
#include <QList>
|
||||
#include <QMainWindow>
|
||||
#include <QStringList>
|
||||
|
||||
#include "settings.h"
|
||||
|
||||
@@ -13,6 +14,8 @@ class QSpinBox;
|
||||
class QStackedWidget;
|
||||
class QVBoxLayout;
|
||||
class PhotoItemWidget;
|
||||
class ManagePostWidget;
|
||||
class UploadClient;
|
||||
|
||||
class MainWindow : public QMainWindow
|
||||
{
|
||||
@@ -23,9 +26,11 @@ public:
|
||||
private:
|
||||
QWidget *buildSettingsPage();
|
||||
QWidget *buildPostPage();
|
||||
QWidget *buildManagePage();
|
||||
|
||||
void showSettings();
|
||||
void showPost();
|
||||
void showManage();
|
||||
|
||||
void saveAndTest();
|
||||
void chooseImages();
|
||||
@@ -38,6 +43,17 @@ private:
|
||||
int inFlightCount() const; // items currently preparing or uploading
|
||||
void refreshPosting(); // updates the Post button + summary from item states
|
||||
|
||||
// Manage page.
|
||||
UploadClient *manageClient(); // lazily-built, lives as long as the window
|
||||
void loadManage(); // fetches the post list and thumbnails
|
||||
void clearManageItems();
|
||||
void editItem(ManagePostWidget *item);
|
||||
void deleteItem(ManagePostWidget *item);
|
||||
|
||||
// Tag autocomplete.
|
||||
void refreshTags(); // fetches /api/tags.json
|
||||
void applyTagSuggestions(); // pushes the list onto every post card
|
||||
|
||||
Settings m_settings;
|
||||
|
||||
QStackedWidget *m_stack = nullptr;
|
||||
@@ -66,4 +82,16 @@ private:
|
||||
QString m_batchUsername;
|
||||
QString m_batchPassword;
|
||||
QString m_batchCacheDir;
|
||||
|
||||
// Manage page
|
||||
QVBoxLayout *m_manageLayout = nullptr; // holds the ManagePostWidgets
|
||||
QList<ManagePostWidget *> m_manageItems;
|
||||
QLabel *m_manageEmptyHint = nullptr;
|
||||
QLabel *m_manageStatus = nullptr;
|
||||
QPushButton *m_manageRefresh = nullptr;
|
||||
UploadClient *m_manageClient = nullptr; // lazily created, reused for manage ops
|
||||
|
||||
// Known tag names for autocomplete, shared by the post cards and the edit
|
||||
// dialog. Best-effort: empty until /api/tags.json arrives.
|
||||
QStringList m_tagSuggestions;
|
||||
};
|
||||
@@ -0,0 +1,92 @@
|
||||
#include "managepostwidget.h"
|
||||
|
||||
#include <QHBoxLayout>
|
||||
#include <QImage>
|
||||
#include <QLabel>
|
||||
#include <QPixmap>
|
||||
#include <QPushButton>
|
||||
#include <QVBoxLayout>
|
||||
|
||||
namespace {
|
||||
constexpr int kThumbSize = 72;
|
||||
}
|
||||
|
||||
ManagePostWidget::ManagePostWidget(const QString &slug, const QString &caption,
|
||||
const QString &date, const QStringList &tags,
|
||||
const QString &url, QWidget *parent)
|
||||
: QWidget(parent)
|
||||
, m_slug(slug)
|
||||
, m_caption(caption)
|
||||
, m_date(date)
|
||||
, m_tags(tags)
|
||||
, m_url(url)
|
||||
{
|
||||
auto *row = new QHBoxLayout(this);
|
||||
row->setContentsMargins(0, 4, 0, 4);
|
||||
|
||||
m_thumb = new QLabel;
|
||||
m_thumb->setFixedSize(kThumbSize, kThumbSize);
|
||||
m_thumb->setAlignment(Qt::AlignCenter);
|
||||
m_thumb->setFrameShape(QFrame::Box);
|
||||
row->addWidget(m_thumb, 0, Qt::AlignTop);
|
||||
|
||||
auto *fields = new QVBoxLayout;
|
||||
m_captionLabel = new QLabel;
|
||||
m_captionLabel->setTextFormat(Qt::RichText);
|
||||
m_captionLabel->setOpenExternalLinks(true);
|
||||
m_captionLabel->setWordWrap(true);
|
||||
fields->addWidget(m_captionLabel);
|
||||
|
||||
m_metaLabel = new QLabel;
|
||||
m_metaLabel->setWordWrap(true);
|
||||
m_metaLabel->setStyleSheet(QStringLiteral("color:#a89984;"));
|
||||
fields->addWidget(m_metaLabel);
|
||||
row->addLayout(fields, 1);
|
||||
|
||||
m_edit = new QPushButton(QStringLiteral("Edit"));
|
||||
connect(m_edit, &QPushButton::clicked, this, [this]() { emit editRequested(this); });
|
||||
row->addWidget(m_edit, 0, Qt::AlignTop);
|
||||
|
||||
m_delete = new QPushButton(QStringLiteral("Delete"));
|
||||
connect(m_delete, &QPushButton::clicked, this, [this]() { emit deleteRequested(this); });
|
||||
row->addWidget(m_delete, 0, Qt::AlignTop);
|
||||
|
||||
refreshSummary();
|
||||
}
|
||||
|
||||
void ManagePostWidget::setThumbnail(const QImage &image)
|
||||
{
|
||||
if (image.isNull()) {
|
||||
m_thumb->setText(QStringLiteral("?"));
|
||||
return;
|
||||
}
|
||||
m_thumb->setPixmap(QPixmap::fromImage(image).scaled(
|
||||
kThumbSize, kThumbSize, Qt::KeepAspectRatioByExpanding, Qt::SmoothTransformation));
|
||||
}
|
||||
|
||||
void ManagePostWidget::applyEdit(const QString &caption, const QString &date,
|
||||
const QStringList &tags)
|
||||
{
|
||||
m_caption = caption;
|
||||
m_date = date;
|
||||
m_tags = tags;
|
||||
refreshSummary();
|
||||
}
|
||||
|
||||
void ManagePostWidget::setBusy(bool busy)
|
||||
{
|
||||
m_edit->setEnabled(!busy);
|
||||
m_delete->setEnabled(!busy);
|
||||
}
|
||||
|
||||
void ManagePostWidget::refreshSummary()
|
||||
{
|
||||
const QString shown = m_caption.isEmpty() ? m_slug : m_caption;
|
||||
m_captionLabel->setText(
|
||||
QStringLiteral("<a href=\"%1\">%2</a>").arg(m_url, shown.toHtmlEscaped()));
|
||||
|
||||
QString meta = m_date;
|
||||
if (!m_tags.isEmpty())
|
||||
meta += QStringLiteral(" · ") + m_tags.join(QStringLiteral(", "));
|
||||
m_metaLabel->setText(meta);
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
#pragma once
|
||||
|
||||
#include <QString>
|
||||
#include <QStringList>
|
||||
#include <QWidget>
|
||||
|
||||
class QImage;
|
||||
class QLabel;
|
||||
class QPushButton;
|
||||
|
||||
// One published post on the Manage page: thumbnail, caption/date/tags summary,
|
||||
// and Edit / Delete buttons. Mirrors a row of the web /manage list and the
|
||||
// Android manage screen.
|
||||
class ManagePostWidget : public QWidget
|
||||
{
|
||||
Q_OBJECT
|
||||
public:
|
||||
ManagePostWidget(const QString &slug, const QString &caption, const QString &date,
|
||||
const QStringList &tags, const QString &url, QWidget *parent = nullptr);
|
||||
|
||||
QString slug() const { return m_slug; }
|
||||
QString caption() const { return m_caption; }
|
||||
QString date() const { return m_date; }
|
||||
QStringList tags() const { return m_tags; }
|
||||
|
||||
void setThumbnail(const QImage &image);
|
||||
void applyEdit(const QString &caption, const QString &date, const QStringList &tags);
|
||||
void setBusy(bool busy); // a save/delete is in flight
|
||||
|
||||
signals:
|
||||
void editRequested(ManagePostWidget *self);
|
||||
void deleteRequested(ManagePostWidget *self);
|
||||
|
||||
private:
|
||||
void refreshSummary();
|
||||
|
||||
QString m_slug;
|
||||
QString m_caption;
|
||||
QString m_date;
|
||||
QStringList m_tags;
|
||||
QString m_url;
|
||||
|
||||
QLabel *m_thumb = nullptr;
|
||||
QLabel *m_captionLabel = nullptr;
|
||||
QLabel *m_metaLabel = nullptr;
|
||||
QPushButton *m_edit = nullptr;
|
||||
QPushButton *m_delete = nullptr;
|
||||
};
|
||||
@@ -1,5 +1,7 @@
|
||||
#include "photoitemwidget.h"
|
||||
|
||||
#include "tagcompleter.h"
|
||||
|
||||
#include <QDate>
|
||||
#include <QDateEdit>
|
||||
#include <QHBoxLayout>
|
||||
@@ -49,6 +51,8 @@ PhotoItemWidget::PhotoItemWidget(QString sourcePath, QWidget *parent)
|
||||
|
||||
m_tags = new QLineEdit;
|
||||
m_tags->setPlaceholderText(QStringLiteral("tags (comma-separated)"));
|
||||
m_tagCompleter = new TagCompleter(this);
|
||||
m_tags->setCompleter(m_tagCompleter);
|
||||
fields->addWidget(m_tags);
|
||||
|
||||
m_statusLabel = new QLabel;
|
||||
@@ -79,6 +83,11 @@ QString PhotoItemWidget::tags() const
|
||||
return m_tags->text();
|
||||
}
|
||||
|
||||
void PhotoItemWidget::setTagSuggestions(const QStringList &tags)
|
||||
{
|
||||
m_tagCompleter->setSuggestions(tags);
|
||||
}
|
||||
|
||||
void PhotoItemWidget::setStatus(Status status, const QString &message, const QString &url)
|
||||
{
|
||||
m_status = status;
|
||||
|
||||
@@ -7,6 +7,7 @@ class QDateEdit;
|
||||
class QLabel;
|
||||
class QLineEdit;
|
||||
class QPushButton;
|
||||
class TagCompleter;
|
||||
|
||||
// One photo in the batch: thumbnail, caption, date, and its own upload status.
|
||||
// A single-photo post is just a batch of one, so the window runs one code path.
|
||||
@@ -26,6 +27,9 @@ public:
|
||||
|
||||
void setStatus(Status status, const QString &message = {}, const QString &url = {});
|
||||
|
||||
// Fills the tags field's autocomplete with the known tag names.
|
||||
void setTagSuggestions(const QStringList &tags);
|
||||
|
||||
signals:
|
||||
void removeRequested(PhotoItemWidget *self);
|
||||
|
||||
@@ -39,4 +43,5 @@ private:
|
||||
QLineEdit *m_tags = nullptr;
|
||||
QLabel *m_statusLabel = nullptr;
|
||||
QPushButton *m_remove = nullptr;
|
||||
TagCompleter *m_tagCompleter = nullptr;
|
||||
};
|
||||
@@ -0,0 +1,42 @@
|
||||
#include "tagcompleter.h"
|
||||
|
||||
#include <QLineEdit>
|
||||
#include <QStringListModel>
|
||||
|
||||
TagCompleter::TagCompleter(QObject *parent)
|
||||
: QCompleter(parent)
|
||||
, m_model(new QStringListModel(this))
|
||||
{
|
||||
setModel(m_model);
|
||||
setCaseSensitivity(Qt::CaseInsensitive);
|
||||
setFilterMode(Qt::MatchContains); // match anywhere in the tag, like Android
|
||||
setCompletionMode(QCompleter::PopupCompletion);
|
||||
}
|
||||
|
||||
void TagCompleter::setSuggestions(const QStringList &tags)
|
||||
{
|
||||
m_model->setStringList(tags);
|
||||
}
|
||||
|
||||
// Complete against the token after the last comma, ignoring the tags already
|
||||
// entered before it.
|
||||
QStringList TagCompleter::splitPath(const QString &path) const
|
||||
{
|
||||
return QStringList(path.section(QLatin1Char(','), -1).trimmed());
|
||||
}
|
||||
|
||||
// Rebuild the full field value: everything up to and including the last comma,
|
||||
// then the chosen tag and a trailing ", " ready for the next one.
|
||||
QString TagCompleter::pathFromIndex(const QModelIndex &index) const
|
||||
{
|
||||
const QString completion = QCompleter::pathFromIndex(index);
|
||||
const auto *edit = qobject_cast<const QLineEdit *>(widget());
|
||||
if (!edit)
|
||||
return completion;
|
||||
|
||||
const QString text = edit->text();
|
||||
const int lastComma = text.lastIndexOf(QLatin1Char(','));
|
||||
const QString head =
|
||||
lastComma >= 0 ? text.left(lastComma + 1) + QLatin1Char(' ') : QString();
|
||||
return head + completion + QStringLiteral(", ");
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
#pragma once
|
||||
|
||||
#include <QCompleter>
|
||||
#include <QStringList>
|
||||
|
||||
class QStringListModel;
|
||||
|
||||
// A QCompleter for a comma-separated tags line edit. It completes only the
|
||||
// token currently being typed (the text after the last comma) and, on
|
||||
// selection, splices the chosen tag back in place of that token — the same
|
||||
// per-token behaviour as the web and Android tag fields. Attach with
|
||||
// QLineEdit::setCompleter; call setSuggestions() to (re)fill the tag list.
|
||||
class TagCompleter : public QCompleter
|
||||
{
|
||||
public:
|
||||
explicit TagCompleter(QObject *parent = nullptr);
|
||||
|
||||
void setSuggestions(const QStringList &tags);
|
||||
|
||||
protected:
|
||||
QStringList splitPath(const QString &path) const override;
|
||||
QString pathFromIndex(const QModelIndex &index) const override;
|
||||
|
||||
private:
|
||||
QStringListModel *m_model;
|
||||
};
|
||||
@@ -4,9 +4,13 @@
|
||||
#include <QFileInfo>
|
||||
#include <QHttpMultiPart>
|
||||
#include <QHttpPart>
|
||||
#include <QJsonArray>
|
||||
#include <QJsonDocument>
|
||||
#include <QJsonObject>
|
||||
#include <QNetworkAccessManager>
|
||||
#include <QNetworkReply>
|
||||
#include <QNetworkRequest>
|
||||
#include <QUrlQuery>
|
||||
|
||||
UploadClient::UploadClient(QString baseUrl, QString username, QString password, QObject *parent)
|
||||
: QObject(parent)
|
||||
@@ -125,3 +129,152 @@ void UploadClient::testConnection()
|
||||
emit testFinished(QStringLiteral("Server returned %1").arg(status));
|
||||
});
|
||||
}
|
||||
|
||||
// --- Manage API ------------------------------------------------------------
|
||||
|
||||
namespace {
|
||||
QString httpError(QNetworkReply *reply, int status)
|
||||
{
|
||||
if (status == 401 || status == 403)
|
||||
return QStringLiteral("Wrong username or password");
|
||||
if (status == 0)
|
||||
return reply->errorString();
|
||||
const QString body = QString::fromUtf8(reply->readAll()).trimmed();
|
||||
return body.isEmpty() ? QStringLiteral("Server returned %1").arg(status) : body;
|
||||
}
|
||||
} // namespace
|
||||
|
||||
void UploadClient::listPhotos()
|
||||
{
|
||||
QNetworkRequest request(QUrl(m_base + QStringLiteral("/api/photos")));
|
||||
request.setRawHeader("Authorization", authHeader());
|
||||
|
||||
QNetworkReply *reply = m_net->get(request);
|
||||
connect(reply, &QNetworkReply::finished, this, [this, reply]() {
|
||||
reply->deleteLater();
|
||||
const int status = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
|
||||
if (reply->error() != QNetworkReply::NoError || status < 200 || status >= 300) {
|
||||
emit photosListed({}, httpError(reply, status));
|
||||
return;
|
||||
}
|
||||
const QJsonDocument doc = QJsonDocument::fromJson(reply->readAll());
|
||||
if (!doc.isArray()) {
|
||||
emit photosListed({}, QStringLiteral("Could not read the server's response"));
|
||||
return;
|
||||
}
|
||||
QList<RemotePhoto> photos;
|
||||
const QJsonArray arr = doc.array();
|
||||
for (const QJsonValue &v : arr) {
|
||||
const QJsonObject o = v.toObject();
|
||||
RemotePhoto p;
|
||||
p.slug = o.value(QStringLiteral("slug")).toString();
|
||||
p.caption = o.value(QStringLiteral("caption")).toString();
|
||||
p.date = o.value(QStringLiteral("date")).toString();
|
||||
p.thumb = o.value(QStringLiteral("thumb")).toString();
|
||||
p.url = o.value(QStringLiteral("url")).toString();
|
||||
const QJsonArray tags = o.value(QStringLiteral("tags")).toArray();
|
||||
for (const QJsonValue &t : tags)
|
||||
p.tags << t.toString();
|
||||
photos << p;
|
||||
}
|
||||
emit photosListed(photos, QString());
|
||||
});
|
||||
}
|
||||
|
||||
void UploadClient::fetchTags()
|
||||
{
|
||||
QNetworkRequest request(QUrl(m_base + QStringLiteral("/api/tags.json")));
|
||||
request.setRawHeader("Authorization", authHeader());
|
||||
|
||||
QNetworkReply *reply = m_net->get(request);
|
||||
connect(reply, &QNetworkReply::finished, this, [this, reply]() {
|
||||
reply->deleteLater();
|
||||
const int status = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
|
||||
if (reply->error() != QNetworkReply::NoError || status < 200 || status >= 300) {
|
||||
emit tagsFetched({}); // best-effort; autocomplete is a convenience
|
||||
return;
|
||||
}
|
||||
const QJsonDocument doc = QJsonDocument::fromJson(reply->readAll());
|
||||
QStringList names;
|
||||
for (const QJsonValue &v : doc.array()) {
|
||||
const QString name = v.toObject().value(QStringLiteral("tag")).toString();
|
||||
if (!name.isEmpty())
|
||||
names << name;
|
||||
}
|
||||
emit tagsFetched(names);
|
||||
});
|
||||
}
|
||||
|
||||
void UploadClient::fetchThumbnail(const QString &slug)
|
||||
{
|
||||
QNetworkRequest request(QUrl(m_base + QStringLiteral("/api/thumb/") + slug));
|
||||
request.setRawHeader("Authorization", authHeader());
|
||||
|
||||
QNetworkReply *reply = m_net->get(request);
|
||||
connect(reply, &QNetworkReply::finished, this, [this, reply, slug]() {
|
||||
reply->deleteLater();
|
||||
const int status = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
|
||||
if (reply->error() != QNetworkReply::NoError || status < 200 || status >= 300) {
|
||||
emit thumbnailReady(slug, QImage()); // null image on any failure
|
||||
return;
|
||||
}
|
||||
QImage image;
|
||||
image.loadFromData(reply->readAll());
|
||||
emit thumbnailReady(slug, image);
|
||||
});
|
||||
}
|
||||
|
||||
void UploadClient::editPost(const QString &slug, const QString &caption,
|
||||
const QString &date, const QString &tags)
|
||||
{
|
||||
QUrlQuery form;
|
||||
form.addQueryItem(QStringLiteral("slug"), slug);
|
||||
form.addQueryItem(QStringLiteral("caption"), caption);
|
||||
form.addQueryItem(QStringLiteral("date"), date);
|
||||
form.addQueryItem(QStringLiteral("tags"), tags);
|
||||
|
||||
QNetworkRequest request(QUrl(m_base + QStringLiteral("/api/edit")));
|
||||
request.setRawHeader("Authorization", authHeader());
|
||||
request.setHeader(QNetworkRequest::ContentTypeHeader,
|
||||
QStringLiteral("application/x-www-form-urlencoded"));
|
||||
|
||||
QNetworkReply *reply =
|
||||
m_net->post(request, form.toString(QUrl::FullyEncoded).toUtf8());
|
||||
connect(reply, &QNetworkReply::finished, this, [this, reply, slug]() {
|
||||
reply->deleteLater();
|
||||
const int status = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
|
||||
if (reply->error() == QNetworkReply::NoError && status >= 200 && status < 300)
|
||||
emit editFinished(slug, QString());
|
||||
else
|
||||
emit editFinished(slug, httpError(reply, status));
|
||||
});
|
||||
}
|
||||
|
||||
void UploadClient::deletePost(const QString &slug)
|
||||
{
|
||||
QUrlQuery form;
|
||||
form.addQueryItem(QStringLiteral("slug"), slug);
|
||||
|
||||
QNetworkRequest request(QUrl(m_base + QStringLiteral("/api/delete")));
|
||||
request.setRawHeader("Authorization", authHeader());
|
||||
request.setHeader(QNetworkRequest::ContentTypeHeader,
|
||||
QStringLiteral("application/x-www-form-urlencoded"));
|
||||
|
||||
QNetworkReply *reply =
|
||||
m_net->post(request, form.toString(QUrl::FullyEncoded).toUtf8());
|
||||
connect(reply, &QNetworkReply::finished, this, [this, reply, slug]() {
|
||||
reply->deleteLater();
|
||||
const int status = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
|
||||
if (reply->error() != QNetworkReply::NoError || status < 200 || status >= 300) {
|
||||
emit deleteFinished(slug, httpError(reply, status));
|
||||
return;
|
||||
}
|
||||
// The server reports how many it moved; 0 means the slug wasn't found.
|
||||
const QJsonDocument doc = QJsonDocument::fromJson(reply->readAll());
|
||||
const int deleted = doc.object().value(QStringLiteral("deleted")).toInt(0);
|
||||
if (deleted > 0)
|
||||
emit deleteFinished(slug, QString());
|
||||
else
|
||||
emit deleteFinished(slug, QStringLiteral("Nothing deleted — not found on the server"));
|
||||
});
|
||||
}
|
||||
@@ -1,10 +1,23 @@
|
||||
#pragma once
|
||||
|
||||
#include <QImage>
|
||||
#include <QList>
|
||||
#include <QObject>
|
||||
#include <QString>
|
||||
#include <QStringList>
|
||||
|
||||
class QNetworkAccessManager;
|
||||
|
||||
// One published post, as returned by GET /api/photos.
|
||||
struct RemotePhoto {
|
||||
QString slug;
|
||||
QString caption;
|
||||
QString date; // yyyy-MM-dd
|
||||
QStringList tags;
|
||||
QString thumb; // site-relative, e.g. "/thumbs/foo.jpg"
|
||||
QString url; // site-relative, e.g. "/photo/foo/"
|
||||
};
|
||||
|
||||
// Talks to the gallery's POST /upload endpoint, which sits behind nginx HTTP
|
||||
// Basic auth. The credentials go out preemptively in the Authorization header
|
||||
// on every request (never via QNetworkAccessManager's authenticationRequired
|
||||
@@ -35,12 +48,29 @@ public:
|
||||
// /health is not usable: nginx only proxies location /upload.
|
||||
void testConnection();
|
||||
|
||||
// Manage API, mirroring the web /manage and the Android app. The desktop
|
||||
// app is a non-browser client: it sends no Origin/Sec-Fetch-Site header, so
|
||||
// the state-changing posts pass the server's same-origin (CSRF) check.
|
||||
void listPhotos(); // GET /api/photos
|
||||
void fetchTags(); // GET /api/tags.json (unguarded)
|
||||
void fetchThumbnail(const QString &slug); // GET /api/thumb/<slug> (unguarded)
|
||||
void editPost(const QString &slug, const QString &caption,
|
||||
const QString &date, const QString &tags); // POST /api/edit
|
||||
void deletePost(const QString &slug); // POST /api/delete (moves to trash)
|
||||
|
||||
signals:
|
||||
void uploadFinished(UploadClient::Result result, const QString &slug,
|
||||
const QString &url, const QString &message);
|
||||
// errorMessage is empty on success.
|
||||
void testFinished(const QString &errorMessage);
|
||||
|
||||
// Manage signals. The error strings are empty on success.
|
||||
void photosListed(const QList<RemotePhoto> &photos, const QString &error);
|
||||
void tagsFetched(const QStringList &tags);
|
||||
void thumbnailReady(const QString &slug, const QImage &image);
|
||||
void editFinished(const QString &slug, const QString &error);
|
||||
void deleteFinished(const QString &slug, const QString &error);
|
||||
|
||||
private:
|
||||
QByteArray authHeader() const;
|
||||
|
||||
|
||||
+66
-42
@@ -27,6 +27,11 @@ const (
|
||||
mediumMaxSize = 1600
|
||||
defaultPageSize = 60
|
||||
|
||||
// The two paginated views. The one chosen as -default-view is published at
|
||||
// the site root, the other under /<name>/.
|
||||
viewTimeline = "timeline"
|
||||
viewGrid = "grid"
|
||||
|
||||
// Open Graph preview image, shared to WhatsApp/Telegram/etc. Kept to a
|
||||
// 1200px longest side and squeezed under ogTargetBytes: WhatsApp is widely
|
||||
// reported to drop the preview entirely once the image passes ~300 KB, so
|
||||
@@ -80,15 +85,19 @@ type Generator struct {
|
||||
serifFamily string
|
||||
mlFamily string
|
||||
pageSize int
|
||||
defaultView string
|
||||
mu sync.Mutex
|
||||
tmpl *template.Template
|
||||
}
|
||||
|
||||
func NewGenerator(contentDir, outputDir, baseURL, author, handle, bio, bioAlt, fontsURL, serifFamily, mlFamily string, pageSize int) *Generator {
|
||||
func NewGenerator(contentDir, outputDir, baseURL, author, handle, bio, bioAlt, fontsURL, serifFamily, mlFamily string, pageSize int, defaultView string) *Generator {
|
||||
tmpl := template.Must(template.ParseFS(assets, "templates/*.html"))
|
||||
if pageSize < 1 {
|
||||
pageSize = defaultPageSize
|
||||
}
|
||||
if defaultView != viewGrid {
|
||||
defaultView = viewTimeline
|
||||
}
|
||||
return &Generator{
|
||||
contentDir: contentDir,
|
||||
outputDir: outputDir,
|
||||
@@ -101,10 +110,33 @@ func NewGenerator(contentDir, outputDir, baseURL, author, handle, bio, bioAlt, f
|
||||
serifFamily: serifFamily,
|
||||
mlFamily: mlFamily,
|
||||
pageSize: pageSize,
|
||||
defaultView: defaultView,
|
||||
tmpl: tmpl,
|
||||
}
|
||||
}
|
||||
|
||||
// viewBase returns the URL prefix a view is published under: "" for the default
|
||||
// view, which owns the site root, and "/<view>" for the other one.
|
||||
func (g *Generator) viewBase(view string) string {
|
||||
if view == g.defaultView {
|
||||
return ""
|
||||
}
|
||||
return "/" + view
|
||||
}
|
||||
|
||||
// pageURL returns the URL of the 1-based page n of a view rooted at base.
|
||||
func pageURL(base string, n int) string {
|
||||
if n == 1 {
|
||||
return base + "/"
|
||||
}
|
||||
return base + "/page/" + strconv.Itoa(n) + "/"
|
||||
}
|
||||
|
||||
// timelineURL and gridURL are the roots of each view, for cross-links in the
|
||||
// page headers.
|
||||
func (g *Generator) timelineURL() string { return pageURL(g.viewBase(viewTimeline), 1) }
|
||||
func (g *Generator) gridURL() string { return pageURL(g.viewBase(viewGrid), 1) }
|
||||
|
||||
func (g *Generator) initial() string {
|
||||
for _, r := range g.author {
|
||||
return strings.ToUpper(string(r))
|
||||
@@ -124,19 +156,19 @@ func (g *Generator) Build() error {
|
||||
}
|
||||
|
||||
// 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"} {
|
||||
// post, a retag, a changed date or a flipped -default-view 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. Both "timeline" and "grid" are removed: whichever is the
|
||||
// default owns the site root and has no dir of its own, so a dir by that
|
||||
// name can only be a leftover from the opposite -default-view.
|
||||
for _, d := range []string{"photo", "day", "album", "page", "timeline", "grid"} {
|
||||
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"} {
|
||||
for _, d := range []string{"images", "thumbs", "medium", "og", "photo", "day", "album", "albums", "static"} {
|
||||
if err := os.MkdirAll(filepath.Join(g.outputDir, d), 0755); err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -467,17 +499,17 @@ func generateOG(src, dst string, maxDim int) error {
|
||||
return os.WriteFile(dst, buf.Bytes(), 0644)
|
||||
}
|
||||
|
||||
// renderGridPages writes the paginated square-grid view under public/grid/:
|
||||
// grid/index.html and grid/page/N/index.html, chunking photos into pageSize
|
||||
// slices for progressive pagination. The grid is the secondary view; the
|
||||
// timeline is the site root.
|
||||
// renderGridPages writes the paginated square-grid view. When grid is the
|
||||
// -default-view it is the site root (index.html + page/N/); otherwise it lives
|
||||
// under /grid/. Photos are chunked into pageSize slices for progressive
|
||||
// pagination.
|
||||
func (g *Generator) renderGridPages(photos []Photo) error {
|
||||
total := len(photos)
|
||||
totalPages := (total + g.pageSize - 1) / g.pageSize
|
||||
if totalPages == 0 {
|
||||
totalPages = 1
|
||||
}
|
||||
gridDir := filepath.Join(g.outputDir, "grid")
|
||||
base := g.viewBase(viewGrid)
|
||||
|
||||
for i := 0; i < totalPages; i++ {
|
||||
start := i * g.pageSize
|
||||
@@ -487,27 +519,19 @@ func (g *Generator) renderGridPages(photos []Photo) error {
|
||||
}
|
||||
slice := photos[start:end]
|
||||
|
||||
dst := filepath.Join(gridDir, "index.html")
|
||||
if i > 0 {
|
||||
dir := filepath.Join(gridDir, "page", strconv.Itoa(i+1))
|
||||
dir := filepath.Join(g.outputDir, filepath.FromSlash(pageURL(base, i+1)))
|
||||
if err := os.MkdirAll(dir, 0755); err != nil {
|
||||
return err
|
||||
}
|
||||
dst = filepath.Join(dir, "index.html")
|
||||
}
|
||||
dst := filepath.Join(dir, "index.html")
|
||||
|
||||
prev := ""
|
||||
next := ""
|
||||
switch i {
|
||||
case 0:
|
||||
// no prev
|
||||
case 1:
|
||||
prev = "/grid/"
|
||||
default:
|
||||
prev = "/grid/page/" + strconv.Itoa(i) + "/"
|
||||
if i > 0 {
|
||||
prev = pageURL(base, i)
|
||||
}
|
||||
if i+1 < totalPages {
|
||||
next = "/grid/page/" + strconv.Itoa(i+2) + "/"
|
||||
next = pageURL(base, i+2)
|
||||
}
|
||||
|
||||
data := map[string]any{
|
||||
@@ -517,6 +541,8 @@ func (g *Generator) renderGridPages(photos []Photo) error {
|
||||
"TotalPages": totalPages,
|
||||
"PrevURL": prev,
|
||||
"NextURL": next,
|
||||
"TimelineURL": g.timelineURL(),
|
||||
"GridURL": g.gridURL(),
|
||||
"BaseURL": g.baseURL,
|
||||
"Year": time.Now().Year(),
|
||||
"Author": g.author,
|
||||
@@ -604,35 +630,29 @@ func chunkDayGroups(groups []DayGroup, target int) [][]DayGroup {
|
||||
return pages
|
||||
}
|
||||
|
||||
// renderTimelinePages writes the day-grouped timeline as the site root:
|
||||
// index.html and page/N/index.html. Photos are grouped by day, then packed
|
||||
// renderTimelinePages writes the day-grouped timeline. When timeline is the
|
||||
// -default-view (the default) it is the site root (index.html + page/N/);
|
||||
// otherwise it lives under /timeline/. Photos are grouped by day, then packed
|
||||
// into pages of roughly pageSize without splitting a day across pages.
|
||||
func (g *Generator) renderTimelinePages(photos []Photo) error {
|
||||
pages := chunkDayGroups(groupByDay(photos), g.pageSize)
|
||||
totalPages := len(pages)
|
||||
base := g.viewBase(viewTimeline)
|
||||
|
||||
for i, groups := range pages {
|
||||
dst := filepath.Join(g.outputDir, "index.html")
|
||||
if i > 0 {
|
||||
dir := filepath.Join(g.outputDir, "page", strconv.Itoa(i+1))
|
||||
dir := filepath.Join(g.outputDir, filepath.FromSlash(pageURL(base, i+1)))
|
||||
if err := os.MkdirAll(dir, 0755); err != nil {
|
||||
return err
|
||||
}
|
||||
dst = filepath.Join(dir, "index.html")
|
||||
}
|
||||
dst := filepath.Join(dir, "index.html")
|
||||
|
||||
prev := ""
|
||||
next := ""
|
||||
switch i {
|
||||
case 0:
|
||||
// no prev
|
||||
case 1:
|
||||
prev = "/"
|
||||
default:
|
||||
prev = "/page/" + strconv.Itoa(i) + "/"
|
||||
if i > 0 {
|
||||
prev = pageURL(base, i)
|
||||
}
|
||||
if i+1 < totalPages {
|
||||
next = "/page/" + strconv.Itoa(i+2) + "/"
|
||||
next = pageURL(base, i+2)
|
||||
}
|
||||
|
||||
data := map[string]any{
|
||||
@@ -642,6 +662,8 @@ func (g *Generator) renderTimelinePages(photos []Photo) error {
|
||||
"TotalPages": totalPages,
|
||||
"PrevURL": prev,
|
||||
"NextURL": next,
|
||||
"TimelineURL": g.timelineURL(),
|
||||
"GridURL": g.gridURL(),
|
||||
"BaseURL": g.baseURL,
|
||||
"Year": time.Now().Year(),
|
||||
"Author": g.author,
|
||||
@@ -673,6 +695,8 @@ func (g *Generator) renderDayPages(photos []Photo) error {
|
||||
"Count": grp.Count,
|
||||
"Photos": grp.Photos,
|
||||
"Total": len(photos),
|
||||
"TimelineURL": g.timelineURL(),
|
||||
"GridURL": g.gridURL(),
|
||||
"BaseURL": g.baseURL,
|
||||
"Year": time.Now().Year(),
|
||||
"Author": g.author,
|
||||
|
||||
@@ -21,15 +21,20 @@ func main() {
|
||||
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)")
|
||||
htpasswd := flag.String("htpasswd", "", "path to an htpasswd file (bcrypt, `htpasswd -B`) guarding /upload; empty disables auth")
|
||||
defaultView := flag.String("default-view", viewTimeline, "view published at the site root: \"timeline\" or \"grid\"; the other is published under /<name>/")
|
||||
flag.Parse()
|
||||
|
||||
if *defaultView != viewTimeline && *defaultView != viewGrid {
|
||||
log.Fatalf("-default-view must be %q or %q, got %q", viewTimeline, viewGrid, *defaultView)
|
||||
}
|
||||
|
||||
for _, d := range []string{*contentDir, *outputDir} {
|
||||
if err := os.MkdirAll(d, 0755); err != nil {
|
||||
log.Fatalf("mkdir %s: %v", d, err)
|
||||
}
|
||||
}
|
||||
|
||||
g := NewGenerator(*contentDir, *outputDir, *baseURL, *author, *handle, *bio, *bioAlt, *fontsURL, *serifFamily, *mlFamily, *pageSize)
|
||||
g := NewGenerator(*contentDir, *outputDir, *baseURL, *author, *handle, *bio, *bioAlt, *fontsURL, *serifFamily, *mlFamily, *pageSize, *defaultView)
|
||||
|
||||
if err := g.Build(); err != nil {
|
||||
log.Printf("initial build: %v", err)
|
||||
|
||||
@@ -26,6 +26,92 @@ type photoJSON struct {
|
||||
URL string `json:"url"`
|
||||
}
|
||||
|
||||
// handleSession reports whether the request carries valid credentials, so the
|
||||
// UI can reveal management links and a signed-in indicator. It always returns
|
||||
// 200 and never sends WWW-Authenticate, so calling it from a public page does
|
||||
// not trigger the browser's Basic-auth dialog.
|
||||
//
|
||||
// It must not become a password-probing oracle that sidesteps the /upload
|
||||
// limiter: a request with no credentials (a logged-out browser) is answered
|
||||
// cheaply as "not authenticated", but one carrying wrong credentials is run
|
||||
// through the same failed-attempt limiter and gets 429 once that is drained.
|
||||
func (s *Server) handleSession(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
|
||||
if s.auth == nil { // auth disabled → everything is open
|
||||
writeJSON(w, map[string]bool{"authenticated": true})
|
||||
return
|
||||
}
|
||||
|
||||
user, pass, ok := r.BasicAuth()
|
||||
if !ok {
|
||||
writeJSON(w, map[string]bool{"authenticated": false})
|
||||
return
|
||||
}
|
||||
if s.auth.check(user, pass) {
|
||||
writeJSON(w, map[string]bool{"authenticated": true})
|
||||
return
|
||||
}
|
||||
if !s.authLimit.Allow() {
|
||||
http.Error(w, "too many attempts", http.StatusTooManyRequests)
|
||||
return
|
||||
}
|
||||
writeJSON(w, map[string]bool{"authenticated": false})
|
||||
}
|
||||
|
||||
// handleThumb serves a photo's thumbnail from the generated output. Non-browser
|
||||
// clients (the Android app) use this instead of the static /thumbs/<slug>.jpg
|
||||
// path, because a front-door botwall on `location /` can block a non-browser
|
||||
// client from the static site while `/api/` is proxied straight to this server.
|
||||
// It is registered UNGUARDED (see server.go): thumbnails are the same public
|
||||
// data as the static /thumbs/, so there is nothing to protect, and staying off
|
||||
// the auth path means it can never 401 and so can never trip an auth-fail jail
|
||||
// that would ban the app over a per-row thumbnail load.
|
||||
func (s *Server) handleThumb(w http.ResponseWriter, r *http.Request) {
|
||||
slug := r.PathValue("slug")
|
||||
if slug == "" || slug != filepath.Base(slug) || strings.HasPrefix(slug, ".") {
|
||||
http.Error(w, "bad slug", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
f, err := os.Open(filepath.Join(s.outputDir, "thumbs", slug+".jpg"))
|
||||
if err != nil {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
defer f.Close()
|
||||
fi, err := f.Stat()
|
||||
if err != nil {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "image/jpeg")
|
||||
http.ServeContent(w, r, slug+".jpg", fi.ModTime(), f)
|
||||
}
|
||||
|
||||
// handleTagsJSON serves the generated tags.json under /api/ so the Android app
|
||||
// can offer tag autocomplete. It is registered UNGUARDED (see server.go): the
|
||||
// tag list is the same public data as the static /tags.json, so there is
|
||||
// nothing to protect, and staying off the auth path means it can never return
|
||||
// 401 and so can never trip an nginx auth-fail jail that would ban the app
|
||||
// over an autocomplete poll. It lives under /api/ only so nginx proxies it to
|
||||
// the app, reaching non-browser clients past a front-door botwall on
|
||||
// `location /` (the same botwall reason /api/thumb/ exists).
|
||||
func (s *Server) handleTagsJSON(w http.ResponseWriter, r *http.Request) {
|
||||
f, err := os.Open(filepath.Join(s.outputDir, "tags.json"))
|
||||
if err != nil {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
defer f.Close()
|
||||
fi, err := f.Stat()
|
||||
if err != nil {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||
http.ServeContent(w, r, "tags.json", fi.ModTime(), f)
|
||||
}
|
||||
|
||||
// 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")
|
||||
@@ -69,7 +155,7 @@ func (s *Server) handleEdit(w http.ResponseWriter, r *http.Request) {
|
||||
if s.rejectCrossSite(w, r) {
|
||||
return
|
||||
}
|
||||
if err := r.ParseForm(); err != nil {
|
||||
if err := parseForm(r); err != nil {
|
||||
http.Error(w, "bad request", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
@@ -191,6 +277,19 @@ func (s *Server) handleBulkTags(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
// ── helpers ────────────────────────────────────────────────────────────────
|
||||
|
||||
// parseForm reads form values from either an application/x-www-form-urlencoded
|
||||
// or a multipart/form-data body. Browsers posting FormData send multipart,
|
||||
// which r.ParseForm alone does not read from the body; ParseMultipartForm
|
||||
// handles both — it runs ParseForm internally (so query and urlencoded values
|
||||
// are parsed) and only reports ErrNotMultipart for a non-multipart body, by
|
||||
// which point those values are already available.
|
||||
func parseForm(r *http.Request) error {
|
||||
if err := r.ParseMultipartForm(32 << 20); err != nil && err != http.ErrNotMultipart {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// 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.
|
||||
@@ -210,7 +309,7 @@ func (s *Server) resolveSlug(slug string) (string, bool) {
|
||||
// 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 {
|
||||
if err := parseForm(r); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
seen := make(map[string]bool)
|
||||
|
||||
+84
-1
@@ -1,9 +1,11 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"image"
|
||||
"image/png"
|
||||
"mime/multipart"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
@@ -29,7 +31,7 @@ func newTestServer(t *testing.T) (*Server, string, string) {
|
||||
}
|
||||
writePNG(t, filepath.Join(content, "bar.png")) // no sidecar
|
||||
|
||||
g := NewGenerator(content, output, "http://x", "A", "@a", "bio", "", "f", "s", "m", 60)
|
||||
g := NewGenerator(content, output, "http://x", "A", "@a", "bio", "", "f", "s", "m", 60, viewTimeline)
|
||||
if err := g.Build(); err != nil {
|
||||
t.Fatalf("initial build: %v", err)
|
||||
}
|
||||
@@ -58,6 +60,20 @@ func form(v url.Values) *http.Request {
|
||||
return r
|
||||
}
|
||||
|
||||
// multipartForm builds a multipart/form-data request, as a browser's FormData
|
||||
// does — the content type the manage handlers must parse, not just urlencoded.
|
||||
func multipartForm(fields map[string]string) *http.Request {
|
||||
var b bytes.Buffer
|
||||
mw := multipart.NewWriter(&b)
|
||||
for k, v := range fields {
|
||||
mw.WriteField(k, v)
|
||||
}
|
||||
mw.Close()
|
||||
r := httptest.NewRequest(http.MethodPost, "/", &b)
|
||||
r.Header.Set("Content-Type", mw.FormDataContentType())
|
||||
return r
|
||||
}
|
||||
|
||||
func readMeta(t *testing.T, content, slug string) PhotoMeta {
|
||||
t.Helper()
|
||||
var m PhotoMeta
|
||||
@@ -213,6 +229,37 @@ func TestHandleDeleteMovesToTrashAndPrunes(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestMultipartBodies guards the regression where the manage handlers used
|
||||
// r.ParseForm (urlencoded only) and silently ignored the multipart bodies that
|
||||
// browsers send via FormData, returning 200 with deleted:0 / no change.
|
||||
func TestMultipartBodies(t *testing.T) {
|
||||
s, content, _ := newTestServer(t)
|
||||
|
||||
// Edit via multipart.
|
||||
rec := httptest.NewRecorder()
|
||||
s.handleEdit(rec, multipartForm(map[string]string{
|
||||
"slug": "foo", "caption": "Multipart", "date": "2021-02-03", "tags": "x,y",
|
||||
}))
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("multipart edit: code=%d", rec.Code)
|
||||
}
|
||||
if m := readMeta(t, content, "foo"); m.Caption != "Multipart" || strings.Join(m.Tags, ",") != "x,y" {
|
||||
t.Errorf("multipart edit not applied: %+v", m)
|
||||
}
|
||||
|
||||
// Delete via multipart actually moves the file.
|
||||
rec = httptest.NewRecorder()
|
||||
s.handleDelete(rec, multipartForm(map[string]string{"slug": "bar"}))
|
||||
var res map[string]int
|
||||
json.Unmarshal(rec.Body.Bytes(), &res)
|
||||
if res["deleted"] != 1 {
|
||||
t.Fatalf("multipart delete: deleted=%d, want 1 (body=%s)", res["deleted"], rec.Body)
|
||||
}
|
||||
if _, err := os.Stat(filepath.Join(content, "bar.png")); !os.IsNotExist(err) {
|
||||
t.Error("bar.png should have moved to trash")
|
||||
}
|
||||
}
|
||||
|
||||
func TestCSRFGuard(t *testing.T) {
|
||||
s, _, _ := newTestServer(t) // generator.baseURL == "http://x"
|
||||
|
||||
@@ -283,3 +330,39 @@ func TestHandleListPhotos(t *testing.T) {
|
||||
t.Errorf("foo tags = %v", foo.Tags)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleTagsJSON(t *testing.T) {
|
||||
s, _, output := newTestServer(t)
|
||||
|
||||
rec := httptest.NewRecorder()
|
||||
s.handleTagsJSON(rec, httptest.NewRequest(http.MethodGet, "/api/tags.json", nil))
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("tags.json: code=%d", rec.Code)
|
||||
}
|
||||
if ct := rec.Header().Get("Content-Type"); !strings.HasPrefix(ct, "application/json") {
|
||||
t.Errorf("content-type = %q", ct)
|
||||
}
|
||||
var tags []struct {
|
||||
Tag string `json:"tag"`
|
||||
}
|
||||
if err := json.Unmarshal(rec.Body.Bytes(), &tags); err != nil {
|
||||
t.Fatalf("decode: %v", err)
|
||||
}
|
||||
got := map[string]bool{}
|
||||
for _, tg := range tags {
|
||||
got[tg.Tag] = true
|
||||
}
|
||||
if !got["berlin"] || !got["street"] {
|
||||
t.Errorf("tags = %v, want berlin+street", tags)
|
||||
}
|
||||
|
||||
// Missing file → 404.
|
||||
if err := os.Remove(filepath.Join(output, "tags.json")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
rec = httptest.NewRecorder()
|
||||
s.handleTagsJSON(rec, httptest.NewRequest(http.MethodGet, "/api/tags.json", nil))
|
||||
if rec.Code != http.StatusNotFound {
|
||||
t.Errorf("missing tags.json: code=%d, want 404", rec.Code)
|
||||
}
|
||||
}
|
||||
@@ -82,6 +82,12 @@ in {
|
||||
description = "Photos per page on the timeline and grid views. The timeline packs whole days, so pages vary slightly around this.";
|
||||
};
|
||||
|
||||
defaultView = lib.mkOption {
|
||||
type = lib.types.enum [ "timeline" "grid" ];
|
||||
default = "timeline";
|
||||
description = "View published at the site root; the other is published under /timeline/ or /grid/.";
|
||||
};
|
||||
|
||||
htpasswdFile = lib.mkOption {
|
||||
type = lib.types.nullOr lib.types.path;
|
||||
default = null;
|
||||
@@ -156,6 +162,7 @@ in {
|
||||
"--serif-family" cfg.serifFamily
|
||||
"--ml-family" cfg.mlFamily
|
||||
"--page-size" (toString cfg.pageSize)
|
||||
"--default-view" cfg.defaultView
|
||||
] ++ lib.optionals (cfg.htpasswdFile != null) [
|
||||
# %d is systemd's credentials directory; LoadCredential below drops
|
||||
# the htpasswd file there, readable only by this service.
|
||||
|
||||
@@ -100,10 +100,24 @@ func (s *Server) Listen() error {
|
||||
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))
|
||||
// Thumbnails and the tag list — deliberately NOT guarded. Both serve the
|
||||
// same public data as the static site (thumbs under /thumbs/, the tag list
|
||||
// at /tags.json), so there is nothing to protect. Keeping them off the auth
|
||||
// path means they can never return 401 and so can never feed an nginx
|
||||
// auth-fail jail (fail2ban), which would otherwise ban the app over a
|
||||
// per-row thumbnail load or an autocomplete poll. They stay under /api/
|
||||
// only so nginx proxies them to the app, reaching non-browser clients past
|
||||
// a front-door botwall on `location /`.
|
||||
mux.HandleFunc("GET /api/thumb/{slug}", s.handleThumb)
|
||||
mux.HandleFunc("GET /api/tags.json", s.handleTagsJSON)
|
||||
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))
|
||||
|
||||
// Login-state probe — deliberately NOT guarded, so public pages can ask
|
||||
// without triggering a Basic-auth dialog. It does its own silent check.
|
||||
mux.HandleFunc("GET /api/session", s.handleSession)
|
||||
|
||||
mux.HandleFunc("GET /health", func(w http.ResponseWriter, r *http.Request) {
|
||||
fmt.Fprintln(w, "ok")
|
||||
})
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
// Shows a management toolbar + signed-in indicator on every page when the
|
||||
// browser holds valid credentials. The public gallery is static and carries no
|
||||
// markup for this; the bar is built here only after /api/session confirms the
|
||||
// viewer is authenticated, so logged-out visitors see nothing and get no login
|
||||
// dialog.
|
||||
//
|
||||
// A page may set <body data-slug="..."> (the photo pages do) to get an
|
||||
// "Edit this" link straight to that post in /manage.
|
||||
(function () {
|
||||
fetch("/api/session", { headers: { Accept: "application/json" }, cache: "no-store" })
|
||||
.then((r) => (r.ok ? r.json() : { authenticated: false }))
|
||||
.then((s) => {
|
||||
if (s && s.authenticated) buildBar();
|
||||
})
|
||||
.catch(() => {});
|
||||
|
||||
function el(tag, cls, text) {
|
||||
const e = document.createElement(tag);
|
||||
if (cls) e.className = cls;
|
||||
if (text != null) e.textContent = text;
|
||||
return e;
|
||||
}
|
||||
|
||||
function buildBar() {
|
||||
document.body.classList.add("authed");
|
||||
|
||||
const bar = el("div", "session-bar");
|
||||
const path = location.pathname.replace(/\/$/, "");
|
||||
|
||||
const link = (href, label) => {
|
||||
const a = el("a", null, label);
|
||||
a.href = href;
|
||||
bar.appendChild(a);
|
||||
};
|
||||
|
||||
if (path !== "/upload") link("/upload", "Upload");
|
||||
if (path !== "/manage") link("/manage", "Manage");
|
||||
|
||||
const slug = document.body.dataset.slug;
|
||||
if (slug) link("/manage?edit=" + encodeURIComponent(slug), "Edit this");
|
||||
|
||||
bar.appendChild(el("span", "session-dot", "● signed in"));
|
||||
|
||||
// Best-effort logout. HTTP Basic has no real sign-out — the browser caches
|
||||
// credentials and clears them reliably only when the window closes — so
|
||||
// this overwrites the cached credential with a throwaway one and reloads.
|
||||
// It works in some browsers and not others; a dependable logout would need
|
||||
// cookie sessions.
|
||||
const out = el("a", "session-out", "log out");
|
||||
out.href = "#";
|
||||
out.title = "Best-effort — HTTP Basic auth has no reliable logout";
|
||||
out.addEventListener("click", (e) => {
|
||||
e.preventDefault();
|
||||
fetch("/api/session", {
|
||||
headers: { Authorization: "Basic " + btoa("logout:" + Date.now()) },
|
||||
cache: "no-store",
|
||||
})
|
||||
.catch(() => {})
|
||||
.finally(() => setTimeout(() => location.reload(), 150));
|
||||
});
|
||||
bar.appendChild(out);
|
||||
|
||||
document.body.appendChild(bar);
|
||||
}
|
||||
})();
|
||||
@@ -476,3 +476,50 @@ body {
|
||||
font-family: var(--serif);
|
||||
margin-top: 16px;
|
||||
}
|
||||
|
||||
/* Tag autocomplete dropdown (tagcomplete.js), shared by upload and manage. */
|
||||
.tagac-menu {
|
||||
position: absolute;
|
||||
z-index: 50;
|
||||
background: var(--bg1);
|
||||
border: 1px solid var(--bg2);
|
||||
max-height: 220px;
|
||||
overflow-y: auto;
|
||||
box-shadow: 0 6px 18px rgba(0, 0, 0, 0.4);
|
||||
}
|
||||
.tagac-item {
|
||||
padding: 7px 11px;
|
||||
font-family: var(--serif);
|
||||
font-size: 14px;
|
||||
color: var(--fg2);
|
||||
cursor: pointer;
|
||||
}
|
||||
.tagac-item.sel,
|
||||
.tagac-item:hover {
|
||||
background: var(--bg2);
|
||||
color: var(--fg);
|
||||
}
|
||||
|
||||
/* Session toolbar (session.js), shown on any page when signed in. */
|
||||
.session-bar {
|
||||
position: fixed;
|
||||
top: 0;
|
||||
right: 0;
|
||||
z-index: 60;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 14px;
|
||||
padding: 7px 14px;
|
||||
background: var(--bg1);
|
||||
border-left: 1px solid var(--bg2);
|
||||
border-bottom: 1px solid var(--bg2);
|
||||
font-family: monospace;
|
||||
font-size: 12px;
|
||||
}
|
||||
.session-bar a {
|
||||
color: var(--aqua, #8ec07c);
|
||||
text-decoration: none;
|
||||
}
|
||||
.session-bar a:hover { text-decoration: underline; }
|
||||
.session-dot { color: var(--green, #b8bb26); }
|
||||
.session-out { color: var(--fg4) !important; }
|
||||
@@ -0,0 +1,152 @@
|
||||
// Per-token tag autocomplete for comma-separated tag inputs, shared by the
|
||||
// upload and manage pages. Suggestions come from /tags.json (regenerated on
|
||||
// every build), so new tags appear on the next load. Only the token after the
|
||||
// last comma is completed; earlier tags in the field are left untouched.
|
||||
//
|
||||
// Usage: add data-tagcomplete to an <input>, or call TagComplete.attach(input)
|
||||
// for inputs created dynamically. TagComplete.invalidate() drops the cached
|
||||
// tag list after an edit that may have introduced new tags.
|
||||
(function () {
|
||||
let tags = null; // cached list of tag names
|
||||
let inflight = null;
|
||||
|
||||
const menu = document.createElement("div");
|
||||
menu.className = "tagac-menu";
|
||||
menu.style.display = "none";
|
||||
menu.setAttribute("role", "listbox");
|
||||
document.body.appendChild(menu);
|
||||
|
||||
let items = []; // currently shown suggestions
|
||||
let sel = -1; // highlighted index
|
||||
|
||||
function loadTags() {
|
||||
if (tags) return Promise.resolve(tags);
|
||||
if (inflight) return inflight;
|
||||
inflight = fetch("/tags.json", { headers: { Accept: "application/json" } })
|
||||
.then((r) => (r.ok ? r.json() : []))
|
||||
.then((list) => {
|
||||
tags = (list || []).map((t) => t.tag);
|
||||
return tags;
|
||||
})
|
||||
.catch(() => {
|
||||
tags = [];
|
||||
return tags;
|
||||
});
|
||||
return inflight;
|
||||
}
|
||||
|
||||
// The token being typed is the text after the last comma.
|
||||
function lastToken(value) {
|
||||
return value.slice(value.lastIndexOf(",") + 1).replace(/^\s+/, "");
|
||||
}
|
||||
|
||||
function replaceLastToken(value, tag) {
|
||||
const i = value.lastIndexOf(",");
|
||||
const head = i < 0 ? "" : value.slice(0, i + 1) + " ";
|
||||
return head + tag + ", ";
|
||||
}
|
||||
|
||||
function presentTags(value) {
|
||||
return value
|
||||
.split(",")
|
||||
.map((s) => s.trim().toLowerCase())
|
||||
.filter(Boolean);
|
||||
}
|
||||
|
||||
function hide() {
|
||||
menu.style.display = "none";
|
||||
sel = -1;
|
||||
items = [];
|
||||
}
|
||||
|
||||
function highlight() {
|
||||
[...menu.children].forEach((c, i) => c.classList.toggle("sel", i === sel));
|
||||
if (sel >= 0 && menu.children[sel]) {
|
||||
menu.children[sel].scrollIntoView({ block: "nearest" });
|
||||
}
|
||||
}
|
||||
|
||||
function render(input) {
|
||||
const token = lastToken(input.value).toLowerCase();
|
||||
if (!token) {
|
||||
hide();
|
||||
return;
|
||||
}
|
||||
const present = new Set(presentTags(input.value));
|
||||
items = (tags || [])
|
||||
.filter((t) => t.toLowerCase().includes(token) && !present.has(t.toLowerCase()))
|
||||
.slice(0, 8);
|
||||
if (items.length === 0) {
|
||||
hide();
|
||||
return;
|
||||
}
|
||||
sel = 0;
|
||||
menu.innerHTML = "";
|
||||
items.forEach((t, idx) => {
|
||||
const row = document.createElement("div");
|
||||
row.className = "tagac-item" + (idx === 0 ? " sel" : "");
|
||||
row.setAttribute("role", "option");
|
||||
row.textContent = t;
|
||||
// mousedown (not click) so it fires before the input's blur.
|
||||
row.addEventListener("mousedown", (e) => {
|
||||
e.preventDefault();
|
||||
choose(input, idx);
|
||||
});
|
||||
menu.appendChild(row);
|
||||
});
|
||||
const r = input.getBoundingClientRect();
|
||||
menu.style.left = window.scrollX + r.left + "px";
|
||||
menu.style.top = window.scrollY + r.bottom + "px";
|
||||
menu.style.width = r.width + "px";
|
||||
menu.style.display = "block";
|
||||
}
|
||||
|
||||
function choose(input, idx) {
|
||||
if (idx < 0 || idx >= items.length) return;
|
||||
input.value = replaceLastToken(input.value, items[idx]);
|
||||
hide();
|
||||
input.focus();
|
||||
input.dispatchEvent(new Event("input", { bubbles: true }));
|
||||
}
|
||||
|
||||
function attach(input) {
|
||||
if (!input || input.dataset.tagacBound) return;
|
||||
input.dataset.tagacBound = "1";
|
||||
input.setAttribute("autocomplete", "off");
|
||||
input.addEventListener("focus", () => loadTags().then(() => render(input)));
|
||||
input.addEventListener("input", () => loadTags().then(() => render(input)));
|
||||
input.addEventListener("keydown", (e) => {
|
||||
if (menu.style.display === "none" || items.length === 0) return;
|
||||
if (e.key === "ArrowDown") {
|
||||
e.preventDefault();
|
||||
sel = (sel + 1) % items.length;
|
||||
highlight();
|
||||
} else if (e.key === "ArrowUp") {
|
||||
e.preventDefault();
|
||||
sel = (sel - 1 + items.length) % items.length;
|
||||
highlight();
|
||||
} else if (e.key === "Enter" || e.key === "Tab") {
|
||||
if (sel >= 0) {
|
||||
e.preventDefault();
|
||||
choose(input, sel);
|
||||
}
|
||||
} else if (e.key === "Escape") {
|
||||
hide();
|
||||
}
|
||||
});
|
||||
// Delay so a mousedown on the menu is processed before hiding.
|
||||
input.addEventListener("blur", () => setTimeout(hide, 120));
|
||||
}
|
||||
|
||||
window.TagComplete = {
|
||||
attach,
|
||||
invalidate() {
|
||||
tags = null;
|
||||
inflight = null;
|
||||
},
|
||||
};
|
||||
|
||||
document.addEventListener("DOMContentLoaded", () => {
|
||||
document.querySelectorAll("input[data-tagcomplete]").forEach(attach);
|
||||
});
|
||||
})();
|
||||
@@ -23,7 +23,7 @@
|
||||
<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="{{.TimelineURL}}" class="rss-a">Timeline</a>
|
||||
<a href="/albums/" class="rss-a">← Albums</a>
|
||||
</div>
|
||||
</div>
|
||||
@@ -92,5 +92,6 @@
|
||||
io.observe(btn);
|
||||
})();
|
||||
</script>
|
||||
<script src="/static/session.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -23,7 +23,7 @@
|
||||
<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="{{.TimelineURL}}" class="rss-a">← Timeline</a>
|
||||
</div>
|
||||
</div>
|
||||
</header>
|
||||
@@ -50,5 +50,6 @@
|
||||
<footer class="site-footer">
|
||||
© 2000–{{.Year}} {{.Author}}. All rights reserved.
|
||||
</footer>
|
||||
<script src="/static/session.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
+2
-1
@@ -23,7 +23,7 @@
|
||||
<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="{{.TimelineURL}}" class="rss-a">← Timeline</a>
|
||||
</div>
|
||||
</div>
|
||||
</header>
|
||||
@@ -46,5 +46,6 @@
|
||||
<footer class="site-footer">
|
||||
© 2000–{{.Year}} {{.Author}}. All rights reserved.
|
||||
</footer>
|
||||
<script src="/static/session.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
+2
-1
@@ -23,7 +23,7 @@
|
||||
<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="{{.TimelineURL}}" class="rss-a">Timeline</a>
|
||||
<a href="/albums/" class="rss-a">Albums</a>
|
||||
<a href="/feed.xml" class="rss-a">
|
||||
<svg width="14" height="14" viewBox="0 0 14 14" fill="currentColor" aria-hidden="true">
|
||||
@@ -103,5 +103,6 @@
|
||||
io.observe(btn);
|
||||
})();
|
||||
</script>
|
||||
<script src="/static/session.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
+34
-7
@@ -83,6 +83,7 @@
|
||||
#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; }
|
||||
.row-hl { outline: 2px solid var(--aqua, #8ec07c); outline-offset: 4px; transition: outline-color .4s; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
@@ -105,9 +106,9 @@
|
||||
|
||||
<div class="bulkbar" id="bulkbar">
|
||||
<span class="sel" id="sel">0 selected</span>
|
||||
<input type="text" id="bulk-add" placeholder="add tags" autocomplete="off">
|
||||
<input type="text" id="bulk-add" placeholder="add tags" autocomplete="off" data-tagcomplete>
|
||||
<button class="btn" id="btn-add">Add</button>
|
||||
<input type="text" id="bulk-remove" placeholder="remove tags" autocomplete="off">
|
||||
<input type="text" id="bulk-remove" placeholder="remove tags" autocomplete="off" data-tagcomplete>
|
||||
<button class="btn" id="btn-remove">Remove</button>
|
||||
<button class="btn danger" id="btn-del-sel">Delete selected</button>
|
||||
</div>
|
||||
@@ -118,6 +119,7 @@
|
||||
|
||||
<div id="toast"></div>
|
||||
|
||||
<script src="/static/tagcomplete.js"></script>
|
||||
<script>
|
||||
const list = document.getElementById('list');
|
||||
const countEl = document.getElementById('count');
|
||||
@@ -166,6 +168,7 @@
|
||||
// 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(', ');
|
||||
if (window.TagComplete) window.TagComplete.attach(el.querySelector('.f-tags'));
|
||||
|
||||
el.querySelector('.pick').addEventListener('change', refreshBulk);
|
||||
el.querySelector('.f-save').addEventListener('click', () => save(el, p.slug));
|
||||
@@ -183,12 +186,27 @@
|
||||
countEl.textContent = photos.length + (photos.length === 1 ? ' post' : ' posts');
|
||||
emptyEl.style.display = photos.length ? 'none' : 'block';
|
||||
refreshBulk();
|
||||
maybeFocusEdit();
|
||||
} catch (err) {
|
||||
countEl.textContent = '';
|
||||
flash('Could not load posts: ' + err.message, false);
|
||||
}
|
||||
}
|
||||
|
||||
// Deep link from a photo page's "Edit this": /manage?edit=<slug> scrolls to
|
||||
// that row, focuses its caption and highlights it briefly.
|
||||
function maybeFocusEdit() {
|
||||
const slug = new URLSearchParams(location.search).get('edit');
|
||||
if (!slug) return;
|
||||
const row = [...list.querySelectorAll('.row')].find(r => r.dataset.slug === slug);
|
||||
if (!row) return;
|
||||
row.scrollIntoView({ behavior: 'smooth', block: 'center' });
|
||||
const cap = row.querySelector('.f-caption');
|
||||
if (cap) cap.focus();
|
||||
row.classList.add('row-hl');
|
||||
setTimeout(() => row.classList.remove('row-hl'), 2000);
|
||||
}
|
||||
|
||||
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));
|
||||
@@ -203,6 +221,7 @@
|
||||
form.append('tags', el.querySelector('.f-tags').value);
|
||||
try {
|
||||
await post('/api/edit', form);
|
||||
if (window.TagComplete) window.TagComplete.invalidate();
|
||||
flash('Saved ' + slug, true);
|
||||
} catch (err) { flash('Save failed: ' + err.message, false); }
|
||||
}
|
||||
@@ -212,7 +231,9 @@
|
||||
const form = new FormData();
|
||||
form.append('slug', slug);
|
||||
try {
|
||||
await post('/api/delete', form);
|
||||
const res = await post('/api/delete', form);
|
||||
const j = await res.json().catch(() => ({}));
|
||||
if (!j.deleted) { flash('Not deleted — "' + slug + '" not found on the server', false); return; }
|
||||
el.remove();
|
||||
flash('Moved ' + slug + ' to trash', true);
|
||||
refreshBulk();
|
||||
@@ -233,8 +254,10 @@
|
||||
const form = new FormData();
|
||||
form.append('slugs', slugs.join(','));
|
||||
try {
|
||||
await post('/api/delete', form);
|
||||
flash('Moved ' + slugs.length + ' to trash', true);
|
||||
const res = await post('/api/delete', form);
|
||||
const j = await res.json().catch(() => ({}));
|
||||
if (!j.deleted) { flash('Nothing deleted — slugs not found on the server', false); return; }
|
||||
flash('Moved ' + j.deleted + ' to trash', true);
|
||||
await load();
|
||||
} catch (err) { flash('Delete failed: ' + err.message, false); }
|
||||
});
|
||||
@@ -247,9 +270,12 @@
|
||||
form.append('slugs', slugs.join(','));
|
||||
form.append(label, val);
|
||||
try {
|
||||
await post('/api/tags', form);
|
||||
const res = await post('/api/tags', form);
|
||||
const j = await res.json().catch(() => ({}));
|
||||
if (!j.updated) { flash('No posts updated', false); return; }
|
||||
if (window.TagComplete) window.TagComplete.invalidate();
|
||||
document.getElementById(field).value = '';
|
||||
flash('Updated tags on ' + slugs.length + ' post(s)', true);
|
||||
flash('Updated tags on ' + j.updated + ' post(s)', true);
|
||||
await load();
|
||||
} catch (err) { flash('Tag update failed: ' + err.message, false); }
|
||||
}
|
||||
@@ -335,5 +361,6 @@
|
||||
|
||||
load();
|
||||
</script>
|
||||
<script src="/static/session.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -11,7 +11,7 @@
|
||||
<meta property="og:type" content="article">
|
||||
<meta property="og:site_name" content="{{.Author}}">
|
||||
<meta property="og:title" content="{{.Photo.Caption}}">
|
||||
<meta property="og:description" content="{{.Author}} — {{.Photo.Date.Format "January 2, 2006"}}">
|
||||
<meta property="og:description" content="{{.Author}} — {{.Photo.Date.Format "January 2, 2006"}}{{if .Photo.Tags}} · {{range $i, $t := .Photo.Tags}}{{if $i}}, {{end}}{{$t.Name}}{{end}}{{end}}">
|
||||
<meta property="og:url" content="{{.BaseURL}}/photo/{{.Photo.Slug}}/">
|
||||
<meta property="og:image" content="{{.BaseURL}}/{{.Photo.OG}}">
|
||||
<meta property="og:image:type" content="image/jpeg">
|
||||
@@ -20,7 +20,7 @@
|
||||
<meta property="og:image:alt" content="{{.Photo.Caption}}">
|
||||
<meta name="twitter:card" content="summary_large_image">
|
||||
<meta name="twitter:title" content="{{.Photo.Caption}}">
|
||||
<meta name="twitter:description" content="{{.Author}} — {{.Photo.Date.Format "January 2, 2006"}}">
|
||||
<meta name="twitter:description" content="{{.Author}} — {{.Photo.Date.Format "January 2, 2006"}}{{if .Photo.Tags}} · {{range $i, $t := .Photo.Tags}}{{if $i}}, {{end}}{{$t.Name}}{{end}}{{end}}">
|
||||
<meta name="twitter:image" content="{{.BaseURL}}/{{.Photo.OG}}">
|
||||
|
||||
<link rel="stylesheet" href="{{.FontsURL}}">
|
||||
@@ -35,7 +35,7 @@
|
||||
{{if .Older}}<link rel="prefetch" href="/photo/{{.Older.Slug}}/">
|
||||
<link rel="prefetch" as="image" href="/{{.Older.Medium}}">{{end}}
|
||||
</head>
|
||||
<body>
|
||||
<body data-slug="{{.Photo.Slug}}">
|
||||
<div class="photo-page">
|
||||
<nav class="photo-nav">
|
||||
<a href="/" class="back-btn">← Back</a>
|
||||
@@ -73,5 +73,6 @@
|
||||
</footer>
|
||||
|
||||
<script src="/static/photo-nav.js" defer></script>
|
||||
<script src="/static/session.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -23,7 +23,7 @@
|
||||
<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="/grid/" class="rss-a">Grid</a>
|
||||
<a href="{{.GridURL}}" class="rss-a">Grid</a>
|
||||
<a href="/albums/" class="rss-a">Albums</a>
|
||||
<a href="/feed.xml" class="rss-a">
|
||||
<svg width="14" height="14" viewBox="0 0 14 14" fill="currentColor" aria-hidden="true">
|
||||
@@ -111,5 +111,6 @@
|
||||
io.observe(btn);
|
||||
})();
|
||||
</script>
|
||||
<script src="/static/session.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
+223
-214
@@ -10,176 +10,246 @@
|
||||
<link rel="icon" type="image/png" href="/static/web-32.png" sizes="32x32">
|
||||
<link rel="apple-touch-icon" href="/static/web-192.png">
|
||||
<style>
|
||||
.upload-page {
|
||||
max-width: 520px;
|
||||
margin: 0 auto;
|
||||
padding: 32px 20px;
|
||||
}
|
||||
.upload-page { max-width: 640px; margin: 0 auto; padding: 32px 20px 80px; }
|
||||
.upload-page h2 {
|
||||
font-family: var(--serif);
|
||||
font-size: 22px;
|
||||
font-weight: 600;
|
||||
color: var(--fg);
|
||||
margin-bottom: 28px;
|
||||
font-family: var(--serif); font-size: 22px; font-weight: 600;
|
||||
color: var(--fg); margin-bottom: 20px;
|
||||
}
|
||||
.drop-zone {
|
||||
border: 1px dashed var(--bg2);
|
||||
background: var(--bg0);
|
||||
width: 100%;
|
||||
aspect-ratio: 1;
|
||||
max-height: 340px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
cursor: pointer;
|
||||
margin-bottom: 24px;
|
||||
position: relative;
|
||||
overflow: hidden;
|
||||
transition: border-color 0.2s;
|
||||
.pick-btn, .submit-btn {
|
||||
width: 100%; background: var(--bg1); border: 1px solid var(--bg2);
|
||||
color: var(--fg2); font-family: var(--serif); font-size: 16px; font-weight: 600;
|
||||
padding: 12px; cursor: pointer; transition: background .2s, color .2s;
|
||||
}
|
||||
.drop-zone:hover { border-color: var(--fg4); }
|
||||
.drop-zone.has-image { border-style: solid; border-color: var(--bg2); }
|
||||
.drop-zone input[type="file"] {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
opacity: 0;
|
||||
cursor: pointer;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
.pick-btn:hover:not(:disabled), .submit-btn:hover:not(:disabled) { background: var(--bg2); color: var(--fg); }
|
||||
.submit-btn:disabled { opacity: .35; cursor: not-allowed; }
|
||||
.pick-btn { margin-bottom: 20px; }
|
||||
#file-input { display: none; }
|
||||
|
||||
#empty {
|
||||
display: flex; align-items: center; justify-content: center;
|
||||
height: 140px; background: var(--bg0); color: var(--fg4);
|
||||
font-family: var(--serif); margin-bottom: 20px;
|
||||
}
|
||||
.drop-prompt {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
color: var(--fg4);
|
||||
pointer-events: none;
|
||||
|
||||
.card { display: grid; grid-template-columns: 84px 1fr auto; gap: 14px; align-items: start; padding: 14px 0; border-top: 1px solid var(--bg1); }
|
||||
.card .thumb { width: 84px; height: 84px; background: var(--bg1); object-fit: cover; display: block; }
|
||||
.card .fields { display: flex; flex-direction: column; gap: 8px; min-width: 0; }
|
||||
.card input {
|
||||
width: 100%; box-sizing: border-box; background: var(--bg0);
|
||||
border: 1px solid var(--bg2); color: var(--fg); font-size: 15px; padding: 8px 10px; outline: none;
|
||||
}
|
||||
.drop-prompt p { font-size: 14px; font-family: var(--serif); }
|
||||
.drop-prompt small { font-size: 12px; font-family: monospace; }
|
||||
#preview {
|
||||
display: none;
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
object-fit: cover;
|
||||
pointer-events: none;
|
||||
.card input[type="text"] { font-family: var(--serif); }
|
||||
.card input[type="date"] { font-family: monospace; font-size: 13px; color-scheme: dark; width: auto; }
|
||||
.card input:focus { border-color: var(--fg4); }
|
||||
.card input:disabled { opacity: .5; }
|
||||
.c-remove {
|
||||
background: none; border: none; color: var(--fg4); font-size: 16px; cursor: pointer; padding: 4px;
|
||||
}
|
||||
.change-hint {
|
||||
display: none;
|
||||
position: absolute;
|
||||
inset: auto 0 0 0;
|
||||
padding: 6px 10px;
|
||||
background: rgba(29, 32, 33, 0.75);
|
||||
color: var(--fg2);
|
||||
font-family: monospace;
|
||||
font-size: 11px;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.08em;
|
||||
text-align: center;
|
||||
pointer-events: none;
|
||||
}
|
||||
.drop-zone.has-image .change-hint { display: block; }
|
||||
.field { margin-bottom: 18px; }
|
||||
.field label {
|
||||
display: block;
|
||||
font-size: 12px;
|
||||
color: var(--fg4);
|
||||
font-family: monospace;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.06em;
|
||||
margin-bottom: 6px;
|
||||
}
|
||||
.field input[type="text"],
|
||||
.field input[type="date"] {
|
||||
width: 100%;
|
||||
background: var(--bg0);
|
||||
border: 1px solid var(--bg2);
|
||||
color: var(--fg);
|
||||
font-size: 16px;
|
||||
padding: 10px 12px;
|
||||
outline: none;
|
||||
transition: border-color 0.2s;
|
||||
}
|
||||
.field input[type="text"] { font-family: var(--serif); }
|
||||
.field input[type="date"] { font-family: monospace; font-size: 14px; color-scheme: dark; }
|
||||
.field input:focus { border-color: var(--fg4); }
|
||||
.submit-btn {
|
||||
width: 100%;
|
||||
background: var(--bg1);
|
||||
border: 1px solid var(--bg2);
|
||||
color: var(--fg2);
|
||||
font-family: var(--serif);
|
||||
font-size: 16px;
|
||||
font-weight: 600;
|
||||
padding: 12px;
|
||||
cursor: pointer;
|
||||
transition: background 0.2s, color 0.2s;
|
||||
}
|
||||
.submit-btn:hover:not(:disabled) { background: var(--bg2); color: var(--fg); }
|
||||
.submit-btn:disabled { opacity: 0.35; cursor: not-allowed; }
|
||||
#feedback {
|
||||
display: none;
|
||||
margin-top: 14px;
|
||||
font-size: 13px;
|
||||
font-family: monospace;
|
||||
padding: 10px 12px;
|
||||
}
|
||||
#feedback.ok { display: block; background: #1d2e1d; color: #b8bb26; border: 1px solid #344d28; }
|
||||
#feedback.err { display: block; background: #2e1d1d; color: #fb4934; border: 1px solid #5a2828; }
|
||||
.c-status { font-family: monospace; font-size: 12px; min-height: 16px; }
|
||||
.c-status.ok { color: #b8bb26; }
|
||||
.c-status.err { color: #fb4934; }
|
||||
.c-status.up { color: var(--fg4); }
|
||||
.c-status a { color: #8ec07c; }
|
||||
|
||||
#bar { margin-top: 20px; }
|
||||
#summary { margin-top: 12px; font-family: monospace; font-size: 13px; color: var(--fg4); }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="upload-page">
|
||||
<a href="/" class="back-btn">← Gallery</a>
|
||||
<h2>Upload photo</h2>
|
||||
<h2>Upload photos</h2>
|
||||
|
||||
<div class="drop-zone" id="drop-zone">
|
||||
<input type="file" id="file-input" accept=".jpg,.jpeg,.png" aria-label="Choose photo">
|
||||
<div class="drop-prompt" id="prompt">
|
||||
<svg width="40" height="40" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1" aria-hidden="true">
|
||||
<rect x="3" y="3" width="18" height="18" rx="1"/>
|
||||
<circle cx="8.5" cy="8.5" r="1.5"/>
|
||||
<path d="M21 15l-5-5L5 21"/>
|
||||
</svg>
|
||||
<p>Click to choose a photo</p>
|
||||
<small>jpg or png</small>
|
||||
<input type="file" id="file-input" accept=".jpg,.jpeg,.png" multiple>
|
||||
<button class="pick-btn" id="pick-btn">Choose photos</button>
|
||||
|
||||
<div id="empty">No photos selected</div>
|
||||
<div id="list"></div>
|
||||
|
||||
<div id="bar" style="display:none">
|
||||
<button class="submit-btn" id="post-btn">Post photos</button>
|
||||
<div id="summary"></div>
|
||||
</div>
|
||||
<img id="preview" alt="Preview">
|
||||
<div class="change-hint">Click to change</div>
|
||||
</div>
|
||||
|
||||
<div class="field">
|
||||
<label for="caption">Caption</label>
|
||||
<input type="text" id="caption" placeholder="Describe the photo" autocomplete="off">
|
||||
</div>
|
||||
|
||||
<div class="field">
|
||||
<label for="date">Date</label>
|
||||
<input type="date" id="date">
|
||||
</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>
|
||||
<div id="feedback"></div>
|
||||
</div>
|
||||
|
||||
<script src="/static/tagcomplete.js"></script>
|
||||
<script>
|
||||
const fileInput = document.getElementById('file-input');
|
||||
const preview = document.getElementById('preview');
|
||||
const prompt = document.getElementById('prompt');
|
||||
const dropZone = document.getElementById('drop-zone');
|
||||
const submitBtn = document.getElementById('submit-btn');
|
||||
const feedback = document.getElementById('feedback');
|
||||
const dateInput = document.getElementById('date');
|
||||
const pickBtn = document.getElementById('pick-btn');
|
||||
const list = document.getElementById('list');
|
||||
const emptyEl = document.getElementById('empty');
|
||||
const bar = document.getElementById('bar');
|
||||
const postBtn = document.getElementById('post-btn');
|
||||
const summary = document.getElementById('summary');
|
||||
|
||||
dateInput.value = new Date().toISOString().slice(0, 10);
|
||||
// One entry per chosen photo. status: pending | uploading | ok | error.
|
||||
let items = [];
|
||||
let seq = 0;
|
||||
let posting = false;
|
||||
|
||||
pickBtn.addEventListener('click', () => fileInput.click());
|
||||
fileInput.addEventListener('change', () => {
|
||||
for (const file of fileInput.files) addItem(file);
|
||||
fileInput.value = ''; // allow re-choosing the same file
|
||||
refresh();
|
||||
});
|
||||
|
||||
// Mirror of the server's sanitiseSlug, so the client can predict the slug a
|
||||
// filename yields and keep two files in one batch from colliding.
|
||||
function slugify(name) {
|
||||
let out = '';
|
||||
for (const ch of name.toLowerCase()) {
|
||||
if ((ch >= 'a' && ch <= 'z') || (ch >= '0' && ch <= '9') || ch === '-') out += ch;
|
||||
else if (ch === ' ' || ch === '_') out += '-';
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
// A slug unique among the current cards. The server derives the slug from
|
||||
// the uploaded filename, so two photos named the same would otherwise
|
||||
// overwrite each other; the second (third, …) gets -2, -3, …
|
||||
function uniqueSlug(filename) {
|
||||
const stem = filename.replace(/\.[^.]+$/, '');
|
||||
const base = slugify(stem) || 'photo';
|
||||
let candidate = base;
|
||||
let n = 2;
|
||||
while (items.some((i) => i.slug === candidate)) candidate = base + '-' + (n++);
|
||||
return candidate;
|
||||
}
|
||||
|
||||
function addItem(file) {
|
||||
const ext = (file.name.match(/\.[^.]+$/)?.[0] || '.jpg').toLowerCase();
|
||||
const item = { id: ++seq, file, ext, slug: '', status: 'pending', el: null };
|
||||
item.slug = uniqueSlug(file.name); // before push, so it compares against the others
|
||||
items.push(item);
|
||||
item.el = buildCard(item);
|
||||
list.appendChild(item.el);
|
||||
// Preview.
|
||||
const url = URL.createObjectURL(file);
|
||||
const img = item.el.querySelector('.thumb');
|
||||
img.onload = () => URL.revokeObjectURL(url);
|
||||
img.src = url;
|
||||
// Prefill date from EXIF, else file mtime.
|
||||
prefillDate(item, file);
|
||||
// Tag autocomplete on this card's tags field.
|
||||
if (window.TagComplete) window.TagComplete.attach(item.el.querySelector('.c-tags'));
|
||||
}
|
||||
|
||||
function buildCard(item) {
|
||||
const el = document.createElement('div');
|
||||
el.className = 'card';
|
||||
el.innerHTML = `
|
||||
<img class="thumb" alt="">
|
||||
<div class="fields">
|
||||
<input type="text" class="c-caption" placeholder="Caption" autocomplete="off">
|
||||
<input type="date" class="c-date">
|
||||
<input type="text" class="c-tags" placeholder="tags, comma-separated" autocomplete="off">
|
||||
<div class="c-status"></div>
|
||||
</div>
|
||||
<button class="c-remove" title="Remove">✕</button>`;
|
||||
el.querySelector('.c-remove').addEventListener('click', () => removeItem(item.id));
|
||||
return el;
|
||||
}
|
||||
|
||||
async function prefillDate(item, file) {
|
||||
let d = null;
|
||||
try { d = await readExifDate(file); } catch (_) {}
|
||||
if (!d && file.lastModified) d = new Date(file.lastModified).toISOString().slice(0, 10);
|
||||
if (!d) d = new Date().toISOString().slice(0, 10);
|
||||
item.el.querySelector('.c-date').value = d;
|
||||
}
|
||||
|
||||
function removeItem(id) {
|
||||
const item = items.find((i) => i.id === id);
|
||||
if (!item || item.status === 'uploading') return;
|
||||
item.el.remove();
|
||||
items = items.filter((i) => i.id !== id);
|
||||
refresh();
|
||||
}
|
||||
|
||||
function refresh() {
|
||||
const has = items.length > 0;
|
||||
emptyEl.style.display = has ? 'none' : 'flex';
|
||||
bar.style.display = has ? 'block' : 'none';
|
||||
pickBtn.textContent = has ? 'Add more photos' : 'Choose photos';
|
||||
updateButton();
|
||||
}
|
||||
|
||||
function pending() { return items.filter((i) => i.status !== 'ok'); }
|
||||
|
||||
function updateButton() {
|
||||
const n = pending().length;
|
||||
postBtn.disabled = posting || n === 0;
|
||||
postBtn.textContent = posting
|
||||
? 'Posting…'
|
||||
: n === 0 ? 'All posted' : (n === 1 ? 'Post 1 photo' : `Post ${n} photos`);
|
||||
}
|
||||
|
||||
function setStatus(item, cls, html) {
|
||||
const s = item.el.querySelector('.c-status');
|
||||
s.className = 'c-status ' + cls;
|
||||
s.innerHTML = html;
|
||||
}
|
||||
|
||||
function setDisabled(item, disabled) {
|
||||
item.el.querySelectorAll('input').forEach((i) => (i.disabled = disabled));
|
||||
item.el.querySelector('.c-remove').disabled = disabled;
|
||||
}
|
||||
|
||||
async function postOne(item) {
|
||||
item.status = 'uploading';
|
||||
setDisabled(item, true);
|
||||
setStatus(item, 'up', 'Uploading…');
|
||||
|
||||
const form = new FormData();
|
||||
// Send under the deduped slug so the server (which slugs from the
|
||||
// filename) can't overwrite another photo in the same batch.
|
||||
form.append('image', item.file, item.slug + item.ext);
|
||||
form.append('caption', item.el.querySelector('.c-caption').value);
|
||||
form.append('date', item.el.querySelector('.c-date').value);
|
||||
form.append('tags', item.el.querySelector('.c-tags').value);
|
||||
|
||||
try {
|
||||
const res = await fetch('/upload', { method: 'POST', body: form });
|
||||
const text = (await res.text()).trim();
|
||||
if (res.ok) {
|
||||
item.status = 'ok';
|
||||
const slug = text.replace(/^uploaded\s+/, '').replace(/\.[^.]+$/, '');
|
||||
setStatus(item, 'ok', '✓ posted · <a href="/photo/' + encodeURIComponent(slug) + '/" target="_blank" rel="noopener">view</a>');
|
||||
} else {
|
||||
item.status = 'error';
|
||||
setDisabled(item, false);
|
||||
setStatus(item, 'err', '✗ ' + (text || res.status));
|
||||
}
|
||||
} catch (err) {
|
||||
item.status = 'error';
|
||||
setDisabled(item, false);
|
||||
setStatus(item, 'err', '✗ ' + err.message);
|
||||
}
|
||||
}
|
||||
|
||||
postBtn.addEventListener('click', async () => {
|
||||
if (posting) return;
|
||||
posting = true;
|
||||
updateButton();
|
||||
if (window.TagComplete) window.TagComplete.invalidate();
|
||||
|
||||
// Sequential: gentler on mobile connections, and the rebuild is debounced
|
||||
// server-side anyway.
|
||||
const todo = pending();
|
||||
let done = 0;
|
||||
for (const item of todo) {
|
||||
await postOne(item);
|
||||
done++;
|
||||
summary.textContent = `${done}/${todo.length} processed`;
|
||||
}
|
||||
|
||||
posting = false;
|
||||
const ok = items.filter((i) => i.status === 'ok').length;
|
||||
const failed = items.filter((i) => i.status === 'error').length;
|
||||
summary.textContent = `${ok} posted` + (failed ? `, ${failed} failed (press Post to retry)` : '');
|
||||
updateButton();
|
||||
});
|
||||
|
||||
// Read DateTimeOriginal from a JPEG's EXIF APP1 segment. Returns "YYYY-MM-DD"
|
||||
// or null if the file isn't a JPEG, has no EXIF, or lacks the tag.
|
||||
@@ -227,68 +297,7 @@
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
fileInput.addEventListener('change', async () => {
|
||||
const file = fileInput.files[0];
|
||||
if (!file) return;
|
||||
const url = URL.createObjectURL(file);
|
||||
preview.onload = () => URL.revokeObjectURL(url);
|
||||
preview.src = url;
|
||||
preview.style.display = 'block';
|
||||
prompt.style.display = 'none';
|
||||
dropZone.classList.add('has-image');
|
||||
submitBtn.disabled = false;
|
||||
feedback.className = '';
|
||||
feedback.style.display = 'none';
|
||||
|
||||
let d = null;
|
||||
try { d = await readExifDate(file); } catch (_) {}
|
||||
if (!d && file.lastModified) {
|
||||
d = new Date(file.lastModified).toISOString().slice(0, 10);
|
||||
}
|
||||
if (d) dateInput.value = d;
|
||||
});
|
||||
|
||||
submitBtn.addEventListener('click', async () => {
|
||||
const file = fileInput.files[0];
|
||||
if (!file) return;
|
||||
|
||||
submitBtn.disabled = true;
|
||||
submitBtn.textContent = 'Uploading…';
|
||||
feedback.className = '';
|
||||
|
||||
const form = new FormData();
|
||||
form.append('image', file);
|
||||
form.append('caption', document.getElementById('caption').value);
|
||||
form.append('date', dateInput.value);
|
||||
form.append('tags', document.getElementById('tags').value);
|
||||
|
||||
try {
|
||||
const res = await fetch('/upload', { method: 'POST', body: form });
|
||||
const text = (await res.text()).trim();
|
||||
if (res.ok) {
|
||||
feedback.className = 'ok';
|
||||
feedback.textContent = '✓ ' + text;
|
||||
fileInput.value = '';
|
||||
preview.style.display = 'none';
|
||||
prompt.style.display = 'flex';
|
||||
dropZone.classList.remove('has-image');
|
||||
document.getElementById('caption').value = '';
|
||||
document.getElementById('tags').value = '';
|
||||
submitBtn.disabled = true;
|
||||
} else {
|
||||
feedback.className = 'err';
|
||||
feedback.textContent = '✗ ' + text;
|
||||
submitBtn.disabled = false;
|
||||
}
|
||||
} catch (err) {
|
||||
feedback.className = 'err';
|
||||
feedback.textContent = '✗ ' + err.message;
|
||||
submitBtn.disabled = false;
|
||||
}
|
||||
|
||||
submitBtn.textContent = 'Upload photo';
|
||||
});
|
||||
</script>
|
||||
<script src="/static/session.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -135,7 +135,7 @@ func (s *Server) handleRestore(w http.ResponseWriter, r *http.Request) {
|
||||
if s.rejectCrossSite(w, r) {
|
||||
return
|
||||
}
|
||||
if err := r.ParseForm(); err != nil {
|
||||
if err := parseForm(r); err != nil {
|
||||
http.Error(w, "bad request", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
@@ -175,7 +175,7 @@ func (s *Server) handleEmptyTrash(w http.ResponseWriter, r *http.Request) {
|
||||
if s.rejectCrossSite(w, r) {
|
||||
return
|
||||
}
|
||||
if err := r.ParseForm(); err != nil {
|
||||
if err := parseForm(r); err != nil {
|
||||
http.Error(w, "bad request", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
+8
-1
@@ -30,6 +30,12 @@ func NewWatcher(dir string, g *Generator) (*Watcher, error) {
|
||||
// Watch blocks, watching for changes and triggering rebuilds.
|
||||
// Rapid events (e.g. scp writing an image then its sidecar) are debounced
|
||||
// with a 500 ms window so only one rebuild fires per logical upload.
|
||||
//
|
||||
// Rename is watched alongside Create/Write/Remove: moving a photo out of the
|
||||
// content directory — which is exactly what a /manage delete does when it
|
||||
// sends files to content/.trash/ — arrives as a Rename (inotify IN_MOVED_FROM)
|
||||
// on Linux, not a Remove, so without it a delete (or a manual mv) would leave
|
||||
// the site unrebuilt.
|
||||
func (w *Watcher) Watch() {
|
||||
var timer *time.Timer
|
||||
rebuild := func() {
|
||||
@@ -47,7 +53,8 @@ func (w *Watcher) Watch() {
|
||||
if !isRelevant(event.Name) {
|
||||
continue
|
||||
}
|
||||
if event.Has(fsnotify.Create) || event.Has(fsnotify.Write) || event.Has(fsnotify.Remove) {
|
||||
if event.Has(fsnotify.Create) || event.Has(fsnotify.Write) ||
|
||||
event.Has(fsnotify.Remove) || event.Has(fsnotify.Rename) {
|
||||
if timer != nil {
|
||||
timer.Stop()
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user