Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
431ac2e610 | ||
|
|
504b96ed31 | ||
|
|
bb8c7109fa | ||
|
|
f1e946228a | ||
|
|
3614cfe1f8 | ||
|
|
2143b95657 | ||
|
|
125b6b5241 | ||
|
|
003a4057bf | ||
|
|
c21ddc5b7e | ||
|
|
225bdc9b4f | ||
|
|
e67d25b191 | ||
|
|
94859fb0d6 | ||
|
|
c4aa345914 | ||
|
|
bf75c9fe8e | ||
|
|
25384d3f3b | ||
|
|
8fa1aa4cd4 | ||
|
|
a7f2afc3ad | ||
|
|
434d2437bf | ||
|
|
3291ed67d5 | ||
|
|
faa1e01c59 | ||
|
|
a42abfab48 | ||
|
|
43075f00d4 | ||
|
|
3f719359de | ||
|
|
f1abd45f24 | ||
|
|
f33bdd55b1 | ||
|
|
91fbf4f93b | ||
|
|
17222f7120 | ||
|
|
591eaed6a3 | ||
|
|
a7783671f2 | ||
|
|
1d81ec4511 | ||
|
|
dc47619937 | ||
|
|
c404aac66c | ||
|
|
23e14f5aa8 | ||
|
|
6af0eb115c | ||
|
|
d07e3eb0dc | ||
|
|
d4fec5b0ff | ||
|
|
eb6dba6eb0 | ||
|
|
4ddf5adf24 | ||
|
|
9b6fcb482b | ||
|
|
c169c030d6 | ||
|
|
15822ed227 | ||
|
|
210ce69e18 | ||
|
|
70d115e11c | ||
|
|
3639bd5577 | ||
|
|
856439f3fd | ||
|
|
613906cd0c |
No files matched your search
@@ -1,8 +1,22 @@
|
|||||||
content/
|
/content/
|
||||||
public/
|
/public/
|
||||||
photogallery
|
/.demo/
|
||||||
result
|
# Anchored: unanchored these would also match the Kotlin package directory
|
||||||
result-*
|
# android/app/src/main/java/ws/inflo/photogallery/ and any nested "result".
|
||||||
|
/photogallery
|
||||||
|
/result
|
||||||
|
/result-*
|
||||||
*.tar.gz
|
*.tar.gz
|
||||||
.envrc
|
.envrc
|
||||||
.direnv/
|
.direnv/
|
||||||
|
|
||||||
|
# Android app
|
||||||
|
android/.gradle/
|
||||||
|
android/build/
|
||||||
|
android/app/build/
|
||||||
|
android/local.properties
|
||||||
|
android/.idea/
|
||||||
|
android/.kotlin/
|
||||||
|
android/keystore.properties
|
||||||
|
*.jks
|
||||||
|
*.keystore
|
||||||
@@ -2,6 +2,7 @@
|
|||||||
|
|
||||||
Personal static photo gallery with Atom feed and upload API. Single-user.
|
Personal static photo gallery with Atom feed and upload API. Single-user.
|
||||||
No database, no framework — just a Go binary that watches a directory and regenerates a static site.
|
No database, no framework — just a Go binary that watches a directory and regenerates a static site.
|
||||||
|
An Android app in `android/` posts to the same upload API.
|
||||||
|
|
||||||
## Architecture
|
## Architecture
|
||||||
|
|
||||||
@@ -9,7 +10,8 @@ No database, no framework — just a Go binary that watches a directory and rege
|
|||||||
content/ # images + .toml sidecars (source of truth)
|
content/ # images + .toml sidecars (source of truth)
|
||||||
public/ # generated output (served by nginx / --serve flag)
|
public/ # generated output (served by nginx / --serve flag)
|
||||||
templates/ # embedded HTML templates
|
templates/ # embedded HTML templates
|
||||||
static/ # embedded CSS
|
static/ # embedded CSS + JS
|
||||||
|
android/ # Kotlin/Compose uploader app, own flake
|
||||||
```
|
```
|
||||||
|
|
||||||
The binary does three things at once:
|
The binary does three things at once:
|
||||||
@@ -17,13 +19,94 @@ The binary does three things at once:
|
|||||||
- Serves a multipart upload API at `POST /upload`
|
- Serves a multipart upload API at `POST /upload`
|
||||||
- In dev mode (`--serve`), also serves `public/` as static files
|
- In dev mode (`--serve`), also serves `public/` as static files
|
||||||
|
|
||||||
In production nginx sits in front: serves `public/` directly, proxies `/upload` to localhost, htpasswd on the upload endpoint.
|
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).
|
||||||
|
|
||||||
|
In production nginx sits in front: serves `public/` directly, proxies the
|
||||||
|
dynamic endpoints (`/upload`, `/manage`, `/api/`) to localhost, terminates TLS.
|
||||||
|
Auth is **no longer nginx's job** — the app checks credentials itself
|
||||||
|
(`auth.go`), so the nginx vhost just proxies. `/health` is **not** proxied, so
|
||||||
|
only `/upload`, `/manage` and `/api/` are reachable from outside the box;
|
||||||
|
anything new the app serves needs a matching `location` in `module.nix` or
|
||||||
|
nginx will 404 it as a missing static file.
|
||||||
|
|
||||||
|
## Auth
|
||||||
|
|
||||||
|
`-htpasswd <file>` points at an Apache htpasswd file — **bcrypt only**, generate
|
||||||
|
with `htpasswd -B`. Each `POST /upload` and `GET /upload` then needs HTTP Basic
|
||||||
|
credentials matching a line in that file; `GET /health` stays open. `$2y$`
|
||||||
|
(Apache) and `$2a$`/`$2b$` hashes are all accepted; non-bcrypt lines (MD5
|
||||||
|
`$apr1$`, SHA, crypt) are skipped with a warning. Empty `-htpasswd` disables
|
||||||
|
auth entirely (dev default) and logs a warning — `/upload` is then open.
|
||||||
|
|
||||||
|
`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`,
|
||||||
|
~1/s, burst 10) that returns `429` once drained — successful and bulk uploads
|
||||||
|
never touch it. Both apps (Android, Qt desktop) already send Basic auth, so no
|
||||||
|
client change was needed. Deps: `golang.org/x/crypto/bcrypt`, `golang.org/x/time/rate`.
|
||||||
|
|
||||||
|
## Manage (edit / delete)
|
||||||
|
|
||||||
|
`GET /manage` is an auth-gated web page (`templates/manage.html`) for editing
|
||||||
|
and deleting posts; it is **not linked from the public site** (reach it by URL).
|
||||||
|
Its API, all behind the same Basic auth and handled in `manage.go`:
|
||||||
|
|
||||||
|
- `GET /api/photos` — every post as JSON (`slug, caption, date, tags, thumb, url`), newest first.
|
||||||
|
- `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.
|
||||||
|
- `GET /api/trash` — list trashed items (`id` = `<slug>.<stamp>`, `slug`, `deletedAt`, `image`, `hasMeta`), newest first.
|
||||||
|
- `POST /api/restore` — move a trashed item (`id`) back to `content/`, stripping the timestamp. Refuses with `409` if a live post already holds that slug.
|
||||||
|
- `POST /api/trash/empty` — **hard delete** trashed items: specific `id`s (repeated), or everything with `all=1`. The only non-reversible delete in the system.
|
||||||
|
|
||||||
|
The manage page has a Trash panel (header toggle) for restore / delete-forever /
|
||||||
|
empty. `trash.go` handles these; filenames parse as `<slug>.<stamp><ext>` (slug
|
||||||
|
is dot-free and the stamp is a fixed `20060102-150405`, so parts peel off
|
||||||
|
unambiguously), and `id`s are validated the same way to block traversal.
|
||||||
|
|
||||||
|
Each non-trash mutation triggers the same async rebuild as upload. Sidecars are written
|
||||||
|
atomically (temp + rename) so a concurrent build never sees a half-written
|
||||||
|
file. Slugs are validated (`resolveSlug`: bare filename only, must name an
|
||||||
|
existing content image) which closes path traversal and dotfile access.
|
||||||
|
|
||||||
|
Every state-changing POST (`edit`, `delete`, `tags`, `restore`, `trash/empty`)
|
||||||
|
first passes `sameOrigin` (`server.go`): because Basic-auth credentials are
|
||||||
|
replayed by the browser on every request to the host, a cross-site page could
|
||||||
|
otherwise drive a logged-in user into a delete (CSRF). The check honours
|
||||||
|
`Sec-Fetch-Site`, falls back to comparing `Origin` against `-base-url`/`Host`,
|
||||||
|
and allows header-less non-browser clients (curl). Cross-site → `403`. (Ported
|
||||||
|
from the independent `/manage` on `plex/trunk-ng`.)
|
||||||
|
|
||||||
|
**Delete relies on `Build`'s prune step** (`generator.go`): a rebuild drops the
|
||||||
|
derived HTML trees (`photo/ day/ album/ page/ grid/page/`) and regenerates them,
|
||||||
|
and `pruneRenditions` removes `images|thumbs|medium|og` files with no backing
|
||||||
|
photo. Without this a deleted post would linger at its old URL and in stale
|
||||||
|
day/album pages. This also cleans up after a sidecar removed by hand.
|
||||||
|
|
||||||
## Stack
|
## Stack
|
||||||
|
|
||||||
- **Go** — stdlib + `BurntSushi/toml`, `fsnotify/fsnotify`, `golang.org/x/image`
|
- **Go** — stdlib + `BurntSushi/toml`, `fsnotify/fsnotify`, `golang.org/x/image`, `golang.org/x/crypto` (bcrypt), `golang.org/x/time` (rate)
|
||||||
- **Templates** — `html/template`, embedded via `embed.FS`
|
- **Templates** — `html/template`, embedded via `embed.FS`
|
||||||
- **Images** — centre-crop to square, Catmull-Rom resize to 600×600 JPEG thumbnails
|
- **Images** — four renditions per photo: original copy, 600×600 centre-cropped square thumbnail, a 1600px-longest-side "medium" for the detail page, and a 1200px "og" for link previews. Catmull-Rom resize. Outputs are skipped when newer than the source.
|
||||||
- **Feed** — Atom (`encoding/xml`)
|
- **Feed** — Atom (`encoding/xml`)
|
||||||
- **NixOS** — `flake.nix` + `module.nix`, exports `nixosModules.default`
|
- **NixOS** — `flake.nix` + `module.nix`, exports `nixosModules.default`
|
||||||
|
|
||||||
@@ -32,17 +115,71 @@ In production nginx sits in front: serves `public/` directly, proxies `/upload`
|
|||||||
```toml
|
```toml
|
||||||
caption = "Tempelhof at sunrise"
|
caption = "Tempelhof at sunrise"
|
||||||
date = "2026-06-14"
|
date = "2026-06-14"
|
||||||
|
tags = ["berlin", "sunrise"]
|
||||||
```
|
```
|
||||||
|
|
||||||
Missing sidecar → filename as caption, today as date.
|
Missing sidecar → filename as caption, today as date. Photos sort newest first by that date.
|
||||||
|
|
||||||
|
`tags` is optional, free-text, and defines albums (see below). Tags are
|
||||||
|
normalized to lowercase on load/upload (`parseTags` in `albums.go`); a tag may
|
||||||
|
contain spaces (`"berlin trip"`), and its URL slug is derived with `sanitiseSlug`.
|
||||||
|
|
||||||
## Design
|
## Design
|
||||||
|
|
||||||
- Gruvbox dark hard colour scheme
|
- Gruvbox dark hard colour scheme
|
||||||
- Vollkorn (serif) for headings and captions
|
- Crimson Pro (serif) for headings and captions — configurable via `-serif-family` / `-fonts-url`
|
||||||
- Manjari for Malayalam text (bio line)
|
- Manjari for Malayalam text (bio line), via `-ml-family`
|
||||||
- 3-column square grid → 2-column on mobile
|
- 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.
|
||||||
- Single photo page with sidebar
|
- **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
|
||||||
|
|
||||||
|
### Albums (tags)
|
||||||
|
|
||||||
|
A second grouping axis, parallel to days: an album is just a tag (`albums.go`).
|
||||||
|
`groupByTag` mirrors `groupByDay`, and `renderAlbumPages` writes a paginated
|
||||||
|
square-grid album per tag at `/album/<slug>/` (like the grid view). `/albums/`
|
||||||
|
is the index of every tag with counts; `/tags.json` is the machine-readable tag
|
||||||
|
list (`[{tag, slug, count}]`, served statically like `feed.xml`). Tags show on
|
||||||
|
each photo page and link to their album; an **Albums** link sits in the
|
||||||
|
timeline/grid header. Tags are assigned at upload via the `tags` field on
|
||||||
|
`POST /upload` (comma-separated) or by editing a sidecar's `tags`. All derived at
|
||||||
|
build time — no database.
|
||||||
|
|
||||||
|
### Link previews
|
||||||
|
|
||||||
|
Photo pages carry Open Graph + Twitter-card meta tags so a shared link unfurls
|
||||||
|
in WhatsApp, Telegram, etc. `generateOG` writes a dedicated `public/og/`
|
||||||
|
rendition — 1200px longest side, quality laddered down until under ~250 KB,
|
||||||
|
because WhatsApp drops the preview above ~300 KB and the medium rendition can
|
||||||
|
exceed that. The `og:image` URL is absolute (`{{.BaseURL}}/...`); both crawlers
|
||||||
|
ignore relative image paths, and previews only work against the deployed
|
||||||
|
`-base-url`, never `http://localhost`. `og:image:width`/`height` come from
|
||||||
|
`DecodeConfig` on the OG file, read even when the file itself was skipped as up
|
||||||
|
to date. Both platforms cache per URL — after a deploy, re-scrape via
|
||||||
|
`@webpagebot` (Telegram) or Facebook's sharing debugger (WhatsApp).
|
||||||
|
|
||||||
|
### Photo page navigation
|
||||||
|
|
||||||
|
`static/photo-nav.js` handles arrow keys and touch swipe. Both read their
|
||||||
|
destinations from the `[data-nav="newer"]` / `[data-nav="older"]` anchors the
|
||||||
|
template renders, so a photo with no sibling in that direction has nothing to
|
||||||
|
find and the gesture rubber-bands. If the script fails to load the links still
|
||||||
|
work.
|
||||||
|
|
||||||
|
Swipe left → older, right → newer, matching ArrowRight/ArrowLeft. Constraints
|
||||||
|
worth knowing before touching it:
|
||||||
|
|
||||||
|
- Swipes starting within 24px of a screen edge are ignored — that strip is the browser's own back-gesture.
|
||||||
|
- Only `pointerType === "touch"`, so desktop drag-to-save is untouched.
|
||||||
|
- Axis locks once after 10px so vertical drags stay scrolls; `touch-action: pan-y` tells the compositor the same.
|
||||||
|
- The image is wrapped in an `<a>` to the full-size original, so the click trailing a swipe is suppressed or it opens a new tab.
|
||||||
|
- `EXIT_MS` in the JS must stay in sync with the transition duration in `style.css`.
|
||||||
|
|
||||||
|
Anything added under `static/` is embedded and copied to `public/static/`
|
||||||
|
automatically — `assets.go` embeds the whole directory and `copyStatic()` walks
|
||||||
|
every entry, so new CSS/JS needs no generator change.
|
||||||
|
|
||||||
## Running locally
|
## Running locally
|
||||||
|
|
||||||
@@ -54,6 +191,20 @@ go run . --serve
|
|||||||
# upload: http://localhost:8080/upload
|
# upload: http://localhost:8080/upload
|
||||||
```
|
```
|
||||||
|
|
||||||
|
## Android app
|
||||||
|
|
||||||
|
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:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cd android
|
||||||
|
nix develop
|
||||||
|
./gradlew assembleRelease # app/build/outputs/apk/release/app-release.apk
|
||||||
|
```
|
||||||
|
|
||||||
|
The server needs no changes to serve it — every gap (slug collisions, EXIF, HEIC, size caps) is closed client-side. Release builds need `android/keystore.properties`; without it the signing config is skipped and only debug builds work.
|
||||||
|
|
||||||
## NixOS module usage
|
## NixOS module usage
|
||||||
|
|
||||||
```nix
|
```nix
|
||||||
@@ -64,10 +215,12 @@ inputs.photogallery.nixosModules.default
|
|||||||
services.photogallery = {
|
services.photogallery = {
|
||||||
enable = true;
|
enable = true;
|
||||||
baseURL = "https://photos.yourdomain.tld";
|
baseURL = "https://photos.yourdomain.tld";
|
||||||
|
# bcrypt htpasswd (`htpasswd -B`); handed to the service via LoadCredential,
|
||||||
|
# so a root-owned 0400 secret is fine. Omit to leave /upload open.
|
||||||
|
htpasswdFile = "/run/secrets/photogallery-htpasswd";
|
||||||
nginx = {
|
nginx = {
|
||||||
enable = true;
|
enable = true;
|
||||||
domain = "photos.yourdomain.tld";
|
domain = "photos.yourdomain.tld";
|
||||||
htpasswdFile = "/etc/nginx/.htpasswd-gallery";
|
|
||||||
};
|
};
|
||||||
};
|
};
|
||||||
```
|
```
|
||||||
@@ -86,16 +239,34 @@ nix build # succeeds
|
|||||||
| File | Purpose |
|
| File | Purpose |
|
||||||
|---|---|
|
|---|---|
|
||||||
| `main.go` | Flags, wires generator + watcher + server |
|
| `main.go` | Flags, wires generator + watcher + server |
|
||||||
| `generator.go` | Scans content dir, renders HTML + Atom feed, generates thumbs |
|
| `generator.go` | Scans content dir, renders HTML + Atom feed, generates thumbs/mediums |
|
||||||
|
| `albums.go` | Tag parsing/normalization, `groupByTag`, album pages + `/albums/` + `/tags.json` |
|
||||||
| `server.go` | Upload API + optional static file serving |
|
| `server.go` | Upload API + optional static file serving |
|
||||||
|
| `auth.go` | htpasswd (bcrypt) HTTP Basic auth + failed-attempt rate limit for `/upload` |
|
||||||
|
| `manage.go` | Edit/delete API (`/api/photos`, `/api/edit`, `/api/tags`, `/api/delete`) + trash move + atomic sidecar writes |
|
||||||
|
| `trash.go` | Trash API: list (`/api/trash`), `/api/restore`, `/api/trash/empty` (hard delete) |
|
||||||
|
| `templates/manage.html` | Auth-gated edit/delete web UI at `/manage`, with a Trash panel |
|
||||||
| `watcher.go` | fsnotify watcher with 500ms debounce |
|
| `watcher.go` | fsnotify watcher with 500ms debounce |
|
||||||
| `assets.go` | `//go:embed` for templates and static |
|
| `assets.go` | `//go:embed` for templates and static |
|
||||||
|
| `templates/timeline.html` | Site root: photos grouped by day, paginated |
|
||||||
|
| `templates/grid.html` | Flat square grid at `/grid/`, paginated |
|
||||||
|
| `templates/day.html` | Single-day page at `/day/<date>/` |
|
||||||
|
| `templates/album.html` | Album (tag) page at `/album/<slug>/`, paginated |
|
||||||
|
| `templates/albums.html` | Album index at `/albums/` |
|
||||||
|
| `templates/photo.html` | Single photo page, neighbour links and prefetch |
|
||||||
|
| `static/photo-nav.js` | Arrow-key and swipe navigation |
|
||||||
| `module.nix` | NixOS module (systemd service, tmpfiles, nginx vhost) |
|
| `module.nix` | NixOS module (systemd service, tmpfiles, nginx vhost) |
|
||||||
| `flake.nix` | `buildGoModule` package + devShell + nixosModules |
|
| `flake.nix` | `buildGoModule` package + devShell + nixosModules |
|
||||||
|
| `android/flake.nix` | Android SDK dev shell (separate from the root flake) |
|
||||||
|
|
||||||
|
## Gotchas
|
||||||
|
|
||||||
|
- `.gitignore` patterns here must be anchored. An unanchored `photogallery` also matches the Kotlin package directory `android/app/src/main/java/ws/inflo/photogallery/` and silently swallows every source file in it.
|
||||||
|
|
||||||
## What's not done yet
|
## What's not done yet
|
||||||
|
|
||||||
- ActivityPub federation (planned later — start with RSS/Atom)
|
- ActivityPub federation (planned later — start with RSS/Atom)
|
||||||
- Multi-image upload
|
- 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.)
|
||||||
- Delete/edit via UI
|
- Any auth beyond the app's htpasswd Basic auth (no sessions, no per-user scopes)
|
||||||
- Any auth beyond nginx htpasswd
|
- The Android app has never been run on real hardware
|
||||||
|
- Photo-page swipe has never been tested on a real touchscreen; the iOS Safari edge-gesture interaction is the untested part
|
||||||
@@ -1,21 +1,24 @@
|
|||||||
MIT License
|
This is free and unencumbered software released into the public domain.
|
||||||
|
|
||||||
Copyright (c) 2026 Ashik S
|
Anyone is free to copy, modify, publish, use, compile, sell, or
|
||||||
|
distribute this software, either in source code form or as a compiled
|
||||||
|
binary, for any purpose, commercial or non-commercial, and by any
|
||||||
|
means.
|
||||||
|
|
||||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
In jurisdictions that recognize copyright laws, the author or authors
|
||||||
of this software and associated documentation files (the "Software"), to deal
|
of this software dedicate any and all copyright interest in the
|
||||||
in the Software without restriction, including without limitation the rights
|
software to the public domain. We make this dedication for the benefit
|
||||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
of the public at large and to the detriment of our heirs and
|
||||||
copies of the Software, and to permit persons to whom the Software is
|
successors. We intend this dedication to be an overt act of
|
||||||
furnished to do so, subject to the following conditions:
|
relinquishment in perpetuity of all present and future rights to this
|
||||||
|
software under copyright law.
|
||||||
|
|
||||||
The above copyright notice and this permission notice shall be included in all
|
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||||
copies or substantial portions of the Software.
|
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
||||||
|
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
|
||||||
|
IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
|
||||||
|
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
|
||||||
|
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
|
||||||
|
OTHER DEALINGS IN THE SOFTWARE.
|
||||||
|
|
||||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
For more information, please refer to <https://unlicense.org>
|
||||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
||||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
||||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
||||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
||||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
||||||
SOFTWARE.
|
|
||||||
@@ -1,12 +1,50 @@
|
|||||||
# photogallery
|
# 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
|
## How it works
|
||||||
|
|
||||||
1. Drop `photo.jpg` + `photo.toml` into the content directory (or upload via the web UI at `/upload`).
|
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.
|
2. The binary watches the directory and rebuilds the static site on any change (and on every upload/edit/delete).
|
||||||
3. nginx serves `public/` and proxies `/upload` to the local API, secured with htpasswd.
|
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
|
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.
|
and an aspect-preserved medium JPEG (longest side 1600) for the detail page.
|
||||||
@@ -23,9 +61,13 @@ editable before submitting.
|
|||||||
```toml
|
```toml
|
||||||
caption = "Tempelhof at sunrise"
|
caption = "Tempelhof at sunrise"
|
||||||
date = "2026-06-14"
|
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;
|
enable = true;
|
||||||
baseURL = "https://photos.yourdomain.tld";
|
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
|
# Optional: identity shown on the header and copyright footer
|
||||||
author = "Ada Lovelace";
|
author = "Ada Lovelace";
|
||||||
handle = "@ada@example.com";
|
handle = "@ada@example.com";
|
||||||
@@ -69,20 +119,19 @@ services.photogallery = {
|
|||||||
serifFamily = "EB Garamond";
|
serifFamily = "EB Garamond";
|
||||||
mlFamily = "Manjari";
|
mlFamily = "Manjari";
|
||||||
|
|
||||||
# Optional: built-in nginx vhost
|
# Optional: built-in nginx vhost (TLS + proxy only; auth is app-side above)
|
||||||
nginx = {
|
nginx = {
|
||||||
enable = true;
|
enable = true;
|
||||||
domain = "photos.yourdomain.tld";
|
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
|
```bash
|
||||||
nix-shell -p apacheHttpd --run \
|
nix-shell -p apacheHttpd --run \
|
||||||
"htpasswd -c /etc/nginx/.htpasswd-gallery youruser"
|
"htpasswd -B -c /run/secrets/photogallery-htpasswd youruser"
|
||||||
```
|
```
|
||||||
|
|
||||||
### Available options
|
### Available options
|
||||||
@@ -94,6 +143,9 @@ nix-shell -p apacheHttpd --run \
|
|||||||
| `contentDir` | `/var/lib/photogallery/content` | Images and .toml sidecars |
|
| `contentDir` | `/var/lib/photogallery/content` | Images and .toml sidecars |
|
||||||
| `outputDir` | `/var/lib/photogallery/public` | Generated site output |
|
| `outputDir` | `/var/lib/photogallery/public` | Generated site output |
|
||||||
| `port` | `8080` | Upload API port (localhost only) |
|
| `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 |
|
| `author` | `Ashik Salahudeen` | Name shown on the header, photo pages and copyright footer |
|
||||||
| `handle` | `@puttaalu@inflo.ws` | Handle line under the author name |
|
| `handle` | `@puttaalu@inflo.ws` | Handle line under the author name |
|
||||||
| `bio` | `Personal photo journal.` | Primary bio line |
|
| `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 |
|
| `fontsURL` | Crimson Pro + Manjari | Stylesheet URL loading both web fonts |
|
||||||
| `serifFamily` | `Crimson Pro` | CSS font-family for the primary serif |
|
| `serifFamily` | `Crimson Pro` | CSS font-family for the primary serif |
|
||||||
| `mlFamily` | `Manjari` | CSS font-family for the alt-script bio |
|
| `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.domain` | — | Domain for the vhost |
|
||||||
| `nginx.htpasswdFile` | — | htpasswd file for `/upload` |
|
|
||||||
| `nginx.enableACME` | `true` | Enable Let's Encrypt |
|
| `nginx.enableACME` | `true` | Enable Let's Encrypt |
|
||||||
|
|
||||||
---
|
---
|
||||||
@@ -134,7 +185,23 @@ curl -u user:password \
|
|||||||
-F "image=@photo.jpg" \
|
-F "image=@photo.jpg" \
|
||||||
-F "caption=Tempelhof at sunrise" \
|
-F "caption=Tempelhof at sunrise" \
|
||||||
-F "date=2026-06-14" \
|
-F "date=2026-06-14" \
|
||||||
|
-F "tags=berlin, sunrise" \
|
||||||
https://photos.yourdomain.tld/upload
|
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/`.
|
||||||
@@ -0,0 +1,206 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"log"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"sort"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Tag is a normalized album tag: a lowercase free-text Name and its URL Slug.
|
||||||
|
type Tag struct {
|
||||||
|
Name string
|
||||||
|
Slug string
|
||||||
|
}
|
||||||
|
|
||||||
|
// Album is all photos sharing one tag, newest first.
|
||||||
|
type Album struct {
|
||||||
|
Tag Tag
|
||||||
|
Count int
|
||||||
|
Photos []Photo
|
||||||
|
}
|
||||||
|
|
||||||
|
// parseTags normalizes raw tag strings into unique Tags. Each input may itself
|
||||||
|
// be comma-separated (as typed in the upload form), so entries are split on
|
||||||
|
// commas, lowercased, trimmed, de-duplicated by name, and given a URL slug via
|
||||||
|
// sanitiseSlug. Entries that are empty or slug to nothing are dropped.
|
||||||
|
func parseTags(raw ...string) []Tag {
|
||||||
|
var tags []Tag
|
||||||
|
seen := map[string]bool{}
|
||||||
|
for _, entry := range raw {
|
||||||
|
for _, part := range strings.Split(entry, ",") {
|
||||||
|
name := strings.ToLower(strings.TrimSpace(part))
|
||||||
|
if name == "" || seen[name] {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
slug := sanitiseSlug(name)
|
||||||
|
if slug == "" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
seen[name] = true
|
||||||
|
tags = append(tags, Tag{Name: name, Slug: slug})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return tags
|
||||||
|
}
|
||||||
|
|
||||||
|
// groupByTag collapses photos (already sorted newest first) into one Album per
|
||||||
|
// distinct tag name, preserving photo order within each album. Albums are
|
||||||
|
// returned sorted alphabetically by tag name. If two different names produce the
|
||||||
|
// same URL slug, the later one is suffixed (-2, -3, …) and a warning is logged,
|
||||||
|
// so album URLs stay unique.
|
||||||
|
func groupByTag(photos []Photo) []Album {
|
||||||
|
byName := map[string][]Photo{}
|
||||||
|
for _, p := range photos {
|
||||||
|
for _, t := range p.Tags {
|
||||||
|
byName[t.Name] = append(byName[t.Name], p)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
names := make([]string, 0, len(byName))
|
||||||
|
for name := range byName {
|
||||||
|
names = append(names, name)
|
||||||
|
}
|
||||||
|
sort.Strings(names)
|
||||||
|
|
||||||
|
slugOwner := map[string]string{}
|
||||||
|
albums := make([]Album, 0, len(names))
|
||||||
|
for _, name := range names {
|
||||||
|
slug := sanitiseSlug(name)
|
||||||
|
if owner, taken := slugOwner[slug]; taken && owner != name {
|
||||||
|
base := slug
|
||||||
|
for n := 2; ; n++ {
|
||||||
|
cand := base + "-" + strconv.Itoa(n)
|
||||||
|
if _, t := slugOwner[cand]; !t {
|
||||||
|
slug = cand
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
log.Printf("album slug collision: %q and %q both slug to %q; using %q for the latter",
|
||||||
|
owner, name, base, slug)
|
||||||
|
}
|
||||||
|
slugOwner[slug] = name
|
||||||
|
ps := byName[name]
|
||||||
|
albums = append(albums, Album{
|
||||||
|
Tag: Tag{Name: name, Slug: slug},
|
||||||
|
Count: len(ps),
|
||||||
|
Photos: ps,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
return albums
|
||||||
|
}
|
||||||
|
|
||||||
|
// baseData returns the profile-header and site-wide fields every page template
|
||||||
|
// expects, so the album templates stay in step with the others.
|
||||||
|
func (g *Generator) baseData() map[string]any {
|
||||||
|
return map[string]any{
|
||||||
|
"BaseURL": g.baseURL,
|
||||||
|
"Year": time.Now().Year(),
|
||||||
|
"Author": g.author,
|
||||||
|
"Handle": g.handle,
|
||||||
|
"Bio": g.bio,
|
||||||
|
"BioAlt": g.bioAlt,
|
||||||
|
"Initial": g.initial(),
|
||||||
|
"FontsURL": g.fontsURL,
|
||||||
|
"SerifFamily": g.serifFamily,
|
||||||
|
"MlFamily": g.mlFamily,
|
||||||
|
"TimelineURL": g.timelineURL(),
|
||||||
|
"GridURL": g.gridURL(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// renderAlbumPages writes one paginated album per tag under public/album/<slug>/,
|
||||||
|
// a flat square grid like the grid view. total is the site-wide photo count, for
|
||||||
|
// the profile header.
|
||||||
|
func (g *Generator) renderAlbumPages(albums []Album, total int) error {
|
||||||
|
for _, al := range albums {
|
||||||
|
albumDir := filepath.Join(g.outputDir, "album", al.Tag.Slug)
|
||||||
|
if err := os.MkdirAll(albumDir, 0755); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
base := "/album/" + al.Tag.Slug + "/"
|
||||||
|
|
||||||
|
totalPages := (al.Count + g.pageSize - 1) / g.pageSize
|
||||||
|
if totalPages == 0 {
|
||||||
|
totalPages = 1
|
||||||
|
}
|
||||||
|
|
||||||
|
for i := 0; i < totalPages; i++ {
|
||||||
|
start := i * g.pageSize
|
||||||
|
end := start + g.pageSize
|
||||||
|
if end > al.Count {
|
||||||
|
end = al.Count
|
||||||
|
}
|
||||||
|
|
||||||
|
dst := filepath.Join(albumDir, "index.html")
|
||||||
|
if i > 0 {
|
||||||
|
dir := filepath.Join(albumDir, "page", strconv.Itoa(i+1))
|
||||||
|
if err := os.MkdirAll(dir, 0755); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
dst = filepath.Join(dir, "index.html")
|
||||||
|
}
|
||||||
|
|
||||||
|
prev := ""
|
||||||
|
next := ""
|
||||||
|
switch i {
|
||||||
|
case 0:
|
||||||
|
// no prev
|
||||||
|
case 1:
|
||||||
|
prev = base
|
||||||
|
default:
|
||||||
|
prev = base + "page/" + strconv.Itoa(i) + "/"
|
||||||
|
}
|
||||||
|
if i+1 < totalPages {
|
||||||
|
next = base + "page/" + strconv.Itoa(i+2) + "/"
|
||||||
|
}
|
||||||
|
|
||||||
|
data := g.baseData()
|
||||||
|
data["Tag"] = al.Tag
|
||||||
|
data["Count"] = al.Count
|
||||||
|
data["Photos"] = al.Photos[start:end]
|
||||||
|
data["Total"] = total
|
||||||
|
data["Page"] = i + 1
|
||||||
|
data["TotalPages"] = totalPages
|
||||||
|
data["PrevURL"] = prev
|
||||||
|
data["NextURL"] = next
|
||||||
|
if err := g.render("album.html", dst, data); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// renderAlbumsIndex writes public/albums/index.html — every tag with its count,
|
||||||
|
// linking to each album.
|
||||||
|
func (g *Generator) renderAlbumsIndex(albums []Album, total int) error {
|
||||||
|
data := g.baseData()
|
||||||
|
data["Albums"] = albums
|
||||||
|
data["Total"] = total
|
||||||
|
return g.render("albums.html", filepath.Join(g.outputDir, "albums", "index.html"), data)
|
||||||
|
}
|
||||||
|
|
||||||
|
type tagJSON struct {
|
||||||
|
Tag string `json:"tag"`
|
||||||
|
Slug string `json:"slug"`
|
||||||
|
Count int `json:"count"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// renderTagsJSON writes public/tags.json — the machine-readable tag list, served
|
||||||
|
// statically like feed.xml.
|
||||||
|
func (g *Generator) renderTagsJSON(albums []Album) error {
|
||||||
|
out := make([]tagJSON, 0, len(albums))
|
||||||
|
for _, a := range albums {
|
||||||
|
out = append(out, tagJSON{Tag: a.Tag.Name, Slug: a.Tag.Slug, Count: a.Count})
|
||||||
|
}
|
||||||
|
b, err := json.MarshalIndent(out, "", " ")
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return os.WriteFile(filepath.Join(g.outputDir, "tags.json"), b, 0644)
|
||||||
|
}
|
||||||
@@ -0,0 +1,73 @@
|
|||||||
|
# Gallery Upload — Android client
|
||||||
|
|
||||||
|
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; the management calls send no browser headers, so they pass the server's
|
||||||
|
same-origin (CSRF) check as a non-browser client.
|
||||||
|
|
||||||
|
## Build
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cd android
|
||||||
|
nix develop # Android SDK 36, build-tools 36.0.0, JDK 17, gradle
|
||||||
|
gradle wrapper # first time only, generates ./gradlew
|
||||||
|
./gradlew assembleDebug
|
||||||
|
adb install -r app/build/outputs/apk/debug/app-debug.apk
|
||||||
|
```
|
||||||
|
|
||||||
|
The dev shell exports `ANDROID_HOME`, `JAVA_HOME` and a `GRADLE_OPTS` that
|
||||||
|
points AGP at the nix-provided `aapt2`. Without that last one AGP downloads a
|
||||||
|
generic-linux `aapt2` from Maven which will not run on NixOS.
|
||||||
|
|
||||||
|
## Release signing
|
||||||
|
|
||||||
|
`app/build.gradle.kts` wires up a release signing config only when
|
||||||
|
`android/keystore.properties` exists. Both that file and `*.jks` are
|
||||||
|
gitignored — keep the keystore outside the repo and back it up somewhere you
|
||||||
|
will still have in five years, because losing it means you can never upgrade an
|
||||||
|
installed build in place.
|
||||||
|
|
||||||
|
```bash
|
||||||
|
mkdir -p ~/keys
|
||||||
|
keytool -genkeypair -v \
|
||||||
|
-keystore ~/keys/photogallery-release.jks \
|
||||||
|
-alias photogallery \
|
||||||
|
-keyalg RSA -keysize 4096 -validity 10000
|
||||||
|
```
|
||||||
|
|
||||||
|
Then write `android/keystore.properties`:
|
||||||
|
|
||||||
|
```properties
|
||||||
|
storeFile=/home/you/keys/photogallery-release.jks
|
||||||
|
storePassword=…
|
||||||
|
keyAlias=photogallery
|
||||||
|
keyPassword=…
|
||||||
|
```
|
||||||
|
|
||||||
|
```bash
|
||||||
|
./gradlew assembleRelease
|
||||||
|
```
|
||||||
|
|
||||||
|
Without `keystore.properties` the release build still runs, it just comes out
|
||||||
|
unsigned.
|
||||||
|
|
||||||
|
## How it maps onto the server
|
||||||
|
|
||||||
|
| Server behaviour | What the app does about it |
|
||||||
|
|---|---|
|
||||||
|
| Slug derived from the uploaded filename | Sends `yyyy-MM-dd-HHmmss.jpg`, generated once at enqueue |
|
||||||
|
| Same filename overwrites the same post | Reused across retries, which makes retries idempotent |
|
||||||
|
| Uploaded file published verbatim as "full size" | Strips EXIF, including GPS, before upload |
|
||||||
|
| Extension check rejects HEIC | Converts HEIC to JPEG; JPEG and PNG pass through losslessly |
|
||||||
|
| nginx `client_max_body_size 20M` | Steps quality, then resolution, if the result exceeds 18 MiB |
|
||||||
|
| Thumbnailer ignores EXIF orientation | Bakes rotation into the pixels rather than relying on the tag |
|
||||||
|
| nginx only proxies `/upload`, so `/health` 404s | Tests credentials with `GET /upload` instead |
|
||||||
|
| Replies `uploaded <slug>.jpg` in plain text | Parses that into `<base>/photo/<slug>/` for the "Open" link |
|
||||||
@@ -0,0 +1,87 @@
|
|||||||
|
import java.util.Properties
|
||||||
|
import org.jetbrains.kotlin.gradle.dsl.JvmTarget
|
||||||
|
|
||||||
|
plugins {
|
||||||
|
alias(libs.plugins.android.application)
|
||||||
|
alias(libs.plugins.kotlin.android)
|
||||||
|
alias(libs.plugins.kotlin.compose)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Release signing is wired up only when android/keystore.properties exists.
|
||||||
|
// That file holds the keystore passwords and is gitignored, as is the .jks
|
||||||
|
// itself — keep both outside the repo. See android/README.md for the
|
||||||
|
// keytool invocation that creates them.
|
||||||
|
val keystorePropsFile = rootProject.file("keystore.properties")
|
||||||
|
val keystoreProps = Properties().apply {
|
||||||
|
if (keystorePropsFile.exists()) keystorePropsFile.inputStream().use { load(it) }
|
||||||
|
}
|
||||||
|
|
||||||
|
android {
|
||||||
|
namespace = "ws.inflo.photogallery"
|
||||||
|
compileSdk = 36
|
||||||
|
|
||||||
|
defaultConfig {
|
||||||
|
applicationId = "ws.inflo.photogallery"
|
||||||
|
minSdk = 28 // ImageDecoder + HEIF decode both land here
|
||||||
|
targetSdk = 36
|
||||||
|
versionCode = 1
|
||||||
|
versionName = "0.1.0"
|
||||||
|
}
|
||||||
|
|
||||||
|
signingConfigs {
|
||||||
|
if (keystorePropsFile.exists()) {
|
||||||
|
create("release") {
|
||||||
|
storeFile = rootProject.file(keystoreProps.getProperty("storeFile"))
|
||||||
|
storePassword = keystoreProps.getProperty("storePassword")
|
||||||
|
keyAlias = keystoreProps.getProperty("keyAlias")
|
||||||
|
keyPassword = keystoreProps.getProperty("keyPassword")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
buildTypes {
|
||||||
|
release {
|
||||||
|
isMinifyEnabled = true
|
||||||
|
isShrinkResources = true
|
||||||
|
proguardFiles(
|
||||||
|
getDefaultProguardFile("proguard-android-optimize.txt"),
|
||||||
|
"proguard-rules.pro",
|
||||||
|
)
|
||||||
|
// Falls back to unsigned when keystore.properties is absent, so a
|
||||||
|
// fresh clone still builds.
|
||||||
|
signingConfig = signingConfigs.findByName("release")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
compileOptions {
|
||||||
|
sourceCompatibility = JavaVersion.VERSION_17
|
||||||
|
targetCompatibility = JavaVersion.VERSION_17
|
||||||
|
}
|
||||||
|
|
||||||
|
buildFeatures {
|
||||||
|
compose = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
kotlin {
|
||||||
|
compilerOptions {
|
||||||
|
jvmTarget.set(JvmTarget.JVM_17)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
dependencies {
|
||||||
|
implementation(libs.androidx.core.ktx)
|
||||||
|
implementation(libs.androidx.lifecycle.runtime.ktx)
|
||||||
|
implementation(libs.androidx.lifecycle.viewmodel.compose)
|
||||||
|
implementation(libs.androidx.activity.compose)
|
||||||
|
implementation(platform(libs.androidx.compose.bom))
|
||||||
|
implementation(libs.androidx.ui)
|
||||||
|
implementation(libs.androidx.ui.graphics)
|
||||||
|
implementation(libs.androidx.ui.tooling.preview)
|
||||||
|
implementation(libs.androidx.material3)
|
||||||
|
implementation(libs.androidx.work.runtime.ktx)
|
||||||
|
implementation(libs.androidx.exifinterface)
|
||||||
|
implementation(libs.okhttp)
|
||||||
|
|
||||||
|
debugImplementation(libs.androidx.ui.tooling)
|
||||||
|
}
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
# OkHttp ships Animal Sniffer and Conscrypt references that are absent at
|
||||||
|
# runtime on Android. Silence them rather than pulling in the dependencies.
|
||||||
|
-dontwarn okhttp3.internal.platform.**
|
||||||
|
-dontwarn org.conscrypt.**
|
||||||
|
-dontwarn org.bouncycastle.**
|
||||||
|
-dontwarn org.openjsse.**
|
||||||
@@ -0,0 +1,49 @@
|
|||||||
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
|
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
|
||||||
|
xmlns:tools="http://schemas.android.com/tools">
|
||||||
|
|
||||||
|
<uses-permission android:name="android.permission.INTERNET" />
|
||||||
|
<!-- WorkManager expedited uploads run in a foreground service on API 31+. -->
|
||||||
|
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
|
||||||
|
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_DATA_SYNC" />
|
||||||
|
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
|
||||||
|
|
||||||
|
<application
|
||||||
|
android:allowBackup="false"
|
||||||
|
android:icon="@mipmap/ic_launcher"
|
||||||
|
android:largeHeap="true"
|
||||||
|
android:label="@string/app_name"
|
||||||
|
android:supportsRtl="true"
|
||||||
|
android:theme="@style/Theme.PhotoGalleryUploader"
|
||||||
|
android:usesCleartextTraffic="false">
|
||||||
|
|
||||||
|
<activity
|
||||||
|
android:name=".MainActivity"
|
||||||
|
android:exported="true"
|
||||||
|
android:label="@string/app_name"
|
||||||
|
android:launchMode="singleTask"
|
||||||
|
android:theme="@style/Theme.PhotoGalleryUploader">
|
||||||
|
|
||||||
|
<intent-filter>
|
||||||
|
<action android:name="android.intent.action.MAIN" />
|
||||||
|
<category android:name="android.intent.category.LAUNCHER" />
|
||||||
|
</intent-filter>
|
||||||
|
|
||||||
|
<!-- Share sheet target: pick a photo in Google Photos, share here. -->
|
||||||
|
<intent-filter>
|
||||||
|
<action android:name="android.intent.action.SEND" />
|
||||||
|
<action android:name="android.intent.action.SEND_MULTIPLE" />
|
||||||
|
<category android:name="android.intent.category.DEFAULT" />
|
||||||
|
<data android:mimeType="image/*" />
|
||||||
|
</intent-filter>
|
||||||
|
</activity>
|
||||||
|
|
||||||
|
<!-- WorkManager runs expedited work in its own foreground service. On
|
||||||
|
Android 14+ the type has to be declared on the service entry, not
|
||||||
|
just requested as a permission, or setForeground() throws. -->
|
||||||
|
<service
|
||||||
|
android:name="androidx.work.impl.foreground.SystemForegroundService"
|
||||||
|
android:foregroundServiceType="dataSync"
|
||||||
|
tools:node="merge" />
|
||||||
|
</application>
|
||||||
|
</manifest>
|
||||||
@@ -0,0 +1,158 @@
|
|||||||
|
package ws.inflo.photogallery
|
||||||
|
|
||||||
|
import android.Manifest
|
||||||
|
import android.content.Intent
|
||||||
|
import android.content.pm.PackageManager
|
||||||
|
import android.net.Uri
|
||||||
|
import android.os.Build
|
||||||
|
import android.os.Bundle
|
||||||
|
import android.widget.Toast
|
||||||
|
import androidx.activity.ComponentActivity
|
||||||
|
import androidx.activity.compose.rememberLauncherForActivityResult
|
||||||
|
import androidx.activity.compose.setContent
|
||||||
|
import androidx.activity.result.PickVisualMediaRequest
|
||||||
|
import androidx.activity.result.contract.ActivityResultContracts
|
||||||
|
import androidx.activity.viewModels
|
||||||
|
import androidx.compose.runtime.LaunchedEffect
|
||||||
|
import androidx.compose.runtime.getValue
|
||||||
|
import androidx.compose.runtime.mutableStateOf
|
||||||
|
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
|
||||||
|
import ws.inflo.photogallery.ui.UploadViewModel
|
||||||
|
|
||||||
|
class MainActivity : ComponentActivity() {
|
||||||
|
|
||||||
|
private val viewModel: UploadViewModel by viewModels()
|
||||||
|
|
||||||
|
override fun onCreate(savedInstanceState: Bundle?) {
|
||||||
|
super.onCreate(savedInstanceState)
|
||||||
|
consumeShareIntent(intent)
|
||||||
|
|
||||||
|
setContent {
|
||||||
|
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(maxItems = 50),
|
||||||
|
) { uris -> if (uris.isNotEmpty()) viewModel.selectImages(uris) }
|
||||||
|
|
||||||
|
val notificationPermission = rememberLauncherForActivityResult(
|
||||||
|
ActivityResultContracts.RequestPermission(),
|
||||||
|
) { /* Upload works either way; this only affects the progress notification. */ }
|
||||||
|
|
||||||
|
LaunchedEffect(Unit) {
|
||||||
|
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU &&
|
||||||
|
ContextCompat.checkSelfPermission(
|
||||||
|
this@MainActivity,
|
||||||
|
Manifest.permission.POST_NOTIFICATIONS,
|
||||||
|
) != PackageManager.PERMISSION_GRANTED
|
||||||
|
) {
|
||||||
|
notificationPermission.launch(Manifest.permission.POST_NOTIFICATIONS)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
when {
|
||||||
|
showSettings -> SettingsScreen(
|
||||||
|
state = viewModel.config,
|
||||||
|
onBaseUrlChange = viewModel::setBaseUrl,
|
||||||
|
onUsernameChange = viewModel::setUsername,
|
||||||
|
onPasswordChange = viewModel::setPassword,
|
||||||
|
onSave = viewModel::saveAndTest,
|
||||||
|
onBack = if (viewModel.isConfigured) {
|
||||||
|
{ showSettings = false }
|
||||||
|
} else {
|
||||||
|
null
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
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(
|
||||||
|
ActivityResultContracts.PickVisualMedia.ImageOnly,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
},
|
||||||
|
onCaptionChange = viewModel::setCaption,
|
||||||
|
onTagsChange = viewModel::setTags,
|
||||||
|
onDateChange = viewModel::setDate,
|
||||||
|
onRemove = viewModel::removeItem,
|
||||||
|
onSubmit = viewModel::submit,
|
||||||
|
onReset = viewModel::clear,
|
||||||
|
onOpenSettings = { showSettings = true },
|
||||||
|
onOpenManage = {
|
||||||
|
viewModel.loadManage()
|
||||||
|
showManage = true
|
||||||
|
},
|
||||||
|
onOpenUrl = ::openUrl,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onNewIntent(intent: Intent) {
|
||||||
|
super.onNewIntent(intent)
|
||||||
|
setIntent(intent)
|
||||||
|
consumeShareIntent(intent)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Picks up one or several photos handed over by the share sheet. */
|
||||||
|
private fun consumeShareIntent(intent: Intent?) {
|
||||||
|
val uris: List<Uri> = when (intent?.action) {
|
||||||
|
Intent.ACTION_SEND -> {
|
||||||
|
val uri: Uri? = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
|
||||||
|
intent.getParcelableExtra(Intent.EXTRA_STREAM, Uri::class.java)
|
||||||
|
} else {
|
||||||
|
@Suppress("DEPRECATION")
|
||||||
|
intent.getParcelableExtra(Intent.EXTRA_STREAM)
|
||||||
|
}
|
||||||
|
listOfNotNull(uri)
|
||||||
|
}
|
||||||
|
|
||||||
|
Intent.ACTION_SEND_MULTIPLE -> {
|
||||||
|
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
|
||||||
|
intent.getParcelableArrayListExtra(Intent.EXTRA_STREAM, Uri::class.java)
|
||||||
|
} else {
|
||||||
|
@Suppress("DEPRECATION")
|
||||||
|
intent.getParcelableArrayListExtra<Uri>(Intent.EXTRA_STREAM)
|
||||||
|
}.orEmpty()
|
||||||
|
}
|
||||||
|
|
||||||
|
else -> return
|
||||||
|
}
|
||||||
|
if (uris.isNotEmpty()) viewModel.selectImages(uris)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun openUrl(url: String) {
|
||||||
|
if (url.isBlank()) return
|
||||||
|
try {
|
||||||
|
startActivity(Intent(Intent.ACTION_VIEW, url.toUri()))
|
||||||
|
} catch (_: Exception) {
|
||||||
|
Toast.makeText(this, "No browser to open $url", Toast.LENGTH_SHORT).show()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,171 @@
|
|||||||
|
package ws.inflo.photogallery.data
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import android.security.keystore.KeyGenParameterSpec
|
||||||
|
import android.security.keystore.KeyProperties
|
||||||
|
import android.util.Base64
|
||||||
|
import okhttp3.HttpUrl.Companion.toHttpUrlOrNull
|
||||||
|
import java.security.KeyStore
|
||||||
|
import javax.crypto.Cipher
|
||||||
|
import javax.crypto.KeyGenerator
|
||||||
|
import javax.crypto.SecretKey
|
||||||
|
import javax.crypto.spec.GCMParameterSpec
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Settings and credential persistence.
|
||||||
|
*
|
||||||
|
* The password is the only secret here and it never hits disk in the clear:
|
||||||
|
* it is sealed with an AES-GCM key held in the Android Keystore, so the bytes
|
||||||
|
* sitting in SharedPreferences are useless without the hardware-backed key.
|
||||||
|
*
|
||||||
|
* The key deliberately does not require user authentication. WorkManager
|
||||||
|
* retries an upload with nobody looking at the screen, and a key gated on a
|
||||||
|
* fingerprint would throw there.
|
||||||
|
*
|
||||||
|
* androidx.security-crypto (EncryptedSharedPreferences) covers this ground but
|
||||||
|
* is deprecated, so the Keystore calls are made directly.
|
||||||
|
*/
|
||||||
|
class SettingsStore(context: Context) {
|
||||||
|
|
||||||
|
private val prefs = context.applicationContext
|
||||||
|
.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
|
||||||
|
|
||||||
|
var baseUrl: String
|
||||||
|
get() = prefs.getString(KEY_BASE_URL, "").orEmpty()
|
||||||
|
set(value) = prefs.edit().putString(KEY_BASE_URL, value.trim().trimEnd('/')).apply()
|
||||||
|
|
||||||
|
var username: String
|
||||||
|
get() = prefs.getString(KEY_USERNAME, "").orEmpty()
|
||||||
|
set(value) = prefs.edit().putString(KEY_USERNAME, value.trim()).apply()
|
||||||
|
|
||||||
|
/** Empty string when unset, or when the Keystore key no longer decrypts it. */
|
||||||
|
var password: String
|
||||||
|
get() = prefs.getString(KEY_PASSWORD, null)?.let(::decrypt).orEmpty()
|
||||||
|
set(value) = prefs.edit().putString(KEY_PASSWORD, encrypt(value)).apply()
|
||||||
|
|
||||||
|
val isConfigured: Boolean
|
||||||
|
get() = baseUrl.isNotEmpty() && username.isNotEmpty() && password.isNotEmpty()
|
||||||
|
|
||||||
|
// ── Last successful post, shown on the post screen ──────────────────────
|
||||||
|
|
||||||
|
var lastPost: LastPost?
|
||||||
|
get() {
|
||||||
|
val slug = prefs.getString(KEY_LAST_SLUG, null) ?: return null
|
||||||
|
return LastPost(
|
||||||
|
slug = slug,
|
||||||
|
url = prefs.getString(KEY_LAST_URL, "").orEmpty(),
|
||||||
|
caption = prefs.getString(KEY_LAST_CAPTION, "").orEmpty(),
|
||||||
|
postedAtMillis = prefs.getLong(KEY_LAST_AT, 0L),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
set(value) {
|
||||||
|
prefs.edit().apply {
|
||||||
|
if (value == null) {
|
||||||
|
remove(KEY_LAST_SLUG); remove(KEY_LAST_URL)
|
||||||
|
remove(KEY_LAST_CAPTION); remove(KEY_LAST_AT)
|
||||||
|
} else {
|
||||||
|
putString(KEY_LAST_SLUG, value.slug)
|
||||||
|
putString(KEY_LAST_URL, value.url)
|
||||||
|
putString(KEY_LAST_CAPTION, value.caption)
|
||||||
|
putLong(KEY_LAST_AT, value.postedAtMillis)
|
||||||
|
}
|
||||||
|
}.apply()
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Keystore sealing ────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
private fun secretKey(): SecretKey {
|
||||||
|
val keystore = KeyStore.getInstance(ANDROID_KEYSTORE).apply { load(null) }
|
||||||
|
(keystore.getEntry(KEY_ALIAS, null) as? KeyStore.SecretKeyEntry)
|
||||||
|
?.let { return it.secretKey }
|
||||||
|
|
||||||
|
val generator = KeyGenerator.getInstance(
|
||||||
|
KeyProperties.KEY_ALGORITHM_AES,
|
||||||
|
ANDROID_KEYSTORE,
|
||||||
|
)
|
||||||
|
generator.init(
|
||||||
|
KeyGenParameterSpec.Builder(
|
||||||
|
KEY_ALIAS,
|
||||||
|
KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT,
|
||||||
|
)
|
||||||
|
.setBlockModes(KeyProperties.BLOCK_MODE_GCM)
|
||||||
|
.setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
|
||||||
|
.setKeySize(256)
|
||||||
|
.setUserAuthenticationRequired(false)
|
||||||
|
.build(),
|
||||||
|
)
|
||||||
|
return generator.generateKey()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun encrypt(plain: String): String {
|
||||||
|
val cipher = Cipher.getInstance(TRANSFORMATION)
|
||||||
|
cipher.init(Cipher.ENCRYPT_MODE, secretKey())
|
||||||
|
val ciphertext = cipher.doFinal(plain.toByteArray(Charsets.UTF_8))
|
||||||
|
return Base64.encodeToString(cipher.iv, Base64.NO_WRAP) +
|
||||||
|
SEPARATOR +
|
||||||
|
Base64.encodeToString(ciphertext, Base64.NO_WRAP)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Returns "" rather than throwing when the sealed blob cannot be opened.
|
||||||
|
* That happens legitimately — a Keystore key can be invalidated by a device
|
||||||
|
* restore or a lock-screen change — and the right response is to prompt for
|
||||||
|
* the password again, not to crash on launch.
|
||||||
|
*/
|
||||||
|
private fun decrypt(stored: String): String = try {
|
||||||
|
val parts = stored.split(SEPARATOR, limit = 2)
|
||||||
|
if (parts.size != 2) {
|
||||||
|
""
|
||||||
|
} else {
|
||||||
|
val iv = Base64.decode(parts[0], Base64.NO_WRAP)
|
||||||
|
val ciphertext = Base64.decode(parts[1], Base64.NO_WRAP)
|
||||||
|
val cipher = Cipher.getInstance(TRANSFORMATION)
|
||||||
|
cipher.init(Cipher.DECRYPT_MODE, secretKey(), GCMParameterSpec(GCM_TAG_BITS, iv))
|
||||||
|
String(cipher.doFinal(ciphertext), Charsets.UTF_8)
|
||||||
|
}
|
||||||
|
} catch (_: Exception) {
|
||||||
|
""
|
||||||
|
}
|
||||||
|
|
||||||
|
companion object {
|
||||||
|
private const val PREFS = "photogallery_settings"
|
||||||
|
private const val KEY_BASE_URL = "base_url"
|
||||||
|
private const val KEY_USERNAME = "username"
|
||||||
|
private const val KEY_PASSWORD = "password_sealed"
|
||||||
|
private const val KEY_LAST_SLUG = "last_slug"
|
||||||
|
private const val KEY_LAST_URL = "last_url"
|
||||||
|
private const val KEY_LAST_CAPTION = "last_caption"
|
||||||
|
private const val KEY_LAST_AT = "last_at"
|
||||||
|
|
||||||
|
private const val ANDROID_KEYSTORE = "AndroidKeyStore"
|
||||||
|
private const val KEY_ALIAS = "photogallery_credentials"
|
||||||
|
private const val TRANSFORMATION = "AES/GCM/NoPadding"
|
||||||
|
private const val GCM_TAG_BITS = 128
|
||||||
|
private const val SEPARATOR = ":"
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Returns an error message, or null when the URL is usable.
|
||||||
|
*
|
||||||
|
* https is required, not preferred. Basic auth puts the password in a
|
||||||
|
* trivially reversible header, so a plain-http base URL would hand the
|
||||||
|
* gallery password to anything on the path. The gallery's nginx vhost
|
||||||
|
* sets forceSSL anyway.
|
||||||
|
*/
|
||||||
|
fun validateBaseUrl(raw: String): String? {
|
||||||
|
val trimmed = raw.trim()
|
||||||
|
if (trimmed.isEmpty()) return "Base URL is required"
|
||||||
|
val url = trimmed.toHttpUrlOrNull() ?: return "Not a valid URL"
|
||||||
|
if (url.scheme != "https") {
|
||||||
|
return "Must be https — plain http sends your password in the clear"
|
||||||
|
}
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
data class LastPost(
|
||||||
|
val slug: String,
|
||||||
|
val url: String,
|
||||||
|
val caption: String,
|
||||||
|
val postedAtMillis: Long,
|
||||||
|
)
|
||||||
@@ -0,0 +1,308 @@
|
|||||||
|
package ws.inflo.photogallery.image
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import android.graphics.Bitmap
|
||||||
|
import android.graphics.ImageDecoder
|
||||||
|
import android.graphics.Matrix
|
||||||
|
import android.net.Uri
|
||||||
|
import androidx.exifinterface.media.ExifInterface
|
||||||
|
import java.io.ByteArrayOutputStream
|
||||||
|
import java.io.File
|
||||||
|
import java.time.LocalDate
|
||||||
|
import java.time.format.DateTimeFormatter
|
||||||
|
import java.time.format.DateTimeParseException
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Turns a picked or shared image into bytes the gallery's upload API accepts.
|
||||||
|
*
|
||||||
|
* Three things have to be true of the result: no EXIF (the gallery publishes
|
||||||
|
* the uploaded file verbatim as its "full size" download, so embedded GPS
|
||||||
|
* would be public), a .jpg or .png extension (server.go checks the extension
|
||||||
|
* and rejects anything else, HEIC included), and under nginx's 20M body cap.
|
||||||
|
*
|
||||||
|
* Where possible this is done without re-encoding, so the published file keeps
|
||||||
|
* the original sensor pixels exactly.
|
||||||
|
*/
|
||||||
|
object ImagePrep {
|
||||||
|
|
||||||
|
/** nginx is configured with client_max_body_size 20M; leave headroom. */
|
||||||
|
private const val MAX_UPLOAD_BYTES = 18L * 1024 * 1024
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Cap on decoded pixels for the paths that must decode. A bitmap is 4 bytes
|
||||||
|
* per pixel, so 40MP is a ~160MB allocation — survivable with largeHeap,
|
||||||
|
* which is why the manifest asks for it. Beyond that we sample down rather
|
||||||
|
* than die.
|
||||||
|
*/
|
||||||
|
private const val MAX_DECODE_PIXELS = 40_000_000L
|
||||||
|
|
||||||
|
private const val JPEG_QUALITY = 92
|
||||||
|
|
||||||
|
/** Quality ladder walked when the encoded result overshoots the cap. */
|
||||||
|
private val QUALITY_LADDER = intArrayOf(92, 85, 75)
|
||||||
|
|
||||||
|
data class Prepared(
|
||||||
|
val file: File,
|
||||||
|
val extension: String,
|
||||||
|
/** Non-null when the app had to depart from a byte-exact copy. */
|
||||||
|
val note: String?,
|
||||||
|
)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* EXIF capture date, for prefilling the date field. Read before any
|
||||||
|
* stripping happens — the same metadata block carries both this and the
|
||||||
|
* GPS tags being removed.
|
||||||
|
*/
|
||||||
|
fun captureDate(context: Context, uri: Uri): LocalDate? = try {
|
||||||
|
context.contentResolver.openInputStream(uri)?.use { stream ->
|
||||||
|
val exif = ExifInterface(stream)
|
||||||
|
val raw = exif.getAttribute(ExifInterface.TAG_DATETIME_ORIGINAL)
|
||||||
|
?: exif.getAttribute(ExifInterface.TAG_DATETIME)
|
||||||
|
raw?.let { parseExifDate(it) }
|
||||||
|
}
|
||||||
|
} catch (_: Exception) {
|
||||||
|
null
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun parseExifDate(raw: String): LocalDate? = try {
|
||||||
|
LocalDate.parse(raw.trim().substringBefore(' '), EXIF_DATE)
|
||||||
|
} catch (_: DateTimeParseException) {
|
||||||
|
null
|
||||||
|
}
|
||||||
|
|
||||||
|
private val EXIF_DATE: DateTimeFormatter = DateTimeFormatter.ofPattern("yyyy:MM:dd")
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Produces the file to upload, written into [cacheDir].
|
||||||
|
*
|
||||||
|
* JPEG and PNG take a lossless route: whole metadata segments are dropped
|
||||||
|
* without touching the compressed image data. Anything else — HEIC being
|
||||||
|
* the common case — has to be decoded and re-encoded as JPEG.
|
||||||
|
*/
|
||||||
|
fun prepare(context: Context, uri: Uri, cacheDir: File, baseName: String): Prepared {
|
||||||
|
val source = context.contentResolver.openInputStream(uri)?.use { it.readBytes() }
|
||||||
|
?: error("Could not read the selected image")
|
||||||
|
|
||||||
|
val orientation = readOrientation(context, uri)
|
||||||
|
val notes = mutableListOf<String>()
|
||||||
|
|
||||||
|
// A rotation flag cannot survive metadata stripping, and the gallery's
|
||||||
|
// thumbnailer ignores EXIF orientation regardless. Bake the rotation
|
||||||
|
// into the pixels instead, which costs a re-encode.
|
||||||
|
val mustRotate = orientation != ExifInterface.ORIENTATION_NORMAL &&
|
||||||
|
orientation != ExifInterface.ORIENTATION_UNDEFINED
|
||||||
|
|
||||||
|
val lossless: Pair<ByteArray, String>? = when {
|
||||||
|
mustRotate -> null
|
||||||
|
isJpeg(source) -> stripJpegSegments(source)?.let { it to "jpg" }
|
||||||
|
isPng(source) -> stripPngChunks(source)?.let { it to "png" }
|
||||||
|
else -> null
|
||||||
|
}
|
||||||
|
|
||||||
|
var bytes: ByteArray
|
||||||
|
var extension: String
|
||||||
|
|
||||||
|
if (lossless != null) {
|
||||||
|
bytes = lossless.first
|
||||||
|
extension = lossless.second
|
||||||
|
} else {
|
||||||
|
if (mustRotate) notes += "rotated to match its EXIF orientation"
|
||||||
|
else if (!isJpeg(source) && !isPng(source)) notes += "converted to JPEG"
|
||||||
|
bytes = encodeJpeg(decodeOriented(context, uri, orientation), JPEG_QUALITY)
|
||||||
|
extension = "jpg"
|
||||||
|
}
|
||||||
|
|
||||||
|
// Size valve. Only trips on genuinely huge originals; stepping quality
|
||||||
|
// is tried before touching resolution.
|
||||||
|
if (bytes.size > MAX_UPLOAD_BYTES) {
|
||||||
|
val bitmap = decodeOriented(context, uri, orientation)
|
||||||
|
var shrunk: ByteArray? = null
|
||||||
|
|
||||||
|
for (quality in QUALITY_LADDER) {
|
||||||
|
val attempt = encodeJpeg(bitmap, quality)
|
||||||
|
if (attempt.size <= MAX_UPLOAD_BYTES) {
|
||||||
|
shrunk = attempt
|
||||||
|
notes += "re-encoded at quality $quality to fit the 20M upload limit"
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (shrunk == null) {
|
||||||
|
var scaled = bitmap
|
||||||
|
var factor = 1.0
|
||||||
|
while (factor > 0.2) {
|
||||||
|
factor *= 0.75
|
||||||
|
scaled = Bitmap.createScaledBitmap(
|
||||||
|
bitmap,
|
||||||
|
(bitmap.width * factor).toInt().coerceAtLeast(1),
|
||||||
|
(bitmap.height * factor).toInt().coerceAtLeast(1),
|
||||||
|
true,
|
||||||
|
)
|
||||||
|
val attempt = encodeJpeg(scaled, QUALITY_LADDER.last())
|
||||||
|
if (attempt.size <= MAX_UPLOAD_BYTES) {
|
||||||
|
shrunk = attempt
|
||||||
|
notes += "scaled to ${scaled.width}×${scaled.height} to fit the 20M upload limit"
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
bytes = shrunk ?: error("Image is too large to upload even after downscaling")
|
||||||
|
extension = "jpg"
|
||||||
|
}
|
||||||
|
|
||||||
|
val file = File(cacheDir, "$baseName.$extension")
|
||||||
|
file.writeBytes(bytes)
|
||||||
|
|
||||||
|
return Prepared(
|
||||||
|
file = file,
|
||||||
|
extension = extension,
|
||||||
|
note = notes.takeIf { it.isNotEmpty() }?.joinToString("; "),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Small, correctly-rotated bitmap for the on-screen preview. Decoded at a
|
||||||
|
* sample size rather than full resolution — the preview is a thumbnail and
|
||||||
|
* has no business allocating a 40MP bitmap.
|
||||||
|
*/
|
||||||
|
fun preview(context: Context, uri: Uri, maxDimension: Int = 1024): Bitmap? = try {
|
||||||
|
val source = ImageDecoder.createSource(context.contentResolver, uri)
|
||||||
|
val bitmap = ImageDecoder.decodeBitmap(source) { decoder, info, _ ->
|
||||||
|
decoder.allocator = ImageDecoder.ALLOCATOR_SOFTWARE
|
||||||
|
val longest = maxOf(info.size.width, info.size.height)
|
||||||
|
var sample = 1
|
||||||
|
while (longest / (sample * 2) >= maxDimension) sample *= 2
|
||||||
|
if (sample > 1) decoder.setTargetSampleSize(sample)
|
||||||
|
}
|
||||||
|
applyOrientation(bitmap, readOrientation(context, uri))
|
||||||
|
} catch (_: Exception) {
|
||||||
|
null
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun readOrientation(context: Context, uri: Uri): Int = try {
|
||||||
|
context.contentResolver.openInputStream(uri)?.use { stream ->
|
||||||
|
ExifInterface(stream).getAttributeInt(
|
||||||
|
ExifInterface.TAG_ORIENTATION,
|
||||||
|
ExifInterface.ORIENTATION_UNDEFINED,
|
||||||
|
)
|
||||||
|
} ?: ExifInterface.ORIENTATION_UNDEFINED
|
||||||
|
} catch (_: Exception) {
|
||||||
|
ExifInterface.ORIENTATION_UNDEFINED
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun decodeOriented(context: Context, uri: Uri, orientation: Int): Bitmap {
|
||||||
|
val source = ImageDecoder.createSource(context.contentResolver, uri)
|
||||||
|
val bitmap = ImageDecoder.decodeBitmap(source) { decoder, info, _ ->
|
||||||
|
decoder.allocator = ImageDecoder.ALLOCATOR_SOFTWARE
|
||||||
|
decoder.isMutableRequired = false
|
||||||
|
val pixels = info.size.width.toLong() * info.size.height.toLong()
|
||||||
|
if (pixels > MAX_DECODE_PIXELS) {
|
||||||
|
var sample = 2
|
||||||
|
while (pixels / (sample.toLong() * sample) > MAX_DECODE_PIXELS) sample *= 2
|
||||||
|
decoder.setTargetSampleSize(sample)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return applyOrientation(bitmap, orientation)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun applyOrientation(bitmap: Bitmap, orientation: Int): Bitmap {
|
||||||
|
val matrix = Matrix()
|
||||||
|
when (orientation) {
|
||||||
|
ExifInterface.ORIENTATION_ROTATE_90 -> matrix.postRotate(90f)
|
||||||
|
ExifInterface.ORIENTATION_ROTATE_180 -> matrix.postRotate(180f)
|
||||||
|
ExifInterface.ORIENTATION_ROTATE_270 -> matrix.postRotate(270f)
|
||||||
|
ExifInterface.ORIENTATION_FLIP_HORIZONTAL -> matrix.postScale(-1f, 1f)
|
||||||
|
ExifInterface.ORIENTATION_FLIP_VERTICAL -> matrix.postScale(1f, -1f)
|
||||||
|
ExifInterface.ORIENTATION_TRANSPOSE -> { matrix.postRotate(90f); matrix.postScale(-1f, 1f) }
|
||||||
|
ExifInterface.ORIENTATION_TRANSVERSE -> { matrix.postRotate(270f); matrix.postScale(-1f, 1f) }
|
||||||
|
else -> return bitmap
|
||||||
|
}
|
||||||
|
return Bitmap.createBitmap(bitmap, 0, 0, bitmap.width, bitmap.height, matrix, true)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun encodeJpeg(bitmap: Bitmap, quality: Int): ByteArray =
|
||||||
|
ByteArrayOutputStream(bitmap.width * bitmap.height / 4).use { out ->
|
||||||
|
bitmap.compress(Bitmap.CompressFormat.JPEG, quality, out)
|
||||||
|
out.toByteArray()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun isJpeg(b: ByteArray) =
|
||||||
|
b.size > 3 && b.u8(0) == 0xFF && b.u8(1) == 0xD8 && b.u8(2) == 0xFF
|
||||||
|
|
||||||
|
private fun isPng(b: ByteArray) =
|
||||||
|
b.size > 8 && b.u8(0) == 0x89 && b.u8(1) == 0x50 && b.u8(2) == 0x4E && b.u8(3) == 0x47
|
||||||
|
|
||||||
|
private fun ByteArray.u8(i: Int) = this[i].toInt() and 0xFF
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Drops APP1 (EXIF and XMP) and COM segments, keeping the compressed scan
|
||||||
|
* data byte-for-byte. APP0/JFIF and APP2/ICC stay: removing the colour
|
||||||
|
* profile would shift the rendered colours.
|
||||||
|
*
|
||||||
|
* Returns null if the marker structure does not parse, in which case the
|
||||||
|
* caller falls back to a decode-and-re-encode that is guaranteed to strip.
|
||||||
|
*/
|
||||||
|
private fun stripJpegSegments(src: ByteArray): ByteArray? {
|
||||||
|
val out = ByteArrayOutputStream(src.size)
|
||||||
|
out.write(0xFF); out.write(0xD8)
|
||||||
|
|
||||||
|
var i = 2
|
||||||
|
while (i + 1 < src.size) {
|
||||||
|
if (src.u8(i) != 0xFF) return null
|
||||||
|
val marker = src.u8(i + 1)
|
||||||
|
|
||||||
|
// Standalone markers: no length field, no payload.
|
||||||
|
if (marker == 0x01 || marker in 0xD0..0xD7) {
|
||||||
|
out.write(0xFF); out.write(marker)
|
||||||
|
i += 2
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
// Start of scan: entropy-coded data runs to the end of the file.
|
||||||
|
if (marker == 0xDA) {
|
||||||
|
out.write(src, i, src.size - i)
|
||||||
|
return out.toByteArray()
|
||||||
|
}
|
||||||
|
|
||||||
|
if (i + 3 >= src.size) return null
|
||||||
|
val length = (src.u8(i + 2) shl 8) or src.u8(i + 3)
|
||||||
|
if (length < 2 || i + 2 + length > src.size) return null
|
||||||
|
|
||||||
|
val isExifOrXmp = marker == 0xE1
|
||||||
|
val isComment = marker == 0xFE
|
||||||
|
if (!isExifOrXmp && !isComment) out.write(src, i, 2 + length)
|
||||||
|
|
||||||
|
i += 2 + length
|
||||||
|
}
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Drops the metadata chunks and keeps everything else, including the
|
||||||
|
* critical IHDR/PLTE/IDAT/IEND run and colour chunks like iCCP and sRGB.
|
||||||
|
* Whole chunks go, so no CRC needs recomputing.
|
||||||
|
*/
|
||||||
|
private fun stripPngChunks(src: ByteArray): ByteArray? {
|
||||||
|
val drop = setOf("eXIf", "tEXt", "zTXt", "iTXt", "tIME")
|
||||||
|
val out = ByteArrayOutputStream(src.size)
|
||||||
|
out.write(src, 0, 8)
|
||||||
|
|
||||||
|
var i = 8
|
||||||
|
while (i + 8 <= src.size) {
|
||||||
|
val length = ((src.u8(i).toLong() shl 24) or (src.u8(i + 1).toLong() shl 16) or
|
||||||
|
(src.u8(i + 2).toLong() shl 8) or src.u8(i + 3).toLong()).toInt()
|
||||||
|
if (length < 0) return null
|
||||||
|
|
||||||
|
val type = String(src, i + 4, 4, Charsets.US_ASCII)
|
||||||
|
val total = 12 + length
|
||||||
|
if (i + total > src.size) return null
|
||||||
|
|
||||||
|
if (type !in drop) out.write(src, i, total)
|
||||||
|
i += total
|
||||||
|
|
||||||
|
if (type == "IEND") return out.toByteArray()
|
||||||
|
}
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,310 @@
|
|||||||
|
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
|
||||||
|
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
|
||||||
|
|
||||||
|
sealed interface UploadOutcome {
|
||||||
|
data class Success(val slug: String, val url: String) : UploadOutcome
|
||||||
|
|
||||||
|
/** Wrong credentials. Retrying will not help. */
|
||||||
|
data object AuthFailed : UploadOutcome
|
||||||
|
|
||||||
|
/** Server said no for a reason a retry will not change. */
|
||||||
|
data class Rejected(val code: Int, val message: String) : UploadOutcome
|
||||||
|
|
||||||
|
/** Network trouble or a 5xx. Worth retrying. */
|
||||||
|
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.
|
||||||
|
*
|
||||||
|
* Behind nginx that endpoint sits under HTTP Basic auth. The credentials go
|
||||||
|
* out on every request via an interceptor rather than through OkHttp's
|
||||||
|
* [okhttp3.Authenticator], on purpose: an Authenticator only reacts to a 401
|
||||||
|
* and then replays the request, and a multipart body streamed off disk is not
|
||||||
|
* reliably replayable — the retry can arrive with an empty body.
|
||||||
|
*/
|
||||||
|
class UploadClient(
|
||||||
|
baseUrl: String,
|
||||||
|
username: String,
|
||||||
|
password: String,
|
||||||
|
) {
|
||||||
|
private val base = baseUrl.trimEnd('/')
|
||||||
|
|
||||||
|
private val client = OkHttpClient.Builder()
|
||||||
|
.connectTimeout(30, TimeUnit.SECONDS)
|
||||||
|
.writeTimeout(5, TimeUnit.MINUTES) // a full-resolution photo on mobile data
|
||||||
|
.readTimeout(60, TimeUnit.SECONDS)
|
||||||
|
.addInterceptor(BasicAuthInterceptor(username, password))
|
||||||
|
.build()
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Uploads [file] as the given [fileName].
|
||||||
|
*
|
||||||
|
* The filename matters more than it looks: server.go derives the photo's
|
||||||
|
* slug from it, so passing the same name on a retry overwrites the same
|
||||||
|
* post instead of creating a duplicate.
|
||||||
|
*/
|
||||||
|
fun upload(
|
||||||
|
file: File,
|
||||||
|
fileName: String,
|
||||||
|
caption: String,
|
||||||
|
date: String,
|
||||||
|
tags: String,
|
||||||
|
): UploadOutcome {
|
||||||
|
val mediaType = if (fileName.endsWith(".png", ignoreCase = true)) {
|
||||||
|
"image/png".toMediaType()
|
||||||
|
} else {
|
||||||
|
"image/jpeg".toMediaType()
|
||||||
|
}
|
||||||
|
|
||||||
|
val body = MultipartBody.Builder()
|
||||||
|
.setType(MultipartBody.FORM)
|
||||||
|
.addFormDataPart("image", fileName, file.asRequestBody(mediaType))
|
||||||
|
.addFormDataPart("caption", caption)
|
||||||
|
.addFormDataPart("date", date)
|
||||||
|
.addFormDataPart("tags", tags)
|
||||||
|
.build()
|
||||||
|
|
||||||
|
val request = Request.Builder()
|
||||||
|
.url("$base/upload")
|
||||||
|
.post(body)
|
||||||
|
.build()
|
||||||
|
|
||||||
|
return try {
|
||||||
|
client.newCall(request).execute().use { response ->
|
||||||
|
val text = response.body?.string().orEmpty()
|
||||||
|
when {
|
||||||
|
response.isSuccessful -> {
|
||||||
|
val slug = parseSlug(text, fileName.substringBeforeLast('.'))
|
||||||
|
UploadOutcome.Success(slug = slug, url = "$base/photo/$slug/")
|
||||||
|
}
|
||||||
|
response.code == 401 || response.code == 403 -> UploadOutcome.AuthFailed
|
||||||
|
response.code in 500..599 ->
|
||||||
|
UploadOutcome.Transient("Server error ${response.code}")
|
||||||
|
else ->
|
||||||
|
UploadOutcome.Rejected(response.code, text.trim().ifEmpty { "Upload rejected" })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (e: IOException) {
|
||||||
|
UploadOutcome.Transient(e.message ?: "Network error")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Credential check. /health is not usable for this — the nginx vhost only
|
||||||
|
* proxies location /upload, so /health falls through to the static root and
|
||||||
|
* 404s. GET /upload returns the upload page through the same Basic-auth
|
||||||
|
* gate the POST uses, which is exactly what needs testing.
|
||||||
|
*/
|
||||||
|
fun testConnection(): String? {
|
||||||
|
val request = Request.Builder().url("$base/upload").get().build()
|
||||||
|
return try {
|
||||||
|
client.newCall(request).execute().use { response ->
|
||||||
|
when {
|
||||||
|
response.isSuccessful -> null
|
||||||
|
response.code == 401 || response.code == 403 -> "Wrong username or password"
|
||||||
|
else -> "Server returned ${response.code}"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (e: IOException) {
|
||||||
|
e.message ?: "Could not reach the server"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 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()
|
||||||
|
val slug = name.substringBeforeLast('.')
|
||||||
|
return slug.ifEmpty { fallback }
|
||||||
|
}
|
||||||
|
|
||||||
|
private class BasicAuthInterceptor(username: String, password: String) : Interceptor {
|
||||||
|
private val header = Credentials.basic(username, password)
|
||||||
|
|
||||||
|
override fun intercept(chain: Interceptor.Chain): Response =
|
||||||
|
chain.proceed(
|
||||||
|
chain.request().newBuilder()
|
||||||
|
.header("Authorization", header)
|
||||||
|
.build(),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,314 @@
|
|||||||
|
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.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.HorizontalDivider
|
||||||
|
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 PostScreen(
|
||||||
|
state: PostUiState,
|
||||||
|
tagSuggestions: List<String>,
|
||||||
|
onPickImages: () -> Unit,
|
||||||
|
onCaptionChange: (id: String, value: String) -> Unit,
|
||||||
|
onTagsChange: (id: String, value: String) -> Unit,
|
||||||
|
onDateChange: (id: String, value: LocalDate) -> Unit,
|
||||||
|
onRemove: (id: String) -> Unit,
|
||||||
|
onSubmit: () -> Unit,
|
||||||
|
onReset: () -> Unit,
|
||||||
|
onOpenSettings: () -> Unit,
|
||||||
|
onOpenManage: () -> Unit,
|
||||||
|
onOpenUrl: (String) -> Unit,
|
||||||
|
) {
|
||||||
|
// Which item's date is being edited, if any.
|
||||||
|
var dateEditFor by remember { mutableStateOf<PickedItem?>(null) }
|
||||||
|
|
||||||
|
val pendingCount = state.items.count { it.status !is ItemStatus.Success }
|
||||||
|
val canPost = state.hasItems && !state.posting && pendingCount > 0
|
||||||
|
|
||||||
|
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("Post photos", style = MaterialTheme.typography.headlineSmall, color = GruvGreen)
|
||||||
|
Row {
|
||||||
|
TextButton(onClick = onOpenManage) { Text("Manage") }
|
||||||
|
TextButton(onClick = onOpenSettings) { Text("Settings") }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Spacer(Modifier.height(12.dp))
|
||||||
|
}
|
||||||
|
|
||||||
|
item {
|
||||||
|
OutlinedButton(onClick = onPickImages, modifier = Modifier.fillMaxWidth()) {
|
||||||
|
Text(if (state.hasItems) "Choose different photos" else "Choose photos")
|
||||||
|
}
|
||||||
|
Spacer(Modifier.height(16.dp))
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!state.hasItems) {
|
||||||
|
item {
|
||||||
|
Box(
|
||||||
|
modifier = Modifier
|
||||||
|
.fillMaxWidth()
|
||||||
|
.height(160.dp)
|
||||||
|
.background(GruvBg1),
|
||||||
|
contentAlignment = Alignment.Center,
|
||||||
|
) {
|
||||||
|
Text("No photos selected", color = GruvFg4)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
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 },
|
||||||
|
onRemove = { onRemove(item.id) },
|
||||||
|
onOpenUrl = onOpenUrl,
|
||||||
|
)
|
||||||
|
Spacer(Modifier.height(12.dp))
|
||||||
|
}
|
||||||
|
|
||||||
|
if (state.hasItems) {
|
||||||
|
item {
|
||||||
|
Spacer(Modifier.height(8.dp))
|
||||||
|
Button(
|
||||||
|
onClick = onSubmit,
|
||||||
|
enabled = canPost,
|
||||||
|
modifier = Modifier.fillMaxWidth(),
|
||||||
|
) {
|
||||||
|
Text(
|
||||||
|
when {
|
||||||
|
state.posting -> "Posting… (${state.succeeded}/${state.items.size})"
|
||||||
|
pendingCount == 0 -> "All posted"
|
||||||
|
pendingCount == 1 -> "Post 1 photo"
|
||||||
|
else -> "Post $pendingCount photos"
|
||||||
|
},
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (state.allDone) {
|
||||||
|
Spacer(Modifier.height(12.dp))
|
||||||
|
val summary = buildString {
|
||||||
|
append("${state.succeeded} posted")
|
||||||
|
if (state.failed > 0) append(", ${state.failed} failed")
|
||||||
|
}
|
||||||
|
Text(summary, color = if (state.failed > 0) GruvRed else GruvAqua)
|
||||||
|
Spacer(Modifier.height(8.dp))
|
||||||
|
TextButton(onClick = onReset) { Text("Clear") }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
state.lastPost?.let { last ->
|
||||||
|
item {
|
||||||
|
Spacer(Modifier.height(24.dp))
|
||||||
|
HorizontalDivider(color = GruvBg2)
|
||||||
|
Spacer(Modifier.height(12.dp))
|
||||||
|
Text("Last post", color = GruvFg4, style = MaterialTheme.typography.labelMedium)
|
||||||
|
Spacer(Modifier.height(4.dp))
|
||||||
|
Text(
|
||||||
|
last.caption.ifBlank { last.slug },
|
||||||
|
color = GruvFg,
|
||||||
|
style = MaterialTheme.typography.bodyMedium,
|
||||||
|
)
|
||||||
|
Text(
|
||||||
|
last.slug,
|
||||||
|
color = GruvFg4,
|
||||||
|
fontFamily = FontFamily.Monospace,
|
||||||
|
style = MaterialTheme.typography.bodySmall,
|
||||||
|
)
|
||||||
|
TextButton(onClick = { onOpenUrl(last.url) }) { Text("Open") }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
dateEditFor?.let { editing ->
|
||||||
|
DatePickerModal(
|
||||||
|
initial = editing.date,
|
||||||
|
onDismiss = { dateEditFor = null },
|
||||||
|
onConfirm = {
|
||||||
|
onDateChange(editing.id, it)
|
||||||
|
dateEditFor = null
|
||||||
|
},
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
private fun ItemCard(
|
||||||
|
item: PickedItem,
|
||||||
|
tagSuggestions: List<String>,
|
||||||
|
onCaptionChange: (String) -> Unit,
|
||||||
|
onTagsChange: (String) -> Unit,
|
||||||
|
onEditDate: () -> Unit,
|
||||||
|
onRemove: () -> Unit,
|
||||||
|
onOpenUrl: (String) -> Unit,
|
||||||
|
) {
|
||||||
|
Row(modifier = Modifier.fillMaxWidth()) {
|
||||||
|
Box(
|
||||||
|
modifier = Modifier
|
||||||
|
.size(84.dp)
|
||||||
|
.background(GruvBg1),
|
||||||
|
contentAlignment = Alignment.Center,
|
||||||
|
) {
|
||||||
|
val preview = item.preview
|
||||||
|
when {
|
||||||
|
preview != null -> Image(
|
||||||
|
bitmap = preview.asImageBitmap(),
|
||||||
|
contentDescription = null,
|
||||||
|
contentScale = ContentScale.Crop,
|
||||||
|
modifier = Modifier.fillMaxSize(),
|
||||||
|
)
|
||||||
|
else -> CircularProgressIndicator(color = GruvAqua, modifier = Modifier.size(24.dp))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Spacer(Modifier.width(12.dp))
|
||||||
|
|
||||||
|
Column(modifier = Modifier.weight(1f)) {
|
||||||
|
OutlinedTextField(
|
||||||
|
value = item.caption,
|
||||||
|
onValueChange = onCaptionChange,
|
||||||
|
label = { Text("Caption") },
|
||||||
|
singleLine = true,
|
||||||
|
enabled = item.status !is ItemStatus.Uploading,
|
||||||
|
modifier = Modifier.fillMaxWidth(),
|
||||||
|
)
|
||||||
|
Spacer(Modifier.height(6.dp))
|
||||||
|
TagField(
|
||||||
|
value = item.tags,
|
||||||
|
onValueChange = onTagsChange,
|
||||||
|
suggestions = tagSuggestions,
|
||||||
|
enabled = item.status !is ItemStatus.Uploading,
|
||||||
|
modifier = Modifier.fillMaxWidth(),
|
||||||
|
)
|
||||||
|
Spacer(Modifier.height(6.dp))
|
||||||
|
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||||
|
OutlinedButton(
|
||||||
|
onClick = onEditDate,
|
||||||
|
enabled = item.status !is ItemStatus.Uploading,
|
||||||
|
) {
|
||||||
|
Text(item.date.format(DISPLAY_DATE))
|
||||||
|
}
|
||||||
|
Spacer(Modifier.width(8.dp))
|
||||||
|
ItemStatusLabel(item.status, onOpenUrl)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Spacer(Modifier.width(8.dp))
|
||||||
|
|
||||||
|
when (item.status) {
|
||||||
|
is ItemStatus.Uploading ->
|
||||||
|
CircularProgressIndicator(color = GruvAqua, modifier = Modifier.size(20.dp))
|
||||||
|
is ItemStatus.Success -> Unit
|
||||||
|
else -> TextButton(onClick = onRemove) { Text("✕", color = GruvFg4) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
private fun ItemStatusLabel(status: ItemStatus, onOpenUrl: (String) -> Unit) {
|
||||||
|
when (status) {
|
||||||
|
is ItemStatus.Pending -> Unit
|
||||||
|
is ItemStatus.Uploading -> Text("Uploading…", color = GruvFg4, style = MaterialTheme.typography.bodySmall)
|
||||||
|
is ItemStatus.Success -> TextButton(onClick = { onOpenUrl(status.url) }) { Text("View") }
|
||||||
|
is ItemStatus.Error -> Text(
|
||||||
|
status.message,
|
||||||
|
color = GruvRed,
|
||||||
|
style = MaterialTheme.typography.bodySmall,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@OptIn(ExperimentalMaterial3Api::class)
|
||||||
|
@Composable
|
||||||
|
private fun DatePickerModal(
|
||||||
|
initial: LocalDate,
|
||||||
|
onDismiss: () -> Unit,
|
||||||
|
onConfirm: (LocalDate) -> Unit,
|
||||||
|
) {
|
||||||
|
val state = rememberDatePickerState(
|
||||||
|
initialSelectedDateMillis = initial
|
||||||
|
.atStartOfDay(ZoneId.systemDefault())
|
||||||
|
.toInstant()
|
||||||
|
.toEpochMilli(),
|
||||||
|
)
|
||||||
|
|
||||||
|
DatePickerDialog(
|
||||||
|
onDismissRequest = onDismiss,
|
||||||
|
confirmButton = {
|
||||||
|
TextButton(
|
||||||
|
onClick = {
|
||||||
|
val millis = state.selectedDateMillis
|
||||||
|
if (millis != null) {
|
||||||
|
onConfirm(
|
||||||
|
Instant.ofEpochMilli(millis)
|
||||||
|
.atZone(ZoneId.systemDefault())
|
||||||
|
.toLocalDate(),
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
onDismiss()
|
||||||
|
}
|
||||||
|
},
|
||||||
|
) { Text("OK") }
|
||||||
|
},
|
||||||
|
dismissButton = { TextButton(onClick = onDismiss) { Text("Cancel") } },
|
||||||
|
) {
|
||||||
|
DatePicker(state = state)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,129 @@
|
|||||||
|
package ws.inflo.photogallery.ui
|
||||||
|
|
||||||
|
import androidx.compose.foundation.layout.Column
|
||||||
|
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.rememberScrollState
|
||||||
|
import androidx.compose.foundation.text.KeyboardOptions
|
||||||
|
import androidx.compose.foundation.verticalScroll
|
||||||
|
import androidx.compose.material3.Button
|
||||||
|
import androidx.compose.material3.MaterialTheme
|
||||||
|
import androidx.compose.material3.OutlinedTextField
|
||||||
|
import androidx.compose.material3.Surface
|
||||||
|
import androidx.compose.material3.Text
|
||||||
|
import androidx.compose.material3.TextButton
|
||||||
|
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.text.input.KeyboardType
|
||||||
|
import androidx.compose.ui.text.input.PasswordVisualTransformation
|
||||||
|
import androidx.compose.ui.text.input.VisualTransformation
|
||||||
|
import androidx.compose.ui.unit.dp
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
fun SettingsScreen(
|
||||||
|
state: SettingsUiState,
|
||||||
|
onBaseUrlChange: (String) -> Unit,
|
||||||
|
onUsernameChange: (String) -> Unit,
|
||||||
|
onPasswordChange: (String) -> Unit,
|
||||||
|
onSave: () -> Unit,
|
||||||
|
onBack: (() -> Unit)?,
|
||||||
|
) {
|
||||||
|
var passwordVisible by remember { mutableStateOf(false) }
|
||||||
|
|
||||||
|
Surface(color = MaterialTheme.colorScheme.background, modifier = Modifier.fillMaxSize()) {
|
||||||
|
Column(
|
||||||
|
modifier = Modifier
|
||||||
|
.fillMaxSize()
|
||||||
|
.verticalScroll(rememberScrollState())
|
||||||
|
.padding(20.dp),
|
||||||
|
) {
|
||||||
|
Text("Settings", style = MaterialTheme.typography.headlineSmall, color = GruvGreen)
|
||||||
|
|
||||||
|
Spacer(Modifier.height(16.dp))
|
||||||
|
|
||||||
|
OutlinedTextField(
|
||||||
|
value = state.baseUrl,
|
||||||
|
onValueChange = onBaseUrlChange,
|
||||||
|
label = { Text("Gallery URL") },
|
||||||
|
placeholder = { Text("https://photos.example.com") },
|
||||||
|
singleLine = true,
|
||||||
|
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Uri),
|
||||||
|
modifier = Modifier.fillMaxWidth(),
|
||||||
|
)
|
||||||
|
|
||||||
|
Spacer(Modifier.height(4.dp))
|
||||||
|
Text(
|
||||||
|
"Must be https. Basic auth puts the password in a trivially " +
|
||||||
|
"reversible header, so plain http would expose it.",
|
||||||
|
color = GruvFg4,
|
||||||
|
style = MaterialTheme.typography.bodySmall,
|
||||||
|
)
|
||||||
|
|
||||||
|
Spacer(Modifier.height(16.dp))
|
||||||
|
|
||||||
|
OutlinedTextField(
|
||||||
|
value = state.username,
|
||||||
|
onValueChange = onUsernameChange,
|
||||||
|
label = { Text("Username") },
|
||||||
|
singleLine = true,
|
||||||
|
modifier = Modifier.fillMaxWidth(),
|
||||||
|
)
|
||||||
|
|
||||||
|
Spacer(Modifier.height(12.dp))
|
||||||
|
|
||||||
|
OutlinedTextField(
|
||||||
|
value = state.password,
|
||||||
|
onValueChange = onPasswordChange,
|
||||||
|
label = { Text("Password") },
|
||||||
|
singleLine = true,
|
||||||
|
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password),
|
||||||
|
visualTransformation = if (passwordVisible) {
|
||||||
|
VisualTransformation.None
|
||||||
|
} else {
|
||||||
|
PasswordVisualTransformation()
|
||||||
|
},
|
||||||
|
trailingIcon = {
|
||||||
|
TextButton(onClick = { passwordVisible = !passwordVisible }) {
|
||||||
|
Text(if (passwordVisible) "Hide" else "Show")
|
||||||
|
}
|
||||||
|
},
|
||||||
|
modifier = Modifier.fillMaxWidth(),
|
||||||
|
)
|
||||||
|
|
||||||
|
Spacer(Modifier.height(4.dp))
|
||||||
|
Text(
|
||||||
|
"Stored sealed with a key held in the Android Keystore, never " +
|
||||||
|
"in the clear.",
|
||||||
|
color = GruvFg4,
|
||||||
|
style = MaterialTheme.typography.bodySmall,
|
||||||
|
)
|
||||||
|
|
||||||
|
Spacer(Modifier.height(24.dp))
|
||||||
|
|
||||||
|
Button(
|
||||||
|
onClick = onSave,
|
||||||
|
enabled = !state.testing,
|
||||||
|
modifier = Modifier.fillMaxWidth(),
|
||||||
|
) {
|
||||||
|
Text(if (state.testing) "Testing…" else "Save and test connection")
|
||||||
|
}
|
||||||
|
|
||||||
|
state.message?.let {
|
||||||
|
Spacer(Modifier.height(12.dp))
|
||||||
|
Text(it, color = if (state.messageIsError) GruvRed else GruvAqua)
|
||||||
|
}
|
||||||
|
|
||||||
|
onBack?.let {
|
||||||
|
Spacer(Modifier.height(16.dp))
|
||||||
|
TextButton(onClick = it) { Text("← Back") }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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 + ", "
|
||||||
|
}
|
||||||
@@ -0,0 +1,40 @@
|
|||||||
|
package ws.inflo.photogallery.ui
|
||||||
|
|
||||||
|
import androidx.compose.material3.MaterialTheme
|
||||||
|
import androidx.compose.material3.darkColorScheme
|
||||||
|
import androidx.compose.runtime.Composable
|
||||||
|
import androidx.compose.ui.graphics.Color
|
||||||
|
|
||||||
|
// Gruvbox dark hard, same values as static/style.css in the gallery.
|
||||||
|
val GruvBg = Color(0xFF1D2021)
|
||||||
|
val GruvBg0 = Color(0xFF282828)
|
||||||
|
val GruvBg1 = Color(0xFF3C3836)
|
||||||
|
val GruvBg2 = Color(0xFF504945)
|
||||||
|
val GruvFg = Color(0xFFEBDBB2)
|
||||||
|
val GruvFg3 = Color(0xFFBDAE93)
|
||||||
|
val GruvFg4 = Color(0xFFA89984)
|
||||||
|
val GruvAqua = Color(0xFF8EC07C)
|
||||||
|
val GruvGreen = Color(0xFF98971A)
|
||||||
|
val GruvBlue = Color(0xFF458588)
|
||||||
|
val GruvRed = Color(0xFFFB4934)
|
||||||
|
|
||||||
|
private val GruvboxDark = darkColorScheme(
|
||||||
|
primary = GruvAqua,
|
||||||
|
onPrimary = GruvBg,
|
||||||
|
secondary = GruvBlue,
|
||||||
|
onSecondary = GruvFg,
|
||||||
|
background = GruvBg,
|
||||||
|
onBackground = GruvFg,
|
||||||
|
surface = GruvBg0,
|
||||||
|
onSurface = GruvFg,
|
||||||
|
surfaceVariant = GruvBg1,
|
||||||
|
onSurfaceVariant = GruvFg3,
|
||||||
|
outline = GruvBg2,
|
||||||
|
error = GruvRed,
|
||||||
|
onError = GruvBg,
|
||||||
|
)
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
fun PhotoGalleryTheme(content: @Composable () -> Unit) {
|
||||||
|
MaterialTheme(colorScheme = GruvboxDark, content = content)
|
||||||
|
}
|
||||||
@@ -0,0 +1,419 @@
|
|||||||
|
package ws.inflo.photogallery.ui
|
||||||
|
|
||||||
|
import android.app.Application
|
||||||
|
import android.graphics.Bitmap
|
||||||
|
import android.net.Uri
|
||||||
|
import androidx.core.net.toUri
|
||||||
|
import androidx.lifecycle.AndroidViewModel
|
||||||
|
import androidx.lifecycle.viewModelScope
|
||||||
|
import androidx.compose.runtime.getValue
|
||||||
|
import androidx.compose.runtime.mutableStateOf
|
||||||
|
import androidx.compose.runtime.setValue
|
||||||
|
import androidx.work.WorkInfo
|
||||||
|
import androidx.work.WorkManager
|
||||||
|
import kotlinx.coroutines.Dispatchers
|
||||||
|
import kotlinx.coroutines.launch
|
||||||
|
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. */
|
||||||
|
sealed interface ItemStatus {
|
||||||
|
data object Pending : ItemStatus
|
||||||
|
data object Uploading : ItemStatus
|
||||||
|
data class Success(val url: String, val note: String?) : ItemStatus
|
||||||
|
data class Error(val message: String) : ItemStatus
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* One photo in the batch. A single-photo post (picker or share) is just a
|
||||||
|
* batch of one, so the whole screen runs a single code path.
|
||||||
|
*/
|
||||||
|
data class PickedItem(
|
||||||
|
val id: String = UUID.randomUUID().toString(),
|
||||||
|
val source: Uri,
|
||||||
|
val preview: Bitmap? = null,
|
||||||
|
val caption: String = "",
|
||||||
|
val tags: String = "", // raw comma-separated; the server normalizes
|
||||||
|
val date: LocalDate = LocalDate.now(),
|
||||||
|
val status: ItemStatus = ItemStatus.Pending,
|
||||||
|
)
|
||||||
|
|
||||||
|
data class PostUiState(
|
||||||
|
val items: List<PickedItem> = emptyList(),
|
||||||
|
val lastPost: LastPost? = null,
|
||||||
|
) {
|
||||||
|
val posting: Boolean get() = items.any { it.status is ItemStatus.Uploading }
|
||||||
|
val hasItems: Boolean get() = items.isNotEmpty()
|
||||||
|
val succeeded: Int get() = items.count { it.status is ItemStatus.Success }
|
||||||
|
val failed: Int get() = items.count { it.status is ItemStatus.Error }
|
||||||
|
/** True once every item has reached a terminal state and at least one ran. */
|
||||||
|
val allDone: Boolean
|
||||||
|
get() = items.isNotEmpty() &&
|
||||||
|
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 = "",
|
||||||
|
val password: String = "",
|
||||||
|
val testing: Boolean = false,
|
||||||
|
val message: String? = null,
|
||||||
|
val messageIsError: Boolean = false,
|
||||||
|
)
|
||||||
|
|
||||||
|
class UploadViewModel(app: Application) : AndroidViewModel(app) {
|
||||||
|
|
||||||
|
private val settings = SettingsStore(app)
|
||||||
|
|
||||||
|
var post by mutableStateOf(PostUiState(lastPost = settings.lastPost))
|
||||||
|
private set
|
||||||
|
|
||||||
|
var config by mutableStateOf(
|
||||||
|
SettingsUiState(
|
||||||
|
baseUrl = settings.baseUrl,
|
||||||
|
username = settings.username,
|
||||||
|
password = settings.password,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
private set
|
||||||
|
|
||||||
|
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)
|
||||||
|
|
||||||
|
val context = getApplication<Application>()
|
||||||
|
for (item in items) {
|
||||||
|
viewModelScope.launch {
|
||||||
|
val preview = withContext(Dispatchers.IO) {
|
||||||
|
ImagePrep.preview(context, item.source, maxDimension = 256)
|
||||||
|
}
|
||||||
|
val captured = withContext(Dispatchers.IO) {
|
||||||
|
ImagePrep.captureDate(context, item.source)
|
||||||
|
}
|
||||||
|
updateItem(item.id) {
|
||||||
|
it.copy(preview = preview, date = captured ?: it.date)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun setCaption(id: String, value: String) {
|
||||||
|
updateItem(id) { it.copy(caption = value) }
|
||||||
|
}
|
||||||
|
|
||||||
|
fun setTags(id: String, value: String) {
|
||||||
|
updateItem(id) { it.copy(tags = value) }
|
||||||
|
}
|
||||||
|
|
||||||
|
fun setDate(id: String, value: LocalDate) {
|
||||||
|
updateItem(id) { it.copy(date = value) }
|
||||||
|
}
|
||||||
|
|
||||||
|
fun removeItem(id: String) {
|
||||||
|
// A photo already uploading keeps its worker; just drop it from the UI.
|
||||||
|
post = post.copy(items = post.items.filterNot { it.id == id })
|
||||||
|
}
|
||||||
|
|
||||||
|
fun clear() {
|
||||||
|
post = PostUiState(lastPost = settings.lastPost)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Uploads every item not already posted. Re-running retries only failures. */
|
||||||
|
fun submit() {
|
||||||
|
if (!settings.isConfigured) {
|
||||||
|
post = post.copy(
|
||||||
|
items = post.items.map {
|
||||||
|
if (it.status is ItemStatus.Success) it
|
||||||
|
else it.copy(status = ItemStatus.Error("Set the server URL and credentials first"))
|
||||||
|
},
|
||||||
|
)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
val pending = post.items.filter { it.status !is ItemStatus.Success }
|
||||||
|
if (pending.isEmpty()) return
|
||||||
|
|
||||||
|
val context = getApplication<Application>()
|
||||||
|
for (item in pending) {
|
||||||
|
updateItem(item.id) { it.copy(status = ItemStatus.Uploading) }
|
||||||
|
viewModelScope.launch {
|
||||||
|
val staged = withContext(Dispatchers.IO) { stage(item.source) }
|
||||||
|
if (staged == null) {
|
||||||
|
updateItem(item.id) {
|
||||||
|
it.copy(status = ItemStatus.Error("Could not read the selected image"))
|
||||||
|
}
|
||||||
|
return@launch
|
||||||
|
}
|
||||||
|
val current = post.items.firstOrNull { it.id == item.id } ?: return@launch
|
||||||
|
val workId = UploadQueue.enqueue(
|
||||||
|
context = context,
|
||||||
|
uri = Uri.fromFile(staged),
|
||||||
|
caption = current.caption,
|
||||||
|
date = current.date,
|
||||||
|
tags = current.tags,
|
||||||
|
uniqueSuffix = item.id.take(6),
|
||||||
|
)
|
||||||
|
observe(item.id, workId)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun stage(uri: Uri): File? {
|
||||||
|
return try {
|
||||||
|
val context = getApplication<Application>()
|
||||||
|
val target = File(context.cacheDir, "staged-${UUID.randomUUID()}")
|
||||||
|
val copied = context.contentResolver.openInputStream(uri)?.use { input ->
|
||||||
|
target.outputStream().use { output -> input.copyTo(output) }
|
||||||
|
}
|
||||||
|
if (copied == null) null else target
|
||||||
|
} catch (_: Exception) {
|
||||||
|
null
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun observe(itemId: String, workId: UUID) {
|
||||||
|
viewModelScope.launch {
|
||||||
|
WorkManager.getInstance(getApplication()).getWorkInfoByIdFlow(workId).collect { info ->
|
||||||
|
if (info == null) return@collect
|
||||||
|
when (info.state) {
|
||||||
|
WorkInfo.State.SUCCEEDED -> {
|
||||||
|
updateItem(itemId) {
|
||||||
|
it.copy(
|
||||||
|
status = ItemStatus.Success(
|
||||||
|
url = info.outputData.getString(UploadWorker.KEY_RESULT_URL).orEmpty(),
|
||||||
|
note = info.outputData.getString(UploadWorker.KEY_RESULT_NOTE),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
post = post.copy(lastPost = settings.lastPost)
|
||||||
|
}
|
||||||
|
|
||||||
|
WorkInfo.State.FAILED -> updateItem(itemId) {
|
||||||
|
it.copy(
|
||||||
|
status = ItemStatus.Error(
|
||||||
|
info.outputData.getString(UploadWorker.KEY_RESULT_ERROR)
|
||||||
|
?: "Upload failed",
|
||||||
|
),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
WorkInfo.State.CANCELLED -> updateItem(itemId) {
|
||||||
|
it.copy(status = ItemStatus.Error("Upload cancelled"))
|
||||||
|
}
|
||||||
|
|
||||||
|
else -> Unit
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private inline fun updateItem(id: String, transform: (PickedItem) -> PickedItem) {
|
||||||
|
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) {
|
||||||
|
config = config.copy(baseUrl = value, message = null)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun setUsername(value: String) {
|
||||||
|
config = config.copy(username = value, message = null)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun setPassword(value: String) {
|
||||||
|
config = config.copy(password = value, message = null)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun saveAndTest() {
|
||||||
|
val urlError = SettingsStore.validateBaseUrl(config.baseUrl)
|
||||||
|
if (urlError != null) {
|
||||||
|
config = config.copy(message = urlError, messageIsError = true)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if (config.username.isBlank() || config.password.isBlank()) {
|
||||||
|
config = config.copy(
|
||||||
|
message = "Username and password are required",
|
||||||
|
messageIsError = true,
|
||||||
|
)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
settings.baseUrl = config.baseUrl
|
||||||
|
settings.username = config.username
|
||||||
|
settings.password = config.password
|
||||||
|
|
||||||
|
config = config.copy(testing = true, message = null)
|
||||||
|
|
||||||
|
viewModelScope.launch {
|
||||||
|
val error = withContext(Dispatchers.IO) {
|
||||||
|
UploadClient(settings.baseUrl, settings.username, settings.password)
|
||||||
|
.testConnection()
|
||||||
|
}
|
||||||
|
config = config.copy(
|
||||||
|
testing = false,
|
||||||
|
message = error ?: "Saved — server reachable and credentials accepted",
|
||||||
|
messageIsError = error != null,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,69 @@
|
|||||||
|
package ws.inflo.photogallery.work
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import android.net.Uri
|
||||||
|
import androidx.work.Constraints
|
||||||
|
import androidx.work.Data
|
||||||
|
import androidx.work.ExistingWorkPolicy
|
||||||
|
import androidx.work.NetworkType
|
||||||
|
import androidx.work.OneTimeWorkRequestBuilder
|
||||||
|
import androidx.work.OutOfQuotaPolicy
|
||||||
|
import androidx.work.WorkManager
|
||||||
|
import java.time.LocalDate
|
||||||
|
import java.time.LocalDateTime
|
||||||
|
import java.time.format.DateTimeFormatter
|
||||||
|
import java.util.UUID
|
||||||
|
|
||||||
|
object UploadQueue {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Slug format. Uses the enqueue wall-clock time rather than the photo's
|
||||||
|
* capture time: capture time collides across a burst. A [uniqueSuffix] is
|
||||||
|
* appended so that a bulk post — several photos enqueued in the same second
|
||||||
|
* — cannot collide either; without it enqueueUniqueWork would silently drop
|
||||||
|
* the duplicates. The real capture date still travels in the `date` field
|
||||||
|
* and lands in the .toml sidecar.
|
||||||
|
*/
|
||||||
|
private val SLUG_FORMAT: DateTimeFormatter =
|
||||||
|
DateTimeFormatter.ofPattern("yyyy-MM-dd-HHmmss")
|
||||||
|
|
||||||
|
private val ISO_DATE: DateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd")
|
||||||
|
|
||||||
|
fun enqueue(
|
||||||
|
context: Context,
|
||||||
|
uri: Uri,
|
||||||
|
caption: String,
|
||||||
|
date: LocalDate,
|
||||||
|
tags: String,
|
||||||
|
uniqueSuffix: String,
|
||||||
|
): UUID {
|
||||||
|
val slug = LocalDateTime.now().format(SLUG_FORMAT) + "-" + uniqueSuffix
|
||||||
|
|
||||||
|
val request = OneTimeWorkRequestBuilder<UploadWorker>()
|
||||||
|
.setInputData(
|
||||||
|
Data.Builder()
|
||||||
|
.putString(UploadWorker.KEY_URI, uri.toString())
|
||||||
|
.putString(UploadWorker.KEY_SLUG, slug)
|
||||||
|
.putString(UploadWorker.KEY_CAPTION, caption)
|
||||||
|
.putString(UploadWorker.KEY_DATE, date.format(ISO_DATE))
|
||||||
|
.putString(UploadWorker.KEY_TAGS, tags)
|
||||||
|
.build(),
|
||||||
|
)
|
||||||
|
.setConstraints(
|
||||||
|
Constraints.Builder()
|
||||||
|
.setRequiredNetworkType(NetworkType.CONNECTED)
|
||||||
|
.build(),
|
||||||
|
)
|
||||||
|
.setExpedited(OutOfQuotaPolicy.RUN_AS_NON_EXPEDITED_WORK_REQUEST)
|
||||||
|
.build()
|
||||||
|
|
||||||
|
// Unique per slug, so a double tap cannot enqueue the same post twice.
|
||||||
|
WorkManager.getInstance(context).enqueueUniqueWork(
|
||||||
|
"upload-$slug",
|
||||||
|
ExistingWorkPolicy.KEEP,
|
||||||
|
request,
|
||||||
|
)
|
||||||
|
|
||||||
|
return request.id
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,163 @@
|
|||||||
|
package ws.inflo.photogallery.work
|
||||||
|
|
||||||
|
import android.app.Notification
|
||||||
|
import android.app.NotificationChannel
|
||||||
|
import android.app.NotificationManager
|
||||||
|
import android.content.Context
|
||||||
|
import android.content.pm.ServiceInfo
|
||||||
|
import android.os.Build
|
||||||
|
import androidx.core.net.toUri
|
||||||
|
import androidx.work.CoroutineWorker
|
||||||
|
import androidx.work.ForegroundInfo
|
||||||
|
import androidx.work.WorkerParameters
|
||||||
|
import kotlinx.coroutines.Dispatchers
|
||||||
|
import kotlinx.coroutines.withContext
|
||||||
|
import ws.inflo.photogallery.R
|
||||||
|
import ws.inflo.photogallery.data.LastPost
|
||||||
|
import ws.inflo.photogallery.data.SettingsStore
|
||||||
|
import ws.inflo.photogallery.image.ImagePrep
|
||||||
|
import ws.inflo.photogallery.net.UploadClient
|
||||||
|
import ws.inflo.photogallery.net.UploadOutcome
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Performs one upload, surviving the app being backgrounded or killed.
|
||||||
|
*
|
||||||
|
* Retries are safe by construction. The slug is generated once when the work
|
||||||
|
* is enqueued and carried in the input data, and server.go derives the stored
|
||||||
|
* filename from the uploaded filename — so a retry after an ambiguous timeout
|
||||||
|
* overwrites the same post rather than creating a second one. That is the only
|
||||||
|
* reason this works without an idempotency key on the server.
|
||||||
|
*/
|
||||||
|
class UploadWorker(
|
||||||
|
appContext: Context,
|
||||||
|
params: WorkerParameters,
|
||||||
|
) : CoroutineWorker(appContext, params) {
|
||||||
|
|
||||||
|
override suspend fun doWork(): Result = withContext(Dispatchers.IO) {
|
||||||
|
val uriString = inputData.getString(KEY_URI) ?: return@withContext Result.failure()
|
||||||
|
val slug = inputData.getString(KEY_SLUG) ?: return@withContext Result.failure()
|
||||||
|
val caption = inputData.getString(KEY_CAPTION).orEmpty()
|
||||||
|
val date = inputData.getString(KEY_DATE).orEmpty()
|
||||||
|
val tags = inputData.getString(KEY_TAGS).orEmpty()
|
||||||
|
|
||||||
|
val settings = SettingsStore(applicationContext)
|
||||||
|
if (!settings.isConfigured) {
|
||||||
|
return@withContext failWith("Set the server URL and credentials first")
|
||||||
|
}
|
||||||
|
|
||||||
|
val prepared = try {
|
||||||
|
ImagePrep.prepare(
|
||||||
|
context = applicationContext,
|
||||||
|
uri = uriString.toUri(),
|
||||||
|
cacheDir = applicationContext.cacheDir,
|
||||||
|
baseName = slug,
|
||||||
|
)
|
||||||
|
} catch (e: Exception) {
|
||||||
|
return@withContext failWith(e.message ?: "Could not read the image")
|
||||||
|
}
|
||||||
|
|
||||||
|
val client = UploadClient(
|
||||||
|
baseUrl = settings.baseUrl,
|
||||||
|
username = settings.username,
|
||||||
|
password = settings.password,
|
||||||
|
)
|
||||||
|
|
||||||
|
val outcome = client.upload(
|
||||||
|
file = prepared.file,
|
||||||
|
fileName = prepared.file.name,
|
||||||
|
caption = caption,
|
||||||
|
date = date,
|
||||||
|
tags = tags,
|
||||||
|
)
|
||||||
|
|
||||||
|
// Keep the staged and prepared copies only while a retry might still
|
||||||
|
// need them.
|
||||||
|
if (outcome !is UploadOutcome.Transient) {
|
||||||
|
prepared.file.delete()
|
||||||
|
deleteStagedSource(uriString)
|
||||||
|
}
|
||||||
|
|
||||||
|
when (outcome) {
|
||||||
|
is UploadOutcome.Success -> {
|
||||||
|
settings.lastPost = LastPost(
|
||||||
|
slug = outcome.slug,
|
||||||
|
url = outcome.url,
|
||||||
|
caption = caption,
|
||||||
|
postedAtMillis = System.currentTimeMillis(),
|
||||||
|
)
|
||||||
|
Result.success(
|
||||||
|
androidx.work.Data.Builder()
|
||||||
|
.putString(KEY_RESULT_SLUG, outcome.slug)
|
||||||
|
.putString(KEY_RESULT_URL, outcome.url)
|
||||||
|
.putString(KEY_RESULT_NOTE, prepared.note)
|
||||||
|
.build(),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
UploadOutcome.AuthFailed -> failWith("Wrong username or password")
|
||||||
|
|
||||||
|
is UploadOutcome.Rejected -> failWith(outcome.message)
|
||||||
|
|
||||||
|
is UploadOutcome.Transient ->
|
||||||
|
if (runAttemptCount < MAX_ATTEMPTS) Result.retry()
|
||||||
|
else failWith(outcome.message)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Removes the copy the UI staged in our cache, never anything outside it. */
|
||||||
|
private fun deleteStagedSource(uriString: String) {
|
||||||
|
val uri = uriString.toUri()
|
||||||
|
if (uri.scheme != "file") return
|
||||||
|
val file = java.io.File(uri.path ?: return)
|
||||||
|
if (file.parentFile == applicationContext.cacheDir) file.delete()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun failWith(message: String) = Result.failure(
|
||||||
|
androidx.work.Data.Builder().putString(KEY_RESULT_ERROR, message).build(),
|
||||||
|
)
|
||||||
|
|
||||||
|
override suspend fun getForegroundInfo(): ForegroundInfo {
|
||||||
|
val manager = applicationContext
|
||||||
|
.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
|
||||||
|
|
||||||
|
if (manager.getNotificationChannel(CHANNEL_ID) == null) {
|
||||||
|
manager.createNotificationChannel(
|
||||||
|
NotificationChannel(
|
||||||
|
CHANNEL_ID,
|
||||||
|
applicationContext.getString(R.string.upload_channel_name),
|
||||||
|
NotificationManager.IMPORTANCE_LOW,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
val notification: Notification = Notification.Builder(applicationContext, CHANNEL_ID)
|
||||||
|
.setContentTitle(applicationContext.getString(R.string.app_name))
|
||||||
|
.setContentText("Posting photo…")
|
||||||
|
.setSmallIcon(android.R.drawable.stat_sys_upload)
|
||||||
|
.setOngoing(true)
|
||||||
|
.build()
|
||||||
|
|
||||||
|
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
|
||||||
|
ForegroundInfo(NOTIFICATION_ID, notification, ServiceInfo.FOREGROUND_SERVICE_TYPE_DATA_SYNC)
|
||||||
|
} else {
|
||||||
|
ForegroundInfo(NOTIFICATION_ID, notification)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
companion object {
|
||||||
|
const val KEY_URI = "uri"
|
||||||
|
const val KEY_SLUG = "slug"
|
||||||
|
const val KEY_CAPTION = "caption"
|
||||||
|
const val KEY_DATE = "date"
|
||||||
|
const val KEY_TAGS = "tags"
|
||||||
|
|
||||||
|
const val KEY_RESULT_SLUG = "result_slug"
|
||||||
|
const val KEY_RESULT_URL = "result_url"
|
||||||
|
const val KEY_RESULT_NOTE = "result_note"
|
||||||
|
const val KEY_RESULT_ERROR = "result_error"
|
||||||
|
|
||||||
|
private const val MAX_ATTEMPTS = 5
|
||||||
|
private const val CHANNEL_ID = "uploads"
|
||||||
|
private const val NOTIFICATION_ID = 4711
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
|
<!-- minSdk is 28, so every device resolves the v26 adaptive icon and no
|
||||||
|
density-bucket PNG fallbacks are needed. The foreground is the full circular
|
||||||
|
app icon (ic_launcher_foreground.png); the launcher mask crops the disc to
|
||||||
|
its shape, and the solid gruvbox background fills the transparent corners. -->
|
||||||
|
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
|
||||||
|
<background android:drawable="@color/gruvbox_bg" />
|
||||||
|
<foreground android:drawable="@mipmap/ic_launcher_foreground" />
|
||||||
|
</adaptive-icon>
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
|
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
|
||||||
|
<background android:drawable="@color/gruvbox_bg" />
|
||||||
|
<foreground android:drawable="@mipmap/ic_launcher_foreground" />
|
||||||
|
</adaptive-icon>
|
||||||
|
After Width: | Height: | Size: 87 KiB |
@@ -0,0 +1,8 @@
|
|||||||
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
|
<!-- Gruvbox dark hard, matching static/style.css in the gallery itself. -->
|
||||||
|
<resources>
|
||||||
|
<color name="gruvbox_bg">#1d2021</color>
|
||||||
|
<color name="gruvbox_bg0">#282828</color>
|
||||||
|
<color name="gruvbox_fg">#ebdbb2</color>
|
||||||
|
<color name="gruvbox_aqua">#8ec07c</color>
|
||||||
|
</resources>
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
|
<resources>
|
||||||
|
<string name="app_name">Photog</string>
|
||||||
|
<string name="upload_channel_name">Uploads</string>
|
||||||
|
</resources>
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
|
<resources>
|
||||||
|
<!-- Platform parent rather than Theme.Material3.* so the app does not need
|
||||||
|
the View-based material-components dependency. Compose supplies the
|
||||||
|
real theming; this only prevents a white flash before it composes. -->
|
||||||
|
<style name="Theme.PhotoGalleryUploader" parent="@android:style/Theme.Material.NoActionBar">
|
||||||
|
<item name="android:windowBackground">@color/gruvbox_bg</item>
|
||||||
|
<item name="android:statusBarColor">@color/gruvbox_bg</item>
|
||||||
|
<item name="android:navigationBarColor">@color/gruvbox_bg</item>
|
||||||
|
</style>
|
||||||
|
</resources>
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
plugins {
|
||||||
|
alias(libs.plugins.android.application) apply false
|
||||||
|
alias(libs.plugins.kotlin.android) apply false
|
||||||
|
alias(libs.plugins.kotlin.compose) apply false
|
||||||
|
}
|
||||||
@@ -0,0 +1,139 @@
|
|||||||
|
{
|
||||||
|
"nodes": {
|
||||||
|
"android-nixpkgs": {
|
||||||
|
"inputs": {
|
||||||
|
"devshell": "devshell",
|
||||||
|
"flake-utils": "flake-utils",
|
||||||
|
"nixpkgs": [
|
||||||
|
"nixpkgs"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"locked": {
|
||||||
|
"lastModified": 1786567347,
|
||||||
|
"narHash": "sha256-I52DnM27HeCMJMgCEyNb5wz8prz6GOjzIxJnvF0ezD0=",
|
||||||
|
"owner": "tadfisher",
|
||||||
|
"repo": "android-nixpkgs",
|
||||||
|
"rev": "ccdf76eeb9011ad795cca84d1cc4bd9baa9a7329",
|
||||||
|
"type": "github"
|
||||||
|
},
|
||||||
|
"original": {
|
||||||
|
"owner": "tadfisher",
|
||||||
|
"ref": "stable",
|
||||||
|
"repo": "android-nixpkgs",
|
||||||
|
"type": "github"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"devshell": {
|
||||||
|
"inputs": {
|
||||||
|
"nixpkgs": [
|
||||||
|
"android-nixpkgs",
|
||||||
|
"nixpkgs"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"locked": {
|
||||||
|
"lastModified": 1768818222,
|
||||||
|
"narHash": "sha256-460jc0+CZfyaO8+w8JNtlClB2n4ui1RbHfPTLkpwhU8=",
|
||||||
|
"owner": "numtide",
|
||||||
|
"repo": "devshell",
|
||||||
|
"rev": "255a2b1725a20d060f566e4755dbf571bbbb5f76",
|
||||||
|
"type": "github"
|
||||||
|
},
|
||||||
|
"original": {
|
||||||
|
"owner": "numtide",
|
||||||
|
"repo": "devshell",
|
||||||
|
"type": "github"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"flake-utils": {
|
||||||
|
"inputs": {
|
||||||
|
"systems": "systems"
|
||||||
|
},
|
||||||
|
"locked": {
|
||||||
|
"lastModified": 1731533236,
|
||||||
|
"narHash": "sha256-l0KFg5HjrsfsO/JpG+r7fRrqm12kzFHyUHqHCVpMMbI=",
|
||||||
|
"owner": "numtide",
|
||||||
|
"repo": "flake-utils",
|
||||||
|
"rev": "11707dc2f618dd54ca8739b309ec4fc024de578b",
|
||||||
|
"type": "github"
|
||||||
|
},
|
||||||
|
"original": {
|
||||||
|
"owner": "numtide",
|
||||||
|
"repo": "flake-utils",
|
||||||
|
"type": "github"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"flake-utils_2": {
|
||||||
|
"inputs": {
|
||||||
|
"systems": "systems_2"
|
||||||
|
},
|
||||||
|
"locked": {
|
||||||
|
"lastModified": 1731533236,
|
||||||
|
"narHash": "sha256-l0KFg5HjrsfsO/JpG+r7fRrqm12kzFHyUHqHCVpMMbI=",
|
||||||
|
"owner": "numtide",
|
||||||
|
"repo": "flake-utils",
|
||||||
|
"rev": "11707dc2f618dd54ca8739b309ec4fc024de578b",
|
||||||
|
"type": "github"
|
||||||
|
},
|
||||||
|
"original": {
|
||||||
|
"owner": "numtide",
|
||||||
|
"repo": "flake-utils",
|
||||||
|
"type": "github"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"nixpkgs": {
|
||||||
|
"locked": {
|
||||||
|
"lastModified": 1786599213,
|
||||||
|
"narHash": "sha256-yNJd40f11EzXBjSByCB7IPpeFFAdeoSKKM67dGkfFoU=",
|
||||||
|
"owner": "NixOS",
|
||||||
|
"repo": "nixpkgs",
|
||||||
|
"rev": "0e251e24a4f24e036a084b6b4b2d2491af4167f4",
|
||||||
|
"type": "github"
|
||||||
|
},
|
||||||
|
"original": {
|
||||||
|
"owner": "NixOS",
|
||||||
|
"ref": "nixos-unstable",
|
||||||
|
"repo": "nixpkgs",
|
||||||
|
"type": "github"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"root": {
|
||||||
|
"inputs": {
|
||||||
|
"android-nixpkgs": "android-nixpkgs",
|
||||||
|
"flake-utils": "flake-utils_2",
|
||||||
|
"nixpkgs": "nixpkgs"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"systems": {
|
||||||
|
"locked": {
|
||||||
|
"lastModified": 1681028828,
|
||||||
|
"narHash": "sha256-Vy1rq5AaRuLzOxct8nz4T6wlgyUR7zLU309k9mBC768=",
|
||||||
|
"owner": "nix-systems",
|
||||||
|
"repo": "default",
|
||||||
|
"rev": "da67096a3b9bf56a91d16901293e51ba5b49a27e",
|
||||||
|
"type": "github"
|
||||||
|
},
|
||||||
|
"original": {
|
||||||
|
"owner": "nix-systems",
|
||||||
|
"repo": "default",
|
||||||
|
"type": "github"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"systems_2": {
|
||||||
|
"locked": {
|
||||||
|
"lastModified": 1681028828,
|
||||||
|
"narHash": "sha256-Vy1rq5AaRuLzOxct8nz4T6wlgyUR7zLU309k9mBC768=",
|
||||||
|
"owner": "nix-systems",
|
||||||
|
"repo": "default",
|
||||||
|
"rev": "da67096a3b9bf56a91d16901293e51ba5b49a27e",
|
||||||
|
"type": "github"
|
||||||
|
},
|
||||||
|
"original": {
|
||||||
|
"owner": "nix-systems",
|
||||||
|
"repo": "default",
|
||||||
|
"type": "github"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"root": "root",
|
||||||
|
"version": 7
|
||||||
|
}
|
||||||
@@ -0,0 +1,60 @@
|
|||||||
|
{
|
||||||
|
description = "photogallery Android uploader dev shell";
|
||||||
|
|
||||||
|
inputs = {
|
||||||
|
nixpkgs.url = "github:NixOS/nixpkgs/nixos-unstable";
|
||||||
|
flake-utils.url = "github:numtide/flake-utils";
|
||||||
|
|
||||||
|
# Reproducible Android SDK across NixOS + macOS without the nixpkgs
|
||||||
|
# androidenv read-only-SDK-root quirks.
|
||||||
|
android-nixpkgs = {
|
||||||
|
url = "github:tadfisher/android-nixpkgs/stable";
|
||||||
|
inputs.nixpkgs.follows = "nixpkgs";
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
outputs = { self, nixpkgs, flake-utils, android-nixpkgs }:
|
||||||
|
flake-utils.lib.eachDefaultSystem (system:
|
||||||
|
let
|
||||||
|
pkgs = import nixpkgs {
|
||||||
|
inherit system;
|
||||||
|
config.allowUnfree = true; # Android SDK is unfree
|
||||||
|
};
|
||||||
|
|
||||||
|
buildToolsVersion = "36.0.0";
|
||||||
|
|
||||||
|
# SDK components for the Compose app. Pinned to the exact versions
|
||||||
|
# the Gradle config requests — adding extras only inflates the
|
||||||
|
# closure. When AGP bumps any of these, the build error names the
|
||||||
|
# exact missing version: look it up in `android-nixpkgs` and replace
|
||||||
|
# the line. No NDK or CMake: there is no native code in this app.
|
||||||
|
androidSdk = android-nixpkgs.sdk.${system} (sdkPkgs: with sdkPkgs; [
|
||||||
|
cmdline-tools-latest # sdkmanager, avdmanager
|
||||||
|
platform-tools # adb, for sideloading to the phone
|
||||||
|
platforms-android-36 # compileSdk / targetSdk
|
||||||
|
build-tools-36-0-0 # aapt2, d8, zipalign
|
||||||
|
build-tools-35-0-0 # AGP 8.x resolves this one too, and the
|
||||||
|
# nix store is read-only so it cannot
|
||||||
|
# download it itself
|
||||||
|
]);
|
||||||
|
in {
|
||||||
|
devShells.default = pkgs.mkShell {
|
||||||
|
packages = [
|
||||||
|
pkgs.jdk17 # AGP 8.x toolchain
|
||||||
|
pkgs.gradle # bootstraps ./gradlew, then the wrapper takes over
|
||||||
|
androidSdk
|
||||||
|
];
|
||||||
|
|
||||||
|
shellHook = ''
|
||||||
|
export ANDROID_HOME="${androidSdk}/share/android-sdk"
|
||||||
|
export ANDROID_SDK_ROOT="$ANDROID_HOME"
|
||||||
|
export JAVA_HOME="${pkgs.jdk17.home}"
|
||||||
|
|
||||||
|
# AGP downloads aapt2 from Maven by default. The Maven binary is
|
||||||
|
# generic-linux ELF and won't run on NixOS. Force Gradle to use the
|
||||||
|
# patchelfed aapt2 shipped in our pinned build-tools instead.
|
||||||
|
export GRADLE_OPTS="-Dorg.gradle.project.android.aapt2FromMavenOverride=$ANDROID_HOME/build-tools/${buildToolsVersion}/aapt2"
|
||||||
|
'';
|
||||||
|
};
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
org.gradle.jvmargs=-Xmx4g -XX:MaxMetaspaceSize=1g
|
||||||
|
org.gradle.parallel=true
|
||||||
|
org.gradle.caching=true
|
||||||
|
|
||||||
|
android.useAndroidX=true
|
||||||
|
android.nonTransitiveRClass=true
|
||||||
|
|
||||||
|
kotlin.code.style=official
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
[versions]
|
||||||
|
agp = "8.13.0"
|
||||||
|
kotlin = "2.2.20"
|
||||||
|
coreKtx = "1.17.0"
|
||||||
|
lifecycle = "2.9.4"
|
||||||
|
activityCompose = "1.11.0"
|
||||||
|
composeBom = "2025.09.00"
|
||||||
|
work = "2.10.5"
|
||||||
|
okhttp = "4.12.0"
|
||||||
|
exifinterface = "1.4.1"
|
||||||
|
|
||||||
|
[libraries]
|
||||||
|
androidx-core-ktx = { group = "androidx.core", name = "core-ktx", version.ref = "coreKtx" }
|
||||||
|
androidx-lifecycle-runtime-ktx = { group = "androidx.lifecycle", name = "lifecycle-runtime-ktx", version.ref = "lifecycle" }
|
||||||
|
androidx-lifecycle-viewmodel-compose = { group = "androidx.lifecycle", name = "lifecycle-viewmodel-compose", version.ref = "lifecycle" }
|
||||||
|
androidx-activity-compose = { group = "androidx.activity", name = "activity-compose", version.ref = "activityCompose" }
|
||||||
|
androidx-compose-bom = { group = "androidx.compose", name = "compose-bom", version.ref = "composeBom" }
|
||||||
|
androidx-ui = { group = "androidx.compose.ui", name = "ui" }
|
||||||
|
androidx-ui-graphics = { group = "androidx.compose.ui", name = "ui-graphics" }
|
||||||
|
androidx-ui-tooling = { group = "androidx.compose.ui", name = "ui-tooling" }
|
||||||
|
androidx-ui-tooling-preview = { group = "androidx.compose.ui", name = "ui-tooling-preview" }
|
||||||
|
androidx-material3 = { group = "androidx.compose.material3", name = "material3" }
|
||||||
|
androidx-work-runtime-ktx = { group = "androidx.work", name = "work-runtime-ktx", version.ref = "work" }
|
||||||
|
androidx-exifinterface = { group = "androidx.exifinterface", name = "exifinterface", version.ref = "exifinterface" }
|
||||||
|
okhttp = { group = "com.squareup.okhttp3", name = "okhttp", version.ref = "okhttp" }
|
||||||
|
|
||||||
|
[plugins]
|
||||||
|
android-application = { id = "com.android.application", version.ref = "agp" }
|
||||||
|
kotlin-android = { id = "org.jetbrains.kotlin.android", version.ref = "kotlin" }
|
||||||
|
kotlin-compose = { id = "org.jetbrains.kotlin.plugin.compose", version.ref = "kotlin" }
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
distributionBase=GRADLE_USER_HOME
|
||||||
|
distributionPath=wrapper/dists
|
||||||
|
distributionUrl=https\://services.gradle.org/distributions/gradle-8.14.4-bin.zip
|
||||||
|
networkTimeout=10000
|
||||||
|
validateDistributionUrl=true
|
||||||
|
zipStoreBase=GRADLE_USER_HOME
|
||||||
|
zipStorePath=wrapper/dists
|
||||||
@@ -0,0 +1,251 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
|
||||||
|
#
|
||||||
|
# Copyright © 2015-2021 the original authors.
|
||||||
|
#
|
||||||
|
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
# you may not use this file except in compliance with the License.
|
||||||
|
# You may obtain a copy of the License at
|
||||||
|
#
|
||||||
|
# https://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
#
|
||||||
|
# Unless required by applicable law or agreed to in writing, software
|
||||||
|
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
# See the License for the specific language governing permissions and
|
||||||
|
# limitations under the License.
|
||||||
|
#
|
||||||
|
# SPDX-License-Identifier: Apache-2.0
|
||||||
|
#
|
||||||
|
|
||||||
|
##############################################################################
|
||||||
|
#
|
||||||
|
# Gradle start up script for POSIX generated by Gradle.
|
||||||
|
#
|
||||||
|
# Important for running:
|
||||||
|
#
|
||||||
|
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
|
||||||
|
# noncompliant, but you have some other compliant shell such as ksh or
|
||||||
|
# bash, then to run this script, type that shell name before the whole
|
||||||
|
# command line, like:
|
||||||
|
#
|
||||||
|
# ksh Gradle
|
||||||
|
#
|
||||||
|
# Busybox and similar reduced shells will NOT work, because this script
|
||||||
|
# requires all of these POSIX shell features:
|
||||||
|
# * functions;
|
||||||
|
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
|
||||||
|
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
|
||||||
|
# * compound commands having a testable exit status, especially «case»;
|
||||||
|
# * various built-in commands including «command», «set», and «ulimit».
|
||||||
|
#
|
||||||
|
# Important for patching:
|
||||||
|
#
|
||||||
|
# (2) This script targets any POSIX shell, so it avoids extensions provided
|
||||||
|
# by Bash, Ksh, etc; in particular arrays are avoided.
|
||||||
|
#
|
||||||
|
# The "traditional" practice of packing multiple parameters into a
|
||||||
|
# space-separated string is a well documented source of bugs and security
|
||||||
|
# problems, so this is (mostly) avoided, by progressively accumulating
|
||||||
|
# options in "$@", and eventually passing that to Java.
|
||||||
|
#
|
||||||
|
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
|
||||||
|
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
|
||||||
|
# see the in-line comments for details.
|
||||||
|
#
|
||||||
|
# There are tweaks for specific operating systems such as AIX, CygWin,
|
||||||
|
# Darwin, MinGW, and NonStop.
|
||||||
|
#
|
||||||
|
# (3) This script is generated from the Groovy template
|
||||||
|
# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
|
||||||
|
# within the Gradle project.
|
||||||
|
#
|
||||||
|
# You can find Gradle at https://github.com/gradle/gradle/.
|
||||||
|
#
|
||||||
|
##############################################################################
|
||||||
|
|
||||||
|
# Attempt to set APP_HOME
|
||||||
|
|
||||||
|
# Resolve links: $0 may be a link
|
||||||
|
app_path=$0
|
||||||
|
|
||||||
|
# Need this for daisy-chained symlinks.
|
||||||
|
while
|
||||||
|
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
|
||||||
|
[ -h "$app_path" ]
|
||||||
|
do
|
||||||
|
ls=$( ls -ld "$app_path" )
|
||||||
|
link=${ls#*' -> '}
|
||||||
|
case $link in #(
|
||||||
|
/*) app_path=$link ;; #(
|
||||||
|
*) app_path=$APP_HOME$link ;;
|
||||||
|
esac
|
||||||
|
done
|
||||||
|
|
||||||
|
# This is normally unused
|
||||||
|
# shellcheck disable=SC2034
|
||||||
|
APP_BASE_NAME=${0##*/}
|
||||||
|
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
|
||||||
|
APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit
|
||||||
|
|
||||||
|
# Use the maximum available, or set MAX_FD != -1 to use that value.
|
||||||
|
MAX_FD=maximum
|
||||||
|
|
||||||
|
warn () {
|
||||||
|
echo "$*"
|
||||||
|
} >&2
|
||||||
|
|
||||||
|
die () {
|
||||||
|
echo
|
||||||
|
echo "$*"
|
||||||
|
echo
|
||||||
|
exit 1
|
||||||
|
} >&2
|
||||||
|
|
||||||
|
# OS specific support (must be 'true' or 'false').
|
||||||
|
cygwin=false
|
||||||
|
msys=false
|
||||||
|
darwin=false
|
||||||
|
nonstop=false
|
||||||
|
case "$( uname )" in #(
|
||||||
|
CYGWIN* ) cygwin=true ;; #(
|
||||||
|
Darwin* ) darwin=true ;; #(
|
||||||
|
MSYS* | MINGW* ) msys=true ;; #(
|
||||||
|
NONSTOP* ) nonstop=true ;;
|
||||||
|
esac
|
||||||
|
|
||||||
|
CLASSPATH="\\\"\\\""
|
||||||
|
|
||||||
|
|
||||||
|
# Determine the Java command to use to start the JVM.
|
||||||
|
if [ -n "$JAVA_HOME" ] ; then
|
||||||
|
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
|
||||||
|
# IBM's JDK on AIX uses strange locations for the executables
|
||||||
|
JAVACMD=$JAVA_HOME/jre/sh/java
|
||||||
|
else
|
||||||
|
JAVACMD=$JAVA_HOME/bin/java
|
||||||
|
fi
|
||||||
|
if [ ! -x "$JAVACMD" ] ; then
|
||||||
|
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
|
||||||
|
|
||||||
|
Please set the JAVA_HOME variable in your environment to match the
|
||||||
|
location of your Java installation."
|
||||||
|
fi
|
||||||
|
else
|
||||||
|
JAVACMD=java
|
||||||
|
if ! command -v java >/dev/null 2>&1
|
||||||
|
then
|
||||||
|
die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
|
||||||
|
|
||||||
|
Please set the JAVA_HOME variable in your environment to match the
|
||||||
|
location of your Java installation."
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Increase the maximum file descriptors if we can.
|
||||||
|
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
|
||||||
|
case $MAX_FD in #(
|
||||||
|
max*)
|
||||||
|
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
|
||||||
|
# shellcheck disable=SC2039,SC3045
|
||||||
|
MAX_FD=$( ulimit -H -n ) ||
|
||||||
|
warn "Could not query maximum file descriptor limit"
|
||||||
|
esac
|
||||||
|
case $MAX_FD in #(
|
||||||
|
'' | soft) :;; #(
|
||||||
|
*)
|
||||||
|
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
|
||||||
|
# shellcheck disable=SC2039,SC3045
|
||||||
|
ulimit -n "$MAX_FD" ||
|
||||||
|
warn "Could not set maximum file descriptor limit to $MAX_FD"
|
||||||
|
esac
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Collect all arguments for the java command, stacking in reverse order:
|
||||||
|
# * args from the command line
|
||||||
|
# * the main class name
|
||||||
|
# * -classpath
|
||||||
|
# * -D...appname settings
|
||||||
|
# * --module-path (only if needed)
|
||||||
|
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
|
||||||
|
|
||||||
|
# For Cygwin or MSYS, switch paths to Windows format before running java
|
||||||
|
if "$cygwin" || "$msys" ; then
|
||||||
|
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
|
||||||
|
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
|
||||||
|
|
||||||
|
JAVACMD=$( cygpath --unix "$JAVACMD" )
|
||||||
|
|
||||||
|
# Now convert the arguments - kludge to limit ourselves to /bin/sh
|
||||||
|
for arg do
|
||||||
|
if
|
||||||
|
case $arg in #(
|
||||||
|
-*) false ;; # don't mess with options #(
|
||||||
|
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
|
||||||
|
[ -e "$t" ] ;; #(
|
||||||
|
*) false ;;
|
||||||
|
esac
|
||||||
|
then
|
||||||
|
arg=$( cygpath --path --ignore --mixed "$arg" )
|
||||||
|
fi
|
||||||
|
# Roll the args list around exactly as many times as the number of
|
||||||
|
# args, so each arg winds up back in the position where it started, but
|
||||||
|
# possibly modified.
|
||||||
|
#
|
||||||
|
# NB: a `for` loop captures its iteration list before it begins, so
|
||||||
|
# changing the positional parameters here affects neither the number of
|
||||||
|
# iterations, nor the values presented in `arg`.
|
||||||
|
shift # remove old arg
|
||||||
|
set -- "$@" "$arg" # push replacement arg
|
||||||
|
done
|
||||||
|
fi
|
||||||
|
|
||||||
|
|
||||||
|
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
|
||||||
|
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
|
||||||
|
|
||||||
|
# Collect all arguments for the java command:
|
||||||
|
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
|
||||||
|
# and any embedded shellness will be escaped.
|
||||||
|
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
|
||||||
|
# treated as '${Hostname}' itself on the command line.
|
||||||
|
|
||||||
|
set -- \
|
||||||
|
"-Dorg.gradle.appname=$APP_BASE_NAME" \
|
||||||
|
-classpath "$CLASSPATH" \
|
||||||
|
-jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \
|
||||||
|
"$@"
|
||||||
|
|
||||||
|
# Stop when "xargs" is not available.
|
||||||
|
if ! command -v xargs >/dev/null 2>&1
|
||||||
|
then
|
||||||
|
die "xargs is not available"
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Use "xargs" to parse quoted args.
|
||||||
|
#
|
||||||
|
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
|
||||||
|
#
|
||||||
|
# In Bash we could simply go:
|
||||||
|
#
|
||||||
|
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
|
||||||
|
# set -- "${ARGS[@]}" "$@"
|
||||||
|
#
|
||||||
|
# but POSIX shell has neither arrays nor command substitution, so instead we
|
||||||
|
# post-process each arg (as a line of input to sed) to backslash-escape any
|
||||||
|
# character that might be a shell metacharacter, then use eval to reverse
|
||||||
|
# that process (while maintaining the separation between arguments), and wrap
|
||||||
|
# the whole thing up as a single "set" statement.
|
||||||
|
#
|
||||||
|
# This will of course break if any of these variables contains a newline or
|
||||||
|
# an unmatched quote.
|
||||||
|
#
|
||||||
|
|
||||||
|
eval "set -- $(
|
||||||
|
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
|
||||||
|
xargs -n1 |
|
||||||
|
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
|
||||||
|
tr '\n' ' '
|
||||||
|
)" '"$@"'
|
||||||
|
|
||||||
|
exec "$JAVACMD" "$@"
|
||||||
@@ -0,0 +1,94 @@
|
|||||||
|
@rem
|
||||||
|
@rem Copyright 2015 the original author or authors.
|
||||||
|
@rem
|
||||||
|
@rem Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
@rem you may not use this file except in compliance with the License.
|
||||||
|
@rem You may obtain a copy of the License at
|
||||||
|
@rem
|
||||||
|
@rem https://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
@rem
|
||||||
|
@rem Unless required by applicable law or agreed to in writing, software
|
||||||
|
@rem distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
@rem See the License for the specific language governing permissions and
|
||||||
|
@rem limitations under the License.
|
||||||
|
@rem
|
||||||
|
@rem SPDX-License-Identifier: Apache-2.0
|
||||||
|
@rem
|
||||||
|
|
||||||
|
@if "%DEBUG%"=="" @echo off
|
||||||
|
@rem ##########################################################################
|
||||||
|
@rem
|
||||||
|
@rem Gradle startup script for Windows
|
||||||
|
@rem
|
||||||
|
@rem ##########################################################################
|
||||||
|
|
||||||
|
@rem Set local scope for the variables with windows NT shell
|
||||||
|
if "%OS%"=="Windows_NT" setlocal
|
||||||
|
|
||||||
|
set DIRNAME=%~dp0
|
||||||
|
if "%DIRNAME%"=="" set DIRNAME=.
|
||||||
|
@rem This is normally unused
|
||||||
|
set APP_BASE_NAME=%~n0
|
||||||
|
set APP_HOME=%DIRNAME%
|
||||||
|
|
||||||
|
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
|
||||||
|
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
|
||||||
|
|
||||||
|
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
|
||||||
|
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
|
||||||
|
|
||||||
|
@rem Find java.exe
|
||||||
|
if defined JAVA_HOME goto findJavaFromJavaHome
|
||||||
|
|
||||||
|
set JAVA_EXE=java.exe
|
||||||
|
%JAVA_EXE% -version >NUL 2>&1
|
||||||
|
if %ERRORLEVEL% equ 0 goto execute
|
||||||
|
|
||||||
|
echo. 1>&2
|
||||||
|
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
|
||||||
|
echo. 1>&2
|
||||||
|
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
|
||||||
|
echo location of your Java installation. 1>&2
|
||||||
|
|
||||||
|
goto fail
|
||||||
|
|
||||||
|
:findJavaFromJavaHome
|
||||||
|
set JAVA_HOME=%JAVA_HOME:"=%
|
||||||
|
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
|
||||||
|
|
||||||
|
if exist "%JAVA_EXE%" goto execute
|
||||||
|
|
||||||
|
echo. 1>&2
|
||||||
|
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
|
||||||
|
echo. 1>&2
|
||||||
|
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
|
||||||
|
echo location of your Java installation. 1>&2
|
||||||
|
|
||||||
|
goto fail
|
||||||
|
|
||||||
|
:execute
|
||||||
|
@rem Setup the command line
|
||||||
|
|
||||||
|
set CLASSPATH=
|
||||||
|
|
||||||
|
|
||||||
|
@rem Execute Gradle
|
||||||
|
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %*
|
||||||
|
|
||||||
|
:end
|
||||||
|
@rem End local scope for the variables with windows NT shell
|
||||||
|
if %ERRORLEVEL% equ 0 goto mainEnd
|
||||||
|
|
||||||
|
:fail
|
||||||
|
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
|
||||||
|
rem the _cmd.exe /c_ return code!
|
||||||
|
set EXIT_CODE=%ERRORLEVEL%
|
||||||
|
if %EXIT_CODE% equ 0 set EXIT_CODE=1
|
||||||
|
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
|
||||||
|
exit /b %EXIT_CODE%
|
||||||
|
|
||||||
|
:mainEnd
|
||||||
|
if "%OS%"=="Windows_NT" endlocal
|
||||||
|
|
||||||
|
:omega
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
pluginManagement {
|
||||||
|
repositories {
|
||||||
|
google()
|
||||||
|
mavenCentral()
|
||||||
|
gradlePluginPortal()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
dependencyResolutionManagement {
|
||||||
|
repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
|
||||||
|
repositories {
|
||||||
|
google()
|
||||||
|
mavenCentral()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
rootProject.name = "photogallery-uploader"
|
||||||
|
include(":app")
|
||||||
@@ -0,0 +1,102 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bufio"
|
||||||
|
"fmt"
|
||||||
|
"log"
|
||||||
|
"net/http"
|
||||||
|
"os"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"golang.org/x/crypto/bcrypt"
|
||||||
|
"golang.org/x/time/rate"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Authenticator checks HTTP Basic credentials against bcrypt hashes loaded from
|
||||||
|
// an Apache-style htpasswd file. Only bcrypt entries are supported — generate
|
||||||
|
// them with `htpasswd -B`. This replaces nginx's basic_auth so the app can run
|
||||||
|
// behind a plain TLS-terminating reverse proxy with no auth of its own.
|
||||||
|
type Authenticator struct {
|
||||||
|
creds map[string][]byte // username -> bcrypt hash
|
||||||
|
|
||||||
|
// A single bcrypt comparison runs on every failed lookup so that a request
|
||||||
|
// for an unknown user costs the same as one for a known user with a wrong
|
||||||
|
// password, closing a user-enumeration timing side channel.
|
||||||
|
dummyHash []byte
|
||||||
|
}
|
||||||
|
|
||||||
|
// LoadHtpasswd reads user:hash lines from path. Blank lines and #-comments are
|
||||||
|
// skipped, as is any entry whose hash is not bcrypt (with a warning). It is an
|
||||||
|
// error for the file to yield no usable entries.
|
||||||
|
func LoadHtpasswd(path string) (*Authenticator, error) {
|
||||||
|
f, err := os.Open(path)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
defer f.Close()
|
||||||
|
|
||||||
|
a := &Authenticator{creds: make(map[string][]byte)}
|
||||||
|
|
||||||
|
sc := bufio.NewScanner(f)
|
||||||
|
for sc.Scan() {
|
||||||
|
line := strings.TrimSpace(sc.Text())
|
||||||
|
if line == "" || strings.HasPrefix(line, "#") {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
user, hash, ok := strings.Cut(line, ":")
|
||||||
|
if !ok || user == "" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
// bcrypt hashes start $2a$, $2b$ or $2y$; everything else (MD5 $apr1$,
|
||||||
|
// SHA {SHA}, crypt) is unsupported here.
|
||||||
|
if !strings.HasPrefix(hash, "$2") {
|
||||||
|
log.Printf("auth: skipping non-bcrypt entry for %q — regenerate with `htpasswd -B`", user)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
a.creds[user] = []byte(hash)
|
||||||
|
}
|
||||||
|
if err := sc.Err(); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if len(a.creds) == 0 {
|
||||||
|
return nil, fmt.Errorf("no bcrypt entries in %s (use `htpasswd -B`)", path)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Cost 10 matches htpasswd -B's default, keeping the dummy comparison the
|
||||||
|
// same price as a real one.
|
||||||
|
a.dummyHash, _ = bcrypt.GenerateFromPassword([]byte("dummy"), 10)
|
||||||
|
return a, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// check reports whether user/pass matches a stored credential.
|
||||||
|
func (a *Authenticator) check(user, pass string) bool {
|
||||||
|
hash, ok := a.creds[user]
|
||||||
|
if !ok {
|
||||||
|
// Spend the same time as a real comparison to avoid leaking which
|
||||||
|
// usernames exist.
|
||||||
|
bcrypt.CompareHashAndPassword(a.dummyHash, []byte(pass))
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
return bcrypt.CompareHashAndPassword(hash, []byte(pass)) == nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// basicAuth wraps next, demanding valid HTTP Basic credentials. On a failed
|
||||||
|
// attempt it consumes a token from limiter; once the limiter is exhausted,
|
||||||
|
// further failures get 429 instead of 401, throttling brute-force guessing.
|
||||||
|
// The limiter is only touched on failure, so legitimate (even bursty, bulk)
|
||||||
|
// uploads are never throttled.
|
||||||
|
func (a *Authenticator) basicAuth(limiter *rate.Limiter, next http.HandlerFunc) http.HandlerFunc {
|
||||||
|
return func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
user, pass, ok := r.BasicAuth()
|
||||||
|
if ok && a.check(user, pass) {
|
||||||
|
next(w, r)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if !limiter.Allow() {
|
||||||
|
http.Error(w, "too many failed attempts", http.StatusTooManyRequests)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
w.Header().Set("WWW-Authenticate", `Basic realm="photog"`)
|
||||||
|
http.Error(w, "unauthorized", http.StatusUnauthorized)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,144 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"golang.org/x/crypto/bcrypt"
|
||||||
|
"golang.org/x/time/rate"
|
||||||
|
)
|
||||||
|
|
||||||
|
// bcryptHash returns a cost-10 hash of pw, matching `htpasswd -B`'s default.
|
||||||
|
func bcryptHash(t *testing.T, pw string) string {
|
||||||
|
t.Helper()
|
||||||
|
h, err := bcrypt.GenerateFromPassword([]byte(pw), 10)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("GenerateFromPassword: %v", err)
|
||||||
|
}
|
||||||
|
return string(h)
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestLoadHtpasswdAndCheck(t *testing.T) {
|
||||||
|
// alice's hash is rewritten to the $2y$ variant that Apache's htpasswd -B
|
||||||
|
// emits, to prove it is accepted. $2a$ and $2y$ are the same algorithm, so
|
||||||
|
// swapping the prefix on a valid hash yields a valid hash for the same
|
||||||
|
// password. bob keeps the $2a$ form.
|
||||||
|
aliceHash := bcryptHash(t, "s3cret")
|
||||||
|
if !strings.HasPrefix(aliceHash, "$2a$") {
|
||||||
|
t.Fatalf("expected $2a$ prefix, got %q", aliceHash[:4])
|
||||||
|
}
|
||||||
|
aliceHashY := "$2y$" + strings.TrimPrefix(aliceHash, "$2a$")
|
||||||
|
bobHash := bcryptHash(t, "hunter2")
|
||||||
|
|
||||||
|
file := filepath.Join(t.TempDir(), "htpasswd")
|
||||||
|
content := strings.Join([]string{
|
||||||
|
"# a comment",
|
||||||
|
"",
|
||||||
|
"alice:" + aliceHashY,
|
||||||
|
"bob:" + bobHash,
|
||||||
|
"legacy:$apr1$abcd$0123456789", // MD5 — must be skipped
|
||||||
|
}, "\n") + "\n"
|
||||||
|
if err := os.WriteFile(file, []byte(content), 0600); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
a, err := LoadHtpasswd(file)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("LoadHtpasswd: %v", err)
|
||||||
|
}
|
||||||
|
if _, ok := a.creds["legacy"]; ok {
|
||||||
|
t.Error("MD5 entry should have been skipped")
|
||||||
|
}
|
||||||
|
|
||||||
|
cases := []struct {
|
||||||
|
user, pass string
|
||||||
|
want bool
|
||||||
|
}{
|
||||||
|
{"alice", "s3cret", true}, // $2y$ accepted
|
||||||
|
{"bob", "hunter2", true}, // $2a$ accepted
|
||||||
|
{"alice", "wrong", false}, // wrong password
|
||||||
|
{"bob", "s3cret", false}, // right password, wrong user
|
||||||
|
{"nobody", "s3cret", false}, // unknown user
|
||||||
|
{"legacy", "whatever", false},
|
||||||
|
}
|
||||||
|
for _, c := range cases {
|
||||||
|
if got := a.check(c.user, c.pass); got != c.want {
|
||||||
|
t.Errorf("check(%q, %q) = %v, want %v", c.user, c.pass, got, c.want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestBasicAuthMiddleware(t *testing.T) {
|
||||||
|
a := &Authenticator{creds: map[string][]byte{"alice": []byte(bcryptHash(t, "s3cret"))}}
|
||||||
|
a.dummyHash, _ = bcrypt.GenerateFromPassword([]byte("dummy"), 10)
|
||||||
|
|
||||||
|
var reached bool
|
||||||
|
// Burst of 2 failures before throttling, so the 429 path is reachable.
|
||||||
|
limiter := rate.NewLimiter(rate.Every(time.Hour), 2)
|
||||||
|
h := a.basicAuth(limiter, func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
reached = true
|
||||||
|
w.WriteHeader(http.StatusCreated)
|
||||||
|
})
|
||||||
|
|
||||||
|
do := func(user, pass string, withCreds bool) *httptest.ResponseRecorder {
|
||||||
|
reached = false
|
||||||
|
req := httptest.NewRequest(http.MethodPost, "/upload", nil)
|
||||||
|
if withCreds {
|
||||||
|
req.SetBasicAuth(user, pass)
|
||||||
|
}
|
||||||
|
rec := httptest.NewRecorder()
|
||||||
|
h(rec, req)
|
||||||
|
return rec
|
||||||
|
}
|
||||||
|
|
||||||
|
// Good credentials pass through.
|
||||||
|
if rec := do("alice", "s3cret", true); rec.Code != http.StatusCreated || !reached {
|
||||||
|
t.Fatalf("valid creds: code=%d reached=%v", rec.Code, reached)
|
||||||
|
}
|
||||||
|
|
||||||
|
// No credentials → 401 with a challenge.
|
||||||
|
rec := do("", "", false)
|
||||||
|
if rec.Code != http.StatusUnauthorized {
|
||||||
|
t.Fatalf("missing creds: code=%d, want 401", rec.Code)
|
||||||
|
}
|
||||||
|
if !strings.HasPrefix(rec.Header().Get("WWW-Authenticate"), "Basic ") {
|
||||||
|
t.Errorf("missing WWW-Authenticate challenge: %q", rec.Header().Get("WWW-Authenticate"))
|
||||||
|
}
|
||||||
|
if reached {
|
||||||
|
t.Error("handler reached despite missing creds")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Wrong password burns the limiter (burst 2: one above + this one), then
|
||||||
|
// the next failure is throttled to 429.
|
||||||
|
if rec := do("alice", "nope", true); rec.Code != http.StatusUnauthorized {
|
||||||
|
t.Fatalf("wrong pass #2: code=%d, want 401", rec.Code)
|
||||||
|
}
|
||||||
|
if rec := do("alice", "nope", true); rec.Code != http.StatusTooManyRequests {
|
||||||
|
t.Fatalf("wrong pass #3: code=%d, want 429", rec.Code)
|
||||||
|
}
|
||||||
|
|
||||||
|
// A valid request still succeeds while failures are throttled — the
|
||||||
|
// limiter only gates failures.
|
||||||
|
if rec := do("alice", "s3cret", true); rec.Code != http.StatusCreated {
|
||||||
|
t.Fatalf("valid creds under throttle: code=%d, want 201", rec.Code)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestLoadHtpasswdErrors(t *testing.T) {
|
||||||
|
if _, err := LoadHtpasswd(filepath.Join(t.TempDir(), "does-not-exist")); err == nil {
|
||||||
|
t.Error("expected error for missing file")
|
||||||
|
}
|
||||||
|
|
||||||
|
empty := filepath.Join(t.TempDir(), "htpasswd")
|
||||||
|
if err := os.WriteFile(empty, []byte("# only comments\n\nlegacy:$apr1$x$y\n"), 0600); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if _, err := LoadHtpasswd(empty); err == nil {
|
||||||
|
t.Error("expected error when no bcrypt entries are usable")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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)
|
||||||
|
}
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
/build/
|
||||||
|
/.direnv/
|
||||||
|
.envrc
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
cmake_minimum_required(VERSION 3.20)
|
||||||
|
project(photogallery_uploader LANGUAGES CXX)
|
||||||
|
|
||||||
|
set(CMAKE_CXX_STANDARD 17)
|
||||||
|
set(CMAKE_CXX_STANDARD_REQUIRED ON)
|
||||||
|
set(CMAKE_AUTOMOC ON)
|
||||||
|
set(CMAKE_AUTORCC ON)
|
||||||
|
|
||||||
|
find_package(Qt6 REQUIRED COMPONENTS Widgets Network Concurrent)
|
||||||
|
find_package(Qt6Keychain REQUIRED)
|
||||||
|
|
||||||
|
add_executable(uploader
|
||||||
|
main.cpp
|
||||||
|
mainwindow.cpp
|
||||||
|
photoitemwidget.cpp
|
||||||
|
managepostwidget.cpp
|
||||||
|
tagcompleter.cpp
|
||||||
|
settings.cpp
|
||||||
|
uploadclient.cpp
|
||||||
|
imageprep.cpp
|
||||||
|
app.qrc
|
||||||
|
)
|
||||||
|
|
||||||
|
target_link_libraries(uploader PRIVATE
|
||||||
|
Qt6::Widgets
|
||||||
|
Qt6::Network
|
||||||
|
Qt6::Concurrent
|
||||||
|
Qt6Keychain::Qt6Keychain
|
||||||
|
)
|
||||||
|
|
||||||
|
# The binary is "photog" (matching the app + package), so `nix run` and the
|
||||||
|
# desktop entry find it; the CMake target stays "uploader".
|
||||||
|
set_target_properties(uploader PROPERTIES OUTPUT_NAME photog)
|
||||||
|
|
||||||
|
# Installation — the binary, a desktop entry, and the app icon in the hicolor
|
||||||
|
# theme, so `nix profile install ./desktop` puts "Photog" in the app menu.
|
||||||
|
include(GNUInstallDirs)
|
||||||
|
install(TARGETS uploader RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR})
|
||||||
|
install(FILES photog.desktop DESTINATION ${CMAKE_INSTALL_DATADIR}/applications)
|
||||||
|
foreach(sz 32 128 256 512)
|
||||||
|
install(FILES icons/app-${sz}.png
|
||||||
|
DESTINATION ${CMAKE_INSTALL_DATADIR}/icons/hicolor/${sz}x${sz}/apps
|
||||||
|
RENAME photog.png)
|
||||||
|
endforeach()
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
<!DOCTYPE RCC>
|
||||||
|
<RCC version="1.0">
|
||||||
|
<qresource prefix="/">
|
||||||
|
<file>icons/app-32.png</file>
|
||||||
|
<file>icons/app-128.png</file>
|
||||||
|
<file>icons/app-256.png</file>
|
||||||
|
<file>icons/app-512.png</file>
|
||||||
|
</qresource>
|
||||||
|
</RCC>
|
||||||
@@ -0,0 +1,61 @@
|
|||||||
|
{
|
||||||
|
"nodes": {
|
||||||
|
"flake-utils": {
|
||||||
|
"inputs": {
|
||||||
|
"systems": "systems"
|
||||||
|
},
|
||||||
|
"locked": {
|
||||||
|
"lastModified": 1731533236,
|
||||||
|
"narHash": "sha256-l0KFg5HjrsfsO/JpG+r7fRrqm12kzFHyUHqHCVpMMbI=",
|
||||||
|
"owner": "numtide",
|
||||||
|
"repo": "flake-utils",
|
||||||
|
"rev": "11707dc2f618dd54ca8739b309ec4fc024de578b",
|
||||||
|
"type": "github"
|
||||||
|
},
|
||||||
|
"original": {
|
||||||
|
"owner": "numtide",
|
||||||
|
"repo": "flake-utils",
|
||||||
|
"type": "github"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"nixpkgs": {
|
||||||
|
"locked": {
|
||||||
|
"lastModified": 1787498568,
|
||||||
|
"narHash": "sha256-9i/VTdusq/+NM/tz+J1Re+ojkMB8MBf0QshnYfzHz30=",
|
||||||
|
"owner": "NixOS",
|
||||||
|
"repo": "nixpkgs",
|
||||||
|
"rev": "56c02bc00adcf003215cc4bd996d6efaf4cff188",
|
||||||
|
"type": "github"
|
||||||
|
},
|
||||||
|
"original": {
|
||||||
|
"owner": "NixOS",
|
||||||
|
"ref": "nixos-unstable",
|
||||||
|
"repo": "nixpkgs",
|
||||||
|
"type": "github"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"root": {
|
||||||
|
"inputs": {
|
||||||
|
"flake-utils": "flake-utils",
|
||||||
|
"nixpkgs": "nixpkgs"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"systems": {
|
||||||
|
"locked": {
|
||||||
|
"lastModified": 1681028828,
|
||||||
|
"narHash": "sha256-Vy1rq5AaRuLzOxct8nz4T6wlgyUR7zLU309k9mBC768=",
|
||||||
|
"owner": "nix-systems",
|
||||||
|
"repo": "default",
|
||||||
|
"rev": "da67096a3b9bf56a91d16901293e51ba5b49a27e",
|
||||||
|
"type": "github"
|
||||||
|
},
|
||||||
|
"original": {
|
||||||
|
"owner": "nix-systems",
|
||||||
|
"repo": "default",
|
||||||
|
"type": "github"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"root": "root",
|
||||||
|
"version": 7
|
||||||
|
}
|
||||||
@@ -0,0 +1,55 @@
|
|||||||
|
{
|
||||||
|
description = "photogallery uploader — Qt6 C++ desktop app";
|
||||||
|
|
||||||
|
inputs = {
|
||||||
|
nixpkgs.url = "github:NixOS/nixpkgs/nixos-unstable";
|
||||||
|
flake-utils.url = "github:numtide/flake-utils";
|
||||||
|
};
|
||||||
|
|
||||||
|
outputs = { self, nixpkgs, flake-utils }:
|
||||||
|
flake-utils.lib.eachDefaultSystem (system:
|
||||||
|
let
|
||||||
|
pkgs = import nixpkgs { inherit system; };
|
||||||
|
inherit (pkgs) lib stdenv;
|
||||||
|
|
||||||
|
# Wayland is Linux-only; macOS uses the Cocoa QPA plugin inside qtbase,
|
||||||
|
# so qtwayland is added only on Linux (it refuses to evaluate on darwin).
|
||||||
|
qtModules = [ pkgs.qt6.qtbase pkgs.qt6.qtimageformats ]
|
||||||
|
++ lib.optionals stdenv.hostPlatform.isLinux [ pkgs.qt6.qtwayland ];
|
||||||
|
|
||||||
|
qtPlugins = lib.makeSearchPathOutput "out" "lib/qt-6/plugins" qtModules;
|
||||||
|
in {
|
||||||
|
# Installable build: `nix profile install ./desktop` drops "Photog" into
|
||||||
|
# the application menu with its icon. wrapQtAppsHook wraps the binary so
|
||||||
|
# it finds the Qt platform (Cocoa on macOS; xcb + wayland on Linux) and
|
||||||
|
# image-format plugins on its own, without the dev shell.
|
||||||
|
packages.default = stdenv.mkDerivation {
|
||||||
|
pname = "photog";
|
||||||
|
version = "0.1.0";
|
||||||
|
src = ./.;
|
||||||
|
nativeBuildInputs = with pkgs; [
|
||||||
|
cmake
|
||||||
|
ninja
|
||||||
|
pkg-config
|
||||||
|
qt6.wrapQtAppsHook
|
||||||
|
];
|
||||||
|
buildInputs = [ pkgs.qt6Packages.qtkeychain ] ++ qtModules;
|
||||||
|
meta.mainProgram = "photog";
|
||||||
|
};
|
||||||
|
|
||||||
|
devShells.default = pkgs.mkShell {
|
||||||
|
packages = with pkgs; [
|
||||||
|
cmake
|
||||||
|
ninja
|
||||||
|
pkg-config
|
||||||
|
qt6Packages.qtkeychain # password → Keychain (macOS) / libsecret / kwallet
|
||||||
|
] ++ qtModules;
|
||||||
|
|
||||||
|
shellHook = ''
|
||||||
|
# Let a binary run straight from the build dir find Qt's platform and
|
||||||
|
# image-format plugins without wrapQtAppsHook.
|
||||||
|
export QT_PLUGIN_PATH="${qtPlugins}''${QT_PLUGIN_PATH:+:$QT_PLUGIN_PATH}"
|
||||||
|
'';
|
||||||
|
};
|
||||||
|
});
|
||||||
|
}
|
||||||
|
After Width: | Height: | Size: 18 KiB |
|
After Width: | Height: | Size: 40 KiB |
|
After Width: | Height: | Size: 7.4 KiB |
|
After Width: | Height: | Size: 97 KiB |
@@ -0,0 +1,237 @@
|
|||||||
|
#include "imageprep.h"
|
||||||
|
|
||||||
|
#include <QBuffer>
|
||||||
|
#include <QDir>
|
||||||
|
#include <QFile>
|
||||||
|
#include <QImage>
|
||||||
|
#include <QImageReader>
|
||||||
|
#include <QImageWriter>
|
||||||
|
|
||||||
|
namespace {
|
||||||
|
// nginx is configured with client_max_body_size 20M; leave headroom.
|
||||||
|
constexpr qint64 kMaxUploadBytes = 18LL * 1024 * 1024;
|
||||||
|
constexpr int kJpegQuality = 92;
|
||||||
|
const int kQualityLadder[] = {92, 85, 75};
|
||||||
|
|
||||||
|
// Encodes to JPEG in memory at the given quality.
|
||||||
|
QByteArray encodeJpeg(const QImage &image, int quality)
|
||||||
|
{
|
||||||
|
QByteArray out;
|
||||||
|
QBuffer buffer(&out);
|
||||||
|
buffer.open(QIODevice::WriteOnly);
|
||||||
|
QImageWriter writer(&buffer, "jpeg");
|
||||||
|
writer.setQuality(quality);
|
||||||
|
writer.write(image);
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Decodes with EXIF orientation baked into the pixels. Works for HEIC too, via
|
||||||
|
// the qtimageformats plugin.
|
||||||
|
QImage decodeOriented(const QString &path)
|
||||||
|
{
|
||||||
|
QImageReader reader(path);
|
||||||
|
reader.setAutoTransform(true);
|
||||||
|
return reader.read();
|
||||||
|
}
|
||||||
|
} // namespace
|
||||||
|
|
||||||
|
ImagePrep::Prepared ImagePrep::prepare(const QString &sourcePath, const QString &cacheDir,
|
||||||
|
const QString &baseName)
|
||||||
|
{
|
||||||
|
Prepared result;
|
||||||
|
|
||||||
|
QFile in(sourcePath);
|
||||||
|
if (!in.open(QIODevice::ReadOnly)) {
|
||||||
|
result.error = QStringLiteral("Could not read the selected image");
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
const QByteArray source = in.readAll();
|
||||||
|
in.close();
|
||||||
|
|
||||||
|
QStringList notes;
|
||||||
|
|
||||||
|
// A rotation flag cannot survive metadata stripping, so bake it into the
|
||||||
|
// pixels instead, which costs a re-encode.
|
||||||
|
QImageReader orientationReader(sourcePath);
|
||||||
|
const bool mustRotate =
|
||||||
|
orientationReader.transformation() != QImageIOHandler::TransformationNone;
|
||||||
|
|
||||||
|
QByteArray bytes;
|
||||||
|
QString extension;
|
||||||
|
|
||||||
|
if (!mustRotate && isJpeg(source)) {
|
||||||
|
bytes = stripJpegSegments(source);
|
||||||
|
extension = QStringLiteral("jpg");
|
||||||
|
} else if (!mustRotate && isPng(source)) {
|
||||||
|
bytes = stripPngChunks(source);
|
||||||
|
extension = QStringLiteral("png");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (bytes.isEmpty()) {
|
||||||
|
// Re-encode path: rotated originals, HEIC, or a JPEG/PNG whose marker
|
||||||
|
// structure did not parse.
|
||||||
|
const QImage image = decodeOriented(sourcePath);
|
||||||
|
if (image.isNull()) {
|
||||||
|
result.error = QStringLiteral("Could not decode the selected image");
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
if (mustRotate)
|
||||||
|
notes << QStringLiteral("rotated to match its EXIF orientation");
|
||||||
|
else if (!isJpeg(source) && !isPng(source))
|
||||||
|
notes << QStringLiteral("converted to JPEG");
|
||||||
|
bytes = encodeJpeg(image, kJpegQuality);
|
||||||
|
extension = QStringLiteral("jpg");
|
||||||
|
}
|
||||||
|
|
||||||
|
// Size valve. Only trips on genuinely huge originals; quality is stepped
|
||||||
|
// before touching resolution.
|
||||||
|
if (bytes.size() > kMaxUploadBytes) {
|
||||||
|
QImage image = decodeOriented(sourcePath);
|
||||||
|
if (image.isNull()) {
|
||||||
|
result.error = QStringLiteral("Could not decode the selected image");
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
QByteArray shrunk;
|
||||||
|
for (int quality : kQualityLadder) {
|
||||||
|
const QByteArray attempt = encodeJpeg(image, quality);
|
||||||
|
if (attempt.size() <= kMaxUploadBytes) {
|
||||||
|
shrunk = attempt;
|
||||||
|
notes << QStringLiteral("re-encoded at quality %1 to fit the 20M upload limit").arg(quality);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (shrunk.isEmpty()) {
|
||||||
|
double factor = 1.0;
|
||||||
|
while (factor > 0.2) {
|
||||||
|
factor *= 0.75;
|
||||||
|
const QImage scaled = image.scaledToWidth(
|
||||||
|
qMax(1, int(image.width() * factor)), Qt::SmoothTransformation);
|
||||||
|
const QByteArray attempt = encodeJpeg(scaled, kQualityLadder[2]);
|
||||||
|
if (attempt.size() <= kMaxUploadBytes) {
|
||||||
|
shrunk = attempt;
|
||||||
|
notes << QStringLiteral("scaled to %1×%2 to fit the 20M upload limit")
|
||||||
|
.arg(scaled.width()).arg(scaled.height());
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (shrunk.isEmpty()) {
|
||||||
|
result.error = QStringLiteral("Image is too large to upload even after downscaling");
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
bytes = shrunk;
|
||||||
|
extension = QStringLiteral("jpg");
|
||||||
|
}
|
||||||
|
|
||||||
|
const QString outPath = QDir(cacheDir).filePath(baseName + QLatin1Char('.') + extension);
|
||||||
|
QFile out(outPath);
|
||||||
|
if (!out.open(QIODevice::WriteOnly) || out.write(bytes) != bytes.size()) {
|
||||||
|
result.error = QStringLiteral("Could not write the prepared image");
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
out.close();
|
||||||
|
|
||||||
|
result.filePath = outPath;
|
||||||
|
result.note = notes.join(QStringLiteral("; "));
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool ImagePrep::isJpeg(const QByteArray &b)
|
||||||
|
{
|
||||||
|
return b.size() > 3 && quint8(b[0]) == 0xFF && quint8(b[1]) == 0xD8 && quint8(b[2]) == 0xFF;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool ImagePrep::isPng(const QByteArray &b)
|
||||||
|
{
|
||||||
|
return b.size() > 8 && quint8(b[0]) == 0x89 && quint8(b[1]) == 0x50 && quint8(b[2]) == 0x4E
|
||||||
|
&& quint8(b[3]) == 0x47;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Drops APP1 (EXIF and XMP) and COM segments, keeping the compressed scan data
|
||||||
|
// byte-for-byte. APP0/JFIF and APP2/ICC stay: removing the colour profile would
|
||||||
|
// shift the rendered colours. Returns an empty array if the marker structure
|
||||||
|
// does not parse, so the caller falls back to a re-encode.
|
||||||
|
QByteArray ImagePrep::stripJpegSegments(const QByteArray &src)
|
||||||
|
{
|
||||||
|
const auto u8 = [&](int i) { return quint8(src[i]); };
|
||||||
|
QByteArray out;
|
||||||
|
out.append(char(0xFF));
|
||||||
|
out.append(char(0xD8));
|
||||||
|
|
||||||
|
int i = 2;
|
||||||
|
while (i + 1 < src.size()) {
|
||||||
|
if (u8(i) != 0xFF)
|
||||||
|
return {};
|
||||||
|
const int marker = u8(i + 1);
|
||||||
|
|
||||||
|
// Standalone markers: no length field, no payload.
|
||||||
|
if (marker == 0x01 || (marker >= 0xD0 && marker <= 0xD7)) {
|
||||||
|
out.append(char(0xFF));
|
||||||
|
out.append(char(marker));
|
||||||
|
i += 2;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Start of scan: entropy-coded data runs to the end of the file.
|
||||||
|
if (marker == 0xDA) {
|
||||||
|
out.append(src.mid(i));
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (i + 3 >= src.size())
|
||||||
|
return {};
|
||||||
|
const int length = (u8(i + 2) << 8) | u8(i + 3);
|
||||||
|
if (length < 2 || i + 2 + length > src.size())
|
||||||
|
return {};
|
||||||
|
|
||||||
|
const bool isExifOrXmp = marker == 0xE1;
|
||||||
|
const bool isComment = marker == 0xFE;
|
||||||
|
if (!isExifOrXmp && !isComment)
|
||||||
|
out.append(src.mid(i, 2 + length));
|
||||||
|
|
||||||
|
i += 2 + length;
|
||||||
|
}
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
|
||||||
|
// Drops the metadata chunks, keeps everything else including the critical
|
||||||
|
// IHDR/PLTE/IDAT/IEND run and colour chunks (iCCP, sRGB). Whole chunks go, so no
|
||||||
|
// CRC needs recomputing.
|
||||||
|
QByteArray ImagePrep::stripPngChunks(const QByteArray &src)
|
||||||
|
{
|
||||||
|
static const QByteArray drop[] = {"eXIf", "tEXt", "zTXt", "iTXt", "tIME"};
|
||||||
|
const auto u8 = [&](int i) { return quint8(src[i]); };
|
||||||
|
if (src.size() < 8)
|
||||||
|
return {};
|
||||||
|
|
||||||
|
QByteArray out;
|
||||||
|
out.append(src.mid(0, 8));
|
||||||
|
|
||||||
|
int i = 8;
|
||||||
|
while (i + 8 <= src.size()) {
|
||||||
|
const qint64 length =
|
||||||
|
(qint64(u8(i)) << 24) | (qint64(u8(i + 1)) << 16) | (qint64(u8(i + 2)) << 8) | qint64(u8(i + 3));
|
||||||
|
if (length < 0)
|
||||||
|
return {};
|
||||||
|
|
||||||
|
const QByteArray type = src.mid(i + 4, 4);
|
||||||
|
const qint64 total = 12 + length;
|
||||||
|
if (i + total > src.size())
|
||||||
|
return {};
|
||||||
|
|
||||||
|
bool dropped = false;
|
||||||
|
for (const QByteArray &d : drop) {
|
||||||
|
if (type == d) {
|
||||||
|
dropped = true;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!dropped)
|
||||||
|
out.append(src.mid(i, int(total)));
|
||||||
|
i += int(total);
|
||||||
|
|
||||||
|
if (type == "IEND")
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
return {};
|
||||||
|
}
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <QByteArray>
|
||||||
|
#include <QString>
|
||||||
|
|
||||||
|
// Turns a picked image into a file the gallery's upload API accepts.
|
||||||
|
//
|
||||||
|
// Three things must be true of the result: no EXIF (the gallery publishes the
|
||||||
|
// uploaded file verbatim as its full-size download, so embedded GPS would be
|
||||||
|
// public), a .jpg or .png extension (server.go rejects anything else, HEIC
|
||||||
|
// included), and under nginx's 20M body cap.
|
||||||
|
//
|
||||||
|
// JPEG and PNG take a lossless route — whole metadata segments are dropped
|
||||||
|
// without touching the compressed image data — so the published file keeps the
|
||||||
|
// original sensor pixels. Anything else, or a file whose EXIF orientation must
|
||||||
|
// be baked in, is decoded and re-encoded as JPEG (HEIC via Qt's qtimageformats
|
||||||
|
// plugin). The strippers are a direct port of the Android app's.
|
||||||
|
class ImagePrep
|
||||||
|
{
|
||||||
|
public:
|
||||||
|
struct Prepared {
|
||||||
|
QString filePath;
|
||||||
|
QString note; // non-empty when the app departed from a byte-exact copy
|
||||||
|
QString error;
|
||||||
|
bool ok() const { return error.isEmpty(); }
|
||||||
|
};
|
||||||
|
|
||||||
|
// Writes the upload-ready file into cacheDir as baseName.(jpg|png).
|
||||||
|
static Prepared prepare(const QString &sourcePath, const QString &cacheDir,
|
||||||
|
const QString &baseName);
|
||||||
|
|
||||||
|
private:
|
||||||
|
static QByteArray stripJpegSegments(const QByteArray &src); // empty on parse failure
|
||||||
|
static QByteArray stripPngChunks(const QByteArray &src);
|
||||||
|
static bool isJpeg(const QByteArray &b);
|
||||||
|
static bool isPng(const QByteArray &b);
|
||||||
|
};
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
#include <QApplication>
|
||||||
|
#include <QIcon>
|
||||||
|
|
||||||
|
#include "mainwindow.h"
|
||||||
|
|
||||||
|
int main(int argc, char **argv)
|
||||||
|
{
|
||||||
|
QApplication app(argc, argv);
|
||||||
|
app.setApplicationName(QStringLiteral("photogallery-uploader"));
|
||||||
|
app.setOrganizationName(QStringLiteral("inflo.ws"));
|
||||||
|
|
||||||
|
// Window / taskbar / alt-tab icon, embedded via app.qrc. Several sizes so
|
||||||
|
// the small titlebar rendering stays crisp rather than downscaling 512px.
|
||||||
|
QIcon icon;
|
||||||
|
icon.addFile(QStringLiteral(":/icons/app-32.png"));
|
||||||
|
icon.addFile(QStringLiteral(":/icons/app-128.png"));
|
||||||
|
icon.addFile(QStringLiteral(":/icons/app-256.png"));
|
||||||
|
icon.addFile(QStringLiteral(":/icons/app-512.png"));
|
||||||
|
app.setWindowIcon(icon);
|
||||||
|
|
||||||
|
MainWindow window;
|
||||||
|
window.resize(440, 680);
|
||||||
|
window.show();
|
||||||
|
return app.exec();
|
||||||
|
}
|
||||||
@@ -0,0 +1,601 @@
|
|||||||
|
#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>
|
||||||
|
#include <QStackedWidget>
|
||||||
|
#include <QStandardPaths>
|
||||||
|
#include <QUuid>
|
||||||
|
#include <QVBoxLayout>
|
||||||
|
#include <QtConcurrent>
|
||||||
|
|
||||||
|
MainWindow::MainWindow(QWidget *parent)
|
||||||
|
: QMainWindow(parent)
|
||||||
|
{
|
||||||
|
setWindowTitle(QStringLiteral("Photo Gallery Uploader"));
|
||||||
|
|
||||||
|
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())
|
||||||
|
showPost();
|
||||||
|
else
|
||||||
|
showSettings();
|
||||||
|
}
|
||||||
|
|
||||||
|
QWidget *MainWindow::buildSettingsPage()
|
||||||
|
{
|
||||||
|
auto *page = new QWidget;
|
||||||
|
auto *layout = new QVBoxLayout(page);
|
||||||
|
layout->setContentsMargins(24, 24, 24, 24);
|
||||||
|
|
||||||
|
auto *form = new QFormLayout;
|
||||||
|
m_baseUrl = new QLineEdit;
|
||||||
|
m_baseUrl->setPlaceholderText(QStringLiteral("https://photos.example.com"));
|
||||||
|
m_username = new QLineEdit;
|
||||||
|
m_password = new QLineEdit;
|
||||||
|
m_password->setEchoMode(QLineEdit::Password);
|
||||||
|
m_concurrency = new QSpinBox;
|
||||||
|
m_concurrency->setRange(1, Settings::kMaxConcurrency);
|
||||||
|
form->addRow(QStringLiteral("Base URL"), m_baseUrl);
|
||||||
|
form->addRow(QStringLiteral("Username"), m_username);
|
||||||
|
form->addRow(QStringLiteral("Password"), m_password);
|
||||||
|
form->addRow(QStringLiteral("Simultaneous uploads"), m_concurrency);
|
||||||
|
layout->addLayout(form);
|
||||||
|
|
||||||
|
m_saveButton = new QPushButton(QStringLiteral("Save && test connection"));
|
||||||
|
connect(m_saveButton, &QPushButton::clicked, this, &MainWindow::saveAndTest);
|
||||||
|
layout->addWidget(m_saveButton);
|
||||||
|
|
||||||
|
m_settingsStatus = new QLabel;
|
||||||
|
m_settingsStatus->setWordWrap(true);
|
||||||
|
layout->addWidget(m_settingsStatus);
|
||||||
|
|
||||||
|
m_settingsBack = new QPushButton(QStringLiteral("Back"));
|
||||||
|
connect(m_settingsBack, &QPushButton::clicked, this, &MainWindow::showPost);
|
||||||
|
layout->addWidget(m_settingsBack);
|
||||||
|
|
||||||
|
layout->addWidget(new QLabel(QStringLiteral(
|
||||||
|
"The password is stored in your system keychain, never in plain text. "
|
||||||
|
"https is required — Basic auth would otherwise send it in the clear.")));
|
||||||
|
layout->addStretch();
|
||||||
|
return page;
|
||||||
|
}
|
||||||
|
|
||||||
|
QWidget *MainWindow::buildPostPage()
|
||||||
|
{
|
||||||
|
auto *page = new QWidget;
|
||||||
|
auto *outer = new QVBoxLayout(page);
|
||||||
|
outer->setContentsMargins(24, 24, 24, 24);
|
||||||
|
|
||||||
|
auto *choose = new QPushButton(QStringLiteral("Choose photos…"));
|
||||||
|
connect(choose, &QPushButton::clicked, this, &MainWindow::chooseImages);
|
||||||
|
outer->addWidget(choose);
|
||||||
|
|
||||||
|
// Scrollable list of per-photo cards.
|
||||||
|
auto *scroll = new QScrollArea;
|
||||||
|
scroll->setWidgetResizable(true);
|
||||||
|
auto *container = new QWidget;
|
||||||
|
m_itemsLayout = new QVBoxLayout(container);
|
||||||
|
m_itemsLayout->setAlignment(Qt::AlignTop);
|
||||||
|
m_emptyHint = new QLabel(QStringLiteral("No photos selected"));
|
||||||
|
m_emptyHint->setAlignment(Qt::AlignCenter);
|
||||||
|
m_itemsLayout->addWidget(m_emptyHint);
|
||||||
|
scroll->setWidget(container);
|
||||||
|
outer->addWidget(scroll, 1);
|
||||||
|
|
||||||
|
m_postButton = new QPushButton(QStringLiteral("Post"));
|
||||||
|
m_postButton->setEnabled(false);
|
||||||
|
connect(m_postButton, &QPushButton::clicked, this, &MainWindow::submit);
|
||||||
|
outer->addWidget(m_postButton);
|
||||||
|
|
||||||
|
m_postSummary = new QLabel;
|
||||||
|
m_postSummary->setWordWrap(true);
|
||||||
|
outer->addWidget(m_postSummary);
|
||||||
|
|
||||||
|
m_lastPost = new QLabel;
|
||||||
|
m_lastPost->setOpenExternalLinks(true);
|
||||||
|
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);
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
|
||||||
|
void MainWindow::showSettings()
|
||||||
|
{
|
||||||
|
m_baseUrl->setText(m_settings.baseUrl());
|
||||||
|
m_username->setText(m_settings.username());
|
||||||
|
m_password->setText(m_settings.readPassword());
|
||||||
|
m_concurrency->setValue(m_settings.concurrency());
|
||||||
|
m_settingsStatus->clear();
|
||||||
|
m_settingsBack->setVisible(m_settings.isConfigured());
|
||||||
|
m_stack->setCurrentIndex(0);
|
||||||
|
}
|
||||||
|
|
||||||
|
void MainWindow::showPost()
|
||||||
|
{
|
||||||
|
const Settings::LastPost last = m_settings.lastPost();
|
||||||
|
if (last.valid()) {
|
||||||
|
m_lastPost->setText(QStringLiteral("Last post: <a href=\"%1\">%2</a>")
|
||||||
|
.arg(last.url, last.caption.isEmpty() ? last.slug : last.caption));
|
||||||
|
} 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.
|
||||||
|
m_settings.setConcurrency(m_concurrency->value());
|
||||||
|
|
||||||
|
const QString urlError = Settings::validateBaseUrl(m_baseUrl->text());
|
||||||
|
if (!urlError.isEmpty()) {
|
||||||
|
m_settingsStatus->setText(urlError);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (m_username->text().trimmed().isEmpty() || m_password->text().isEmpty()) {
|
||||||
|
m_settingsStatus->setText(QStringLiteral("Username and password are required"));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
m_settings.setBaseUrl(m_baseUrl->text());
|
||||||
|
m_settings.setUsername(m_username->text());
|
||||||
|
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…"));
|
||||||
|
|
||||||
|
auto *client = new UploadClient(m_settings.baseUrl(), m_settings.username(),
|
||||||
|
m_settings.readPassword(), this);
|
||||||
|
connect(client, &UploadClient::testFinished, this, [this, client](const QString &error) {
|
||||||
|
m_saveButton->setEnabled(true);
|
||||||
|
m_settingsBack->setVisible(m_settings.isConfigured());
|
||||||
|
m_settingsStatus->setText(error.isEmpty()
|
||||||
|
? QStringLiteral("Saved — server reachable and credentials accepted")
|
||||||
|
: error);
|
||||||
|
client->deleteLater();
|
||||||
|
});
|
||||||
|
client->testConnection();
|
||||||
|
}
|
||||||
|
|
||||||
|
void MainWindow::chooseImages()
|
||||||
|
{
|
||||||
|
const QStringList paths = QFileDialog::getOpenFileNames(
|
||||||
|
this, QStringLiteral("Choose photos"), QString(),
|
||||||
|
QStringLiteral("Images (*.jpg *.jpeg *.png *.heic *.heif *.webp *.tif *.tiff *.bmp);;All files (*)"));
|
||||||
|
for (const QString &path : paths)
|
||||||
|
addItem(path);
|
||||||
|
refreshPosting();
|
||||||
|
}
|
||||||
|
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
|
||||||
|
void MainWindow::removeItem(PhotoItemWidget *item)
|
||||||
|
{
|
||||||
|
m_items.removeOne(item);
|
||||||
|
m_queue.removeOne(item); // may be waiting for a slot — drop it before deleting
|
||||||
|
item->deleteLater();
|
||||||
|
if (m_items.isEmpty())
|
||||||
|
m_emptyHint->show();
|
||||||
|
refreshPosting();
|
||||||
|
}
|
||||||
|
|
||||||
|
void MainWindow::clearItems()
|
||||||
|
{
|
||||||
|
for (PhotoItemWidget *item : std::as_const(m_items))
|
||||||
|
item->deleteLater();
|
||||||
|
m_items.clear();
|
||||||
|
m_queue.clear();
|
||||||
|
m_emptyHint->show();
|
||||||
|
m_postSummary->clear();
|
||||||
|
refreshPosting();
|
||||||
|
}
|
||||||
|
|
||||||
|
void MainWindow::submit()
|
||||||
|
{
|
||||||
|
if (m_items.isEmpty())
|
||||||
|
return;
|
||||||
|
if (!m_settings.isConfigured()) {
|
||||||
|
m_postSummary->setText(QStringLiteral("Set the server URL and credentials first"));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Capture the batch's credentials once, then feed the queue through a
|
||||||
|
// concurrency cap rather than firing every photo at the server at once.
|
||||||
|
m_batchCacheDir = QStandardPaths::writableLocation(QStandardPaths::TempLocation);
|
||||||
|
m_batchBaseUrl = m_settings.baseUrl();
|
||||||
|
m_batchUsername = m_settings.username();
|
||||||
|
m_batchPassword = m_settings.readPassword();
|
||||||
|
|
||||||
|
m_queue.clear();
|
||||||
|
for (PhotoItemWidget *item : std::as_const(m_items)) {
|
||||||
|
if (item->status() != PhotoItemWidget::Status::Success)
|
||||||
|
m_queue.append(item); // re-posting retries only failures
|
||||||
|
}
|
||||||
|
if (m_queue.isEmpty())
|
||||||
|
return;
|
||||||
|
|
||||||
|
m_postSummary->clear();
|
||||||
|
pumpQueue();
|
||||||
|
refreshPosting();
|
||||||
|
}
|
||||||
|
|
||||||
|
int MainWindow::inFlightCount() const
|
||||||
|
{
|
||||||
|
int n = 0;
|
||||||
|
for (PhotoItemWidget *item : std::as_const(m_items)) {
|
||||||
|
const PhotoItemWidget::Status s = item->status();
|
||||||
|
if (s == PhotoItemWidget::Status::Preparing || s == PhotoItemWidget::Status::Uploading)
|
||||||
|
++n;
|
||||||
|
}
|
||||||
|
return n;
|
||||||
|
}
|
||||||
|
|
||||||
|
void MainWindow::pumpQueue()
|
||||||
|
{
|
||||||
|
const int cap = m_settings.concurrency();
|
||||||
|
while (inFlightCount() < cap && !m_queue.isEmpty())
|
||||||
|
startItem(m_queue.takeFirst());
|
||||||
|
}
|
||||||
|
|
||||||
|
void MainWindow::startItem(PhotoItemWidget *item)
|
||||||
|
{
|
||||||
|
item->setStatus(PhotoItemWidget::Status::Preparing);
|
||||||
|
|
||||||
|
// Slug from wall-clock time plus a per-item suffix so a batch posted in the
|
||||||
|
// same second cannot collide (server derives the stored name from the
|
||||||
|
// uploaded filename). The real capture date rides in the date field.
|
||||||
|
const QString slug = QDateTime::currentDateTime().toString(QStringLiteral("yyyy-MM-dd-HHmmss"))
|
||||||
|
+ QLatin1Char('-') + QUuid::createUuid().toString(QUuid::Id128).left(6);
|
||||||
|
const QString source = item->sourcePath();
|
||||||
|
const QString cacheDir = m_batchCacheDir;
|
||||||
|
const QString baseUrl = m_batchBaseUrl;
|
||||||
|
const QString username = m_batchUsername;
|
||||||
|
const QString password = m_batchPassword;
|
||||||
|
|
||||||
|
auto *watcher = new QFutureWatcher<ImagePrep::Prepared>(this);
|
||||||
|
connect(watcher, &QFutureWatcher<ImagePrep::Prepared>::finished, this,
|
||||||
|
[this, watcher, item, baseUrl, username, password]() {
|
||||||
|
const ImagePrep::Prepared prepared = watcher->result();
|
||||||
|
watcher->deleteLater();
|
||||||
|
|
||||||
|
if (!prepared.ok()) {
|
||||||
|
item->setStatus(PhotoItemWidget::Status::Error, prepared.error);
|
||||||
|
pumpQueue(); // free the slot for the next photo
|
||||||
|
refreshPosting();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
item->setStatus(PhotoItemWidget::Status::Uploading);
|
||||||
|
const QString caption = item->caption();
|
||||||
|
|
||||||
|
auto *client = new UploadClient(baseUrl, username, password, this);
|
||||||
|
connect(client, &UploadClient::uploadFinished, this,
|
||||||
|
[this, client, item, prepared, caption](UploadClient::Result result,
|
||||||
|
const QString &slug, const QString &url,
|
||||||
|
const QString &message) {
|
||||||
|
QFile::remove(prepared.filePath); // no retry queue on the desktop
|
||||||
|
if (result == UploadClient::Result::Success) {
|
||||||
|
m_settings.setLastPost({slug, url, caption, QDateTime::currentDateTime()});
|
||||||
|
item->setStatus(PhotoItemWidget::Status::Success, {}, url);
|
||||||
|
} else {
|
||||||
|
item->setStatus(PhotoItemWidget::Status::Error, message);
|
||||||
|
}
|
||||||
|
client->deleteLater();
|
||||||
|
pumpQueue(); // free the slot for the next photo
|
||||||
|
refreshPosting();
|
||||||
|
});
|
||||||
|
client->upload(prepared.filePath, QFileInfo(prepared.filePath).fileName(),
|
||||||
|
caption, item->date(), item->tags());
|
||||||
|
});
|
||||||
|
watcher->setFuture(QtConcurrent::run([source, cacheDir, slug]() {
|
||||||
|
return ImagePrep::prepare(source, cacheDir, slug);
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
void MainWindow::refreshPosting()
|
||||||
|
{
|
||||||
|
int pending = 0;
|
||||||
|
int inFlight = 0;
|
||||||
|
int succeeded = 0;
|
||||||
|
int failed = 0;
|
||||||
|
for (PhotoItemWidget *item : std::as_const(m_items)) {
|
||||||
|
switch (item->status()) {
|
||||||
|
case PhotoItemWidget::Status::Pending:
|
||||||
|
++pending;
|
||||||
|
break;
|
||||||
|
case PhotoItemWidget::Status::Preparing:
|
||||||
|
case PhotoItemWidget::Status::Uploading:
|
||||||
|
++inFlight;
|
||||||
|
break;
|
||||||
|
case PhotoItemWidget::Status::Success:
|
||||||
|
++succeeded;
|
||||||
|
break;
|
||||||
|
case PhotoItemWidget::Status::Error:
|
||||||
|
++failed;
|
||||||
|
++pending; // a failure is re-postable
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const bool posting = inFlight > 0;
|
||||||
|
m_postButton->setEnabled(!m_items.isEmpty() && !posting && pending > 0);
|
||||||
|
m_postButton->setText(posting ? QStringLiteral("Posting… (%1/%2)").arg(succeeded).arg(m_items.size())
|
||||||
|
: pending == 1 ? QStringLiteral("Post 1 photo")
|
||||||
|
: pending > 1 ? QStringLiteral("Post %1 photos").arg(pending)
|
||||||
|
: QStringLiteral("All posted"));
|
||||||
|
|
||||||
|
if (!posting && (succeeded + failed) > 0) {
|
||||||
|
QString summary = QStringLiteral("%1 posted").arg(succeeded);
|
||||||
|
if (failed > 0)
|
||||||
|
summary += QStringLiteral(", %1 failed").arg(failed);
|
||||||
|
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());
|
||||||
|
}
|
||||||
@@ -0,0 +1,97 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <QList>
|
||||||
|
#include <QMainWindow>
|
||||||
|
#include <QStringList>
|
||||||
|
|
||||||
|
#include "settings.h"
|
||||||
|
|
||||||
|
class QDateEdit;
|
||||||
|
class QLabel;
|
||||||
|
class QLineEdit;
|
||||||
|
class QPushButton;
|
||||||
|
class QSpinBox;
|
||||||
|
class QStackedWidget;
|
||||||
|
class QVBoxLayout;
|
||||||
|
class PhotoItemWidget;
|
||||||
|
class ManagePostWidget;
|
||||||
|
class UploadClient;
|
||||||
|
|
||||||
|
class MainWindow : public QMainWindow
|
||||||
|
{
|
||||||
|
Q_OBJECT
|
||||||
|
public:
|
||||||
|
explicit MainWindow(QWidget *parent = nullptr);
|
||||||
|
|
||||||
|
private:
|
||||||
|
QWidget *buildSettingsPage();
|
||||||
|
QWidget *buildPostPage();
|
||||||
|
QWidget *buildManagePage();
|
||||||
|
|
||||||
|
void showSettings();
|
||||||
|
void showPost();
|
||||||
|
void showManage();
|
||||||
|
|
||||||
|
void saveAndTest();
|
||||||
|
void chooseImages();
|
||||||
|
void addItem(const QString &path);
|
||||||
|
void removeItem(PhotoItemWidget *item);
|
||||||
|
void clearItems();
|
||||||
|
void submit();
|
||||||
|
void pumpQueue(); // starts queued items up to the concurrency cap
|
||||||
|
void startItem(PhotoItemWidget *item);
|
||||||
|
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;
|
||||||
|
|
||||||
|
// Settings page
|
||||||
|
QLineEdit *m_baseUrl = nullptr;
|
||||||
|
QLineEdit *m_username = nullptr;
|
||||||
|
QLineEdit *m_password = nullptr;
|
||||||
|
QSpinBox *m_concurrency = nullptr;
|
||||||
|
QPushButton *m_saveButton = nullptr;
|
||||||
|
QPushButton *m_settingsBack = nullptr;
|
||||||
|
QLabel *m_settingsStatus = nullptr;
|
||||||
|
|
||||||
|
// Post page
|
||||||
|
QVBoxLayout *m_itemsLayout = nullptr; // holds the PhotoItemWidgets
|
||||||
|
QList<PhotoItemWidget *> m_items;
|
||||||
|
QLabel *m_emptyHint = nullptr;
|
||||||
|
QPushButton *m_postButton = nullptr;
|
||||||
|
QLabel *m_postSummary = nullptr;
|
||||||
|
QLabel *m_lastPost = nullptr;
|
||||||
|
|
||||||
|
// Bulk-post state: items waiting for a free upload slot, plus the batch's
|
||||||
|
// credentials captured once at submit time.
|
||||||
|
QList<PhotoItemWidget *> m_queue;
|
||||||
|
QString m_batchBaseUrl;
|
||||||
|
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;
|
||||||
|
};
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
[Desktop Entry]
|
||||||
|
Type=Application
|
||||||
|
Name=Photog
|
||||||
|
GenericName=Photo Uploader
|
||||||
|
Comment=Upload photos to your gallery
|
||||||
|
Exec=photog
|
||||||
|
Icon=photog
|
||||||
|
Terminal=false
|
||||||
|
Categories=Graphics;Photography;Network;
|
||||||
@@ -0,0 +1,120 @@
|
|||||||
|
#include "photoitemwidget.h"
|
||||||
|
|
||||||
|
#include "tagcompleter.h"
|
||||||
|
|
||||||
|
#include <QDate>
|
||||||
|
#include <QDateEdit>
|
||||||
|
#include <QHBoxLayout>
|
||||||
|
#include <QImageReader>
|
||||||
|
#include <QLabel>
|
||||||
|
#include <QLineEdit>
|
||||||
|
#include <QPixmap>
|
||||||
|
#include <QPushButton>
|
||||||
|
#include <QVBoxLayout>
|
||||||
|
|
||||||
|
namespace {
|
||||||
|
constexpr int kThumbSize = 72;
|
||||||
|
}
|
||||||
|
|
||||||
|
PhotoItemWidget::PhotoItemWidget(QString sourcePath, QWidget *parent)
|
||||||
|
: QWidget(parent)
|
||||||
|
, m_sourcePath(std::move(sourcePath))
|
||||||
|
{
|
||||||
|
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);
|
||||||
|
{
|
||||||
|
QImageReader reader(m_sourcePath);
|
||||||
|
reader.setAutoTransform(true);
|
||||||
|
const QImage image = reader.read();
|
||||||
|
if (!image.isNull())
|
||||||
|
m_thumb->setPixmap(QPixmap::fromImage(image).scaled(
|
||||||
|
kThumbSize, kThumbSize, Qt::KeepAspectRatioByExpanding, Qt::SmoothTransformation));
|
||||||
|
else
|
||||||
|
m_thumb->setText(QStringLiteral("?"));
|
||||||
|
}
|
||||||
|
row->addWidget(m_thumb);
|
||||||
|
|
||||||
|
auto *fields = new QVBoxLayout;
|
||||||
|
m_caption = new QLineEdit;
|
||||||
|
m_caption->setPlaceholderText(QStringLiteral("Caption (defaults to the filename)"));
|
||||||
|
fields->addWidget(m_caption);
|
||||||
|
|
||||||
|
m_date = new QDateEdit(QDate::currentDate());
|
||||||
|
m_date->setCalendarPopup(true);
|
||||||
|
m_date->setDisplayFormat(QStringLiteral("yyyy-MM-dd"));
|
||||||
|
fields->addWidget(m_date);
|
||||||
|
|
||||||
|
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;
|
||||||
|
m_statusLabel->setOpenExternalLinks(true);
|
||||||
|
m_statusLabel->setWordWrap(true);
|
||||||
|
fields->addWidget(m_statusLabel);
|
||||||
|
row->addLayout(fields, 1);
|
||||||
|
|
||||||
|
m_remove = new QPushButton(QStringLiteral("✕"));
|
||||||
|
m_remove->setFlat(true);
|
||||||
|
m_remove->setFixedWidth(32);
|
||||||
|
connect(m_remove, &QPushButton::clicked, this, [this]() { emit removeRequested(this); });
|
||||||
|
row->addWidget(m_remove, 0, Qt::AlignTop);
|
||||||
|
}
|
||||||
|
|
||||||
|
QString PhotoItemWidget::caption() const
|
||||||
|
{
|
||||||
|
return m_caption->text();
|
||||||
|
}
|
||||||
|
|
||||||
|
QString PhotoItemWidget::date() const
|
||||||
|
{
|
||||||
|
return m_date->date().toString(QStringLiteral("yyyy-MM-dd"));
|
||||||
|
}
|
||||||
|
|
||||||
|
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;
|
||||||
|
|
||||||
|
// Inputs are frozen once the photo is in flight; the remove button stays
|
||||||
|
// usable except mid-transfer.
|
||||||
|
const bool editable = status == Status::Pending || status == Status::Error;
|
||||||
|
m_caption->setEnabled(editable);
|
||||||
|
m_date->setEnabled(editable);
|
||||||
|
m_tags->setEnabled(editable);
|
||||||
|
m_remove->setEnabled(status != Status::Preparing && status != Status::Uploading);
|
||||||
|
|
||||||
|
switch (status) {
|
||||||
|
case Status::Pending:
|
||||||
|
m_statusLabel->clear();
|
||||||
|
break;
|
||||||
|
case Status::Preparing:
|
||||||
|
m_statusLabel->setText(QStringLiteral("Preparing…"));
|
||||||
|
break;
|
||||||
|
case Status::Uploading:
|
||||||
|
m_statusLabel->setText(QStringLiteral("Uploading…"));
|
||||||
|
break;
|
||||||
|
case Status::Success:
|
||||||
|
m_statusLabel->setText(QStringLiteral("Posted — <a href=\"%1\">View</a>").arg(url));
|
||||||
|
break;
|
||||||
|
case Status::Error:
|
||||||
|
m_statusLabel->setText(QStringLiteral("<span style=\"color:#fb4934\">%1</span>").arg(message));
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,47 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <QString>
|
||||||
|
#include <QWidget>
|
||||||
|
|
||||||
|
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.
|
||||||
|
class PhotoItemWidget : public QWidget
|
||||||
|
{
|
||||||
|
Q_OBJECT
|
||||||
|
public:
|
||||||
|
enum class Status { Pending, Preparing, Uploading, Success, Error };
|
||||||
|
|
||||||
|
explicit PhotoItemWidget(QString sourcePath, QWidget *parent = nullptr);
|
||||||
|
|
||||||
|
QString sourcePath() const { return m_sourcePath; }
|
||||||
|
QString caption() const;
|
||||||
|
QString date() const; // yyyy-MM-dd
|
||||||
|
QString tags() const; // raw comma-separated; the server normalizes
|
||||||
|
Status status() const { return m_status; }
|
||||||
|
|
||||||
|
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);
|
||||||
|
|
||||||
|
private:
|
||||||
|
QString m_sourcePath;
|
||||||
|
Status m_status = Status::Pending;
|
||||||
|
|
||||||
|
QLabel *m_thumb = nullptr;
|
||||||
|
QLineEdit *m_caption = nullptr;
|
||||||
|
QDateEdit *m_date = nullptr;
|
||||||
|
QLineEdit *m_tags = nullptr;
|
||||||
|
QLabel *m_statusLabel = nullptr;
|
||||||
|
QPushButton *m_remove = nullptr;
|
||||||
|
TagCompleter *m_tagCompleter = nullptr;
|
||||||
|
};
|
||||||
@@ -0,0 +1,126 @@
|
|||||||
|
#include "settings.h"
|
||||||
|
|
||||||
|
#include <QEventLoop>
|
||||||
|
#include <QUrl>
|
||||||
|
|
||||||
|
#include <algorithm>
|
||||||
|
|
||||||
|
#include <qt6keychain/keychain.h>
|
||||||
|
|
||||||
|
namespace {
|
||||||
|
const QLatin1String kService("photogallery-uploader");
|
||||||
|
const QLatin1String kPasswordKey("password");
|
||||||
|
} // namespace
|
||||||
|
|
||||||
|
Settings::Settings()
|
||||||
|
: m_settings(QStringLiteral("inflo.ws"), QStringLiteral("photogallery-uploader"))
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
|
QString Settings::baseUrl() const
|
||||||
|
{
|
||||||
|
return m_settings.value(QStringLiteral("baseUrl")).toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
void Settings::setBaseUrl(const QString &value)
|
||||||
|
{
|
||||||
|
m_settings.setValue(QStringLiteral("baseUrl"), normalizeBaseUrl(value));
|
||||||
|
}
|
||||||
|
|
||||||
|
QString Settings::username() const
|
||||||
|
{
|
||||||
|
return m_settings.value(QStringLiteral("username")).toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
void Settings::setUsername(const QString &value)
|
||||||
|
{
|
||||||
|
m_settings.setValue(QStringLiteral("username"), value.trimmed());
|
||||||
|
}
|
||||||
|
|
||||||
|
int Settings::concurrency() const
|
||||||
|
{
|
||||||
|
const int v = m_settings.value(QStringLiteral("concurrency"), kDefaultConcurrency).toInt();
|
||||||
|
return std::clamp(v, 1, kMaxConcurrency);
|
||||||
|
}
|
||||||
|
|
||||||
|
void Settings::setConcurrency(int value)
|
||||||
|
{
|
||||||
|
m_settings.setValue(QStringLiteral("concurrency"), std::clamp(value, 1, kMaxConcurrency));
|
||||||
|
}
|
||||||
|
|
||||||
|
QString Settings::readPassword() const
|
||||||
|
{
|
||||||
|
QKeychain::ReadPasswordJob job(kService);
|
||||||
|
job.setAutoDelete(false);
|
||||||
|
job.setKey(kPasswordKey);
|
||||||
|
|
||||||
|
QEventLoop loop;
|
||||||
|
QObject::connect(&job, &QKeychain::Job::finished, &loop, &QEventLoop::quit);
|
||||||
|
job.start();
|
||||||
|
loop.exec();
|
||||||
|
|
||||||
|
if (job.error() != QKeychain::NoError)
|
||||||
|
return QString();
|
||||||
|
return job.textData();
|
||||||
|
}
|
||||||
|
|
||||||
|
void Settings::writePassword(const QString &value) const
|
||||||
|
{
|
||||||
|
QKeychain::WritePasswordJob job(kService);
|
||||||
|
job.setAutoDelete(false);
|
||||||
|
job.setKey(kPasswordKey);
|
||||||
|
job.setTextData(value);
|
||||||
|
|
||||||
|
QEventLoop loop;
|
||||||
|
QObject::connect(&job, &QKeychain::Job::finished, &loop, &QEventLoop::quit);
|
||||||
|
job.start();
|
||||||
|
loop.exec();
|
||||||
|
}
|
||||||
|
|
||||||
|
bool Settings::isConfigured() const
|
||||||
|
{
|
||||||
|
return !baseUrl().isEmpty() && !username().isEmpty() && !readPassword().isEmpty();
|
||||||
|
}
|
||||||
|
|
||||||
|
Settings::LastPost Settings::lastPost() const
|
||||||
|
{
|
||||||
|
LastPost p;
|
||||||
|
p.slug = m_settings.value(QStringLiteral("last/slug")).toString();
|
||||||
|
p.url = m_settings.value(QStringLiteral("last/url")).toString();
|
||||||
|
p.caption = m_settings.value(QStringLiteral("last/caption")).toString();
|
||||||
|
p.postedAt = m_settings.value(QStringLiteral("last/postedAt")).toDateTime();
|
||||||
|
return p;
|
||||||
|
}
|
||||||
|
|
||||||
|
void Settings::setLastPost(const LastPost &value)
|
||||||
|
{
|
||||||
|
m_settings.setValue(QStringLiteral("last/slug"), value.slug);
|
||||||
|
m_settings.setValue(QStringLiteral("last/url"), value.url);
|
||||||
|
m_settings.setValue(QStringLiteral("last/caption"), value.caption);
|
||||||
|
m_settings.setValue(QStringLiteral("last/postedAt"), value.postedAt);
|
||||||
|
}
|
||||||
|
|
||||||
|
QString Settings::validateBaseUrl(const QString &raw)
|
||||||
|
{
|
||||||
|
const QString trimmed = raw.trimmed();
|
||||||
|
if (trimmed.isEmpty())
|
||||||
|
return QStringLiteral("Base URL is required");
|
||||||
|
const QUrl url(trimmed);
|
||||||
|
if (!url.isValid() || url.host().isEmpty())
|
||||||
|
return QStringLiteral("Not a valid URL");
|
||||||
|
if (url.scheme() != QStringLiteral("https"))
|
||||||
|
return QStringLiteral("Must be https — plain http sends your password in the clear");
|
||||||
|
return QString();
|
||||||
|
}
|
||||||
|
|
||||||
|
QString Settings::normalizeBaseUrl(const QString &raw)
|
||||||
|
{
|
||||||
|
QString v = raw.trimmed();
|
||||||
|
while (v.endsWith(QLatin1Char('/')))
|
||||||
|
v.chop(1);
|
||||||
|
if (v.endsWith(QStringLiteral("/upload"), Qt::CaseInsensitive))
|
||||||
|
v.chop(QStringLiteral("/upload").size());
|
||||||
|
while (v.endsWith(QLatin1Char('/')))
|
||||||
|
v.chop(1);
|
||||||
|
return v;
|
||||||
|
}
|
||||||
@@ -0,0 +1,58 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <QDateTime>
|
||||||
|
#include <QSettings>
|
||||||
|
#include <QString>
|
||||||
|
|
||||||
|
// Persists the non-secret settings (base URL, username, last post) in a
|
||||||
|
// QSettings INI under ~/.config, and the password in the system keychain
|
||||||
|
// (libsecret / kwallet via QtKeychain). The password never lands on disk in the
|
||||||
|
// clear, mirroring the Android app's Keystore sealing.
|
||||||
|
class Settings
|
||||||
|
{
|
||||||
|
public:
|
||||||
|
struct LastPost {
|
||||||
|
QString slug;
|
||||||
|
QString url;
|
||||||
|
QString caption;
|
||||||
|
QDateTime postedAt;
|
||||||
|
bool valid() const { return !slug.isEmpty(); }
|
||||||
|
};
|
||||||
|
|
||||||
|
Settings();
|
||||||
|
|
||||||
|
QString baseUrl() const;
|
||||||
|
void setBaseUrl(const QString &value);
|
||||||
|
|
||||||
|
QString username() const;
|
||||||
|
void setUsername(const QString &value);
|
||||||
|
|
||||||
|
// Max photos uploaded at once in a bulk post, clamped to [1, kMaxConcurrency].
|
||||||
|
static constexpr int kMaxConcurrency = 8;
|
||||||
|
static constexpr int kDefaultConcurrency = 3;
|
||||||
|
int concurrency() const;
|
||||||
|
void setConcurrency(int value);
|
||||||
|
|
||||||
|
// Keychain access is synchronous here (a local event loop): the app does
|
||||||
|
// nothing until the credential is in hand, and there is no background retry
|
||||||
|
// worker as on Android that would need it off the UI thread.
|
||||||
|
QString readPassword() const;
|
||||||
|
void writePassword(const QString &value) const;
|
||||||
|
|
||||||
|
bool isConfigured() const;
|
||||||
|
|
||||||
|
LastPost lastPost() const;
|
||||||
|
void setLastPost(const LastPost &value);
|
||||||
|
|
||||||
|
// Returns an error message, or an empty string when the URL is usable.
|
||||||
|
// https is required: Basic auth would otherwise send the password in the
|
||||||
|
// clear.
|
||||||
|
static QString validateBaseUrl(const QString &raw);
|
||||||
|
|
||||||
|
// Trims trailing slashes and a trailing "/upload" (the endpoint path a user
|
||||||
|
// pasting the upload URL would leave on — the client appends it itself).
|
||||||
|
static QString normalizeBaseUrl(const QString &raw);
|
||||||
|
|
||||||
|
private:
|
||||||
|
mutable QSettings m_settings;
|
||||||
|
};
|
||||||
@@ -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;
|
||||||
|
};
|
||||||
@@ -0,0 +1,280 @@
|
|||||||
|
#include "uploadclient.h"
|
||||||
|
|
||||||
|
#include <QFile>
|
||||||
|
#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)
|
||||||
|
, m_base(std::move(baseUrl))
|
||||||
|
, m_username(std::move(username))
|
||||||
|
, m_password(std::move(password))
|
||||||
|
, m_net(new QNetworkAccessManager(this))
|
||||||
|
{
|
||||||
|
while (m_base.endsWith(QLatin1Char('/')))
|
||||||
|
m_base.chop(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
QByteArray UploadClient::authHeader() const
|
||||||
|
{
|
||||||
|
const QByteArray raw = (m_username + QLatin1Char(':') + m_password).toUtf8();
|
||||||
|
return "Basic " + raw.toBase64();
|
||||||
|
}
|
||||||
|
|
||||||
|
void UploadClient::upload(const QString &filePath, const QString &fileName,
|
||||||
|
const QString &caption, const QString &date, const QString &tags)
|
||||||
|
{
|
||||||
|
auto *file = new QFile(filePath);
|
||||||
|
if (!file->open(QIODevice::ReadOnly)) {
|
||||||
|
delete file;
|
||||||
|
emit uploadFinished(Result::Rejected, {}, {}, QStringLiteral("Could not read the prepared image"));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
auto *multiPart = new QHttpMultiPart(QHttpMultiPart::FormDataType);
|
||||||
|
|
||||||
|
const QByteArray contentType =
|
||||||
|
fileName.endsWith(QStringLiteral(".png"), Qt::CaseInsensitive) ? "image/png" : "image/jpeg";
|
||||||
|
|
||||||
|
QHttpPart imagePart;
|
||||||
|
imagePart.setHeader(QNetworkRequest::ContentTypeHeader, QVariant(contentType));
|
||||||
|
imagePart.setHeader(QNetworkRequest::ContentDispositionHeader,
|
||||||
|
QVariant(QStringLiteral("form-data; name=\"image\"; filename=\"%1\"").arg(fileName)));
|
||||||
|
file->setParent(multiPart);
|
||||||
|
imagePart.setBodyDevice(file);
|
||||||
|
multiPart->append(imagePart);
|
||||||
|
|
||||||
|
const auto textPart = [](const QString &name, const QString &value) {
|
||||||
|
QHttpPart part;
|
||||||
|
part.setHeader(QNetworkRequest::ContentDispositionHeader,
|
||||||
|
QVariant(QStringLiteral("form-data; name=\"%1\"").arg(name)));
|
||||||
|
part.setBody(value.toUtf8());
|
||||||
|
return part;
|
||||||
|
};
|
||||||
|
multiPart->append(textPart(QStringLiteral("caption"), caption));
|
||||||
|
multiPart->append(textPart(QStringLiteral("date"), date));
|
||||||
|
multiPart->append(textPart(QStringLiteral("tags"), tags));
|
||||||
|
|
||||||
|
QNetworkRequest request(QUrl(m_base + QStringLiteral("/upload")));
|
||||||
|
request.setRawHeader("Authorization", authHeader());
|
||||||
|
|
||||||
|
QNetworkReply *reply = m_net->post(request, multiPart);
|
||||||
|
multiPart->setParent(reply);
|
||||||
|
|
||||||
|
const QString fallbackSlug = QFileInfo(fileName).completeBaseName();
|
||||||
|
|
||||||
|
connect(reply, &QNetworkReply::finished, this, [this, reply, fallbackSlug]() {
|
||||||
|
reply->deleteLater();
|
||||||
|
const int status = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
|
||||||
|
const QString body = QString::fromUtf8(reply->readAll()).trimmed();
|
||||||
|
|
||||||
|
if (reply->error() == QNetworkReply::NoError && status >= 200 && status < 300) {
|
||||||
|
// Server replies "uploaded slug.ext"; recover the slug.
|
||||||
|
QString name = body;
|
||||||
|
if (name.startsWith(QStringLiteral("uploaded ")))
|
||||||
|
name = name.mid(QStringLiteral("uploaded ").size()).trimmed();
|
||||||
|
const int dot = name.lastIndexOf(QLatin1Char('.'));
|
||||||
|
QString slug = dot > 0 ? name.left(dot) : name;
|
||||||
|
if (slug.isEmpty())
|
||||||
|
slug = fallbackSlug;
|
||||||
|
emit uploadFinished(Result::Success, slug, m_base + QStringLiteral("/photo/") + slug + QLatin1Char('/'), {});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (status == 401 || status == 403) {
|
||||||
|
emit uploadFinished(Result::AuthFailed, {}, {}, QStringLiteral("Wrong username or password"));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (status >= 500 && status < 600) {
|
||||||
|
emit uploadFinished(Result::Transient, {}, {}, QStringLiteral("Server error %1").arg(status));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (status == 0) {
|
||||||
|
// No HTTP response — a socket/TLS failure. Worth retrying.
|
||||||
|
emit uploadFinished(Result::Transient, {}, {}, reply->errorString());
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
emit uploadFinished(Result::Rejected, {}, {}, body.isEmpty() ? QStringLiteral("Upload rejected") : body);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
void UploadClient::testConnection()
|
||||||
|
{
|
||||||
|
QNetworkRequest request(QUrl(m_base + QStringLiteral("/upload")));
|
||||||
|
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 testFinished(QString());
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (status == 401 || status == 403) {
|
||||||
|
emit testFinished(QStringLiteral("Wrong username or password"));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (status == 0) {
|
||||||
|
emit testFinished(reply->errorString());
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
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"));
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,81 @@
|
|||||||
|
#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
|
||||||
|
// signal, which only fires on a 401 and would replay a multipart body already
|
||||||
|
// streamed off disk).
|
||||||
|
//
|
||||||
|
// Asynchronous: results arrive via signals so the UI stays responsive during an
|
||||||
|
// upload over a slow link.
|
||||||
|
class UploadClient : public QObject
|
||||||
|
{
|
||||||
|
Q_OBJECT
|
||||||
|
public:
|
||||||
|
enum class Result {
|
||||||
|
Success, // uploaded; slug/url populated
|
||||||
|
AuthFailed, // wrong credentials — a retry will not help
|
||||||
|
Rejected, // server said no for a reason a retry won't change
|
||||||
|
Transient, // network trouble or a 5xx — worth retrying
|
||||||
|
};
|
||||||
|
|
||||||
|
UploadClient(QString baseUrl, QString username, QString password, QObject *parent = nullptr);
|
||||||
|
|
||||||
|
// The filename matters: server.go derives the slug from it, so re-sending
|
||||||
|
// the same name overwrites the same post instead of duplicating it.
|
||||||
|
void upload(const QString &filePath, const QString &fileName,
|
||||||
|
const QString &caption, const QString &date, const QString &tags);
|
||||||
|
|
||||||
|
// Credential check via GET /upload (same Basic-auth gate the POST uses).
|
||||||
|
// /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;
|
||||||
|
|
||||||
|
QString m_base;
|
||||||
|
QString m_username;
|
||||||
|
QString m_password;
|
||||||
|
QNetworkAccessManager *m_net;
|
||||||
|
};
|
||||||
@@ -18,11 +18,11 @@
|
|||||||
|
|
||||||
# Run `go mod tidy` to generate go.sum, then `nix build`.
|
# Run `go mod tidy` to generate go.sum, then `nix build`.
|
||||||
# Nix will fail and print the correct hash — paste it here.
|
# Nix will fail and print the correct hash — paste it here.
|
||||||
vendorHash = "sha256-SxQDRProQtauWXPvPzbZZChLQd0iey9hnXFLiPYTS98=";
|
vendorHash = "sha256-Q+VeDZX9DlZtOZrYRwZo19eyob8jIu19IRhdvChmVL4=";
|
||||||
|
|
||||||
meta = with pkgs.lib; {
|
meta = with pkgs.lib; {
|
||||||
description = "Minimal static photo gallery";
|
description = "Minimal static photo gallery";
|
||||||
license = licenses.mit;
|
license = licenses.unlicense;
|
||||||
mainProgram = "photogallery";
|
mainProgram = "photogallery";
|
||||||
platforms = platforms.linux;
|
platforms = platforms.linux;
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"bytes"
|
||||||
"encoding/xml"
|
"encoding/xml"
|
||||||
"html/template"
|
"html/template"
|
||||||
"image"
|
"image"
|
||||||
@@ -12,6 +13,7 @@ import (
|
|||||||
"os"
|
"os"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
"sort"
|
"sort"
|
||||||
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
"sync"
|
"sync"
|
||||||
"time"
|
"time"
|
||||||
@@ -21,24 +23,54 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
const (
|
const (
|
||||||
thumbSize = 600
|
thumbSize = 600
|
||||||
mediumMaxSize = 1600
|
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
|
||||||
|
// the medium rendition (which can exceed that) is not reused here.
|
||||||
|
ogMaxSize = 1200
|
||||||
|
ogTargetBytes = 250 * 1024
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// ogQualityLadder is walked from best to worst until the encoded OG image
|
||||||
|
// fits under ogTargetBytes. The last entry is used as-is even if still over.
|
||||||
|
var ogQualityLadder = []int{85, 78, 70, 62}
|
||||||
|
|
||||||
// PhotoMeta is the structure of a .toml sidecar file.
|
// PhotoMeta is the structure of a .toml sidecar file.
|
||||||
type PhotoMeta struct {
|
type PhotoMeta struct {
|
||||||
Caption string `toml:"caption"`
|
Caption string `toml:"caption"`
|
||||||
Date string `toml:"date"` // YYYY-MM-DD
|
Date string `toml:"date"` // YYYY-MM-DD
|
||||||
|
Tags []string `toml:"tags,omitempty"` // free-text, lowercased; each tag is an album
|
||||||
}
|
}
|
||||||
|
|
||||||
// Photo is the in-memory representation of one image.
|
// Photo is the in-memory representation of one image.
|
||||||
type Photo struct {
|
type Photo struct {
|
||||||
Slug string
|
Slug string
|
||||||
File string // relative path under public/, e.g. "images/foo.jpg"
|
File string // relative path under public/, e.g. "images/foo.jpg"
|
||||||
Thumb string // relative path under public/, e.g. "thumbs/foo.jpg"
|
Thumb string // relative path under public/, e.g. "thumbs/foo.jpg"
|
||||||
Medium string // relative path under public/, e.g. "medium/foo.jpg"
|
Medium string // relative path under public/, e.g. "medium/foo.jpg"
|
||||||
Caption string
|
OG string // relative path under public/, e.g. "og/foo.jpg"
|
||||||
Date time.Time
|
OGWidth int // pixel dimensions of the OG image, for og:image:width/height
|
||||||
|
OGHeight int
|
||||||
|
Caption string
|
||||||
|
Date time.Time
|
||||||
|
Tags []Tag // albums this photo belongs to
|
||||||
|
}
|
||||||
|
|
||||||
|
// DayGroup is a run of photos sharing the same calendar day, for the timeline.
|
||||||
|
type DayGroup struct {
|
||||||
|
day string // "2006-01-02", grouping key (unexported: not for templates)
|
||||||
|
Label string // "14 June 2026"
|
||||||
|
Count int
|
||||||
|
Photos []Photo
|
||||||
}
|
}
|
||||||
|
|
||||||
type Generator struct {
|
type Generator struct {
|
||||||
@@ -52,12 +84,20 @@ type Generator struct {
|
|||||||
fontsURL string
|
fontsURL string
|
||||||
serifFamily string
|
serifFamily string
|
||||||
mlFamily string
|
mlFamily string
|
||||||
|
pageSize int
|
||||||
|
defaultView string
|
||||||
mu sync.Mutex
|
mu sync.Mutex
|
||||||
tmpl *template.Template
|
tmpl *template.Template
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewGenerator(contentDir, outputDir, baseURL, author, handle, bio, bioAlt, fontsURL, serifFamily, mlFamily string) *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"))
|
tmpl := template.Must(template.ParseFS(assets, "templates/*.html"))
|
||||||
|
if pageSize < 1 {
|
||||||
|
pageSize = defaultPageSize
|
||||||
|
}
|
||||||
|
if defaultView != viewGrid {
|
||||||
|
defaultView = viewTimeline
|
||||||
|
}
|
||||||
return &Generator{
|
return &Generator{
|
||||||
contentDir: contentDir,
|
contentDir: contentDir,
|
||||||
outputDir: outputDir,
|
outputDir: outputDir,
|
||||||
@@ -69,10 +109,34 @@ func NewGenerator(contentDir, outputDir, baseURL, author, handle, bio, bioAlt, f
|
|||||||
fontsURL: fontsURL,
|
fontsURL: fontsURL,
|
||||||
serifFamily: serifFamily,
|
serifFamily: serifFamily,
|
||||||
mlFamily: mlFamily,
|
mlFamily: mlFamily,
|
||||||
|
pageSize: pageSize,
|
||||||
|
defaultView: defaultView,
|
||||||
tmpl: tmpl,
|
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 {
|
func (g *Generator) initial() string {
|
||||||
for _, r := range g.author {
|
for _, r := range g.author {
|
||||||
return strings.ToUpper(string(r))
|
return strings.ToUpper(string(r))
|
||||||
@@ -91,23 +155,64 @@ func (g *Generator) Build() error {
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
for _, d := range []string{"images", "thumbs", "medium", "photo", "static"} {
|
// Drop fully-derived HTML trees before regenerating them, so a deleted
|
||||||
|
// 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
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
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 {
|
if err := os.MkdirAll(filepath.Join(g.outputDir, d), 0755); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Remove rendition files whose source photo is gone (e.g. after a delete),
|
||||||
|
// keeping the expensive resize outputs of surviving photos in place so
|
||||||
|
// up-to-date skipping still works.
|
||||||
|
g.pruneRenditions(photos)
|
||||||
|
|
||||||
for i := range photos {
|
for i := range photos {
|
||||||
if err := g.processImage(&photos[i]); err != nil {
|
if err := g.processImage(&photos[i]); err != nil {
|
||||||
log.Printf("processImage %s: %v", photos[i].Slug, err)
|
log.Printf("processImage %s: %v", photos[i].Slug, err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if err := g.renderIndex(photos); err != nil {
|
if err := g.renderTimelinePages(photos); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
for _, p := range photos {
|
if err := g.renderGridPages(photos); err != nil {
|
||||||
if err := g.renderPhotoPage(p); err != nil {
|
return err
|
||||||
|
}
|
||||||
|
if err := g.renderDayPages(photos); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
albums := groupByTag(photos)
|
||||||
|
if err := g.renderAlbumPages(albums, len(photos)); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if err := g.renderAlbumsIndex(albums, len(photos)); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if err := g.renderTagsJSON(albums); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
for i := range photos {
|
||||||
|
var newer, older *Photo
|
||||||
|
if i > 0 {
|
||||||
|
newer = &photos[i-1]
|
||||||
|
}
|
||||||
|
if i+1 < len(photos) {
|
||||||
|
older = &photos[i+1]
|
||||||
|
}
|
||||||
|
if err := g.renderPhotoPage(photos[i], newer, older); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -163,8 +268,10 @@ func (g *Generator) loadPhotos() ([]Photo, error) {
|
|||||||
File: "images/" + name,
|
File: "images/" + name,
|
||||||
Thumb: "thumbs/" + slug + ".jpg",
|
Thumb: "thumbs/" + slug + ".jpg",
|
||||||
Medium: "medium/" + slug + ".jpg",
|
Medium: "medium/" + slug + ".jpg",
|
||||||
|
OG: "og/" + slug + ".jpg",
|
||||||
Caption: meta.Caption,
|
Caption: meta.Caption,
|
||||||
Date: date,
|
Date: date,
|
||||||
|
Tags: parseTags(meta.Tags...),
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -174,6 +281,35 @@ func (g *Generator) loadPhotos() ([]Photo, error) {
|
|||||||
return photos, nil
|
return photos, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// pruneRenditions deletes files in the image output directories that no longer
|
||||||
|
// have a backing photo in content/. Called on every build, it is what makes a
|
||||||
|
// delete (and the stale sidecar left by any removed source) actually disappear
|
||||||
|
// from public/ rather than linger as an orphan reachable by direct URL.
|
||||||
|
func (g *Generator) pruneRenditions(photos []Photo) {
|
||||||
|
valid := make(map[string]bool, len(photos))
|
||||||
|
for _, p := range photos {
|
||||||
|
valid[p.Slug] = true
|
||||||
|
}
|
||||||
|
for _, d := range []string{"images", "thumbs", "medium", "og"} {
|
||||||
|
full := filepath.Join(g.outputDir, d)
|
||||||
|
entries, err := os.ReadDir(full)
|
||||||
|
if err != nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
for _, e := range entries {
|
||||||
|
if e.IsDir() {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
slug := strings.TrimSuffix(e.Name(), filepath.Ext(e.Name()))
|
||||||
|
if !valid[slug] {
|
||||||
|
if err := os.Remove(filepath.Join(full, e.Name())); err != nil {
|
||||||
|
log.Printf("prune %s/%s: %v", d, e.Name(), err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// processImage copies the original to public/images/ and writes a square
|
// processImage copies the original to public/images/ and writes a square
|
||||||
// thumbnail to public/thumbs/ plus an aspect-preserved medium image to
|
// thumbnail to public/thumbs/ plus an aspect-preserved medium image to
|
||||||
// public/medium/. Outputs are skipped when already newer than the source.
|
// public/medium/. Outputs are skipped when already newer than the source.
|
||||||
@@ -182,6 +318,7 @@ func (g *Generator) processImage(p *Photo) error {
|
|||||||
dstImg := filepath.Join(g.outputDir, p.File)
|
dstImg := filepath.Join(g.outputDir, p.File)
|
||||||
dstThumb := filepath.Join(g.outputDir, p.Thumb)
|
dstThumb := filepath.Join(g.outputDir, p.Thumb)
|
||||||
dstMedium := filepath.Join(g.outputDir, p.Medium)
|
dstMedium := filepath.Join(g.outputDir, p.Medium)
|
||||||
|
dstOG := filepath.Join(g.outputDir, p.OG)
|
||||||
|
|
||||||
if !upToDate(src, dstImg) {
|
if !upToDate(src, dstImg) {
|
||||||
if err := copyFile(src, dstImg); err != nil {
|
if err := copyFile(src, dstImg); err != nil {
|
||||||
@@ -198,9 +335,36 @@ func (g *Generator) processImage(p *Photo) error {
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
if !upToDate(src, dstOG) {
|
||||||
|
if err := generateOG(src, dstOG, ogMaxSize); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// og:image:width/height need the OG image's real dimensions, and they must
|
||||||
|
// be known even when the file above was skipped as up to date. DecodeConfig
|
||||||
|
// reads only the JPEG header, so this is cheap.
|
||||||
|
if cfg, err := decodeConfigFile(dstOG); err == nil {
|
||||||
|
p.OGWidth = cfg.Width
|
||||||
|
p.OGHeight = cfg.Height
|
||||||
|
} else {
|
||||||
|
log.Printf("og dimensions %s: %v", p.Slug, err)
|
||||||
|
}
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// decodeConfigFile reads just the image header of path and returns its config
|
||||||
|
// (dimensions, colour model) without decoding the pixels.
|
||||||
|
func decodeConfigFile(path string) (image.Config, error) {
|
||||||
|
f, err := os.Open(path)
|
||||||
|
if err != nil {
|
||||||
|
return image.Config{}, err
|
||||||
|
}
|
||||||
|
defer f.Close()
|
||||||
|
cfg, _, err := image.DecodeConfig(f)
|
||||||
|
return cfg, err
|
||||||
|
}
|
||||||
|
|
||||||
// upToDate reports whether dst exists and is at least as new as src.
|
// upToDate reports whether dst exists and is at least as new as src.
|
||||||
func upToDate(src, dst string) bool {
|
func upToDate(src, dst string) bool {
|
||||||
si, err := os.Stat(src)
|
si, err := os.Stat(src)
|
||||||
@@ -290,16 +454,127 @@ func generateMedium(src, dst string, maxDim int) error {
|
|||||||
return jpeg.Encode(out, resized, &jpeg.Options{Quality: 88})
|
return jpeg.Encode(out, resized, &jpeg.Options{Quality: 88})
|
||||||
}
|
}
|
||||||
|
|
||||||
// renderIndex writes public/index.html.
|
// generateOG reads src, resizes it so its longest side is at most maxDim, and
|
||||||
func (g *Generator) renderIndex(photos []Photo) error {
|
// writes a JPEG small enough for social link previews. It walks ogQualityLadder
|
||||||
return g.render("index.html", filepath.Join(g.outputDir, "index.html"), map[string]any{
|
// from best to worst, stopping at the first quality whose output is under
|
||||||
"Photos": photos,
|
// ogTargetBytes, and falls back to the lowest quality if none fits.
|
||||||
|
func generateOG(src, dst string, maxDim int) error {
|
||||||
|
f, err := os.Open(src)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
defer f.Close()
|
||||||
|
|
||||||
|
img, _, err := image.Decode(f)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
b := img.Bounds()
|
||||||
|
w, h := b.Dx(), b.Dy()
|
||||||
|
nw, nh := w, h
|
||||||
|
if w > maxDim || h > maxDim {
|
||||||
|
if w >= h {
|
||||||
|
nw = maxDim
|
||||||
|
nh = h * maxDim / w
|
||||||
|
} else {
|
||||||
|
nh = maxDim
|
||||||
|
nw = w * maxDim / h
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
resized := image.NewRGBA(image.Rect(0, 0, nw, nh))
|
||||||
|
xdraw.CatmullRom.Scale(resized, resized.Bounds(), img, b, xdraw.Over, nil)
|
||||||
|
|
||||||
|
var buf bytes.Buffer
|
||||||
|
for i, q := range ogQualityLadder {
|
||||||
|
buf.Reset()
|
||||||
|
if err := jpeg.Encode(&buf, resized, &jpeg.Options{Quality: q}); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if buf.Len() <= ogTargetBytes || i == len(ogQualityLadder)-1 {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return os.WriteFile(dst, buf.Bytes(), 0644)
|
||||||
|
}
|
||||||
|
|
||||||
|
// 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
|
||||||
|
}
|
||||||
|
base := g.viewBase(viewGrid)
|
||||||
|
|
||||||
|
for i := 0; i < totalPages; i++ {
|
||||||
|
start := i * g.pageSize
|
||||||
|
end := start + g.pageSize
|
||||||
|
if end > total {
|
||||||
|
end = total
|
||||||
|
}
|
||||||
|
slice := photos[start:end]
|
||||||
|
|
||||||
|
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")
|
||||||
|
|
||||||
|
prev := ""
|
||||||
|
next := ""
|
||||||
|
if i > 0 {
|
||||||
|
prev = pageURL(base, i)
|
||||||
|
}
|
||||||
|
if i+1 < totalPages {
|
||||||
|
next = pageURL(base, i+2)
|
||||||
|
}
|
||||||
|
|
||||||
|
data := map[string]any{
|
||||||
|
"Photos": slice,
|
||||||
|
"Total": total,
|
||||||
|
"Page": i + 1,
|
||||||
|
"TotalPages": totalPages,
|
||||||
|
"PrevURL": prev,
|
||||||
|
"NextURL": next,
|
||||||
|
"TimelineURL": g.timelineURL(),
|
||||||
|
"GridURL": g.gridURL(),
|
||||||
|
"BaseURL": g.baseURL,
|
||||||
|
"Year": time.Now().Year(),
|
||||||
|
"Author": g.author,
|
||||||
|
"Handle": g.handle,
|
||||||
|
"Bio": g.bio,
|
||||||
|
"BioAlt": g.bioAlt,
|
||||||
|
"Initial": g.initial(),
|
||||||
|
"FontsURL": g.fontsURL,
|
||||||
|
"SerifFamily": g.serifFamily,
|
||||||
|
"MlFamily": g.mlFamily,
|
||||||
|
}
|
||||||
|
if err := g.render("grid.html", dst, data); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// renderPhotoPage writes public/photo/<slug>/index.html.
|
||||||
|
func (g *Generator) renderPhotoPage(p Photo, newer, older *Photo) error {
|
||||||
|
dir := filepath.Join(g.outputDir, "photo", p.Slug)
|
||||||
|
if err := os.MkdirAll(dir, 0755); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return g.render("photo.html", filepath.Join(dir, "index.html"), map[string]any{
|
||||||
|
"Photo": p,
|
||||||
|
"Newer": newer,
|
||||||
|
"Older": older,
|
||||||
"BaseURL": g.baseURL,
|
"BaseURL": g.baseURL,
|
||||||
"Year": time.Now().Year(),
|
"Year": time.Now().Year(),
|
||||||
"Author": g.author,
|
"Author": g.author,
|
||||||
"Handle": g.handle,
|
"Handle": g.handle,
|
||||||
"Bio": g.bio,
|
|
||||||
"BioAlt": g.bioAlt,
|
|
||||||
"Initial": g.initial(),
|
"Initial": g.initial(),
|
||||||
"FontsURL": g.fontsURL,
|
"FontsURL": g.fontsURL,
|
||||||
"SerifFamily": g.serifFamily,
|
"SerifFamily": g.serifFamily,
|
||||||
@@ -307,23 +582,137 @@ func (g *Generator) renderIndex(photos []Photo) error {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
// renderPhotoPage writes public/photo/<slug>/index.html.
|
// groupByDay collapses photos (already sorted newest first) into per-day runs,
|
||||||
func (g *Generator) renderPhotoPage(p Photo) error {
|
// preserving order. Two photos land in the same group iff their dates share a
|
||||||
dir := filepath.Join(g.outputDir, "photo", p.Slug)
|
// calendar day.
|
||||||
if err := os.MkdirAll(dir, 0755); err != nil {
|
func groupByDay(photos []Photo) []DayGroup {
|
||||||
return err
|
var groups []DayGroup
|
||||||
|
for _, p := range photos {
|
||||||
|
day := p.Date.Format("2006-01-02")
|
||||||
|
if n := len(groups); n > 0 && groups[n-1].day == day {
|
||||||
|
groups[n-1].Photos = append(groups[n-1].Photos, p)
|
||||||
|
groups[n-1].Count++
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
groups = append(groups, DayGroup{
|
||||||
|
day: day,
|
||||||
|
Label: day, // ISO 2006-01-02
|
||||||
|
Count: 1,
|
||||||
|
Photos: []Photo{p},
|
||||||
|
})
|
||||||
}
|
}
|
||||||
return g.render("photo.html", filepath.Join(dir, "index.html"), map[string]any{
|
return groups
|
||||||
"Photo": p,
|
}
|
||||||
"BaseURL": g.baseURL,
|
|
||||||
"Year": time.Now().Year(),
|
// chunkDayGroups packs day groups into pages, filling each page until it holds
|
||||||
"Author": g.author,
|
// at least target photos, then starting a new one. A single day is never split
|
||||||
"Handle": g.handle,
|
// across a page boundary, so page sizes vary slightly around target. Always
|
||||||
"Initial": g.initial(),
|
// returns at least one page (empty when there are no photos) so the site root
|
||||||
"FontsURL": g.fontsURL,
|
// renders.
|
||||||
"SerifFamily": g.serifFamily,
|
func chunkDayGroups(groups []DayGroup, target int) [][]DayGroup {
|
||||||
"MlFamily": g.mlFamily,
|
var pages [][]DayGroup
|
||||||
})
|
var cur []DayGroup
|
||||||
|
count := 0
|
||||||
|
for _, grp := range groups {
|
||||||
|
cur = append(cur, grp)
|
||||||
|
count += grp.Count
|
||||||
|
if count >= target {
|
||||||
|
pages = append(pages, cur)
|
||||||
|
cur, count = nil, 0
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(cur) > 0 {
|
||||||
|
pages = append(pages, cur)
|
||||||
|
}
|
||||||
|
if len(pages) == 0 {
|
||||||
|
pages = [][]DayGroup{nil}
|
||||||
|
}
|
||||||
|
return pages
|
||||||
|
}
|
||||||
|
|
||||||
|
// 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 {
|
||||||
|
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")
|
||||||
|
|
||||||
|
prev := ""
|
||||||
|
next := ""
|
||||||
|
if i > 0 {
|
||||||
|
prev = pageURL(base, i)
|
||||||
|
}
|
||||||
|
if i+1 < totalPages {
|
||||||
|
next = pageURL(base, i+2)
|
||||||
|
}
|
||||||
|
|
||||||
|
data := map[string]any{
|
||||||
|
"Groups": groups,
|
||||||
|
"Total": len(photos),
|
||||||
|
"Page": i + 1,
|
||||||
|
"TotalPages": totalPages,
|
||||||
|
"PrevURL": prev,
|
||||||
|
"NextURL": next,
|
||||||
|
"TimelineURL": g.timelineURL(),
|
||||||
|
"GridURL": g.gridURL(),
|
||||||
|
"BaseURL": g.baseURL,
|
||||||
|
"Year": time.Now().Year(),
|
||||||
|
"Author": g.author,
|
||||||
|
"Handle": g.handle,
|
||||||
|
"Bio": g.bio,
|
||||||
|
"BioAlt": g.bioAlt,
|
||||||
|
"Initial": g.initial(),
|
||||||
|
"FontsURL": g.fontsURL,
|
||||||
|
"SerifFamily": g.serifFamily,
|
||||||
|
"MlFamily": g.mlFamily,
|
||||||
|
}
|
||||||
|
if err := g.render("timeline.html", dst, data); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// renderDayPages writes one page per calendar day under public/day/<ISO>/,
|
||||||
|
// holding just that day's photos. Timeline date headings link here.
|
||||||
|
func (g *Generator) renderDayPages(photos []Photo) error {
|
||||||
|
for _, grp := range groupByDay(photos) {
|
||||||
|
dir := filepath.Join(g.outputDir, "day", grp.day)
|
||||||
|
if err := os.MkdirAll(dir, 0755); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
err := g.render("day.html", filepath.Join(dir, "index.html"), map[string]any{
|
||||||
|
"Date": grp.Label,
|
||||||
|
"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,
|
||||||
|
"Handle": g.handle,
|
||||||
|
"Bio": g.bio,
|
||||||
|
"BioAlt": g.bioAlt,
|
||||||
|
"Initial": g.initial(),
|
||||||
|
"FontsURL": g.fontsURL,
|
||||||
|
"SerifFamily": g.serifFamily,
|
||||||
|
"MlFamily": g.mlFamily,
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (g *Generator) render(tmpl, dst string, data any) error {
|
func (g *Generator) render(tmpl, dst string, data any) error {
|
||||||
@@ -408,6 +797,14 @@ func (g *Generator) copyStatic() error {
|
|||||||
if err := os.WriteFile(dst, data, 0644); err != nil {
|
if err := os.WriteFile(dst, data, 0644); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Also serve the favicon from the site root, where browsers and
|
||||||
|
// crawlers request /favicon.ico by default without a <link> tag.
|
||||||
|
if e.Name() == "favicon.ico" {
|
||||||
|
if err := os.WriteFile(filepath.Join(g.outputDir, e.Name()), data, 0644); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,11 +1,13 @@
|
|||||||
module photogallery
|
module photogallery
|
||||||
|
|
||||||
go 1.22
|
go 1.26.0
|
||||||
|
|
||||||
require (
|
require (
|
||||||
github.com/BurntSushi/toml v1.4.0
|
github.com/BurntSushi/toml v1.4.0
|
||||||
github.com/fsnotify/fsnotify v1.7.0
|
github.com/fsnotify/fsnotify v1.7.0
|
||||||
|
golang.org/x/crypto v0.58.0
|
||||||
golang.org/x/image v0.21.0
|
golang.org/x/image v0.21.0
|
||||||
|
golang.org/x/time v0.16.0
|
||||||
)
|
)
|
||||||
|
|
||||||
require golang.org/x/sys v0.4.0 // indirect
|
require golang.org/x/sys v0.49.0 // indirect
|
||||||
@@ -2,7 +2,11 @@ github.com/BurntSushi/toml v1.4.0 h1:kuoIxZQy2WRRk1pttg9asf+WVv6tWQuBNVmK8+nqPr0
|
|||||||
github.com/BurntSushi/toml v1.4.0/go.mod h1:ukJfTF/6rtPPRCnwkur4qwRxa8vTRFBF0uk2lLoLwho=
|
github.com/BurntSushi/toml v1.4.0/go.mod h1:ukJfTF/6rtPPRCnwkur4qwRxa8vTRFBF0uk2lLoLwho=
|
||||||
github.com/fsnotify/fsnotify v1.7.0 h1:8JEhPFa5W2WU7YfeZzPNqzMP6Lwt7L2715Ggo0nosvA=
|
github.com/fsnotify/fsnotify v1.7.0 h1:8JEhPFa5W2WU7YfeZzPNqzMP6Lwt7L2715Ggo0nosvA=
|
||||||
github.com/fsnotify/fsnotify v1.7.0/go.mod h1:40Bi/Hjc2AVfZrqy+aj+yEI+/bRxZnMJyTJwOpGvigM=
|
github.com/fsnotify/fsnotify v1.7.0/go.mod h1:40Bi/Hjc2AVfZrqy+aj+yEI+/bRxZnMJyTJwOpGvigM=
|
||||||
|
golang.org/x/crypto v0.58.0 h1:COkYLr4k7nDI4r6QtMML2AfzeIswWHAJthLS6K/M/54=
|
||||||
|
golang.org/x/crypto v0.58.0/go.mod h1:Xh+kl5A+M0gMiWDytH2Hhr5Z7WbNCpv/eB/EFgfSk+w=
|
||||||
golang.org/x/image v0.21.0 h1:c5qV36ajHpdj4Qi0GnE0jUc/yuo33OLFaa0d+crTD5s=
|
golang.org/x/image v0.21.0 h1:c5qV36ajHpdj4Qi0GnE0jUc/yuo33OLFaa0d+crTD5s=
|
||||||
golang.org/x/image v0.21.0/go.mod h1:vUbsLavqK/W303ZroQQVKQ+Af3Yl6Uz1Ppu5J/cLz78=
|
golang.org/x/image v0.21.0/go.mod h1:vUbsLavqK/W303ZroQQVKQ+Af3Yl6Uz1Ppu5J/cLz78=
|
||||||
golang.org/x/sys v0.4.0 h1:Zr2JFtRQNX3BCZ8YtxRE9hNJYC8J6I1MVbMg6owUp18=
|
golang.org/x/sys v0.49.0 h1:XbzkgYJHdqh/8m2Uu0W/dQv8nktxx4BFHp1M0gROTXA=
|
||||||
golang.org/x/sys v0.4.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
golang.org/x/sys v0.49.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og=
|
||||||
|
golang.org/x/time v0.16.0 h1:vMb6ptszcQMkcwiRTAuNNU50gom6++Q/6gY2hDM6VDE=
|
||||||
|
golang.org/x/time v0.16.0/go.mod h1:rVKOqvZeKvrDKTQiAHJ7wmwP0RzleSphoEA9RcdLA0s=
|
||||||
|
After Width: | Height: | Size: 22 KiB |
|
After Width: | Height: | Size: 32 KiB |
|
After Width: | Height: | Size: 87 KiB |
|
After Width: | Height: | Size: 9.2 KiB |
|
After Width: | Height: | Size: 96 KiB |
|
After Width: | Height: | Size: 12 KiB |
|
After Width: | Height: | Size: 15 KiB |
|
After Width: | Height: | Size: 241 KiB |
|
After Width: | Height: | Size: 21 KiB |
|
After Width: | Height: | Size: 27 KiB |
|
After Width: | Height: | Size: 30 KiB |
|
After Width: | Height: | Size: 33 KiB |
|
After Width: | Height: | Size: 8.6 KiB |
|
After Width: | Height: | Size: 11 KiB |
|
After Width: | Height: | Size: 11 KiB |
|
After Width: | Height: | Size: 14 KiB |
|
After Width: | Height: | Size: 15 KiB |
|
After Width: | Height: | Size: 54 KiB |
|
After Width: | Height: | Size: 247 KiB |
|
After Width: | Height: | Size: 18 KiB |
|
After Width: | Height: | Size: 6.4 KiB |
|
After Width: | Height: | Size: 40 KiB |
|
After Width: | Height: | Size: 7.4 KiB |
|
After Width: | Height: | Size: 97 KiB |
|
After Width: | Height: | Size: 10 KiB |
|
After Width: | Height: | Size: 7.5 KiB |
|
After Width: | Height: | Size: 6.5 KiB |
|
After Width: | Height: | Size: 35 KiB |
|
After Width: | Height: | Size: 7.9 KiB |
|
After Width: | Height: | Size: 10 KiB |