Compare commits
46
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f164e0d0d2 | ||
|
|
f5a20b72af | ||
|
|
db733a6bf4 | ||
|
|
bdcdfc2dbe | ||
|
|
a2454812f9 | ||
|
|
d2ad20e0f8 | ||
|
|
170076ef4d | ||
|
|
43d77dd47c | ||
|
|
97a5ecdf83 | ||
|
|
5bf8ec5cee | ||
|
|
ac516a7dc8 | ||
|
|
7c813cce9e | ||
|
|
858cc1ac63 | ||
|
|
51a8e11ef6 | ||
|
|
1347b671e0 | ||
|
|
00359c538b | ||
|
|
38a349eb52 | ||
|
|
acde180086 | ||
|
|
79d9461769 | ||
|
|
94af6d7601 | ||
|
|
fa69e6ef3c | ||
|
|
91f372612a | ||
|
|
3f5ff73a49 | ||
|
|
fc0e376df8 | ||
|
|
d005ee6f51 | ||
|
|
e8a9b25037 | ||
|
|
4227293345 | ||
|
|
a53bafff3f | ||
|
|
c94f749430 | ||
|
|
a90f4eb71f | ||
|
|
6c364623fd | ||
|
|
5ebaafc113 | ||
|
|
61bed33c8a | ||
|
|
81077527ac | ||
|
|
d0b18a4902 | ||
|
|
e3544617e1 | ||
|
|
ce6db8a457 | ||
|
|
da1cdca3b2 | ||
|
|
df68167d04 | ||
|
|
9a79e6f649 | ||
|
|
dfae1cb572 | ||
|
|
752f3ba433 | ||
|
|
72a5e289f6 | ||
|
|
01401cb1cd | ||
|
|
d3cb76dc32 | ||
|
|
61b1eda37d |
No files matched your search
@@ -0,0 +1,5 @@
|
|||||||
|
---
|
||||||
|
"@gabriel20xx/web-ui": minor
|
||||||
|
---
|
||||||
|
|
||||||
|
Add a shared `NotificationStack` component and `notify` API (`notify.success/error/warning/info`) for toast-style action feedback. `AppShell` now mounts `NotificationStack` automatically, so any application using `AppShell` gets it without further wiring.
|
||||||
@@ -4,6 +4,9 @@ on:
|
|||||||
push:
|
push:
|
||||||
tags:
|
tags:
|
||||||
- 'backend/v*'
|
- 'backend/v*'
|
||||||
|
release:
|
||||||
|
types:
|
||||||
|
- published
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
publish:
|
publish:
|
||||||
@@ -32,8 +35,13 @@ jobs:
|
|||||||
|
|
||||||
- name: Package Go module
|
- name: Package Go module
|
||||||
env:
|
env:
|
||||||
RELEASE_TAG: ${{ github.ref_name }}
|
RELEASE_TAG: ${{ github.event_name == 'release' && github.event.release.tag_name || github.ref_name }}
|
||||||
run: bash scripts/package-go-module.sh "$RELEASE_TAG" "$RUNNER_TEMP/gitea-go-package"
|
run: |
|
||||||
|
package_directory='gitea-go-package'
|
||||||
|
rm -rf "$package_directory"
|
||||||
|
mkdir -p "$package_directory"
|
||||||
|
bash scripts/package-go-module.sh "$RELEASE_TAG" "$package_directory"
|
||||||
|
find "$package_directory" -maxdepth 1 -type f -name '*.zip' -print -quit | grep -q .
|
||||||
|
|
||||||
- name: Publish to Gitea Package Registry
|
- name: Publish to Gitea Package Registry
|
||||||
env:
|
env:
|
||||||
@@ -46,8 +54,25 @@ jobs:
|
|||||||
echo 'PACKAGE_REGISTRY_USERNAME and PACKAGE_REGISTRY_TOKEN secrets are required.' >&2
|
echo 'PACKAGE_REGISTRY_USERNAME and PACKAGE_REGISTRY_TOKEN secrets are required.' >&2
|
||||||
exit 1
|
exit 1
|
||||||
fi
|
fi
|
||||||
package_file="$(find "$RUNNER_TEMP/gitea-go-package" -maxdepth 1 -type f -name '*.zip' -print -quit)"
|
package_file="$(find gitea-go-package -maxdepth 1 -type f -name '*.zip' -print -quit)"
|
||||||
test -n "$package_file"
|
test -n "$package_file"
|
||||||
curl --fail-with-body --user "$PACKAGE_REGISTRY_USERNAME:$PACKAGE_REGISTRY_TOKEN" \
|
response_file="$(mktemp)"
|
||||||
|
http_status="$(curl --silent --show-error --fail-with-body \
|
||||||
|
--user "$PACKAGE_REGISTRY_USERNAME:$PACKAGE_REGISTRY_TOKEN" \
|
||||||
|
--output "$response_file" \
|
||||||
|
--write-out '%{http_code}' \
|
||||||
--upload-file "$package_file" \
|
--upload-file "$package_file" \
|
||||||
"$GITEA_GO_REGISTRY"
|
"$GITEA_GO_REGISTRY" || true)"
|
||||||
|
case "$http_status" in
|
||||||
|
201)
|
||||||
|
echo 'Go package published.'
|
||||||
|
;;
|
||||||
|
409)
|
||||||
|
echo 'Go package version already exists; leaving the immutable package unchanged.'
|
||||||
|
;;
|
||||||
|
*)
|
||||||
|
cat "$response_file" >&2
|
||||||
|
echo "Gitea Go package upload failed with HTTP status $http_status." >&2
|
||||||
|
exit 1
|
||||||
|
;;
|
||||||
|
esac
|
||||||
@@ -0,0 +1,93 @@
|
|||||||
|
name: Publish npm packages
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
tags:
|
||||||
|
- 'v*'
|
||||||
|
release:
|
||||||
|
types:
|
||||||
|
- published
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
publish:
|
||||||
|
name: Publish shared npm packages
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
permissions:
|
||||||
|
contents: read
|
||||||
|
steps:
|
||||||
|
- name: Checkout source
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
|
||||||
|
- name: Set up Node.js
|
||||||
|
uses: actions/setup-node@v4
|
||||||
|
with:
|
||||||
|
node-version: 22
|
||||||
|
cache: npm
|
||||||
|
|
||||||
|
- name: Install and build packages
|
||||||
|
run: |
|
||||||
|
npm ci
|
||||||
|
npm run build
|
||||||
|
|
||||||
|
- name: Configure Gitea npm registry
|
||||||
|
env:
|
||||||
|
PACKAGE_REGISTRY_USERNAME: ${{ secrets.PACKAGE_REGISTRY_USERNAME }}
|
||||||
|
PACKAGE_REGISTRY_TOKEN: ${{ secrets.PACKAGE_REGISTRY_TOKEN }}
|
||||||
|
run: |
|
||||||
|
set -euo pipefail
|
||||||
|
if [ -z "$PACKAGE_REGISTRY_USERNAME" ] || [ -z "$PACKAGE_REGISTRY_TOKEN" ]; then
|
||||||
|
echo 'PACKAGE_REGISTRY_USERNAME and PACKAGE_REGISTRY_TOKEN secrets are required.' >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
npmrc_path="$RUNNER_TEMP/gitea-npmrc"
|
||||||
|
umask 077
|
||||||
|
{
|
||||||
|
printf '@gabriel20xx:registry=https://repos.gfranz.ch/api/packages/Gabriel20xx/npm/\n'
|
||||||
|
printf '//repos.gfranz.ch/api/packages/Gabriel20xx/npm/:_authToken=%s\n' "$PACKAGE_REGISTRY_TOKEN"
|
||||||
|
printf 'always-auth=true\n'
|
||||||
|
} > "$npmrc_path"
|
||||||
|
printf 'NPM_CONFIG_USERCONFIG=%s\n' "$npmrc_path" >> "$GITHUB_ENV"
|
||||||
|
|
||||||
|
- name: Publish npm packages
|
||||||
|
env:
|
||||||
|
PACKAGE_REGISTRY_USERNAME: ${{ secrets.PACKAGE_REGISTRY_USERNAME }}
|
||||||
|
PACKAGE_REGISTRY_TOKEN: ${{ secrets.PACKAGE_REGISTRY_TOKEN }}
|
||||||
|
NPM_REGISTRY: https://repos.gfranz.ch/api/packages/Gabriel20xx/npm/
|
||||||
|
run: |
|
||||||
|
set -euo pipefail
|
||||||
|
if [ -z "$PACKAGE_REGISTRY_USERNAME" ] || [ -z "$PACKAGE_REGISTRY_TOKEN" ]; then
|
||||||
|
echo 'PACKAGE_REGISTRY_USERNAME and PACKAGE_REGISTRY_TOKEN secrets are required.' >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
for package in \
|
||||||
|
@gabriel20xx/design-tokens \
|
||||||
|
@gabriel20xx/web-ui \
|
||||||
|
@gabriel20xx/node-backend; do
|
||||||
|
version="$(npm pkg get version --workspace="$package" | tr -d '"[:space:]')"
|
||||||
|
package_path="${package//@/%40}"
|
||||||
|
package_path="${package_path//\//%2f}"
|
||||||
|
metadata_file="$(mktemp)"
|
||||||
|
metadata_status="$(curl --silent --show-error --fail-with-body \
|
||||||
|
--user "$PACKAGE_REGISTRY_USERNAME:$PACKAGE_REGISTRY_TOKEN" \
|
||||||
|
--output "$metadata_file" \
|
||||||
|
--write-out '%{http_code}' \
|
||||||
|
"${NPM_REGISTRY}${package_path}" || true)"
|
||||||
|
case "$metadata_status" in
|
||||||
|
200)
|
||||||
|
if grep -Fq "\"$version\"" "$metadata_file"; then
|
||||||
|
echo "$package@$version is already published; skipping."
|
||||||
|
rm -f "$metadata_file"
|
||||||
|
continue
|
||||||
|
fi
|
||||||
|
;;
|
||||||
|
404)
|
||||||
|
;;
|
||||||
|
*)
|
||||||
|
cat "$metadata_file" >&2
|
||||||
|
echo "Gitea npm metadata lookup failed with HTTP status $metadata_status." >&2
|
||||||
|
exit 1
|
||||||
|
;;
|
||||||
|
esac
|
||||||
|
npm publish --workspace="$package" --registry="$NPM_REGISTRY"
|
||||||
|
rm -f "$metadata_file"
|
||||||
|
done
|
||||||
@@ -0,0 +1,74 @@
|
|||||||
|
name: Publish Python package
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
tags:
|
||||||
|
- 'v*'
|
||||||
|
release:
|
||||||
|
types:
|
||||||
|
- published
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
publish:
|
||||||
|
name: Publish shared Python package
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
permissions:
|
||||||
|
contents: read
|
||||||
|
steps:
|
||||||
|
- name: Checkout source
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
|
||||||
|
- name: Set up Python
|
||||||
|
uses: actions/setup-python@v5
|
||||||
|
with:
|
||||||
|
python-version: '3.12'
|
||||||
|
|
||||||
|
- name: Build and publish package
|
||||||
|
env:
|
||||||
|
PACKAGE_REGISTRY_USERNAME: ${{ secrets.PACKAGE_REGISTRY_USERNAME }}
|
||||||
|
PACKAGE_REGISTRY_TOKEN: ${{ secrets.PACKAGE_REGISTRY_TOKEN }}
|
||||||
|
TWINE_REPOSITORY_URL: https://repos.gfranz.ch/api/packages/Gabriel20xx/pypi
|
||||||
|
run: |
|
||||||
|
set -euo pipefail
|
||||||
|
if [ -z "$PACKAGE_REGISTRY_USERNAME" ] || [ -z "$PACKAGE_REGISTRY_TOKEN" ]; then
|
||||||
|
echo 'PACKAGE_REGISTRY_USERNAME and PACKAGE_REGISTRY_TOKEN secrets are required.' >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
python -m pip install --disable-pip-version-check --no-cache-dir build twine
|
||||||
|
package_directory="$RUNNER_TEMP/gitea-pypi-package"
|
||||||
|
python -m build packages/python-backend --outdir "$package_directory"
|
||||||
|
package_index_url="${TWINE_REPOSITORY_URL%/}/simple/gabriel20xx-shared-backend/"
|
||||||
|
package_index_file="$(mktemp)"
|
||||||
|
package_index_status="$(curl --silent --show-error --fail-with-body \
|
||||||
|
--user "$PACKAGE_REGISTRY_USERNAME:$PACKAGE_REGISTRY_TOKEN" \
|
||||||
|
--output "$package_index_file" \
|
||||||
|
--write-out '%{http_code}' \
|
||||||
|
"$package_index_url" || true)"
|
||||||
|
package_files=("$package_directory"/*)
|
||||||
|
files_to_upload=()
|
||||||
|
case "$package_index_status" in
|
||||||
|
200)
|
||||||
|
for package_file in "${package_files[@]}"; do
|
||||||
|
if ! grep -Fq "$(basename "$package_file")" "$package_index_file"; then
|
||||||
|
files_to_upload+=("$package_file")
|
||||||
|
fi
|
||||||
|
done
|
||||||
|
;;
|
||||||
|
404)
|
||||||
|
files_to_upload=("${package_files[@]}")
|
||||||
|
;;
|
||||||
|
*)
|
||||||
|
cat "$package_index_file" >&2
|
||||||
|
echo "Gitea PyPI package lookup failed with HTTP status $package_index_status." >&2
|
||||||
|
exit 1
|
||||||
|
;;
|
||||||
|
esac
|
||||||
|
if [ "${#files_to_upload[@]}" -eq 0 ]; then
|
||||||
|
echo 'Python package version already exists with all build artifacts; leaving it unchanged.'
|
||||||
|
exit 0
|
||||||
|
fi
|
||||||
|
TWINE_USERNAME="$PACKAGE_REGISTRY_USERNAME" \
|
||||||
|
TWINE_PASSWORD="$PACKAGE_REGISTRY_TOKEN" \
|
||||||
|
python -m twine upload --non-interactive \
|
||||||
|
--repository-url "$TWINE_REPOSITORY_URL" \
|
||||||
|
"${files_to_upload[@]}"
|
||||||
Executable
+14
@@ -0,0 +1,14 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
set -euo pipefail
|
||||||
|
|
||||||
|
repo_root="$(git rev-parse --show-toplevel)"
|
||||||
|
sync_script="$repo_root/scripts/sync-consumers.ps1"
|
||||||
|
|
||||||
|
if command -v pwsh >/dev/null 2>&1; then
|
||||||
|
pwsh -NoProfile -NonInteractive -ExecutionPolicy Bypass -File "$sync_script" -Commit
|
||||||
|
elif command -v powershell.exe >/dev/null 2>&1; then
|
||||||
|
powershell.exe -NoProfile -NonInteractive -ExecutionPolicy Bypass -File "$sync_script" -Commit
|
||||||
|
else
|
||||||
|
echo "shared synchronization requires pwsh or powershell.exe." >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
name: Lint (media-backend)
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
branches: ['**']
|
||||||
|
paths:
|
||||||
|
- 'media-backend/**'
|
||||||
|
- '.github/workflows/media-backend-lint.yml'
|
||||||
|
pull_request:
|
||||||
|
branches: [main, master]
|
||||||
|
paths:
|
||||||
|
- 'media-backend/**'
|
||||||
|
- '.github/workflows/media-backend-lint.yml'
|
||||||
|
workflow_dispatch: {}
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
vet:
|
||||||
|
name: Lint
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
permissions:
|
||||||
|
contents: read
|
||||||
|
steps:
|
||||||
|
- name: Checkout
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
- name: Set up Go
|
||||||
|
uses: actions/setup-go@v5
|
||||||
|
with:
|
||||||
|
go-version: '1.26.x'
|
||||||
|
cache-dependency-path: media-backend/go.sum
|
||||||
|
- name: Vet backend
|
||||||
|
working-directory: media-backend
|
||||||
|
run: go vet ./...
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
name: Tests (media-backend)
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
branches: ['**']
|
||||||
|
paths:
|
||||||
|
- 'media-backend/**'
|
||||||
|
- '.github/workflows/media-backend-tests.yml'
|
||||||
|
pull_request:
|
||||||
|
branches: [main, master]
|
||||||
|
paths:
|
||||||
|
- 'media-backend/**'
|
||||||
|
- '.github/workflows/media-backend-tests.yml'
|
||||||
|
workflow_dispatch: {}
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
test:
|
||||||
|
name: Tests
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
permissions:
|
||||||
|
contents: read
|
||||||
|
steps:
|
||||||
|
- name: Checkout
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
- name: Set up Go
|
||||||
|
uses: actions/setup-go@v5
|
||||||
|
with:
|
||||||
|
go-version: '1.26.x'
|
||||||
|
cache-dependency-path: media-backend/go.sum
|
||||||
|
- name: Test backend
|
||||||
|
working-directory: media-backend
|
||||||
|
run: go test ./...
|
||||||
@@ -7,3 +7,4 @@ __pycache__/
|
|||||||
*.py[cod]
|
*.py[cod]
|
||||||
*.egg-info/
|
*.egg-info/
|
||||||
.venv/
|
.venv/
|
||||||
|
packages/*/target/
|
||||||
@@ -1,196 +1,99 @@
|
|||||||
# SharedCode packages
|
# shared
|
||||||
|
|
||||||
This folder is the single source of truth for reusable web UI across the projects in this workspace.
|
The single source of truth for code reused across every project in this workspace: a Svelte design system and application shell, backend helpers (Postgres access, config, auth/session persistence, an AuthGuard client, log shipping) in four languages, and the Go media-backend/media-webui powering the whole `MEDIA_SERVICE`-family of projects.
|
||||||
|
|
||||||
The first packages are:
|
---
|
||||||
|
|
||||||
- `@gabriel20xx/design-tokens` — colors, typography, spacing, radii, shadows, and light/dark theme variables.
|
## Tech Stack
|
||||||
- `@gabriel20xx/web-ui` — Svelte components for the application shell, header/navigation, authentication, dialogs, profile/settings/about windows, buttons, cards, badges, and page headers.
|
|
||||||
- `repos.gfranz.ch/Gabriel20xx/shared/backend` — Go helpers for environment configuration, `pgx` PostgreSQL pools, transactions, common auth persistence/passwords/tokens, and embedded Goose migrations.
|
|
||||||
- `@gabriel20xx/node-backend` — Node.js `pg` pool/configuration, transactions, migrations, and auth/session persistence.
|
|
||||||
- `gabriel20xx-shared-backend` — Python `asyncpg` pool/configuration and auth/session persistence.
|
|
||||||
|
|
||||||
The components do not import `$app/state`, `$lib` stores, or a project-specific API. Applications provide those things through props and callbacks.
|
| Layer | Technology |
|
||||||
|
|-------|------------|
|
||||||
|
| Web UI | Svelte, TypeScript |
|
||||||
|
| Backend helpers | Go, Node.js, Python, Java |
|
||||||
|
| Database | PostgreSQL (via `pgx`, `pg`, or `asyncpg`) |
|
||||||
|
| Package registry | Gitea npm / Go / PyPI registries |
|
||||||
|
|
||||||
## Build and check the packages
|
---
|
||||||
|
|
||||||
Run these commands from this directory:
|
## Packages
|
||||||
|
|
||||||
|
| Package | Language | Purpose |
|
||||||
|
|---|---|---|
|
||||||
|
| `@gabriel20xx/design-tokens` | CSS | Colors, typography, spacing, radii, shadows, light/dark theme variables. |
|
||||||
|
| `@gabriel20xx/web-ui` | Svelte | Application shell, header/navigation, auth screens, dialogs, buttons, cards, badges. |
|
||||||
|
| `@gabriel20xx/media-shared-assets` | Browser JS/CSS | Shared client-side assets for the media-backend/`MEDIA_SERVICE` family. |
|
||||||
|
| `repos.gfranz.ch/Gabriel20xx/shared/backend` | Go | Env config, `pgx` pools/transactions, auth persistence, an AuthGuard client (`authclient`), log shipping (`logshipper`), embedded Goose migrations. |
|
||||||
|
| `@gabriel20xx/node-backend` | Node.js | `pg` pool/config/transactions/migrations, auth/session persistence, an AuthGuard client. |
|
||||||
|
| `gabriel20xx-shared-backend` | Python | `asyncpg` pool/config, auth/session persistence, an AuthGuard client. |
|
||||||
|
| `com.gabriel20xx.shared.auth` | Java | An AuthGuard client, mirroring the Go/Node/Python ones. |
|
||||||
|
| `media-backend` / `media-webui` | Go / Svelte | The Go binary and web UI powering the `MEDIA_SERVICE`-family projects (see below). |
|
||||||
|
|
||||||
|
The `web-ui` components don't import `$app/state`, `$lib` stores, or a project-specific API — applications provide those through props and callbacks.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## How consumers actually use this
|
||||||
|
|
||||||
|
There are two different distribution paths in this workspace, used for different things:
|
||||||
|
|
||||||
|
### Vendored snapshot (the one every project actually uses)
|
||||||
|
|
||||||
|
Every consumer project vendors a full copy of this repo's tracked files into its own `shared/` (or, for the `media-backend` family, `engine/`) directory, committed directly rather than installed from a registry. This exists because none of these projects are meant to resolve a private registry dependency in a fresh CI checkout without extra credentials, and because a git submodule pointing at this (private) repo breaks the same way — see `scripts/sync-consumers.ps1`'s own comments for the full history.
|
||||||
|
|
||||||
|
To pull the latest snapshot into every registered consumer:
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
# from this repo
|
||||||
|
.\scripts\sync-consumers.ps1 -Commit -Push
|
||||||
|
```
|
||||||
|
|
||||||
|
The script copies every tracked file in this repo into each consumer's destination folder, regenerates any `package-lock.json` that depends on a local `file:` package, and commits/pushes only if something actually changed ("Sync shared/engine snapshot from `<short-sha>`"). Consumers are registered in the script's `$consumerProjects` list, each with a destination folder (`shared` by default, `engine` for the media-backend family). A `post-commit` hook (installed via `scripts/install-sync-hook.ps1`) runs this automatically — with `-Commit` only, never `-Push` — after every commit to this repo, so pushing the sync commits it creates to each consumer is still a manual follow-up step.
|
||||||
|
|
||||||
|
### Published registry packages (for standalone/external use)
|
||||||
|
|
||||||
|
The npm, Go, and Python packages are also published to this Gitea instance's package registries, for a project that genuinely wants a version-pinned dependency rather than a vendored snapshot. `.gitea/workflows/publish-*.yml` publish on a `v*` tag push or a matching Gitea release; `PACKAGE_REGISTRY_USERNAME`/`PACKAGE_REGISTRY_TOKEN` must be configured as Actions secrets. See "Publishing" below for the details. No project in this workspace currently consumes a package this way — it exists for future/external use.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Development
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
npm install
|
npm install
|
||||||
npm run check
|
npm run check
|
||||||
npm run build
|
npm run build # builds packages/web-ui/dist (gitignored, not committed)
|
||||||
npm run test:node-backend
|
npm run test:node-backend
|
||||||
```
|
```
|
||||||
|
|
||||||
`npm run build` creates the distributable package in `packages/web-ui/dist`. The generated `dist` directory is intentionally ignored by the package configuration and should not be committed.
|
|
||||||
|
|
||||||
Validate the Go backend package from `shared/backend`:
|
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
cd backend
|
cd backend
|
||||||
go test ./...
|
go test ./...
|
||||||
go vet ./...
|
go vet ./...
|
||||||
```
|
```
|
||||||
|
|
||||||
## Consume from the Gitea repository
|
|
||||||
|
|
||||||
The repository is the canonical source and is installable directly from Gitea. The root package
|
|
||||||
builds the Svelte package during installation and exposes the runtime packages as subpaths:
|
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
npm install --save-exact git+https://repos.gfranz.ch/Gabriel20xx/shared#<commit>
|
cd media-backend
|
||||||
|
go test ./...
|
||||||
|
go vet ./...
|
||||||
```
|
```
|
||||||
|
|
||||||
Use the shared UI from the root package:
|
---
|
||||||
|
|
||||||
```ts
|
## Typical `web-ui` wiring
|
||||||
import { AppShell, AuthPage, Header, SettingsDialog } from '@gabriel20xx/shared-code/web-ui';
|
|
||||||
```
|
|
||||||
|
|
||||||
Import the shared stylesheet once from the application's global stylesheet:
|
|
||||||
|
|
||||||
```css
|
|
||||||
@import '@gabriel20xx/shared-code/web-ui/styles.css';
|
|
||||||
```
|
|
||||||
|
|
||||||
The dependency should be pinned to a commit in application lockfiles. Update it when a new
|
|
||||||
SharedCode version has been validated.
|
|
||||||
|
|
||||||
## Publish the individual packages
|
|
||||||
|
|
||||||
The package names use the `@gabriel20xx` npm scope. That scope must belong to the npm account used to publish. If a different scope is preferred, replace the scope consistently in both package manifests and imports before publishing.
|
|
||||||
|
|
||||||
Publish the tokens first because `web-ui` depends on them:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
npm login
|
|
||||||
npm publish --workspace=@gabriel20xx/design-tokens --access public
|
|
||||||
npm publish --workspace=@gabriel20xx/web-ui --access public
|
|
||||||
npm publish --workspace=@gabriel20xx/node-backend --access public
|
|
||||||
```
|
|
||||||
|
|
||||||
For a private registry, configure that registry and omit `--access public` if the registry does not use npm's public scoped-package rules.
|
|
||||||
|
|
||||||
## Install individual packages from a registry
|
|
||||||
|
|
||||||
From a project's frontend directory, install the published UI package:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
npm install @gabriel20xx/web-ui@^0.1.0
|
|
||||||
```
|
|
||||||
|
|
||||||
The design-token package is installed transitively. Install it directly only when an application needs to reference its theme file itself:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
npm install @gabriel20xx/design-tokens@^0.1.0
|
|
||||||
```
|
|
||||||
|
|
||||||
Import the shared stylesheet once from the application's global stylesheet, before project-specific overrides:
|
|
||||||
|
|
||||||
```css
|
|
||||||
@import '@gabriel20xx/web-ui/styles.css';
|
|
||||||
```
|
|
||||||
|
|
||||||
The stylesheet imports the design tokens and uses an `sc-` prefix, so it does not require Tailwind and does not collide with existing project class names. Set `data-theme="light"` or `data-theme="dark"` on the application root to select a theme. Dark is the default.
|
|
||||||
|
|
||||||
## Use the shared Go backend package
|
|
||||||
|
|
||||||
The Go module is published to the private Gitea Go Package Registry. Configure a
|
|
||||||
read-only package token in the consuming workflow as `PACKAGE_REGISTRY_USERNAME`
|
|
||||||
and `PACKAGE_REGISTRY_TOKEN`, then configure Go to use the registry before running
|
|
||||||
`go get`, `go test`, or `go build`:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
export GOPROXY=https://repos.gfranz.ch/api/packages/Gabriel20xx/go,https://proxy.golang.org
|
|
||||||
export GONOSUMDB=repos.gfranz.ch/Gabriel20xx/shared/*
|
|
||||||
```
|
|
||||||
|
|
||||||
From a Go backend directory, add the released module (the module is a subdirectory of the shared repository):
|
|
||||||
|
|
||||||
```bash
|
|
||||||
go get repos.gfranz.ch/Gabriel20xx/shared/backend@v0.1.0
|
|
||||||
```
|
|
||||||
|
|
||||||
Then initialize the pool and shared auth store at startup:
|
|
||||||
|
|
||||||
```go
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"log"
|
|
||||||
|
|
||||||
"repos.gfranz.ch/Gabriel20xx/shared/backend/auth"
|
|
||||||
"repos.gfranz.ch/Gabriel20xx/shared/backend/postgres"
|
|
||||||
)
|
|
||||||
|
|
||||||
cfg, err := postgres.FromEnv()
|
|
||||||
if err != nil {
|
|
||||||
log.Fatal(err)
|
|
||||||
}
|
|
||||||
pool, err := postgres.Open(context.Background(), cfg)
|
|
||||||
if err != nil {
|
|
||||||
log.Fatal(err)
|
|
||||||
}
|
|
||||||
defer pool.Close()
|
|
||||||
|
|
||||||
if err := auth.EnsureSchema(context.Background(), pool, auth.DefaultSchemaOptions()); err != nil {
|
|
||||||
log.Fatal(err)
|
|
||||||
}
|
|
||||||
authStore := auth.NewStore(pool)
|
|
||||||
```
|
|
||||||
|
|
||||||
Use `auth.SchemaOptions{SingleUser: false, APITokens: true}` for a multi-user service that needs API tokens. The shared package owns persistence primitives and password/token utilities; each application still owns authorization rules, cookies, HTTP handlers, roles, and domain tables.
|
|
||||||
|
|
||||||
For embedded SQL migrations, use `migrate.Up(ctx, databaseURL, embeddedMigrations, "migrations")`. The package does not contain application tables, so migrations remain versioned with the service that owns those tables.
|
|
||||||
|
|
||||||
The Go module lives under `backend`, so its release tag must use the submodule prefix (`backend/v0.1.0`). The consuming `go.mod` uses the normal module version (`v0.1.0`). To publish a release, push a tag such as `backend/v0.1.0`; the Gitea workflow packages the module and uploads it to the private registry. Never reuse an existing package version.
|
|
||||||
|
|
||||||
For Node services, install the shared package after publishing it:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
npm install @gabriel20xx/node-backend@^0.1.0
|
|
||||||
```
|
|
||||||
|
|
||||||
For Python services, build and publish the wheel to the Python package index used by the projects, then install it normally:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
python -m pip install build
|
|
||||||
python -m build packages/python-backend
|
|
||||||
python -m pip install gabriel20xx-shared-backend==0.1.0
|
|
||||||
```
|
|
||||||
|
|
||||||
The Node and Python packages intentionally expose the same infrastructure concepts but use their native database drivers. This is the safe way to share behavior across the polyglot services; a Go package cannot be imported by the Python or Node applications.
|
|
||||||
|
|
||||||
## Existing MediaCollection shared package
|
|
||||||
|
|
||||||
`Original/MediaCollection/MediaShared` is an existing, larger media-specific package. It remains in place for media workflows and startup integration, while the MediaCollection WebUI authentication surface and admin-reset code use this shared package. Its remaining generic responsibilities can be migrated independently without introducing another authentication screen.
|
|
||||||
|
|
||||||
## Typical application wiring
|
|
||||||
|
|
||||||
```svelte
|
```svelte
|
||||||
<script lang="ts">
|
<script lang="ts">
|
||||||
import {
|
import { AboutDialog, AppShell, ProfileDialog, SettingsDialog } from '@gabriel20xx/web-ui';
|
||||||
AboutDialog,
|
|
||||||
AppShell,
|
|
||||||
ProfileDialog,
|
|
||||||
SettingsDialog
|
|
||||||
} from '@gabriel20xx/web-ui';
|
|
||||||
import { page } from '$app/state';
|
import { page } from '$app/state';
|
||||||
|
|
||||||
let aboutOpen = $state(false);
|
let aboutOpen = $state(false);
|
||||||
let profileOpen = $state(false);
|
let profileOpen = $state(false);
|
||||||
let settingsOpen = $state(false);
|
let settingsOpen = $state(false);
|
||||||
|
|
||||||
const navItems = [
|
|
||||||
{ href: '/', label: 'Dashboard' },
|
|
||||||
{ href: '/about', label: 'About' }
|
|
||||||
];
|
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<AppShell
|
<AppShell
|
||||||
brand="My application"
|
brand="My application"
|
||||||
currentPath={page.url.pathname}
|
currentPath={page.url.pathname}
|
||||||
navItems={navItems}
|
navItems={[{ href: '/', label: 'Dashboard' }]}
|
||||||
onLogout={() => auth.logout()}
|
onLogout={() => auth.logout()}
|
||||||
onProfile={() => (profileOpen = true)}
|
onProfile={() => (profileOpen = true)}
|
||||||
onSettings={() => (settingsOpen = true)}
|
onSettings={() => (settingsOpen = true)}
|
||||||
@@ -200,70 +103,44 @@ The Node and Python packages intentionally expose the same infrastructure concep
|
|||||||
<slot />
|
<slot />
|
||||||
{/snippet}
|
{/snippet}
|
||||||
</AppShell>
|
</AppShell>
|
||||||
|
|
||||||
<AboutDialog
|
|
||||||
bind:open={aboutOpen}
|
|
||||||
brand="My application"
|
|
||||||
description="A short description supplied by this project."
|
|
||||||
version="1.0.0"
|
|
||||||
/>
|
|
||||||
|
|
||||||
<SettingsDialog bind:open={settingsOpen}>
|
|
||||||
{#snippet children()}
|
|
||||||
<!-- Project-specific settings controls go here. -->
|
|
||||||
{/snippet}
|
|
||||||
</SettingsDialog>
|
|
||||||
|
|
||||||
<ProfileDialog
|
|
||||||
bind:open={profileOpen}
|
|
||||||
currentEmail={auth.user?.email ?? ''}
|
|
||||||
currentUsername={auth.user?.username ?? ''}
|
|
||||||
onSave={(profile) => auth.updateProfile(profile)}
|
|
||||||
/>
|
|
||||||
```
|
```
|
||||||
|
|
||||||
For authentication, use the same shell with `AuthPage` and connect the callbacks to the application's existing auth service:
|
Import the stylesheet once, before project-specific overrides: `@import '@gabriel20xx/web-ui/styles.css';`. It uses an `sc-` class prefix, so it doesn't require Tailwind and doesn't collide with existing project classes. Set `data-theme="light"` or `data-theme="dark"` on the application root; dark is the default.
|
||||||
|
|
||||||
```svelte
|
For authentication, use `AuthPage` and wire its callbacks to the project's auth service — every project in this workspace either talks to AuthGuard directly or proxies through its own backend to AuthGuard. See `Central/AuthGuard/README.md` for the identity service this whole authentication surface is built to work with.
|
||||||
<AuthPage
|
|
||||||
brand="My application"
|
---
|
||||||
onLogin={(credentials) => auth.login(credentials.identifier, credentials.password)}
|
|
||||||
onSetup={(credentials) => auth.setup(credentials)}
|
## Using the Go backend package
|
||||||
onRequestReset={() => auth.requestAdminReset()}
|
|
||||||
onConfirmReset={(code) => auth.confirmAdminReset(code)}
|
```go
|
||||||
setupRequired={setupRequired}
|
import (
|
||||||
tagline="Your project tagline"
|
"repos.gfranz.ch/Gabriel20xx/shared/backend/auth"
|
||||||
/>
|
"repos.gfranz.ch/Gabriel20xx/shared/backend/authclient"
|
||||||
|
"repos.gfranz.ch/Gabriel20xx/shared/backend/postgres"
|
||||||
|
)
|
||||||
|
|
||||||
|
pool, _ := postgres.Open(ctx, postgres.FromEnv())
|
||||||
|
authStore := auth.NewStore(pool) // local Postgres-backed accounts
|
||||||
|
client := authclient.New(authGuardURL) // or proxy to AuthGuard instead
|
||||||
```
|
```
|
||||||
|
|
||||||
Applications that support MFA can enable the shared optional authenticator-code field with
|
Use `auth.SchemaOptions{SingleUser: false, APITokens: true}` for a multi-user service that needs API tokens. This package owns persistence primitives and password/token utilities; each application still owns authorization rules, cookies, HTTP handlers, roles, and domain tables. For embedded SQL migrations, use `migrate.Up(ctx, databaseURL, embeddedMigrations, "migrations")` — this package has no application tables of its own, so migrations stay versioned with the service that owns those tables.
|
||||||
`showTotp` and forward `credentials.totpToken` to their login endpoint. The base layout and reset
|
|
||||||
controls remain the same as every other shared auth screen.
|
|
||||||
|
|
||||||
The shared reset controls request a short-lived code printed by the server-side auth package and consume it once after confirmation. The package handles form state, validation attributes, loading state, and error presentation. The application remains responsible for deciding where to navigate after a successful action and how errors are returned.
|
---
|
||||||
|
|
||||||
## Local package development
|
## Publishing
|
||||||
|
|
||||||
Before publishing, build the packages and install them from the local workspace in a frontend project:
|
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
# From Web/shared
|
npm run changeset # describe the change
|
||||||
npm run build
|
npm run version-packages # bump versions, commit the changelog
|
||||||
|
npm run release # publishes npm packages in dependency order (design-tokens first)
|
||||||
# From a project frontend directory; do not commit this file dependency for CI
|
|
||||||
npm install ../../../shared/packages/design-tokens ../../../shared/packages/web-ui
|
|
||||||
```
|
```
|
||||||
|
|
||||||
For CI and normal development, use the published version instead of a `file:` dependency. A local file dependency only works when the checkout also contains the sibling `shared` directory.
|
The Go module lives under `backend`, so its release tag uses the submodule prefix (`backend/v0.1.0`); push that tag and the Gitea workflow packages and uploads the module. The npm and Python workflows both skip a version already present in the registry, so retrying a partially completed release is safe.
|
||||||
|
|
||||||
## Updating the design system
|
---
|
||||||
|
|
||||||
When a component or token changes:
|
## CI/CD
|
||||||
|
|
||||||
1. Run `npm run changeset` and describe the change.
|
`lint.yml` and `tests.yml` each run three jobs — Node/Svelte, Go, and Python — plus dedicated `media-backend-lint.yml`/`media-backend-tests.yml` for the `media-backend` Go module. `publish-npm.yml`, `publish-go.yml`, and `publish-python.yml` handle registry publishing as described above.
|
||||||
2. Run `npm run version-packages` and commit the generated version/changelog files.
|
|
||||||
3. Run `npm install`, `npm run check`, `npm run build`, and `npm run test:node-backend`.
|
|
||||||
4. Run `npm run release`; Changesets publishes the npm packages in dependency order.
|
|
||||||
5. Update each project with `npm install @gabriel20xx/web-ui@<new-version>` and commit its lockfile.
|
|
||||||
|
|
||||||
The package boundary is intentional: application-specific screens stay in their project, while repeated visual language and account/layout infrastructure stays here.
|
|
||||||
@@ -6,7 +6,9 @@ services, not application-specific SQL or HTTP handlers.
|
|||||||
- `config` — environment string, required value, boolean, integer, and duration helpers.
|
- `config` — environment string, required value, boolean, integer, and duration helpers.
|
||||||
- `postgres` — validated `DATABASE_URL` configuration, `pgxpool` creation/ping, transaction wrapper, and PostgreSQL error classification.
|
- `postgres` — validated `DATABASE_URL` configuration, `pgxpool` creation/ping, transaction wrapper, and PostgreSQL error classification.
|
||||||
- `auth` — shared bcrypt policy, secure token generation/hashing, account/session schema, and account/session persistence.
|
- `auth` — shared bcrypt policy, secure token generation/hashing, account/session schema, and account/session persistence.
|
||||||
|
- `authclient` — HTTP client and `net/http` middleware for services that adopt the centralized AuthServer instead of embedding `auth` against their own database.
|
||||||
- `migrate` — embedded filesystem adapter for Goose migrations.
|
- `migrate` — embedded filesystem adapter for Goose migrations.
|
||||||
|
- `logshipper` — client adapter for LoggingServer (Web/LoggingServer): batches and ships log entries centrally while mirroring the same human-readable output and Debug/Info/Warn/Error/Critical/Audit/*Ctx method surface as each project's local internal/logging package.
|
||||||
|
|
||||||
Run `go test ./...` and `go vet ./...` from this directory. The module path is
|
Run `go test ./...` and `go vet ./...` from this directory. The module path is
|
||||||
`repos.gfranz.ch/Gabriel20xx/shared/backend`; change it if the shared folder is
|
`repos.gfranz.ch/Gabriel20xx/shared/backend`; change it if the shared folder is
|
||||||
|
|||||||
@@ -423,7 +423,7 @@ func (s *Store) validate() error {
|
|||||||
func (s *Store) find(ctx context.Context, query string, arg any) (*User, error) {
|
func (s *Store) find(ctx context.Context, query string, arg any) (*User, error) {
|
||||||
var user User
|
var user User
|
||||||
err := s.pool.QueryRow(ctx, query, arg).Scan(
|
err := s.pool.QueryRow(ctx, query, arg).Scan(
|
||||||
&user.ID, &user.Username, &user.Email, &user.PasswordHash, &user.CreatedAt, &user.UpdatedAt,
|
&user.ID, &user.Username, &user.Email, &user.PasswordHash, &user.Role, &user.CreatedAt, &user.UpdatedAt,
|
||||||
)
|
)
|
||||||
if errors.Is(err, pgx.ErrNoRows) {
|
if errors.Is(err, pgx.ErrNoRows) {
|
||||||
return nil, nil
|
return nil, nil
|
||||||
|
|||||||
@@ -0,0 +1,104 @@
|
|||||||
|
package auth
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"os"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"repos.gfranz.ch/Gabriel20xx/shared/backend/postgres"
|
||||||
|
)
|
||||||
|
|
||||||
|
// TestStoreIntegration exercises Store against a real PostgreSQL database,
|
||||||
|
// covering exactly what the fake stores unit tests (in each consumer's own
|
||||||
|
// httpapi package) use instead cannot: a mismatch between a query's column
|
||||||
|
// list and Scan's destination count only surfaces against a real driver
|
||||||
|
// round-trip. Skipped unless DATABASE_URL points at a scratch database -
|
||||||
|
// never run by default in CI; point it at a local/throwaway database to run
|
||||||
|
// it, e.g.:
|
||||||
|
//
|
||||||
|
// DATABASE_URL=postgres://user:pass@localhost:5432/scratch?sslmode=disable go test ./auth/... -run TestStoreIntegration
|
||||||
|
func TestStoreIntegration(t *testing.T) {
|
||||||
|
url := os.Getenv("DATABASE_URL")
|
||||||
|
if url == "" {
|
||||||
|
t.Skip("DATABASE_URL not set; skipping Postgres integration test")
|
||||||
|
}
|
||||||
|
|
||||||
|
ctx := context.Background()
|
||||||
|
pool, err := postgres.Open(ctx, postgres.DefaultConfig(url))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("open pool: %v", err)
|
||||||
|
}
|
||||||
|
// Registered before the DeleteAllUsers cleanup below so it runs after
|
||||||
|
// that one (t.Cleanup runs in LIFO order).
|
||||||
|
t.Cleanup(pool.Close)
|
||||||
|
|
||||||
|
if err := EnsureSchema(ctx, pool, SchemaOptions{SingleUser: false, APITokens: true}); err != nil {
|
||||||
|
t.Fatalf("EnsureSchema() error = %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
store := NewStore(pool)
|
||||||
|
if err := store.DeleteAllUsers(ctx); err != nil {
|
||||||
|
t.Fatalf("DeleteAllUsers() (pre-test cleanup) error = %v", err)
|
||||||
|
}
|
||||||
|
t.Cleanup(func() {
|
||||||
|
if err := store.DeleteAllUsers(context.Background()); err != nil {
|
||||||
|
t.Logf("cleanup: DeleteAllUsers() error = %v", err)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
hash, err := HashPassword("correct horse battery staple")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("HashPassword() error = %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// The very first account is promoted to superadmin; this also exercises
|
||||||
|
// CreateUser's own Scan (7 RETURNING columns), separately from find's.
|
||||||
|
created, err := store.CreateUser(ctx, "root", "root@example.com", hash)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("CreateUser() error = %v", err)
|
||||||
|
}
|
||||||
|
if created.Role != RoleSuperAdmin {
|
||||||
|
t.Fatalf("first CreateUser() role = %q, want %q", created.Role, RoleSuperAdmin)
|
||||||
|
}
|
||||||
|
|
||||||
|
byIdentifier, err := store.FindByIdentifier(ctx, "root")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("FindByIdentifier() error = %v", err)
|
||||||
|
}
|
||||||
|
if byIdentifier == nil || byIdentifier.ID != created.ID || byIdentifier.Role != RoleSuperAdmin {
|
||||||
|
t.Fatalf("FindByIdentifier() = %+v, want a superadmin match for %+v", byIdentifier, created)
|
||||||
|
}
|
||||||
|
|
||||||
|
byID, err := store.FindByID(ctx, created.ID)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("FindByID() error = %v", err)
|
||||||
|
}
|
||||||
|
if byID == nil || byID.Username != "root" || byID.Role != RoleSuperAdmin {
|
||||||
|
t.Fatalf("FindByID() = %+v, want username %q and superadmin role", byID, "root")
|
||||||
|
}
|
||||||
|
|
||||||
|
_, hashedToken, err := NewSessionToken()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("NewSessionToken() error = %v", err)
|
||||||
|
}
|
||||||
|
if err := store.CreateSession(ctx, created.ID, hashedToken, time.Now().Add(time.Hour)); err != nil {
|
||||||
|
t.Fatalf("CreateSession() error = %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
bySession, err := store.FindSessionUser(ctx, hashedToken)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("FindSessionUser() error = %v", err)
|
||||||
|
}
|
||||||
|
if bySession == nil || bySession.ID != created.ID {
|
||||||
|
t.Fatalf("FindSessionUser() = %+v, want a match for %+v", bySession, created)
|
||||||
|
}
|
||||||
|
|
||||||
|
users, err := store.ListUsers(ctx)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("ListUsers() error = %v", err)
|
||||||
|
}
|
||||||
|
if len(users) != 1 || users[0].ID != created.ID {
|
||||||
|
t.Fatalf("ListUsers() = %+v, want exactly the created user", users)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,516 @@
|
|||||||
|
// Package authclient is how any Go service in this workspace adopts a
|
||||||
|
// centralized AuthServer (see the AuthServer project, a sibling of this
|
||||||
|
// shared/backend module) instead of embedding shared/backend/auth's
|
||||||
|
// Store directly against its own private database.
|
||||||
|
//
|
||||||
|
// A service that switches to AuthServer trades "its own local user table"
|
||||||
|
// for "one HTTP call per request to AuthServer's /api/session/validate",
|
||||||
|
// gaining a single shared identity across every project that does the
|
||||||
|
// same. This package is additive: it does not change how
|
||||||
|
// shared/backend/auth works, and no project in this workspace is wired up
|
||||||
|
// to use it yet — that migration is a deliberate per-project decision, not
|
||||||
|
// something this package does automatically. See AuthServer/README.md's
|
||||||
|
// "Migration notes" section.
|
||||||
|
package authclient
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"net/http"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
// User is the account AuthServer resolved for a validated session. It
|
||||||
|
// mirrors the fields returned by GET /api/session/validate.
|
||||||
|
type User struct {
|
||||||
|
ID int64 `json:"user_id"`
|
||||||
|
Username string `json:"username"`
|
||||||
|
Role string `json:"role"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// ErrInvalidSession is returned by Validate when AuthServer reports the
|
||||||
|
// token/cookie as not currently valid (expired, unknown, or missing).
|
||||||
|
var ErrInvalidSession = errors.New("authclient: invalid or missing session")
|
||||||
|
|
||||||
|
// DefaultCookieName is the session cookie AuthServer sets and reads
|
||||||
|
// (AuthServer's own httpapi.SessionCookieName). A service that forwards
|
||||||
|
// AuthServer's Set-Cookie header straight through to its own browser client
|
||||||
|
// (see the "Cookie forwarding" note below) ends up reading this same cookie
|
||||||
|
// name back off incoming requests, so it is exported here rather than left
|
||||||
|
// as an unexported default only Middleware can see.
|
||||||
|
const DefaultCookieName = "auth_session"
|
||||||
|
|
||||||
|
// Client calls a centralized AuthServer instance over HTTP.
|
||||||
|
type Client struct {
|
||||||
|
// BaseURL is AuthServer's base URL, e.g. "https://auth.example.com"
|
||||||
|
// (no trailing slash required).
|
||||||
|
baseURL string
|
||||||
|
// HTTPClient is used for every request; defaults to a client with a
|
||||||
|
// short timeout suitable for a per-request auth check.
|
||||||
|
httpClient *http.Client
|
||||||
|
// CookieName is the cookie this client looks for on incoming requests
|
||||||
|
// when Middleware has no Authorization header to use. Defaults to
|
||||||
|
// "auth_session", matching AuthServer's SessionCookieName.
|
||||||
|
cookieName string
|
||||||
|
}
|
||||||
|
|
||||||
|
// Option configures optional Client behavior.
|
||||||
|
type Option func(*Client)
|
||||||
|
|
||||||
|
// WithHTTPClient overrides the default HTTP client (e.g. to tune timeouts
|
||||||
|
// or transport pooling).
|
||||||
|
func WithHTTPClient(hc *http.Client) Option {
|
||||||
|
return func(c *Client) { c.httpClient = hc }
|
||||||
|
}
|
||||||
|
|
||||||
|
// WithCookieName overrides the cookie name Middleware reads from incoming
|
||||||
|
// requests. Only needed if the AuthServer deployment was configured with a
|
||||||
|
// non-default session cookie name.
|
||||||
|
func WithCookieName(name string) Option {
|
||||||
|
return func(c *Client) { c.cookieName = name }
|
||||||
|
}
|
||||||
|
|
||||||
|
// New creates a Client for the AuthServer instance at baseURL.
|
||||||
|
func New(baseURL string, opts ...Option) *Client {
|
||||||
|
c := &Client{
|
||||||
|
baseURL: strings.TrimRight(strings.TrimSpace(baseURL), "/"),
|
||||||
|
httpClient: &http.Client{Timeout: 5 * time.Second},
|
||||||
|
cookieName: DefaultCookieName,
|
||||||
|
}
|
||||||
|
for _, opt := range opts {
|
||||||
|
opt(c)
|
||||||
|
}
|
||||||
|
return c
|
||||||
|
}
|
||||||
|
|
||||||
|
// Validate calls AuthServer's GET /api/session/validate with token as a
|
||||||
|
// Bearer credential and returns the resolved user. It returns
|
||||||
|
// ErrInvalidSession (wrapped) when AuthServer reports the session as not
|
||||||
|
// valid, and a plain error for any transport/decoding failure.
|
||||||
|
func (c *Client) Validate(ctx context.Context, token string) (*User, error) {
|
||||||
|
if c == nil || c.baseURL == "" {
|
||||||
|
return nil, errors.New("authclient: client has no base URL")
|
||||||
|
}
|
||||||
|
token = strings.TrimSpace(token)
|
||||||
|
if token == "" {
|
||||||
|
return nil, ErrInvalidSession
|
||||||
|
}
|
||||||
|
|
||||||
|
req, err := http.NewRequestWithContext(ctx, http.MethodGet, c.baseURL+"/api/session/validate", nil)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("authclient: build request: %w", err)
|
||||||
|
}
|
||||||
|
req.Header.Set("Authorization", "Bearer "+token)
|
||||||
|
|
||||||
|
resp, err := c.httpClient.Do(req)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("authclient: call AuthServer: %w", err)
|
||||||
|
}
|
||||||
|
defer resp.Body.Close()
|
||||||
|
|
||||||
|
var payload struct {
|
||||||
|
Valid bool `json:"valid"`
|
||||||
|
UserID int64 `json:"user_id"`
|
||||||
|
Username string `json:"username"`
|
||||||
|
Role string `json:"role"`
|
||||||
|
}
|
||||||
|
if err := json.NewDecoder(resp.Body).Decode(&payload); err != nil {
|
||||||
|
if resp.StatusCode == http.StatusUnauthorized {
|
||||||
|
return nil, ErrInvalidSession
|
||||||
|
}
|
||||||
|
return nil, fmt.Errorf("authclient: decode AuthServer response: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if resp.StatusCode != http.StatusOK || !payload.Valid {
|
||||||
|
return nil, ErrInvalidSession
|
||||||
|
}
|
||||||
|
return &User{ID: payload.UserID, Username: payload.Username, Role: payload.Role}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// contextKey is unexported so only this package can set/read the resolved
|
||||||
|
// user on a request context.
|
||||||
|
type contextKey struct{}
|
||||||
|
|
||||||
|
var userContextKey contextKey
|
||||||
|
|
||||||
|
// UserFromContext returns the user Middleware attached to the request
|
||||||
|
// context, or nil if none is present (e.g. called outside Middleware).
|
||||||
|
func UserFromContext(ctx context.Context) *User {
|
||||||
|
user, _ := ctx.Value(userContextKey).(*User)
|
||||||
|
return user
|
||||||
|
}
|
||||||
|
|
||||||
|
// Middleware extracts the session token from an incoming request — the
|
||||||
|
// cookie named by WithCookieName (default "auth_session"), falling back to
|
||||||
|
// an Authorization: Bearer header — validates it against AuthServer, and
|
||||||
|
// either responds 401 or attaches the resolved *User to the request
|
||||||
|
// context (retrieve it with UserFromContext) before calling next.
|
||||||
|
func (c *Client) Middleware(next http.Handler) http.Handler {
|
||||||
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
token := c.tokenFromRequest(r)
|
||||||
|
user, err := c.Validate(r.Context(), token)
|
||||||
|
if err != nil {
|
||||||
|
status := http.StatusUnauthorized
|
||||||
|
if !errors.Is(err, ErrInvalidSession) {
|
||||||
|
// A transport/decoding failure talking to AuthServer is not
|
||||||
|
// the same as "this visitor is unauthenticated"; still fail
|
||||||
|
// closed (401) rather than letting the request through, but
|
||||||
|
// keep the two cases distinguishable for callers that want
|
||||||
|
// to log or alert differently.
|
||||||
|
status = http.StatusUnauthorized
|
||||||
|
}
|
||||||
|
http.Error(w, "authentication required", status)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
r = r.WithContext(context.WithValue(r.Context(), userContextKey, user))
|
||||||
|
next.ServeHTTP(w, r)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *Client) tokenFromRequest(r *http.Request) string {
|
||||||
|
if header := r.Header.Get("Authorization"); header != "" {
|
||||||
|
if token, ok := strings.CutPrefix(header, "Bearer "); ok {
|
||||||
|
if token = strings.TrimSpace(token); token != "" {
|
||||||
|
return token
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if cookie, err := r.Cookie(c.cookieName); err == nil {
|
||||||
|
return cookie.Value
|
||||||
|
}
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Full API surface -------------------------------------------------------
|
||||||
|
//
|
||||||
|
// Validate/Middleware above are all a service needs when it only ever
|
||||||
|
// forwards an already-established AuthServer session to check it's still
|
||||||
|
// valid. A service that used to run its own local register/login/logout/
|
||||||
|
// TOTP/password-reset/admin-user-management flow (backed by its own copy of
|
||||||
|
// shared/backend/auth's Store) and is migrating that flow onto AuthServer
|
||||||
|
// instead needs to originate those same calls itself — that's what the rest
|
||||||
|
// of this file adds. Every method mirrors one of AuthServer's
|
||||||
|
// internal/httpapi handlers exactly (method, path, request/response JSON
|
||||||
|
// shape); see AuthServer/README.md's HTTP API table and
|
||||||
|
// AuthServer/internal/httpapi/*.go for the source of truth this was written
|
||||||
|
// against.
|
||||||
|
//
|
||||||
|
// # Cookie forwarding
|
||||||
|
//
|
||||||
|
// Register and Login both return the Set-Cookie header(s) AuthServer's
|
||||||
|
// response carried, as SessionResult.Cookies (Logout returns them directly).
|
||||||
|
// A service proxying its own e.g. POST /login to AuthServer's POST
|
||||||
|
// /api/login should generally pass these straight through to its own
|
||||||
|
// http.ResponseWriter with ForwardCookies (or by hand with http.SetCookie):
|
||||||
|
// the browser then transparently holds AuthServer's own auth_session cookie
|
||||||
|
// under whatever Domain/Secure/SameSite/Max-Age AuthServer was configured
|
||||||
|
// with (see AUTH_COOKIE_DOMAIN in AuthServer's README for the cross-project
|
||||||
|
// SSO implications of that Domain scope), and every subsequent request's
|
||||||
|
// session token is that same cookie value — no separate mapping between "the
|
||||||
|
// proxying service's own session cookie" and "the AuthServer token" is
|
||||||
|
// needed anywhere. A service adopting this pattern should stop minting a
|
||||||
|
// session cookie of its own and read/forward the incoming auth_session
|
||||||
|
// cookie the same way Middleware does (see tokenFromRequest).
|
||||||
|
|
||||||
|
// PublicUser is the account payload register/login/me return: {"id",
|
||||||
|
// "username", "email", "role", "totp_enabled"}. It is deliberately distinct
|
||||||
|
// from the slimmer User type Validate/Middleware use (which mirrors GET
|
||||||
|
// /api/session/validate's {"user_id", "username", "role"} instead, and does
|
||||||
|
// not carry TOTP status at all).
|
||||||
|
type PublicUser struct {
|
||||||
|
ID int64 `json:"id"`
|
||||||
|
Username string `json:"username"`
|
||||||
|
Email string `json:"email"`
|
||||||
|
Role string `json:"role"`
|
||||||
|
TOTPEnabled bool `json:"totp_enabled"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// ManagedUser is one row of GET /api/admin/users, and the payload returned
|
||||||
|
// by CreateManagedUser. It additionally carries CreatedAt, which PublicUser
|
||||||
|
// does not.
|
||||||
|
type ManagedUser struct {
|
||||||
|
ID int64 `json:"id"`
|
||||||
|
Username string `json:"username"`
|
||||||
|
Email string `json:"email"`
|
||||||
|
Role string `json:"role"`
|
||||||
|
CreatedAt time.Time `json:"created_at"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// SessionResult is returned by Register and Login: the account AuthServer
|
||||||
|
// resolved, plus the Set-Cookie header(s) its response carried. See the
|
||||||
|
// "Cookie forwarding" note above.
|
||||||
|
type SessionResult struct {
|
||||||
|
User PublicUser
|
||||||
|
Cookies []*http.Cookie
|
||||||
|
}
|
||||||
|
|
||||||
|
// TOTPEnableResult is returned by TOTPEnable: a freshly provisioned, not yet
|
||||||
|
// active TOTP secret and its otpauth:// URI for a QR code / authenticator
|
||||||
|
// app. Confirm it with TOTPVerify.
|
||||||
|
type TOTPEnableResult struct {
|
||||||
|
Secret string `json:"secret"`
|
||||||
|
OTPAuthURL string `json:"otpauth_url"`
|
||||||
|
Enabled bool `json:"enabled"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// ManagedUserInput is the body of CreateManagedUser (POST /api/admin/users)
|
||||||
|
// and UpdateManagedUser (PUT /api/admin/users/{id}). On update, a zero-value
|
||||||
|
// Username/Email/Password field means "leave unchanged" (AuthServer applies
|
||||||
|
// only non-empty fields), and Role is only honored when AuthServer's own
|
||||||
|
// authorization rules let the caller reassign it (only a superadmin actor,
|
||||||
|
// and never onto/away from a superadmin target) — see AuthServer's
|
||||||
|
// admin_users.go doc comments for the exact rules, which this client does
|
||||||
|
// not re-implement or pre-validate.
|
||||||
|
type ManagedUserInput struct {
|
||||||
|
Username string `json:"username,omitempty"`
|
||||||
|
Email string `json:"email,omitempty"`
|
||||||
|
Password string `json:"password,omitempty"`
|
||||||
|
Role *string `json:"role,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// APIError is returned when AuthServer responds with a non-2xx status. It
|
||||||
|
// carries the status code and (when AuthServer's JSON body decoded
|
||||||
|
// successfully) its {"error": "..."} message, so a caller can map it back
|
||||||
|
// onto its own service's response shape/status code rather than exposing
|
||||||
|
// AuthServer's wording verbatim. Use errors.As to recover it.
|
||||||
|
type APIError struct {
|
||||||
|
StatusCode int
|
||||||
|
Message string
|
||||||
|
// TOTPRequired is set only by Login, mirroring AuthServer's
|
||||||
|
// {"totp_required": true} flag on a 401 that means "credentials were
|
||||||
|
// correct, but this account has two-factor auth enabled and no (or an
|
||||||
|
// incorrect) code was supplied" — distinct from a plain invalid-
|
||||||
|
// credentials 401.
|
||||||
|
TOTPRequired bool
|
||||||
|
}
|
||||||
|
|
||||||
|
func (e *APIError) Error() string {
|
||||||
|
return fmt.Sprintf("authclient: authserver responded %d: %s", e.StatusCode, e.Message)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ForwardCookies re-sets each cookie (typically SessionResult.Cookies or
|
||||||
|
// Logout's return value) on w. This is the mechanical half of the "cookie
|
||||||
|
// forwarding" pattern described above.
|
||||||
|
func ForwardCookies(w http.ResponseWriter, cookies []*http.Cookie) {
|
||||||
|
for _, cookie := range cookies {
|
||||||
|
if cookie != nil {
|
||||||
|
http.SetCookie(w, cookie)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// call is the shared request/response plumbing for every method below: it
|
||||||
|
// builds a JSON request (skipped when body is nil), attaches token as a
|
||||||
|
// Bearer credential (skipped when token is ""), and on a 2xx response
|
||||||
|
// decodes the JSON body into out (skipped when out is nil). A non-2xx
|
||||||
|
// response is translated into *APIError. The returned *http.Response (nil
|
||||||
|
// on a transport-level failure) is provided so callers can read Cookies();
|
||||||
|
// its Body is always already fully read and closed.
|
||||||
|
func (c *Client) call(ctx context.Context, method, path, token string, body, out any) (*http.Response, error) {
|
||||||
|
if c == nil || c.baseURL == "" {
|
||||||
|
return nil, errors.New("authclient: client has no base URL")
|
||||||
|
}
|
||||||
|
|
||||||
|
var reader io.Reader
|
||||||
|
if body != nil {
|
||||||
|
data, err := json.Marshal(body)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("authclient: encode request body: %w", err)
|
||||||
|
}
|
||||||
|
reader = bytes.NewReader(data)
|
||||||
|
}
|
||||||
|
req, err := http.NewRequestWithContext(ctx, method, c.baseURL+path, reader)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("authclient: build request: %w", err)
|
||||||
|
}
|
||||||
|
if body != nil {
|
||||||
|
req.Header.Set("Content-Type", "application/json")
|
||||||
|
}
|
||||||
|
if token != "" {
|
||||||
|
req.Header.Set("Authorization", "Bearer "+token)
|
||||||
|
}
|
||||||
|
|
||||||
|
resp, err := c.httpClient.Do(req)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("authclient: call AuthServer: %w", err)
|
||||||
|
}
|
||||||
|
defer resp.Body.Close()
|
||||||
|
|
||||||
|
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
||||||
|
var payload struct {
|
||||||
|
Error string `json:"error"`
|
||||||
|
TOTPRequired bool `json:"totp_required"`
|
||||||
|
}
|
||||||
|
_ = json.NewDecoder(io.LimitReader(resp.Body, 64*1024)).Decode(&payload)
|
||||||
|
message := payload.Error
|
||||||
|
if message == "" {
|
||||||
|
message = resp.Status
|
||||||
|
}
|
||||||
|
return resp, &APIError{StatusCode: resp.StatusCode, Message: message, TOTPRequired: payload.TOTPRequired}
|
||||||
|
}
|
||||||
|
if out != nil {
|
||||||
|
if err := json.NewDecoder(io.LimitReader(resp.Body, 1<<20)).Decode(out); err != nil {
|
||||||
|
return resp, fmt.Errorf("authclient: decode AuthServer response: %w", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return resp, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// SetupStatus calls GET /api/setup-status, an unauthenticated endpoint that
|
||||||
|
// reports whether AuthServer has any account at all. Accounts are
|
||||||
|
// centralized in AuthServer, so a caller with its own "first launch, create
|
||||||
|
// the initial admin" flow should consult this first: when it reports false,
|
||||||
|
// some account already exists (possibly created by a different project, or
|
||||||
|
// directly against AuthServer), and the caller should show its ordinary
|
||||||
|
// login screen instead of its own account-creation form.
|
||||||
|
func (c *Client) SetupStatus(ctx context.Context) (bool, error) {
|
||||||
|
var out struct {
|
||||||
|
SetupRequired bool `json:"setup_required"`
|
||||||
|
}
|
||||||
|
if _, err := c.call(ctx, http.MethodGet, "/api/setup-status", "", nil, &out); err != nil {
|
||||||
|
return false, err
|
||||||
|
}
|
||||||
|
return out.SetupRequired, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Register calls POST /api/register, creating a new AuthServer account and
|
||||||
|
// starting a session for it.
|
||||||
|
func (c *Client) Register(ctx context.Context, username, email, password string) (*SessionResult, error) {
|
||||||
|
var out struct {
|
||||||
|
User PublicUser `json:"user"`
|
||||||
|
}
|
||||||
|
body := map[string]string{"username": username, "email": email, "password": password}
|
||||||
|
resp, err := c.call(ctx, http.MethodPost, "/api/register", "", body, &out)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return &SessionResult{User: out.User, Cookies: resp.Cookies()}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Login calls POST /api/login. totpToken may be empty; AuthServer returns an
|
||||||
|
// *APIError with TOTPRequired set when the account has two-factor auth
|
||||||
|
// enabled and no valid code was supplied.
|
||||||
|
func (c *Client) Login(ctx context.Context, usernameOrEmail, password, totpToken string) (*SessionResult, error) {
|
||||||
|
var out struct {
|
||||||
|
User PublicUser `json:"user"`
|
||||||
|
}
|
||||||
|
body := map[string]string{"username_or_email": usernameOrEmail, "password": password}
|
||||||
|
if totpToken != "" {
|
||||||
|
body["totp_token"] = totpToken
|
||||||
|
}
|
||||||
|
resp, err := c.call(ctx, http.MethodPost, "/api/login", "", body, &out)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return &SessionResult{User: out.User, Cookies: resp.Cookies()}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Logout calls POST /api/logout, deleting the session identified by token
|
||||||
|
// server-side. It returns the (cookie-clearing) Set-Cookie header(s)
|
||||||
|
// AuthServer's response carried; see ForwardCookies.
|
||||||
|
func (c *Client) Logout(ctx context.Context, token string) ([]*http.Cookie, error) {
|
||||||
|
resp, err := c.call(ctx, http.MethodPost, "/api/logout", token, nil, nil)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return resp.Cookies(), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Me calls GET /api/me, resolving token to its account.
|
||||||
|
func (c *Client) Me(ctx context.Context, token string) (*PublicUser, error) {
|
||||||
|
var out struct {
|
||||||
|
User PublicUser `json:"user"`
|
||||||
|
}
|
||||||
|
if _, err := c.call(ctx, http.MethodGet, "/api/me", token, nil, &out); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return &out.User, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// TOTPEnable calls POST /api/totp/enable, provisioning (or re-provisioning)
|
||||||
|
// a pending TOTP secret for token's account. The secret is not active until
|
||||||
|
// TOTPVerify confirms a generated code.
|
||||||
|
func (c *Client) TOTPEnable(ctx context.Context, token string) (*TOTPEnableResult, error) {
|
||||||
|
var out TOTPEnableResult
|
||||||
|
if _, err := c.call(ctx, http.MethodPost, "/api/totp/enable", token, nil, &out); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return &out, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// TOTPVerify calls POST /api/totp/verify, confirming code against the
|
||||||
|
// pending secret TOTPEnable provisioned and activating two-factor auth.
|
||||||
|
func (c *Client) TOTPVerify(ctx context.Context, token, code string) error {
|
||||||
|
_, err := c.call(ctx, http.MethodPost, "/api/totp/verify", token, map[string]string{"token": code}, nil)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
// TOTPDisable calls POST /api/totp/disable, turning two-factor auth off for
|
||||||
|
// token's account. AuthServer requires code to be one last valid TOTP code
|
||||||
|
// as proof of possession.
|
||||||
|
func (c *Client) TOTPDisable(ctx context.Context, token, code string) error {
|
||||||
|
_, err := c.call(ctx, http.MethodPost, "/api/totp/disable", token, map[string]string{"token": code}, nil)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
// RequestPasswordReset calls POST /api/password-reset/request. See
|
||||||
|
// AuthServer's README for an important caveat: this is not an "email me a
|
||||||
|
// link" flow — AuthServer prints a one-time code to its own process
|
||||||
|
// console, and only an operator with access to that console can relay it to
|
||||||
|
// the user. The response never reveals whether usernameOrEmail matched an
|
||||||
|
// account.
|
||||||
|
func (c *Client) RequestPasswordReset(ctx context.Context, usernameOrEmail string) error {
|
||||||
|
_, err := c.call(ctx, http.MethodPost, "/api/password-reset/request", "", map[string]string{"username_or_email": usernameOrEmail}, nil)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
// ConfirmPasswordReset calls POST /api/password-reset/confirm with the code
|
||||||
|
// an operator relayed out-of-band (see RequestPasswordReset) and a new
|
||||||
|
// password, and invalidates every existing session for that account.
|
||||||
|
func (c *Client) ConfirmPasswordReset(ctx context.Context, code, newPassword string) error {
|
||||||
|
_, err := c.call(ctx, http.MethodPost, "/api/password-reset/confirm", "", map[string]string{"code": code, "password": newPassword}, nil)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
// ListManagedUsers calls GET /api/admin/users. token's account must satisfy
|
||||||
|
// AuthServer's CanManageUsers check (admin or superadmin), or this returns
|
||||||
|
// an *APIError with StatusCode 401/403.
|
||||||
|
func (c *Client) ListManagedUsers(ctx context.Context, token string) ([]ManagedUser, error) {
|
||||||
|
var out struct {
|
||||||
|
Users []ManagedUser `json:"users"`
|
||||||
|
}
|
||||||
|
if _, err := c.call(ctx, http.MethodGet, "/api/admin/users", token, nil, &out); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return out.Users, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// CreateManagedUser calls POST /api/admin/users. Only honored when token's
|
||||||
|
// account can manage users; see ManagedUserInput's doc comment for the Role
|
||||||
|
// authorization rule.
|
||||||
|
func (c *Client) CreateManagedUser(ctx context.Context, token string, input ManagedUserInput) (*ManagedUser, error) {
|
||||||
|
var out struct {
|
||||||
|
User ManagedUser `json:"user"`
|
||||||
|
}
|
||||||
|
if _, err := c.call(ctx, http.MethodPost, "/api/admin/users", token, input, &out); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return &out.User, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// UpdateManagedUser calls PUT /api/admin/users/{id}.
|
||||||
|
func (c *Client) UpdateManagedUser(ctx context.Context, token string, id int64, input ManagedUserInput) error {
|
||||||
|
_, err := c.call(ctx, http.MethodPut, fmt.Sprintf("/api/admin/users/%d", id), token, input, nil)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
// DeleteManagedUser calls DELETE /api/admin/users/{id}.
|
||||||
|
func (c *Client) DeleteManagedUser(ctx context.Context, token string, id int64) error {
|
||||||
|
_, err := c.call(ctx, http.MethodDelete, fmt.Sprintf("/api/admin/users/%d", id), token, nil, nil)
|
||||||
|
return err
|
||||||
|
}
|
||||||
@@ -0,0 +1,49 @@
|
|||||||
|
package authclient
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestSetupStatus(t *testing.T) {
|
||||||
|
cases := []struct {
|
||||||
|
name string
|
||||||
|
response any
|
||||||
|
want bool
|
||||||
|
}{
|
||||||
|
{name: "no accounts yet", response: map[string]bool{"setup_required": true}, want: true},
|
||||||
|
{name: "an account already exists", response: map[string]bool{"setup_required": false}, want: false},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, tc := range cases {
|
||||||
|
t.Run(tc.name, func(t *testing.T) {
|
||||||
|
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
if r.Method != http.MethodGet || r.URL.Path != "/api/setup-status" {
|
||||||
|
t.Fatalf("unexpected request: %s %s", r.Method, r.URL.Path)
|
||||||
|
}
|
||||||
|
w.Header().Set("Content-Type", "application/json")
|
||||||
|
_ = json.NewEncoder(w).Encode(tc.response)
|
||||||
|
}))
|
||||||
|
defer server.Close()
|
||||||
|
|
||||||
|
client := New(server.URL)
|
||||||
|
got, err := client.SetupStatus(context.Background())
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("SetupStatus() error = %v", err)
|
||||||
|
}
|
||||||
|
if got != tc.want {
|
||||||
|
t.Fatalf("SetupStatus() = %v, want %v", got, tc.want)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSetupStatusPropagatesTransportError(t *testing.T) {
|
||||||
|
client := New("http://127.0.0.1:0")
|
||||||
|
if _, err := client.SetupStatus(context.Background()); err == nil {
|
||||||
|
t.Fatal("SetupStatus() expected an error against an unreachable server, got nil")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,438 @@
|
|||||||
|
// Package logshipper is the client-side adapter for LoggingServer
|
||||||
|
// (Web/LoggingServer), the workspace's centralized log sink. It is the
|
||||||
|
// logging equivalent of the authclient package added alongside AuthServer:
|
||||||
|
// each service currently owns its own local internal/logging package (see
|
||||||
|
// Original/OutdoorGames/OutdoorGamesServerGo/internal/logging/logging.go for
|
||||||
|
// the canonical shape — a Logger tagged by module name, an env-driven level
|
||||||
|
// threshold, Debug/Info/Warn/Error/Critical/Audit/*Ctx methods, and an
|
||||||
|
// optional verbose JSON context dump gated by LOG_ALL). Shipper exposes that
|
||||||
|
// exact same method surface so a project can eventually swap its local
|
||||||
|
// logging.New(...) call for logshipper.New(...) with no call-site changes,
|
||||||
|
// once the owner decides to migrate a given service.
|
||||||
|
//
|
||||||
|
// No project imports this yet — see LoggingServer/README.md's "Migration
|
||||||
|
// notes" for the deliberate, per-project follow-up this requires.
|
||||||
|
//
|
||||||
|
// Shipper always writes the same human-readable line to stdout/stderr that
|
||||||
|
// the local loggers write today, in addition to batching entries off to
|
||||||
|
// LoggingServer. Nothing is lost if LoggingServer is never wired up, never
|
||||||
|
// reachable, or removed later — this is a mirror, not a replacement, for the
|
||||||
|
// container's own stdout/stderr logs.
|
||||||
|
package logshipper
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"net/http"
|
||||||
|
"os"
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Level mirrors internal/logging's severity scale in every service's local
|
||||||
|
// logger, so a threshold configured via the same LOG env var behaves
|
||||||
|
// identically whether it gates a local Logger or a Shipper.
|
||||||
|
type Level int
|
||||||
|
|
||||||
|
const (
|
||||||
|
LevelDebug Level = 10
|
||||||
|
LevelInfo Level = 20
|
||||||
|
LevelWarn Level = 30
|
||||||
|
LevelError Level = 40
|
||||||
|
LevelCritical Level = 50
|
||||||
|
LevelSilent Level = 100
|
||||||
|
)
|
||||||
|
|
||||||
|
func levelOf(s string) Level {
|
||||||
|
switch strings.ToLower(strings.TrimSpace(s)) {
|
||||||
|
case "debug":
|
||||||
|
return LevelDebug
|
||||||
|
case "warn", "warning":
|
||||||
|
return LevelWarn
|
||||||
|
case "error":
|
||||||
|
return LevelError
|
||||||
|
case "critical":
|
||||||
|
return LevelCritical
|
||||||
|
case "silent", "none", "off":
|
||||||
|
return LevelSilent
|
||||||
|
default:
|
||||||
|
return LevelInfo
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// sevName is the canonical, lowercase level name LoggingServer's ingest API
|
||||||
|
// expects (debug/info/warn/error/critical), independent of the uppercase
|
||||||
|
// name used in the local stdout/stderr line.
|
||||||
|
func sevName(sev Level) (upper, lower string) {
|
||||||
|
switch sev {
|
||||||
|
case LevelDebug:
|
||||||
|
return "DEBUG", "debug"
|
||||||
|
case LevelWarn:
|
||||||
|
return "WARN", "warn"
|
||||||
|
case LevelError:
|
||||||
|
return "ERROR", "error"
|
||||||
|
case LevelCritical:
|
||||||
|
return "CRITICAL", "critical"
|
||||||
|
default:
|
||||||
|
return "INFO", "info"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const (
|
||||||
|
defaultFlushInterval = 2 * time.Second
|
||||||
|
defaultMaxBatchSize = 100
|
||||||
|
defaultBufferCapacity = 2000
|
||||||
|
defaultHTTPTimeout = 5 * time.Second
|
||||||
|
defaultWarnInterval = time.Minute
|
||||||
|
)
|
||||||
|
|
||||||
|
// Config configures a Shipper. Only BaseURL, IngestToken, and Service are
|
||||||
|
// normally set by a caller; everything else has a workable default.
|
||||||
|
type Config struct {
|
||||||
|
// BaseURL is LoggingServer's base URL, e.g. "http://loggingserver:8090".
|
||||||
|
// Required.
|
||||||
|
BaseURL string
|
||||||
|
// IngestToken is the shared INGEST_TOKEN bearer secret LoggingServer
|
||||||
|
// requires (see LoggingServer/README.md). Required.
|
||||||
|
IngestToken string
|
||||||
|
// Service is this process's service name as reported to LoggingServer,
|
||||||
|
// e.g. "playhouse" or "outdoorgames-server-go". Required.
|
||||||
|
Service string
|
||||||
|
|
||||||
|
// Module is the local tag included in the human-readable stdout/stderr
|
||||||
|
// line, mirroring internal/logging.New's module argument. Defaults to
|
||||||
|
// Service when empty.
|
||||||
|
Module string
|
||||||
|
// Level is the severity threshold, same values/aliases as the LOG env
|
||||||
|
// var (debug/info/warn/error/critical/silent). Defaults to "info".
|
||||||
|
Level string
|
||||||
|
// LogAll mirrors the LOG_ALL env var: when true, a verbose JSON context
|
||||||
|
// dump is also printed locally (never sent to LoggingServer differently
|
||||||
|
// than normal — see Debug/InfoCtx doc comments).
|
||||||
|
LogAll bool
|
||||||
|
|
||||||
|
// FlushInterval is how often buffered entries are sent to LoggingServer.
|
||||||
|
// Defaults to 2s.
|
||||||
|
FlushInterval time.Duration
|
||||||
|
// MaxBatchSize triggers an out-of-band flush as soon as the buffer
|
||||||
|
// reaches this many entries, instead of waiting for FlushInterval.
|
||||||
|
// Defaults to 100.
|
||||||
|
MaxBatchSize int
|
||||||
|
// BufferCapacity is the maximum number of not-yet-flushed entries held
|
||||||
|
// in memory. Once full, new entries are dropped (oldest-first callers
|
||||||
|
// are not blocked) rather than applying backpressure to the caller.
|
||||||
|
// Defaults to 2000.
|
||||||
|
BufferCapacity int
|
||||||
|
|
||||||
|
// HTTPClient overrides the client used to POST to LoggingServer.
|
||||||
|
// Defaults to a client with a 5s timeout.
|
||||||
|
HTTPClient *http.Client
|
||||||
|
}
|
||||||
|
|
||||||
|
// wireEntry mirrors LoggingServer's POST /api/logs request shape
|
||||||
|
// (LoggingServer/internal/httpapi.LogEntryInput) field-for-field.
|
||||||
|
type wireEntry struct {
|
||||||
|
Service string `json:"service"`
|
||||||
|
Level string `json:"level"`
|
||||||
|
Message string `json:"message"`
|
||||||
|
Context json.RawMessage `json:"context,omitempty"`
|
||||||
|
OccurredAt time.Time `json:"occurred_at"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// Shipper batches log entries in memory and flushes them to LoggingServer on
|
||||||
|
// a background goroutine, while also behaving like a local
|
||||||
|
// internal/logging.Logger (same method surface, same stdout/stderr output).
|
||||||
|
// A Shipper is safe for concurrent use.
|
||||||
|
type Shipper struct {
|
||||||
|
module string
|
||||||
|
threshold Level
|
||||||
|
logAll bool
|
||||||
|
|
||||||
|
service string
|
||||||
|
url string
|
||||||
|
token string
|
||||||
|
client *http.Client
|
||||||
|
|
||||||
|
maxBatch int
|
||||||
|
bufCap int
|
||||||
|
|
||||||
|
mu sync.Mutex
|
||||||
|
buffer []wireEntry
|
||||||
|
|
||||||
|
flushSignal chan struct{}
|
||||||
|
closeOnce sync.Once
|
||||||
|
closeCh chan struct{}
|
||||||
|
doneCh chan struct{}
|
||||||
|
|
||||||
|
warnMu sync.Mutex
|
||||||
|
lastWarn time.Time
|
||||||
|
}
|
||||||
|
|
||||||
|
// New creates a Shipper. It starts a background flush goroutine immediately;
|
||||||
|
// call Close (or Flush, for a one-off synchronous flush) during shutdown to
|
||||||
|
// avoid losing buffered entries.
|
||||||
|
func New(cfg Config) *Shipper {
|
||||||
|
module := cfg.Module
|
||||||
|
if module == "" {
|
||||||
|
module = cfg.Service
|
||||||
|
}
|
||||||
|
flushInterval := cfg.FlushInterval
|
||||||
|
if flushInterval <= 0 {
|
||||||
|
flushInterval = defaultFlushInterval
|
||||||
|
}
|
||||||
|
maxBatch := cfg.MaxBatchSize
|
||||||
|
if maxBatch <= 0 {
|
||||||
|
maxBatch = defaultMaxBatchSize
|
||||||
|
}
|
||||||
|
bufCap := cfg.BufferCapacity
|
||||||
|
if bufCap <= 0 {
|
||||||
|
bufCap = defaultBufferCapacity
|
||||||
|
}
|
||||||
|
client := cfg.HTTPClient
|
||||||
|
if client == nil {
|
||||||
|
client = &http.Client{Timeout: defaultHTTPTimeout}
|
||||||
|
}
|
||||||
|
|
||||||
|
s := &Shipper{
|
||||||
|
module: module,
|
||||||
|
threshold: levelOf(cfg.Level),
|
||||||
|
logAll: cfg.LogAll,
|
||||||
|
service: cfg.Service,
|
||||||
|
url: strings.TrimRight(cfg.BaseURL, "/") + "/api/logs",
|
||||||
|
token: cfg.IngestToken,
|
||||||
|
client: client,
|
||||||
|
maxBatch: maxBatch,
|
||||||
|
bufCap: bufCap,
|
||||||
|
flushSignal: make(chan struct{}, 1),
|
||||||
|
closeCh: make(chan struct{}),
|
||||||
|
doneCh: make(chan struct{}),
|
||||||
|
}
|
||||||
|
|
||||||
|
go s.loop(flushInterval)
|
||||||
|
return s
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Shipper) loop(flushInterval time.Duration) {
|
||||||
|
defer close(s.doneCh)
|
||||||
|
ticker := time.NewTicker(flushInterval)
|
||||||
|
defer ticker.Stop()
|
||||||
|
for {
|
||||||
|
select {
|
||||||
|
case <-ticker.C:
|
||||||
|
s.flush()
|
||||||
|
case <-s.flushSignal:
|
||||||
|
s.flush()
|
||||||
|
case <-s.closeCh:
|
||||||
|
s.flush() // final, best-effort flush of whatever is left
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// requestFlush asks the background loop to flush soon, without blocking the
|
||||||
|
// caller: if a flush is already pending the request is simply dropped.
|
||||||
|
func (s *Shipper) requestFlush() {
|
||||||
|
select {
|
||||||
|
case s.flushSignal <- struct{}{}:
|
||||||
|
default:
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// enqueue appends one entry to the buffer, dropping the incoming entry
|
||||||
|
// (rather than blocking the caller or evicting older entries) once the
|
||||||
|
// buffer is full. This is the sole non-blocking guarantee this package
|
||||||
|
// makes: a caller's Debug/Info/... call never waits on network I/O.
|
||||||
|
func (s *Shipper) enqueue(entry wireEntry) {
|
||||||
|
s.mu.Lock()
|
||||||
|
full := len(s.buffer) >= s.bufCap
|
||||||
|
if !full {
|
||||||
|
s.buffer = append(s.buffer, entry)
|
||||||
|
}
|
||||||
|
atCap := len(s.buffer) >= s.maxBatch
|
||||||
|
s.mu.Unlock()
|
||||||
|
|
||||||
|
if full {
|
||||||
|
s.warnOnce(fmt.Errorf("logshipper: buffer full (cap=%d), dropping log entries for service %q", s.bufCap, s.service))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if atCap {
|
||||||
|
s.requestFlush()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// flush sends every currently buffered entry to LoggingServer in one
|
||||||
|
// request. Failures are swallowed (beyond a rate-limited local warning) by
|
||||||
|
// design: a host application must never fail, panic, or slow down because
|
||||||
|
// its log sink is unreachable.
|
||||||
|
func (s *Shipper) flush() {
|
||||||
|
s.mu.Lock()
|
||||||
|
if len(s.buffer) == 0 {
|
||||||
|
s.mu.Unlock()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
batch := s.buffer
|
||||||
|
s.buffer = nil
|
||||||
|
s.mu.Unlock()
|
||||||
|
|
||||||
|
body, err := json.Marshal(batch)
|
||||||
|
if err != nil {
|
||||||
|
s.warnOnce(fmt.Errorf("logshipper: marshal batch: %w", err))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), defaultHTTPTimeout)
|
||||||
|
defer cancel()
|
||||||
|
|
||||||
|
req, err := http.NewRequestWithContext(ctx, http.MethodPost, s.url, bytes.NewReader(body))
|
||||||
|
if err != nil {
|
||||||
|
s.warnOnce(fmt.Errorf("logshipper: build request: %w", err))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
req.Header.Set("Content-Type", "application/json")
|
||||||
|
req.Header.Set("Authorization", "Bearer "+s.token)
|
||||||
|
|
||||||
|
resp, err := s.client.Do(req)
|
||||||
|
if err != nil {
|
||||||
|
s.warnOnce(fmt.Errorf("logshipper: send %d entries to %s: %w", len(batch), s.url, err))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
defer resp.Body.Close()
|
||||||
|
|
||||||
|
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
||||||
|
s.warnOnce(fmt.Errorf("logshipper: LoggingServer rejected %d entries: HTTP %d", len(batch), resp.StatusCode))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// warnOnce prints a local stderr warning at most once per minute, no matter
|
||||||
|
// how many sends fail in that window, so an unreachable LoggingServer cannot
|
||||||
|
// itself become a log-spam problem.
|
||||||
|
func (s *Shipper) warnOnce(err error) {
|
||||||
|
s.warnMu.Lock()
|
||||||
|
defer s.warnMu.Unlock()
|
||||||
|
if time.Since(s.lastWarn) < defaultWarnInterval {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
s.lastWarn = time.Now()
|
||||||
|
fmt.Fprintf(os.Stderr, "[%s] [logshipper] %s\n", time.Now().Format("2006-01-02 15:04:05.000"), err.Error())
|
||||||
|
}
|
||||||
|
|
||||||
|
// Flush synchronously sends any currently buffered entries. It never blocks
|
||||||
|
// longer than the underlying HTTP client's timeout and never returns an
|
||||||
|
// error to the caller (failures are reported via the same rate-limited
|
||||||
|
// stderr warning as background flushes) — this mirrors the "never block or
|
||||||
|
// panic the host app" guarantee the background path makes.
|
||||||
|
func (s *Shipper) Flush() {
|
||||||
|
s.flush()
|
||||||
|
}
|
||||||
|
|
||||||
|
// Close stops the background flush goroutine after performing one final
|
||||||
|
// flush of any buffered entries, and waits for that flush to finish. Call it
|
||||||
|
// during graceful shutdown so the last few log lines before exit are not
|
||||||
|
// silently dropped.
|
||||||
|
func (s *Shipper) Close() error {
|
||||||
|
s.closeOnce.Do(func() { close(s.closeCh) })
|
||||||
|
<-s.doneCh
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- Logger-shaped methods -------------------------------------------------
|
||||||
|
//
|
||||||
|
// Everything below matches internal/logging.Logger's method surface
|
||||||
|
// (Debug/Info/Warn/Error/Critical/Audit/*Ctx) so a Shipper can act as a
|
||||||
|
// near drop-in replacement for a project's local logger.
|
||||||
|
|
||||||
|
func (s *Shipper) emit(sev Level, ctx map[string]any, args ...any) {
|
||||||
|
if sev < s.threshold {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
now := time.Now()
|
||||||
|
msg := formatArgs(args)
|
||||||
|
upper, lower := sevName(sev)
|
||||||
|
|
||||||
|
line := fmt.Sprintf("[%s] [%s] [%s] [%s] %s",
|
||||||
|
now.Format("2006-01-02"), now.Format("15:04:05.000"), upper, s.module, msg)
|
||||||
|
switch sev {
|
||||||
|
case LevelError, LevelCritical, LevelWarn:
|
||||||
|
fmt.Fprintln(os.Stderr, line)
|
||||||
|
default:
|
||||||
|
fmt.Fprintln(os.Stdout, line)
|
||||||
|
}
|
||||||
|
|
||||||
|
if s.logAll && ctx != nil {
|
||||||
|
if b, err := json.Marshal(scrubIDs(ctx)); err == nil {
|
||||||
|
fmt.Fprintf(os.Stdout, "[%s] [%s] [DEBUG] [%s] [DETAILS] %s\n",
|
||||||
|
now.Format("2006-01-02"), now.Format("15:04:05.000"), s.module, string(b))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Unlike the local-only verbose dump above (which scrubs IDs for
|
||||||
|
// readability), the context shipped to LoggingServer is sent unscrubbed:
|
||||||
|
// the whole point of centralizing logs is cross-service correlation by
|
||||||
|
// request/user/entity ID, so stripping IDs here would defeat that.
|
||||||
|
var rawCtx json.RawMessage
|
||||||
|
if ctx != nil {
|
||||||
|
if b, err := json.Marshal(ctx); err == nil {
|
||||||
|
rawCtx = b
|
||||||
|
}
|
||||||
|
}
|
||||||
|
s.enqueue(wireEntry{
|
||||||
|
Service: s.service,
|
||||||
|
Level: lower,
|
||||||
|
Message: msg,
|
||||||
|
Context: rawCtx,
|
||||||
|
OccurredAt: now,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func formatArgs(args []any) string {
|
||||||
|
parts := make([]string, 0, len(args))
|
||||||
|
for _, a := range args {
|
||||||
|
switch v := a.(type) {
|
||||||
|
case error:
|
||||||
|
parts = append(parts, v.Error())
|
||||||
|
case string:
|
||||||
|
parts = append(parts, v)
|
||||||
|
default:
|
||||||
|
if b, err := json.Marshal(v); err == nil {
|
||||||
|
parts = append(parts, string(b))
|
||||||
|
} else {
|
||||||
|
parts = append(parts, fmt.Sprintf("%v", v))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return strings.Join(parts, " ")
|
||||||
|
}
|
||||||
|
|
||||||
|
// scrubIDs drops raw identifier fields from the verbose local-only context
|
||||||
|
// dump, matching internal/logging.Logger's behavior.
|
||||||
|
func scrubIDs(ctx map[string]any) map[string]any {
|
||||||
|
out := make(map[string]any, len(ctx))
|
||||||
|
for k, v := range ctx {
|
||||||
|
lower := strings.ToLower(k)
|
||||||
|
if lower == "id" || strings.HasSuffix(lower, "id") || strings.HasSuffix(lower, "_id") {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
out[k] = v
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Shipper) Debug(args ...any) { s.emit(LevelDebug, nil, args...) }
|
||||||
|
func (s *Shipper) Info(args ...any) { s.emit(LevelInfo, nil, args...) }
|
||||||
|
func (s *Shipper) Warn(args ...any) { s.emit(LevelWarn, nil, args...) }
|
||||||
|
func (s *Shipper) Error(args ...any) { s.emit(LevelError, nil, args...) }
|
||||||
|
func (s *Shipper) Critical(args ...any) { s.emit(LevelCritical, nil, args...) }
|
||||||
|
|
||||||
|
// Audit logs a structured audit-trail event at info level, matching
|
||||||
|
// internal/logging.Logger.Audit.
|
||||||
|
func (s *Shipper) Audit(event string, details map[string]any) {
|
||||||
|
s.emit(LevelInfo, details, "audit:"+event, details)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Shipper) DebugCtx(ctx map[string]any, args ...any) { s.emit(LevelDebug, ctx, args...) }
|
||||||
|
func (s *Shipper) InfoCtx(ctx map[string]any, args ...any) { s.emit(LevelInfo, ctx, args...) }
|
||||||
|
func (s *Shipper) WarnCtx(ctx map[string]any, args ...any) { s.emit(LevelWarn, ctx, args...) }
|
||||||
|
func (s *Shipper) ErrorCtx(ctx map[string]any, args ...any) { s.emit(LevelError, ctx, args...) }
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
DATABASE_URL=postgresql://media:media@127.0.0.1:5432/mediadb
|
||||||
|
MEDIA_SERVICE=viewer
|
||||||
|
PORT=3000
|
||||||
|
WEB_ROOT=../WebUI/build
|
||||||
|
MEDIA_ROOTS=../media
|
||||||
|
INPUT_DIR=../input
|
||||||
|
UPLOAD_COPY_DIR=../copy
|
||||||
|
OUTPUT_DIR=../output
|
||||||
|
DOWNLOADS_DIR=../downloads
|
||||||
|
THUMBNAIL_DIR=../thumbnails
|
||||||
|
MODEL_CACHE_DIR=../models
|
||||||
|
WORKFLOWS_DIR=../MediaTools/public/workflows
|
||||||
|
FFMPEG_PATH=ffmpeg
|
||||||
|
FFPROBE_PATH=ffprobe
|
||||||
|
YT_DLP_PATH=yt-dlp
|
||||||
|
COMFYUI_URL=http://127.0.0.1:8188
|
||||||
|
ANALYZER_MODELS_URL=http://127.0.0.1:8801
|
||||||
|
CORS_ORIGIN=http://localhost:5173
|
||||||
|
SESSION_COOKIE=mediacollection_session
|
||||||
|
COOKIE_SECURE=false
|
||||||
|
INTERNAL_SERVICE_SECRET=
|
||||||
|
MAX_UPLOAD_BYTES=50gb
|
||||||
@@ -0,0 +1,52 @@
|
|||||||
|
# MediaCollection Go backend
|
||||||
|
|
||||||
|
The backend is one Go module. Set `MEDIA_SERVICE` to `viewer`, `tools`, `analyzer`, `config`, `moderator`, `kiosk`, `servant`, or `desktop` to select the route set while keeping the same auth, database, migration, file-safety, and worker implementation.
|
||||||
|
|
||||||
|
From this directory:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
go mod download
|
||||||
|
MEDIA_SERVICE=viewer \
|
||||||
|
DATABASE_URL=postgresql://media:media@localhost:5432/mediadb \
|
||||||
|
WEB_ROOT=../WebUI/build \
|
||||||
|
go run ./cmd/mediacollectiond
|
||||||
|
```
|
||||||
|
|
||||||
|
Important settings:
|
||||||
|
|
||||||
|
- `MEDIA_ROOTS` is a comma- or semicolon-separated list of media roots. MediaServant also walks
|
||||||
|
every path saved under a `media`/`images`/`videos`/`audios`/`funscripts` mount in MediaConfig's
|
||||||
|
Mounts workspace (the `configured_mounts` setting) regardless of which project's tab it was
|
||||||
|
entered under - see `effectiveMediaRoots` in `internal/server/admin_storage.go`. `MEDIA_ROOTS`
|
||||||
|
is only needed for a root that isn't already configured there.
|
||||||
|
- `INPUT_DIR`, `UPLOAD_COPY_DIR`, `THUMBNAIL_DIR`, `OUTPUT_DIR`, `DOWNLOADS_DIR`, and `MODEL_CACHE_DIR` control writable storage.
|
||||||
|
- `WORKFLOWS_DIR` points to the built-in ComfyUI workflow definitions.
|
||||||
|
- `FFMPEG_PATH`, `FFPROBE_PATH`, and `YT_DLP_PATH` select workflow executables.
|
||||||
|
- `COMFYUI_URL` configures the generator service.
|
||||||
|
- `SERVANT_URL` is only the bootstrap fallback for MediaServant's URL - once configured through
|
||||||
|
MediaConfig it's read from the `mediaservant_url` row in the `settings` table instead (see
|
||||||
|
`servantBaseURL` in `internal/server/servant_client.go`).
|
||||||
|
- `INTERNAL_SERVICE_SECRET` protects service-to-service mount and media-proxy APIs.
|
||||||
|
|
||||||
|
Run `go test ./...` before packaging. Each service repo's Dockerfile builds this module (via the
|
||||||
|
`engine/` submodule) and copies `media-webui` into the final image; no Node server runs at runtime.
|
||||||
|
|
||||||
|
### Configuration reference
|
||||||
|
|
||||||
|
| Variable | Default | Purpose |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| `DATABASE_URL` | required | PostgreSQL connection string |
|
||||||
|
| `MEDIA_SERVICE` | `viewer` | Route/service selection |
|
||||||
|
| `PORT` | service-specific | HTTP port |
|
||||||
|
| `WEB_ROOT` | service web root | Built media-webui directory |
|
||||||
|
| `MEDIA_ROOTS` | `./media` | Comma/semicolon-separated media roots |
|
||||||
|
| `THUMBNAIL_DIR` | `./thumbnails` | Thumbnail storage |
|
||||||
|
| `INPUT_DIR` | `./input` | Workflow input storage |
|
||||||
|
| `UPLOAD_COPY_DIR` | `./copy` | Generator copy-upload storage |
|
||||||
|
| `OUTPUT_DIR` | `./output` | Generated and converted output |
|
||||||
|
| `DOWNLOADS_DIR` | `./downloads` | yt-dlp/download storage |
|
||||||
|
| `WORKFLOWS_DIR` | service-specific | ComfyUI workflow JSON files |
|
||||||
|
| `INTERNAL_SERVICE_SECRET` | empty | Shared-secret service authentication |
|
||||||
|
| `CORS_ORIGIN` | `http://localhost:5173` | Allowed browser origin |
|
||||||
|
|
||||||
|
See `.env.example` for the complete list.
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
# MediaCollection security notes
|
||||||
|
|
||||||
|
The backend rewrite consolidates the security boundary in `internal/`.
|
||||||
|
|
||||||
|
Implemented controls include:
|
||||||
|
|
||||||
|
- bcrypt passwords, PostgreSQL cookie sessions, TOTP verification, role checks, and disabled-user checks;
|
||||||
|
- explicit CORS and WebSocket origin validation, security headers, and bounded request bodies;
|
||||||
|
- additive PostgreSQL migrations with a startup advisory lock;
|
||||||
|
- traversal, absolute-path, drive-path, and symlink-escape protection for every configured media root;
|
||||||
|
- fixed ffmpeg argument construction and bounded workflow workers;
|
||||||
|
- HTTPS-only downloader URLs with credential, private-IP, link-local, metadata-host, and DNS-rebinding checks;
|
||||||
|
- internal-service secret checks for mount, download, reload, upload, and catalog mutation routes;
|
||||||
|
- non-root Docker images and no Node server runtime.
|
||||||
|
|
||||||
|
Before deployment, set a unique `INTERNAL_SERVICE_SECRET`, use a strong database password, configure
|
||||||
|
`CORS_ORIGIN` to the real frontend origin, and enable TLS so `COOKIE_SECURE` can remain enabled.
|
||||||
|
Review the canonical Go routes when adding a capability; do not reintroduce the removed JavaScript
|
||||||
|
server paths or Socket.IO transport.
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"flag"
|
||||||
|
"log"
|
||||||
|
"net/http"
|
||||||
|
"os"
|
||||||
|
"os/signal"
|
||||||
|
"syscall"
|
||||||
|
|
||||||
|
"mediacollection/internal/config"
|
||||||
|
"mediacollection/internal/database"
|
||||||
|
"mediacollection/internal/server"
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
service := flag.String("service", "", "service route set to run")
|
||||||
|
flag.Parse()
|
||||||
|
if *service != "" {
|
||||||
|
_ = os.Setenv("MEDIA_SERVICE", *service)
|
||||||
|
}
|
||||||
|
cfg, err := config.Load()
|
||||||
|
if err != nil {
|
||||||
|
log.Fatalf("config: %v", err)
|
||||||
|
}
|
||||||
|
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
|
||||||
|
defer stop()
|
||||||
|
pool, err := database.Open(ctx, cfg.DatabaseURL)
|
||||||
|
if err != nil {
|
||||||
|
log.Fatalf("database: %v", err)
|
||||||
|
}
|
||||||
|
defer pool.Close()
|
||||||
|
if err := database.Migrate(ctx, pool); err != nil {
|
||||||
|
log.Fatalf("migrate: %v", err)
|
||||||
|
}
|
||||||
|
app := server.New(cfg, pool)
|
||||||
|
if err := app.Run(ctx); err != nil && !errors.Is(err, http.ErrServerClosed) {
|
||||||
|
log.Fatalf("server: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
module mediacollection
|
||||||
|
|
||||||
|
go 1.26.5
|
||||||
|
|
||||||
|
require (
|
||||||
|
github.com/coder/websocket v1.8.15
|
||||||
|
github.com/go-chi/chi/v5 v5.3.1
|
||||||
|
github.com/jackc/pgx/v5 v5.10.0
|
||||||
|
golang.org/x/crypto v0.54.0
|
||||||
|
repos.gfranz.ch/Gabriel20xx/shared/backend v0.1.1
|
||||||
|
)
|
||||||
|
|
||||||
|
replace repos.gfranz.ch/Gabriel20xx/shared/backend => ../backend
|
||||||
|
|
||||||
|
require (
|
||||||
|
github.com/jackc/pgpassfile v1.0.0 // indirect
|
||||||
|
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
|
||||||
|
github.com/jackc/puddle/v2 v2.2.2 // indirect
|
||||||
|
golang.org/x/sync v0.22.0 // indirect
|
||||||
|
golang.org/x/text v0.40.0 // indirect
|
||||||
|
)
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
github.com/coder/websocket v1.8.15 h1:6B2JPeOGlpff2Uz6vOEH1Vzpi0iUz20A+lPVhPHtNUA=
|
||||||
|
github.com/coder/websocket v1.8.15/go.mod h1:NX3SzP+inril6yawo5CQXx8+fk145lPDC6pumgx0mVg=
|
||||||
|
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||||
|
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||||
|
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||||
|
github.com/go-chi/chi/v5 v5.3.1 h1:3j4HZLGZQ3JpMCrPJF/Jl3mYJfWLKBfNJ6quurUGCf8=
|
||||||
|
github.com/go-chi/chi/v5 v5.3.1/go.mod h1:R+tYY2hNuVUUjxoPtqUdgBqevM9s9njzkTLutVsOCto=
|
||||||
|
github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM=
|
||||||
|
github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg=
|
||||||
|
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo=
|
||||||
|
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM=
|
||||||
|
github.com/jackc/pgx/v5 v5.10.0 h1:VhSvgU2jSli8o3AqIEOTJr7rZwAEUVo4E4XhR94Zfr0=
|
||||||
|
github.com/jackc/pgx/v5 v5.10.0/go.mod h1:mal1tBGAFfLHvZzaYh77YS/eC6IX9OWbRV1QIIM0Jn4=
|
||||||
|
github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo=
|
||||||
|
github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4=
|
||||||
|
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||||
|
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||||
|
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||||
|
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
|
||||||
|
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||||
|
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
|
||||||
|
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
|
||||||
|
golang.org/x/crypto v0.54.0 h1:YLIA59K4fiNzHzjnZt2tUJQjQtUWfWbeHBqKtk3eScw=
|
||||||
|
golang.org/x/crypto v0.54.0/go.mod h1:KWL8ny2AZdGR2cWmzeHrp2azQPGogOv+HeQaVEXC2dk=
|
||||||
|
golang.org/x/sync v0.22.0 h1:SZjpbeLmrCk4xhRSZFNZW5gFUeCeFgjekvI/+gfScek=
|
||||||
|
golang.org/x/sync v0.22.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
|
||||||
|
golang.org/x/text v0.40.0 h1:Ub2Z6/xjgF1WrYQz2nuITOEegKFtiIy+rieRJ5lHZKs=
|
||||||
|
golang.org/x/text v0.40.0/go.mod h1:hpnzDAfGV753zIKo+wk3u1bVKCGPbrnF7+7LBF/UHVY=
|
||||||
|
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||||
|
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||||
|
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||||
|
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||||
@@ -0,0 +1,956 @@
|
|||||||
|
package auth
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"crypto/rand"
|
||||||
|
"crypto/sha256"
|
||||||
|
"encoding/base64"
|
||||||
|
"encoding/hex"
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"net/http"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/go-chi/chi/v5"
|
||||||
|
"github.com/jackc/pgx/v5"
|
||||||
|
"github.com/jackc/pgx/v5/pgxpool"
|
||||||
|
"golang.org/x/crypto/bcrypt"
|
||||||
|
sharedauth "repos.gfranz.ch/Gabriel20xx/shared/backend/auth"
|
||||||
|
)
|
||||||
|
|
||||||
|
type User struct {
|
||||||
|
ID int64 `json:"id"`
|
||||||
|
Email string `json:"email"`
|
||||||
|
Username string `json:"username,omitempty"`
|
||||||
|
Role string `json:"role,omitempty"`
|
||||||
|
CanManageUsers bool `json:"canManageUsers"`
|
||||||
|
Bio string `json:"bio,omitempty"`
|
||||||
|
Avatar string `json:"avatarUrl,omitempty"`
|
||||||
|
MFAEnabled bool `json:"mfaEnabled"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type storedUser struct {
|
||||||
|
User
|
||||||
|
PasswordHash string
|
||||||
|
Disabled bool
|
||||||
|
TOTPSecret string
|
||||||
|
}
|
||||||
|
|
||||||
|
type contextKey struct{}
|
||||||
|
|
||||||
|
var userContextKey contextKey
|
||||||
|
|
||||||
|
var (
|
||||||
|
ErrUnauthorized = errors.New("authentication required")
|
||||||
|
ErrForbidden = errors.New("administrator access required")
|
||||||
|
ErrInvalidLogin = errors.New("Invalid username or password.")
|
||||||
|
)
|
||||||
|
|
||||||
|
const loginRequiredSettingKey = "auth_required"
|
||||||
|
|
||||||
|
type Service struct {
|
||||||
|
db *pgxpool.Pool
|
||||||
|
cookieName string
|
||||||
|
secureCookies bool
|
||||||
|
sessionTTL time.Duration
|
||||||
|
resetManager *sharedauth.ResetManager
|
||||||
|
}
|
||||||
|
|
||||||
|
func New(db *pgxpool.Pool, cookieName string, secureCookies bool) *Service {
|
||||||
|
return &Service{
|
||||||
|
db: db,
|
||||||
|
cookieName: cookieName,
|
||||||
|
secureCookies: secureCookies,
|
||||||
|
sessionTTL: 7 * 24 * time.Hour,
|
||||||
|
resetManager: sharedauth.NewResetManager(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func UserFromContext(ctx context.Context) *User {
|
||||||
|
value, _ := ctx.Value(userContextKey).(*User)
|
||||||
|
return value
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Service) CurrentUser(r *http.Request) (*User, error) {
|
||||||
|
cookie, err := r.Cookie(s.cookieName)
|
||||||
|
if errors.Is(err, http.ErrNoCookie) || cookie.Value == "" {
|
||||||
|
return nil, nil
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
ctx, cancel := context.WithTimeout(r.Context(), 2*time.Second)
|
||||||
|
defer cancel()
|
||||||
|
var user User
|
||||||
|
var disabled bool
|
||||||
|
err = s.db.QueryRow(ctx, `
|
||||||
|
SELECT u.id, u.email, COALESCE(u.username, ''), COALESCE(u.role, 'user'),
|
||||||
|
COALESCE(u.bio, ''), COALESCE(u.avatar_url, ''), u.disabled, COALESCE(u.mfa_enabled, false)
|
||||||
|
FROM go_sessions session
|
||||||
|
JOIN users u ON u.id = session.user_id
|
||||||
|
WHERE session.token_hash = $1 AND session.expires_at > NOW()
|
||||||
|
`, tokenHash(cookie.Value)).Scan(&user.ID, &user.Email, &user.Username, &user.Role, &user.Bio, &user.Avatar, &disabled, &user.MFAEnabled)
|
||||||
|
if errors.Is(err, pgx.ErrNoRows) || disabled {
|
||||||
|
return nil, nil
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
user.CanManageUsers = sharedauth.CanManageUsers(user.Role)
|
||||||
|
return &user, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Service) Optional(next http.Handler) http.Handler {
|
||||||
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
user, err := s.CurrentUser(r)
|
||||||
|
if err != nil {
|
||||||
|
writeError(w, http.StatusInternalServerError, "authentication lookup failed")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if user != nil {
|
||||||
|
r = r.WithContext(context.WithValue(r.Context(), userContextKey, user))
|
||||||
|
}
|
||||||
|
next.ServeHTTP(w, r)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Service) Require(next http.Handler) http.Handler {
|
||||||
|
return s.Optional(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
if UserFromContext(r.Context()) == nil {
|
||||||
|
writeError(w, http.StatusUnauthorized, ErrUnauthorized.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
next.ServeHTTP(w, r)
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
// RequireIfLoginRequired protects actions when the application has login
|
||||||
|
// enabled, while allowing explicitly public installations to use actions that
|
||||||
|
// do not need a user identity.
|
||||||
|
func (s *Service) RequireIfLoginRequired(next http.Handler) http.Handler {
|
||||||
|
return s.Optional(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
if UserFromContext(r.Context()) != nil {
|
||||||
|
next.ServeHTTP(w, r)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
loginRequired, err := s.LoginRequired(r.Context())
|
||||||
|
if err != nil {
|
||||||
|
writeError(w, http.StatusInternalServerError, "authentication status unavailable")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if !loginRequired {
|
||||||
|
next.ServeHTTP(w, r)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
writeError(w, http.StatusUnauthorized, ErrUnauthorized.Error())
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Service) RequireAdmin(next http.Handler) http.Handler {
|
||||||
|
return s.Require(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
user := UserFromContext(r.Context())
|
||||||
|
if !IsAdmin(user) {
|
||||||
|
writeError(w, http.StatusForbidden, ErrForbidden.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
next.ServeHTTP(w, r)
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
// RequireAdminIfLoginRequired keeps administrative actions protected for
|
||||||
|
// authenticated users, while allowing explicitly public installations to use
|
||||||
|
// configuration endpoints that do not require a user identity.
|
||||||
|
func (s *Service) RequireAdminIfLoginRequired(next http.Handler) http.Handler {
|
||||||
|
return s.Optional(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
user := UserFromContext(r.Context())
|
||||||
|
if user == nil {
|
||||||
|
loginRequired, err := s.LoginRequired(r.Context())
|
||||||
|
if err != nil {
|
||||||
|
writeError(w, http.StatusInternalServerError, "authentication status unavailable")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if !loginRequired {
|
||||||
|
next.ServeHTTP(w, r)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
writeError(w, http.StatusUnauthorized, ErrUnauthorized.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if !IsAdmin(user) {
|
||||||
|
writeError(w, http.StatusForbidden, ErrForbidden.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
next.ServeHTTP(w, r)
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
func IsAdmin(user *User) bool {
|
||||||
|
if user == nil {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
switch strings.ToLower(strings.TrimSpace(user.Role)) {
|
||||||
|
case "admin", "superadmin", "moderator":
|
||||||
|
return true
|
||||||
|
default:
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Service) Me(w http.ResponseWriter, r *http.Request) {
|
||||||
|
user, err := s.CurrentUser(r)
|
||||||
|
if err != nil {
|
||||||
|
writeError(w, http.StatusInternalServerError, "authentication lookup failed")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
count, err := s.CountUsers(r.Context())
|
||||||
|
if err != nil {
|
||||||
|
writeError(w, http.StatusInternalServerError, "authentication status unavailable")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
loginRequired, err := s.LoginRequired(r.Context())
|
||||||
|
if err != nil {
|
||||||
|
writeError(w, http.StatusInternalServerError, "authentication status unavailable")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
writeJSON(w, http.StatusOK, map[string]any{
|
||||||
|
"user": user,
|
||||||
|
"authRequired": loginRequired,
|
||||||
|
"setupRequired": count == 0,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Service) UpdateMe(w http.ResponseWriter, r *http.Request) {
|
||||||
|
user := UserFromContext(r.Context())
|
||||||
|
if user == nil {
|
||||||
|
writeError(w, http.StatusUnauthorized, ErrUnauthorized.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
var input struct {
|
||||||
|
Email string `json:"email"`
|
||||||
|
Username string `json:"username"`
|
||||||
|
Password string `json:"password"`
|
||||||
|
}
|
||||||
|
if err := decodeJSON(r, &input); err != nil {
|
||||||
|
writeError(w, http.StatusBadRequest, "invalid JSON body")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
email := strings.ToLower(strings.TrimSpace(input.Email))
|
||||||
|
username := strings.TrimSpace(input.Username)
|
||||||
|
if !strings.Contains(email, "@") || len(email) > 254 {
|
||||||
|
writeError(w, http.StatusBadRequest, "a valid email is required")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if username == "" || len([]rune(username)) > 64 {
|
||||||
|
writeError(w, http.StatusBadRequest, "a username is required")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
passwordHash := ""
|
||||||
|
if input.Password != "" {
|
||||||
|
if err := validatePassword(input.Password); err != nil {
|
||||||
|
writeError(w, http.StatusBadRequest, err.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
hash, err := bcrypt.GenerateFromPassword([]byte(input.Password), bcrypt.DefaultCost)
|
||||||
|
if err != nil {
|
||||||
|
writeError(w, http.StatusInternalServerError, "password could not be updated")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
passwordHash = string(hash)
|
||||||
|
}
|
||||||
|
|
||||||
|
if _, err := s.db.Exec(r.Context(), `
|
||||||
|
UPDATE users
|
||||||
|
SET email = $1, username = $2, password_hash = COALESCE(NULLIF($3, ''), password_hash)
|
||||||
|
WHERE id = $4
|
||||||
|
`, email, username, passwordHash, user.ID); err != nil {
|
||||||
|
writeError(w, http.StatusBadRequest, "profile could not be updated")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
updated, err := s.CurrentUser(r)
|
||||||
|
if err != nil || updated == nil {
|
||||||
|
writeError(w, http.StatusInternalServerError, "profile could not be loaded")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
writeJSON(w, http.StatusOK, map[string]any{"user": updated})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Service) RequireUserManager(next http.Handler) http.Handler {
|
||||||
|
return s.Require(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
user := UserFromContext(r.Context())
|
||||||
|
if !sharedauth.CanManageUsers(user.Role) {
|
||||||
|
writeError(w, http.StatusForbidden, ErrForbidden.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
next.ServeHTTP(w, r)
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Service) AdminNeeded(w http.ResponseWriter, r *http.Request) {
|
||||||
|
count, err := s.CountUsers(r.Context())
|
||||||
|
if err != nil {
|
||||||
|
writeError(w, http.StatusInternalServerError, "authentication status unavailable")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
writeJSON(w, http.StatusOK, map[string]bool{"adminNeeded": count == 0})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Service) LoginRequired(ctx context.Context) (bool, error) {
|
||||||
|
var value string
|
||||||
|
err := s.db.QueryRow(ctx, `SELECT COALESCE(value, '') FROM settings WHERE key = $1`, loginRequiredSettingKey).Scan(&value)
|
||||||
|
if errors.Is(err, pgx.ErrNoRows) {
|
||||||
|
return true, nil
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return true, err
|
||||||
|
}
|
||||||
|
|
||||||
|
switch strings.ToLower(strings.TrimSpace(value)) {
|
||||||
|
case "false", "0", "no", "off":
|
||||||
|
return false, nil
|
||||||
|
default:
|
||||||
|
return true, nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Service) AccessSettings(w http.ResponseWriter, r *http.Request) {
|
||||||
|
loginRequired, err := s.LoginRequired(r.Context())
|
||||||
|
if err != nil {
|
||||||
|
writeError(w, http.StatusInternalServerError, "access settings unavailable")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
writeJSON(w, http.StatusOK, map[string]bool{"loginRequired": loginRequired})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Service) UpdateAccessSettings(w http.ResponseWriter, r *http.Request) {
|
||||||
|
var input struct {
|
||||||
|
LoginRequired *bool `json:"loginRequired"`
|
||||||
|
}
|
||||||
|
if err := decodeJSON(r, &input); err != nil || input.LoginRequired == nil {
|
||||||
|
writeError(w, http.StatusBadRequest, "loginRequired must be a boolean")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if _, err := s.db.Exec(r.Context(), `
|
||||||
|
INSERT INTO settings (key, value, updated_at)
|
||||||
|
VALUES ($1, $2, NOW())
|
||||||
|
ON CONFLICT (key) DO UPDATE SET value = EXCLUDED.value, updated_at = NOW()
|
||||||
|
`, loginRequiredSettingKey, strconv.FormatBool(*input.LoginRequired)); err != nil {
|
||||||
|
writeError(w, http.StatusInternalServerError, "access setting could not be saved")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
writeJSON(w, http.StatusOK, map[string]bool{"loginRequired": *input.LoginRequired})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Service) Status(w http.ResponseWriter, r *http.Request) {
|
||||||
|
count, err := s.CountUsers(r.Context())
|
||||||
|
if err != nil {
|
||||||
|
writeError(w, http.StatusInternalServerError, "authentication status unavailable")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
user, _ := s.CurrentUser(r)
|
||||||
|
loginRequired, err := s.LoginRequired(r.Context())
|
||||||
|
if err != nil {
|
||||||
|
writeError(w, http.StatusInternalServerError, "authentication status unavailable")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
writeJSON(w, http.StatusOK, map[string]any{
|
||||||
|
"setupRequired": count == 0,
|
||||||
|
"authenticated": user != nil,
|
||||||
|
"authRequired": loginRequired,
|
||||||
|
"user": user,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
type managedAccount struct {
|
||||||
|
ID int64
|
||||||
|
Email string
|
||||||
|
Username string
|
||||||
|
Role string
|
||||||
|
Disabled bool
|
||||||
|
CreatedAt time.Time
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Service) managedAccount(ctx context.Context, id int64) (*managedAccount, error) {
|
||||||
|
var user managedAccount
|
||||||
|
err := s.db.QueryRow(ctx, `
|
||||||
|
SELECT id, email, COALESCE(username, ''), COALESCE(role, 'user'), disabled, created_at
|
||||||
|
FROM users WHERE id = $1
|
||||||
|
`, id).Scan(&user.ID, &user.Email, &user.Username, &user.Role, &user.Disabled, &user.CreatedAt)
|
||||||
|
if errors.Is(err, pgx.ErrNoRows) {
|
||||||
|
return nil, nil
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return &user, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func managedAccountPayload(user *managedAccount) map[string]any {
|
||||||
|
return map[string]any{
|
||||||
|
"id": user.ID,
|
||||||
|
"username": user.Username,
|
||||||
|
"email": user.Email,
|
||||||
|
"role": string(sharedauth.NormalizeRole(user.Role)),
|
||||||
|
"createdAt": user.CreatedAt,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Service) ManagedUsers(w http.ResponseWriter, r *http.Request) {
|
||||||
|
rows, err := s.db.Query(r.Context(), `
|
||||||
|
SELECT id, email, COALESCE(username, ''), COALESCE(role, 'user'), disabled, created_at
|
||||||
|
FROM users ORDER BY created_at, id
|
||||||
|
`)
|
||||||
|
if err != nil {
|
||||||
|
writeError(w, http.StatusInternalServerError, "users unavailable")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
users := make([]map[string]any, 0)
|
||||||
|
for rows.Next() {
|
||||||
|
var user managedAccount
|
||||||
|
if err := rows.Scan(&user.ID, &user.Email, &user.Username, &user.Role, &user.Disabled, &user.CreatedAt); err != nil {
|
||||||
|
writeError(w, http.StatusInternalServerError, "users unavailable")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
users = append(users, managedAccountPayload(&user))
|
||||||
|
}
|
||||||
|
if err := rows.Err(); err != nil {
|
||||||
|
writeError(w, http.StatusInternalServerError, "users unavailable")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
writeJSON(w, http.StatusOK, users)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Service) ManagedCreateUser(w http.ResponseWriter, r *http.Request) {
|
||||||
|
var input struct {
|
||||||
|
Email string `json:"email"`
|
||||||
|
Username string `json:"username"`
|
||||||
|
Password string `json:"password"`
|
||||||
|
Role string `json:"role"`
|
||||||
|
}
|
||||||
|
if err := decodeJSON(r, &input); err != nil {
|
||||||
|
writeError(w, http.StatusBadRequest, "invalid JSON body")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
actor := UserFromContext(r.Context())
|
||||||
|
role := sharedauth.NormalizeRole(input.Role)
|
||||||
|
if role == sharedauth.RoleSuperAdmin {
|
||||||
|
writeError(w, http.StatusBadRequest, "a new user cannot be a superadmin")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if actor == nil || sharedauth.NormalizeRole(actor.Role) != sharedauth.RoleSuperAdmin {
|
||||||
|
role = sharedauth.RoleUser
|
||||||
|
}
|
||||||
|
user, err := s.CreateUser(r.Context(), input.Email, input.Username, input.Password, string(role))
|
||||||
|
if err != nil {
|
||||||
|
writeError(w, http.StatusBadRequest, err.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
created, err := s.managedAccount(r.Context(), user.ID)
|
||||||
|
if err != nil || created == nil {
|
||||||
|
writeError(w, http.StatusInternalServerError, "user could not be loaded")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
writeJSON(w, http.StatusCreated, managedAccountPayload(created))
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Service) ManagedUpdateUser(w http.ResponseWriter, r *http.Request) {
|
||||||
|
id, err := strconv.ParseInt(chi.URLParam(r, "id"), 10, 64)
|
||||||
|
if err != nil {
|
||||||
|
writeError(w, http.StatusBadRequest, "invalid user id")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
target, err := s.managedAccount(r.Context(), id)
|
||||||
|
if err != nil {
|
||||||
|
writeError(w, http.StatusInternalServerError, "user could not be loaded")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if target == nil {
|
||||||
|
writeError(w, http.StatusNotFound, "user not found")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
var input struct {
|
||||||
|
Email string `json:"email"`
|
||||||
|
Username string `json:"username"`
|
||||||
|
Password string `json:"password"`
|
||||||
|
Role *string `json:"role"`
|
||||||
|
}
|
||||||
|
if err := decodeJSON(r, &input); err != nil {
|
||||||
|
writeError(w, http.StatusBadRequest, "invalid JSON body")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
actor := UserFromContext(r.Context())
|
||||||
|
targetRole := sharedauth.NormalizeRole(target.Role)
|
||||||
|
role := targetRole
|
||||||
|
if targetRole != sharedauth.RoleSuperAdmin && actor != nil && sharedauth.NormalizeRole(actor.Role) == sharedauth.RoleSuperAdmin && input.Role != nil {
|
||||||
|
requested := sharedauth.NormalizeRole(*input.Role)
|
||||||
|
if requested == sharedauth.RoleSuperAdmin {
|
||||||
|
writeError(w, http.StatusBadRequest, "the superadmin role is protected")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
role = requested
|
||||||
|
}
|
||||||
|
if err := s.UpdateUser(r.Context(), id, input.Email, input.Username, string(role), nil); err != nil {
|
||||||
|
writeError(w, http.StatusBadRequest, "user could not be updated")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if strings.TrimSpace(input.Password) != "" {
|
||||||
|
if err := s.SetPassword(r.Context(), id, input.Password); err != nil {
|
||||||
|
writeError(w, http.StatusBadRequest, "password could not be updated")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
updated, err := s.managedAccount(r.Context(), id)
|
||||||
|
if err != nil || updated == nil {
|
||||||
|
writeError(w, http.StatusInternalServerError, "user could not be loaded")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
writeJSON(w, http.StatusOK, managedAccountPayload(updated))
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Service) ManagedDeleteUser(w http.ResponseWriter, r *http.Request) {
|
||||||
|
id, err := strconv.ParseInt(chi.URLParam(r, "id"), 10, 64)
|
||||||
|
if err != nil {
|
||||||
|
writeError(w, http.StatusBadRequest, "invalid user id")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
target, err := s.managedAccount(r.Context(), id)
|
||||||
|
if err != nil {
|
||||||
|
writeError(w, http.StatusInternalServerError, "user could not be loaded")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if target == nil {
|
||||||
|
writeError(w, http.StatusNotFound, "user not found")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
actor := UserFromContext(r.Context())
|
||||||
|
if actor == nil || actor.ID == target.ID || sharedauth.NormalizeRole(target.Role) == sharedauth.RoleSuperAdmin {
|
||||||
|
writeError(w, http.StatusForbidden, "the current or first account cannot be removed")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err := s.DeleteUser(r.Context(), id); err != nil {
|
||||||
|
writeError(w, http.StatusNotFound, "user not found")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
writeJSON(w, http.StatusOK, map[string]bool{"ok": true})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Service) Signup(w http.ResponseWriter, r *http.Request) {
|
||||||
|
var input struct {
|
||||||
|
Email string `json:"email"`
|
||||||
|
Username string `json:"username"`
|
||||||
|
Password string `json:"password"`
|
||||||
|
}
|
||||||
|
if err := decodeJSON(r, &input); err != nil {
|
||||||
|
writeError(w, http.StatusBadRequest, "invalid JSON body")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
email, username, password, err := normalizeCredentials(input.Email, input.Username, input.Password)
|
||||||
|
if err != nil {
|
||||||
|
writeError(w, http.StatusBadRequest, err.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if username == "" {
|
||||||
|
writeError(w, http.StatusBadRequest, "a username is required")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
|
||||||
|
if err != nil {
|
||||||
|
writeError(w, http.StatusInternalServerError, "could not secure password")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
var user User
|
||||||
|
err = s.db.QueryRow(r.Context(), `
|
||||||
|
INSERT INTO users (email, username, password_hash, role)
|
||||||
|
SELECT $1, $2, $3, 'superadmin'
|
||||||
|
WHERE NOT EXISTS (SELECT 1 FROM users)
|
||||||
|
RETURNING id, email, COALESCE(username, ''), COALESCE(role, 'superadmin')
|
||||||
|
`, email, username, string(hash)).Scan(&user.ID, &user.Email, &user.Username, &user.Role)
|
||||||
|
if errors.Is(err, pgx.ErrNoRows) {
|
||||||
|
writeError(w, http.StatusConflict, "Setup has already been completed.")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
writeError(w, http.StatusInternalServerError, "could not create account")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
user.CanManageUsers = sharedauth.CanManageUsers(user.Role)
|
||||||
|
if err := s.startSession(w, r.Context(), user.ID); err != nil {
|
||||||
|
writeError(w, http.StatusInternalServerError, "could not start session")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
writeJSON(w, http.StatusCreated, map[string]any{"user": user})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Service) Login(w http.ResponseWriter, r *http.Request) {
|
||||||
|
var input struct {
|
||||||
|
Identifier string `json:"identifier"`
|
||||||
|
Email string `json:"email"`
|
||||||
|
Password string `json:"password"`
|
||||||
|
TOTPToken string `json:"totpToken"`
|
||||||
|
}
|
||||||
|
if err := decodeJSON(r, &input); err != nil {
|
||||||
|
writeError(w, http.StatusBadRequest, "invalid JSON body")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
identifier := strings.TrimSpace(input.Identifier)
|
||||||
|
if identifier == "" {
|
||||||
|
identifier = strings.TrimSpace(input.Email)
|
||||||
|
}
|
||||||
|
var user storedUser
|
||||||
|
err := s.db.QueryRow(r.Context(), `
|
||||||
|
SELECT id, email, COALESCE(username, ''), COALESCE(role, 'user'), COALESCE(bio, ''),
|
||||||
|
COALESCE(avatar_url, ''), password_hash, disabled, COALESCE(mfa_enabled, false), COALESCE(totp_secret, '')
|
||||||
|
FROM users WHERE LOWER(email) = LOWER($1) OR LOWER(COALESCE(username, '')) = LOWER($1)
|
||||||
|
LIMIT 1
|
||||||
|
`, identifier).Scan(&user.ID, &user.Email, &user.Username, &user.Role, &user.Bio, &user.Avatar, &user.PasswordHash, &user.Disabled, &user.MFAEnabled, &user.TOTPSecret)
|
||||||
|
if errors.Is(err, pgx.ErrNoRows) {
|
||||||
|
writeError(w, http.StatusUnauthorized, ErrInvalidLogin.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
writeError(w, http.StatusInternalServerError, "could not authenticate")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
user.User.CanManageUsers = sharedauth.CanManageUsers(user.Role)
|
||||||
|
if user.Disabled || bcrypt.CompareHashAndPassword([]byte(user.PasswordHash), []byte(input.Password)) != nil {
|
||||||
|
writeError(w, http.StatusUnauthorized, ErrInvalidLogin.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if user.MFAEnabled && !sharedauth.VerifyTOTP(user.TOTPSecret, strings.TrimSpace(input.TOTPToken), time.Now()) {
|
||||||
|
writeJSON(w, http.StatusUnauthorized, map[string]any{"error": "Two-factor authentication code required.", "mfaRequired": true})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
_, _ = s.db.Exec(r.Context(), `UPDATE users SET last_login_at = NOW() WHERE id = $1`, user.ID)
|
||||||
|
if err := s.startSession(w, r.Context(), user.ID); err != nil {
|
||||||
|
writeError(w, http.StatusInternalServerError, "could not start session")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
writeJSON(w, http.StatusOK, map[string]any{"user": user.User})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Service) TOTPStatus(w http.ResponseWriter, r *http.Request) {
|
||||||
|
user := UserFromContext(r.Context())
|
||||||
|
if user == nil {
|
||||||
|
writeError(w, http.StatusUnauthorized, ErrUnauthorized.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
writeJSON(w, http.StatusOK, map[string]any{"enabled": user.MFAEnabled, "mfaEnabled": user.MFAEnabled})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Service) TOTPInitiate(w http.ResponseWriter, r *http.Request) {
|
||||||
|
user := UserFromContext(r.Context())
|
||||||
|
if user == nil {
|
||||||
|
writeError(w, http.StatusUnauthorized, ErrUnauthorized.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if user.MFAEnabled {
|
||||||
|
writeError(w, http.StatusConflict, "multi-factor authentication is already enabled")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
secret, err := sharedauth.GenerateTOTPSecret()
|
||||||
|
if err != nil {
|
||||||
|
writeError(w, http.StatusInternalServerError, "could not create authenticator secret")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if _, err := s.db.Exec(r.Context(), `UPDATE users SET totp_secret = $1, mfa_enabled = false WHERE id = $2`, secret, user.ID); err != nil {
|
||||||
|
writeError(w, http.StatusInternalServerError, "could not save authenticator secret")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
account := user.Username
|
||||||
|
if account == "" {
|
||||||
|
account = user.Email
|
||||||
|
}
|
||||||
|
uri := sharedauth.TOTPProvisioningURI("MediaCollection", account, secret)
|
||||||
|
writeJSON(w, http.StatusOK, map[string]any{"data": map[string]any{"secret": secret, "otpauth": uri, "otpauthUrl": uri, "enabled": false}})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Service) TOTPVerify(w http.ResponseWriter, r *http.Request) {
|
||||||
|
user := UserFromContext(r.Context())
|
||||||
|
if user == nil {
|
||||||
|
writeError(w, http.StatusUnauthorized, ErrUnauthorized.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
var input struct {
|
||||||
|
Token string `json:"token"`
|
||||||
|
TOTPToken string `json:"totpToken"`
|
||||||
|
}
|
||||||
|
if err := decodeJSON(r, &input); err != nil {
|
||||||
|
writeError(w, http.StatusBadRequest, "invalid JSON body")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
var secret string
|
||||||
|
if err := s.db.QueryRow(r.Context(), `SELECT COALESCE(totp_secret, '') FROM users WHERE id = $1`, user.ID).Scan(&secret); err != nil {
|
||||||
|
writeError(w, http.StatusInternalServerError, "could not load authenticator secret")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
token := strings.TrimSpace(input.TOTPToken)
|
||||||
|
if token == "" {
|
||||||
|
token = strings.TrimSpace(input.Token)
|
||||||
|
}
|
||||||
|
if !sharedauth.VerifyTOTP(secret, token, time.Now()) {
|
||||||
|
writeError(w, http.StatusUnauthorized, "Invalid authenticator code.")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if _, err := s.db.Exec(r.Context(), `UPDATE users SET mfa_enabled = true WHERE id = $1 AND totp_secret <> ''`, user.ID); err != nil {
|
||||||
|
writeError(w, http.StatusInternalServerError, "could not enable multi-factor authentication")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
writeJSON(w, http.StatusOK, map[string]any{"data": map[string]any{"mfaEnabled": true, "enabled": true, "backupCodes": []string{}}})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Service) TOTPDisable(w http.ResponseWriter, r *http.Request) {
|
||||||
|
user := UserFromContext(r.Context())
|
||||||
|
if user == nil {
|
||||||
|
writeError(w, http.StatusUnauthorized, ErrUnauthorized.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
var input struct {
|
||||||
|
Token string `json:"token"`
|
||||||
|
TOTPToken string `json:"totpToken"`
|
||||||
|
}
|
||||||
|
if err := decodeJSON(r, &input); err != nil {
|
||||||
|
writeError(w, http.StatusBadRequest, "invalid JSON body")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
var secret string
|
||||||
|
var enabled bool
|
||||||
|
if err := s.db.QueryRow(r.Context(), `SELECT COALESCE(totp_secret, ''), COALESCE(mfa_enabled, false) FROM users WHERE id = $1`, user.ID).Scan(&secret, &enabled); err != nil {
|
||||||
|
writeError(w, http.StatusInternalServerError, "could not load authenticator state")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
token := strings.TrimSpace(input.TOTPToken)
|
||||||
|
if token == "" {
|
||||||
|
token = strings.TrimSpace(input.Token)
|
||||||
|
}
|
||||||
|
if !enabled || !sharedauth.VerifyTOTP(secret, token, time.Now()) {
|
||||||
|
writeError(w, http.StatusUnauthorized, "Invalid authenticator code.")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if _, err := s.db.Exec(r.Context(), `UPDATE users SET mfa_enabled = false, totp_secret = NULL WHERE id = $1`, user.ID); err != nil {
|
||||||
|
writeError(w, http.StatusInternalServerError, "could not disable multi-factor authentication")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
writeJSON(w, http.StatusOK, map[string]any{"data": map[string]any{"mfaEnabled": false, "enabled": false}})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Service) Logout(w http.ResponseWriter, r *http.Request) {
|
||||||
|
if cookie, err := r.Cookie(s.cookieName); err == nil && cookie.Value != "" {
|
||||||
|
_, _ = s.db.Exec(r.Context(), `DELETE FROM go_sessions WHERE token_hash = $1`, tokenHash(cookie.Value))
|
||||||
|
}
|
||||||
|
http.SetCookie(w, &http.Cookie{Name: s.cookieName, Value: "", Path: "/", HttpOnly: true, Secure: s.secureCookies, SameSite: http.SameSiteLaxMode, MaxAge: -1})
|
||||||
|
writeJSON(w, http.StatusOK, map[string]bool{"ok": true})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Service) RequestAdminReset(w http.ResponseWriter, _ *http.Request) {
|
||||||
|
if _, err := s.resetManager.Request(); err != nil {
|
||||||
|
writeError(w, http.StatusInternalServerError, "could not create reset code")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
writeJSON(w, http.StatusOK, map[string]bool{"ok": true})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Service) ConfirmAdminReset(w http.ResponseWriter, r *http.Request) {
|
||||||
|
var input struct {
|
||||||
|
Code string `json:"code"`
|
||||||
|
}
|
||||||
|
if err := decodeJSON(r, &input); err != nil {
|
||||||
|
writeError(w, http.StatusBadRequest, "invalid JSON body")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if !s.resetManager.Confirm(input.Code) {
|
||||||
|
writeError(w, http.StatusUnauthorized, "Invalid or expired reset code.")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if _, err := s.db.Exec(r.Context(), `DELETE FROM users`); err != nil {
|
||||||
|
writeError(w, http.StatusInternalServerError, "could not reset administrator accounts")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
http.SetCookie(w, &http.Cookie{
|
||||||
|
Name: s.cookieName,
|
||||||
|
Value: "",
|
||||||
|
Path: "/",
|
||||||
|
HttpOnly: true,
|
||||||
|
Secure: s.secureCookies,
|
||||||
|
SameSite: http.SameSiteLaxMode,
|
||||||
|
MaxAge: -1,
|
||||||
|
})
|
||||||
|
writeJSON(w, http.StatusOK, map[string]bool{"ok": true})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Service) CountUsers(ctx context.Context) (int64, error) {
|
||||||
|
var count int64
|
||||||
|
err := s.db.QueryRow(ctx, `SELECT COUNT(*) FROM users`).Scan(&count)
|
||||||
|
return count, err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Service) CreateUser(ctx context.Context, email, username, password, role string) (*User, error) {
|
||||||
|
email, username, password, err := normalizeCredentials(email, username, password)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
role = normalizeRole(role)
|
||||||
|
hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
var user User
|
||||||
|
err = s.db.QueryRow(ctx, `
|
||||||
|
INSERT INTO users (email, username, password_hash, role)
|
||||||
|
VALUES ($1, $2, $3, $4)
|
||||||
|
RETURNING id, email, COALESCE(username, ''), COALESCE(role, 'user')
|
||||||
|
`, email, username, string(hash), role).Scan(&user.ID, &user.Email, &user.Username, &user.Role)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return &user, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Service) ListUsers(ctx context.Context, search string, limit, offset int) ([]map[string]any, int64, error) {
|
||||||
|
search = strings.TrimSpace(search)
|
||||||
|
if limit <= 0 || limit > 200 {
|
||||||
|
limit = 50
|
||||||
|
}
|
||||||
|
if offset < 0 {
|
||||||
|
offset = 0
|
||||||
|
}
|
||||||
|
pattern := "%" + search + "%"
|
||||||
|
rows, err := s.db.Query(ctx, `
|
||||||
|
SELECT id, email, COALESCE(username, ''), COALESCE(role, 'user'), disabled, created_at, last_login_at
|
||||||
|
FROM users
|
||||||
|
WHERE ($1 = '' OR email ILIKE $2 OR COALESCE(username, '') ILIKE $2)
|
||||||
|
ORDER BY id DESC LIMIT $3 OFFSET $4
|
||||||
|
`, search, pattern, limit, offset)
|
||||||
|
if err != nil {
|
||||||
|
return nil, 0, err
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
users := make([]map[string]any, 0)
|
||||||
|
for rows.Next() {
|
||||||
|
var id int64
|
||||||
|
var email, username, role string
|
||||||
|
var disabled bool
|
||||||
|
var created time.Time
|
||||||
|
var lastLogin *time.Time
|
||||||
|
if err := rows.Scan(&id, &email, &username, &role, &disabled, &created, &lastLogin); err != nil {
|
||||||
|
return nil, 0, err
|
||||||
|
}
|
||||||
|
users = append(users, map[string]any{"id": id, "email": email, "username": username, "role": role, "disabled": disabled, "createdAt": created, "lastLoginAt": lastLogin})
|
||||||
|
}
|
||||||
|
var total int64
|
||||||
|
err = s.db.QueryRow(ctx, `SELECT COUNT(*) FROM users WHERE ($1 = '' OR email ILIKE $2 OR COALESCE(username, '') ILIKE $2)`, search, pattern).Scan(&total)
|
||||||
|
return users, total, err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Service) DeleteUser(ctx context.Context, id int64) error {
|
||||||
|
_, err := s.db.Exec(ctx, `DELETE FROM users WHERE id = $1`, id)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Service) UpdateUser(ctx context.Context, id int64, email, username, role string, disabled *bool) error {
|
||||||
|
role = strings.ToLower(strings.TrimSpace(role))
|
||||||
|
if role != "" {
|
||||||
|
role = normalizeRole(role)
|
||||||
|
}
|
||||||
|
_, err := s.db.Exec(ctx, `
|
||||||
|
UPDATE users SET email = COALESCE(NULLIF($2, ''), email), username = COALESCE(NULLIF($3, ''), username),
|
||||||
|
role = COALESCE(NULLIF($4, ''), role), disabled = COALESCE($5, disabled) WHERE id = $1
|
||||||
|
`, id, strings.TrimSpace(email), strings.TrimSpace(username), role, disabled)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Service) SetPassword(ctx context.Context, id int64, password string) error {
|
||||||
|
if err := validatePassword(password); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
_, err = s.db.Exec(ctx, `UPDATE users SET password_hash=$2 WHERE id=$1`, id, string(hash))
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
func validatePassword(password string) error {
|
||||||
|
if len([]rune(password)) < 8 || len([]rune(password)) > 1024 {
|
||||||
|
return fmt.Errorf("Password must be at least 8 characters.")
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Service) startSession(w http.ResponseWriter, ctx context.Context, userID int64) error {
|
||||||
|
token, err := randomToken()
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
expires := time.Now().Add(s.sessionTTL)
|
||||||
|
if _, err := s.db.Exec(ctx, `INSERT INTO go_sessions (token_hash, user_id, expires_at) VALUES ($1, $2, $3)`, tokenHash(token), userID, expires); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
_, _ = s.db.Exec(ctx, `DELETE FROM go_sessions WHERE expires_at <= NOW()`)
|
||||||
|
http.SetCookie(w, &http.Cookie{Name: s.cookieName, Value: token, Path: "/", HttpOnly: true, Secure: s.secureCookies, SameSite: http.SameSiteLaxMode, Expires: expires, MaxAge: int(s.sessionTTL.Seconds())})
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func normalizeCredentials(email, username, password string) (string, string, string, error) {
|
||||||
|
email = strings.ToLower(strings.TrimSpace(email))
|
||||||
|
username = strings.TrimSpace(username)
|
||||||
|
if !strings.Contains(email, "@") || len(email) > 254 {
|
||||||
|
return "", "", "", fmt.Errorf("a valid email is required")
|
||||||
|
}
|
||||||
|
if len([]rune(username)) > 64 {
|
||||||
|
return "", "", "", fmt.Errorf("username is too long")
|
||||||
|
}
|
||||||
|
if len([]rune(password)) < 8 || len([]rune(password)) > 1024 {
|
||||||
|
return "", "", "", fmt.Errorf("Password must be at least 8 characters.")
|
||||||
|
}
|
||||||
|
return email, username, password, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func normalizeRole(role string) string {
|
||||||
|
switch strings.ToLower(strings.TrimSpace(role)) {
|
||||||
|
case "admin", "superadmin", "moderator":
|
||||||
|
return strings.ToLower(strings.TrimSpace(role))
|
||||||
|
default:
|
||||||
|
return "user"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func randomToken() (string, error) {
|
||||||
|
data := make([]byte, 32)
|
||||||
|
if _, err := rand.Read(data); err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
return base64.RawURLEncoding.EncodeToString(data), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func tokenHash(token string) string {
|
||||||
|
sum := sha256.Sum256([]byte(token))
|
||||||
|
return hex.EncodeToString(sum[:])
|
||||||
|
}
|
||||||
|
|
||||||
|
func decodeJSON(r *http.Request, target any) error {
|
||||||
|
defer r.Body.Close()
|
||||||
|
decoder := json.NewDecoder(io.LimitReader(r.Body, 128*1024))
|
||||||
|
return decoder.Decode(target)
|
||||||
|
}
|
||||||
|
|
||||||
|
func writeJSON(w http.ResponseWriter, status int, value any) {
|
||||||
|
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||||
|
w.WriteHeader(status)
|
||||||
|
_ = json.NewEncoder(w).Encode(value)
|
||||||
|
}
|
||||||
|
|
||||||
|
func writeError(w http.ResponseWriter, status int, message string) {
|
||||||
|
writeJSON(w, status, map[string]string{"error": message, "message": message})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (u User) String() string { return strconv.FormatInt(u.ID, 10) }
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
package auth
|
||||||
|
|
||||||
|
import "testing"
|
||||||
|
|
||||||
|
func TestNormalizeCredentials(t *testing.T) {
|
||||||
|
email, username, password, err := normalizeCredentials(" User@Example.com ", "user", "correct horse battery staple")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if email != "user@example.com" || username != "user" || password == "" {
|
||||||
|
t.Fatalf("normalized credentials = %q, %q, %q", email, username, password)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestNormalizeCredentialsAllowsAdminEmailOnly(t *testing.T) {
|
||||||
|
if _, _, _, err := normalizeCredentials("admin@example.com", "", "correct horse battery staple"); err != nil {
|
||||||
|
t.Fatalf("empty optional username rejected: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestNormalizeRole(t *testing.T) {
|
||||||
|
if normalizeRole("MODERATOR") != "moderator" {
|
||||||
|
t.Fatal("moderator role was not normalized")
|
||||||
|
}
|
||||||
|
if normalizeRole("unknown") != "user" {
|
||||||
|
t.Fatal("unknown role was not reduced to user")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,237 @@
|
|||||||
|
package config
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Service string
|
||||||
|
|
||||||
|
const (
|
||||||
|
Viewer Service = "viewer"
|
||||||
|
Tools Service = "tools"
|
||||||
|
Analyzer Service = "analyzer"
|
||||||
|
ConfigService Service = "config"
|
||||||
|
Moderator Service = "moderator"
|
||||||
|
Kiosk Service = "kiosk"
|
||||||
|
Servant Service = "servant"
|
||||||
|
Desktop Service = "desktop"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Config struct {
|
||||||
|
Port string
|
||||||
|
DatabaseURL string
|
||||||
|
Service Service
|
||||||
|
ServiceName string
|
||||||
|
WebRoot string
|
||||||
|
MediaRoots []string
|
||||||
|
InputRoot string
|
||||||
|
CopyRoot string
|
||||||
|
WorkflowsRoot string
|
||||||
|
ThumbnailRoot string
|
||||||
|
OutputRoot string
|
||||||
|
DownloadsRoot string
|
||||||
|
ModelsRoot string
|
||||||
|
AllowedOrigin string
|
||||||
|
PublicURL string
|
||||||
|
SessionCookie string
|
||||||
|
SecureCookies bool
|
||||||
|
InternalServiceSecret string
|
||||||
|
FFmpeg string
|
||||||
|
FFprobe string
|
||||||
|
YTDLP string
|
||||||
|
ComfyURL string
|
||||||
|
AnalyzerModelsURL string
|
||||||
|
ServantURL string
|
||||||
|
MaxUploadBytes int64
|
||||||
|
TLSCertFile string
|
||||||
|
TLSKeyFile string
|
||||||
|
}
|
||||||
|
|
||||||
|
func Load() (*Config, error) {
|
||||||
|
service := normalizeService(os.Getenv("MEDIA_SERVICE"))
|
||||||
|
if service == "" {
|
||||||
|
service = normalizeService(os.Getenv("SERVICE"))
|
||||||
|
}
|
||||||
|
if service == "" {
|
||||||
|
service = Viewer
|
||||||
|
}
|
||||||
|
|
||||||
|
name := serviceName(service)
|
||||||
|
port := envOr("PORT", defaultPort(service))
|
||||||
|
root := envOr("MEDIA_ROOT", envOr("MEDIA_PATH", "./media"))
|
||||||
|
roots := splitPaths(os.Getenv("MEDIA_ROOTS"))
|
||||||
|
if len(roots) == 0 {
|
||||||
|
roots = []string{root}
|
||||||
|
}
|
||||||
|
for i := range roots {
|
||||||
|
roots[i] = filepath.Clean(roots[i])
|
||||||
|
}
|
||||||
|
|
||||||
|
maxUpload, err := parseBytes(envOr("MAX_UPLOAD_BYTES", "53687091200"))
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("MAX_UPLOAD_BYTES: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
cfg := &Config{
|
||||||
|
Port: port,
|
||||||
|
DatabaseURL: strings.TrimSpace(os.Getenv("DATABASE_URL")),
|
||||||
|
Service: service,
|
||||||
|
ServiceName: name,
|
||||||
|
WebRoot: resolveWebRoot(service),
|
||||||
|
MediaRoots: roots,
|
||||||
|
InputRoot: filepath.Clean(envOr("INPUT_DIR", "./input")),
|
||||||
|
CopyRoot: filepath.Clean(envOr("UPLOAD_COPY_DIR", "./copy")),
|
||||||
|
WorkflowsRoot: filepath.Clean(envOr("WORKFLOWS_DIR", filepath.Join("..", "MediaTools", "public", "workflows"))),
|
||||||
|
ThumbnailRoot: filepath.Clean(envOr("THUMBNAIL_DIR", "./thumbnails")),
|
||||||
|
OutputRoot: filepath.Clean(envOr("OUTPUT_DIR", "./output")),
|
||||||
|
DownloadsRoot: filepath.Clean(envOr("DOWNLOADS_DIR", "./downloads")),
|
||||||
|
ModelsRoot: filepath.Clean(envOr("MODEL_CACHE_DIR", "./models")),
|
||||||
|
AllowedOrigin: envOr("CORS_ORIGIN", "http://localhost:5173"),
|
||||||
|
PublicURL: strings.TrimRight(strings.TrimSpace(os.Getenv("PUBLIC_URL")), "/"),
|
||||||
|
SessionCookie: envOr("SESSION_COOKIE", "mediacollection_session"),
|
||||||
|
SecureCookies: envBool("COOKIE_SECURE", os.Getenv("TLS_CERT_FILE") != ""),
|
||||||
|
InternalServiceSecret: strings.TrimSpace(os.Getenv("INTERNAL_SERVICE_SECRET")),
|
||||||
|
FFmpeg: envOr("FFMPEG_PATH", "ffmpeg"),
|
||||||
|
FFprobe: envOr("FFPROBE_PATH", "ffprobe"),
|
||||||
|
YTDLP: envOr("YT_DLP_PATH", "yt-dlp"),
|
||||||
|
ComfyURL: strings.TrimRight(envOr("COMFYUI_URL", "http://127.0.0.1:8188"), "/"),
|
||||||
|
AnalyzerModelsURL: strings.TrimRight(envOr("ANALYZER_MODELS_URL", "http://127.0.0.1:8801"), "/"),
|
||||||
|
ServantURL: strings.TrimRight(envOr("SERVANT_URL", "http://127.0.0.1:3003"), "/"),
|
||||||
|
MaxUploadBytes: maxUpload,
|
||||||
|
TLSCertFile: strings.TrimSpace(os.Getenv("TLS_CERT_FILE")),
|
||||||
|
TLSKeyFile: strings.TrimSpace(os.Getenv("TLS_KEY_FILE")),
|
||||||
|
}
|
||||||
|
|
||||||
|
if cfg.DatabaseURL == "" {
|
||||||
|
return nil, fmt.Errorf("DATABASE_URL is required")
|
||||||
|
}
|
||||||
|
if (cfg.TLSCertFile == "") != (cfg.TLSKeyFile == "") {
|
||||||
|
return nil, fmt.Errorf("TLS_CERT_FILE and TLS_KEY_FILE must be set together")
|
||||||
|
}
|
||||||
|
return cfg, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func normalizeService(value string) Service {
|
||||||
|
switch strings.ToLower(strings.TrimSpace(value)) {
|
||||||
|
case "viewer", "mediaviewer":
|
||||||
|
return Viewer
|
||||||
|
case "tools", "mediatools":
|
||||||
|
return Tools
|
||||||
|
case "analyzer", "mediaanalyzer":
|
||||||
|
return Analyzer
|
||||||
|
case "config", "mediaconfig":
|
||||||
|
return ConfigService
|
||||||
|
case "moderator", "mediamoderator":
|
||||||
|
return Moderator
|
||||||
|
case "kiosk", "mediakiosk":
|
||||||
|
return Kiosk
|
||||||
|
case "servant", "mediaservant":
|
||||||
|
return Servant
|
||||||
|
case "desktop", "mediadesktop":
|
||||||
|
return Desktop
|
||||||
|
default:
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func serviceName(service Service) string {
|
||||||
|
switch service {
|
||||||
|
case Viewer:
|
||||||
|
return "MediaViewer"
|
||||||
|
case Tools:
|
||||||
|
return "MediaTools"
|
||||||
|
case Analyzer:
|
||||||
|
return "MediaAnalyzer"
|
||||||
|
case ConfigService:
|
||||||
|
return "MediaConfig"
|
||||||
|
case Moderator:
|
||||||
|
return "MediaModerator"
|
||||||
|
case Kiosk:
|
||||||
|
return "MediaKiosk"
|
||||||
|
case Servant:
|
||||||
|
return "MediaServant"
|
||||||
|
case Desktop:
|
||||||
|
return "MediaDesktop"
|
||||||
|
default:
|
||||||
|
return "MediaCollection"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func defaultPort(service Service) string {
|
||||||
|
switch service {
|
||||||
|
case ConfigService:
|
||||||
|
return "3005"
|
||||||
|
case Moderator:
|
||||||
|
return "8090"
|
||||||
|
case Servant:
|
||||||
|
return "3003"
|
||||||
|
default:
|
||||||
|
return "3000"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func resolveWebRoot(_ Service) string {
|
||||||
|
if value := strings.TrimSpace(os.Getenv("WEB_ROOT")); value != "" {
|
||||||
|
return filepath.Clean(value)
|
||||||
|
}
|
||||||
|
return filepath.Join("..", "WebUI", "build")
|
||||||
|
}
|
||||||
|
|
||||||
|
func splitPaths(value string) []string {
|
||||||
|
parts := strings.FieldsFunc(value, func(r rune) bool { return r == ',' || r == ';' })
|
||||||
|
result := make([]string, 0, len(parts))
|
||||||
|
for _, part := range parts {
|
||||||
|
if trimmed := strings.TrimSpace(part); trimmed != "" {
|
||||||
|
result = append(result, trimmed)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return result
|
||||||
|
}
|
||||||
|
|
||||||
|
func parseBytes(value string) (int64, error) {
|
||||||
|
value = strings.TrimSpace(strings.ToLower(value))
|
||||||
|
if value == "" {
|
||||||
|
return 0, nil
|
||||||
|
}
|
||||||
|
multiplier := int64(1)
|
||||||
|
suffixes := []struct {
|
||||||
|
suffix string
|
||||||
|
factor int64
|
||||||
|
}{
|
||||||
|
{"gb", 1 << 30},
|
||||||
|
{"mb", 1 << 20},
|
||||||
|
{"kb", 1 << 10},
|
||||||
|
{"b", 1},
|
||||||
|
}
|
||||||
|
for _, s := range suffixes {
|
||||||
|
if strings.HasSuffix(value, s.suffix) {
|
||||||
|
value = strings.TrimSpace(strings.TrimSuffix(value, s.suffix))
|
||||||
|
multiplier = s.factor
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
n, err := strconv.ParseInt(value, 10, 64)
|
||||||
|
if err != nil || n < 0 {
|
||||||
|
return 0, fmt.Errorf("must be a non-negative byte count")
|
||||||
|
}
|
||||||
|
return n * multiplier, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func envOr(key, fallback string) string {
|
||||||
|
if value := strings.TrimSpace(os.Getenv(key)); value != "" {
|
||||||
|
return value
|
||||||
|
}
|
||||||
|
return fallback
|
||||||
|
}
|
||||||
|
|
||||||
|
func envBool(key string, fallback bool) bool {
|
||||||
|
value := strings.ToLower(strings.TrimSpace(os.Getenv(key)))
|
||||||
|
if value == "" {
|
||||||
|
return fallback
|
||||||
|
}
|
||||||
|
return value == "1" || value == "true" || value == "yes" || value == "on"
|
||||||
|
}
|
||||||
@@ -0,0 +1,43 @@
|
|||||||
|
package config
|
||||||
|
|
||||||
|
import (
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestLoadDefaultsAndServiceSelection(t *testing.T) {
|
||||||
|
t.Setenv("DATABASE_URL", "postgres://media:media@localhost/mediadb")
|
||||||
|
t.Setenv("MEDIA_SERVICE", "MediaKiosk")
|
||||||
|
t.Setenv("SERVICE", "viewer")
|
||||||
|
t.Setenv("MEDIA_ROOTS", `./media;./other-media`)
|
||||||
|
t.Setenv("MAX_UPLOAD_BYTES", "2mb")
|
||||||
|
t.Setenv("WEB_ROOT", "./webui")
|
||||||
|
|
||||||
|
cfg, err := Load()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Load() error = %v", err)
|
||||||
|
}
|
||||||
|
if cfg.Service != Kiosk {
|
||||||
|
t.Fatalf("service = %q, want %q", cfg.Service, Kiosk)
|
||||||
|
}
|
||||||
|
if len(cfg.MediaRoots) != 2 {
|
||||||
|
t.Fatalf("media roots = %#v, want two roots", cfg.MediaRoots)
|
||||||
|
}
|
||||||
|
if cfg.MaxUploadBytes != 2*1024*1024 {
|
||||||
|
t.Fatalf("max upload bytes = %d", cfg.MaxUploadBytes)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestLoadRequiresDatabase(t *testing.T) {
|
||||||
|
t.Setenv("DATABASE_URL", "")
|
||||||
|
if _, err := Load(); err == nil {
|
||||||
|
t.Fatal("Load() succeeded without DATABASE_URL")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestParseBytesRejectsInvalidValues(t *testing.T) {
|
||||||
|
for _, value := range []string{"-1", "nope", "1tb"} {
|
||||||
|
if _, err := parseBytes(value); err == nil {
|
||||||
|
t.Errorf("parseBytes(%q) succeeded", value)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,55 @@
|
|||||||
|
package database
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"embed"
|
||||||
|
"fmt"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/jackc/pgx/v5/pgxpool"
|
||||||
|
)
|
||||||
|
|
||||||
|
//go:embed migrations/001_initial.sql
|
||||||
|
var migrations embed.FS
|
||||||
|
|
||||||
|
func Open(ctx context.Context, databaseURL string) (*pgxpool.Pool, error) {
|
||||||
|
cfg, err := pgxpool.ParseConfig(databaseURL)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("parse database URL: %w", err)
|
||||||
|
}
|
||||||
|
cfg.MaxConns = 20
|
||||||
|
cfg.MinConns = 1
|
||||||
|
cfg.MaxConnLifetime = 30 * time.Minute
|
||||||
|
cfg.MaxConnIdleTime = 5 * time.Minute
|
||||||
|
pool, err := pgxpool.NewWithConfig(ctx, cfg)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("open database: %w", err)
|
||||||
|
}
|
||||||
|
if err := pool.Ping(ctx); err != nil {
|
||||||
|
pool.Close()
|
||||||
|
return nil, fmt.Errorf("ping database: %w", err)
|
||||||
|
}
|
||||||
|
return pool, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func Migrate(ctx context.Context, pool *pgxpool.Pool) error {
|
||||||
|
data, err := migrations.ReadFile("migrations/001_initial.sql")
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("read migration: %w", err)
|
||||||
|
}
|
||||||
|
lockCtx, cancel := context.WithTimeout(ctx, 5*time.Minute)
|
||||||
|
defer cancel()
|
||||||
|
conn, err := pool.Acquire(lockCtx)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("acquire migration connection: %w", err)
|
||||||
|
}
|
||||||
|
defer conn.Release()
|
||||||
|
if _, err := conn.Exec(lockCtx, `SELECT pg_advisory_lock(42424242)`); err != nil {
|
||||||
|
return fmt.Errorf("acquire migration lock: %w", err)
|
||||||
|
}
|
||||||
|
defer func() { _, _ = conn.Exec(context.Background(), `SELECT pg_advisory_unlock(42424242)`) }()
|
||||||
|
if _, err := conn.Exec(lockCtx, string(data)); err != nil {
|
||||||
|
return fmt.Errorf("run migration: %w", err)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,321 @@
|
|||||||
|
CREATE EXTENSION IF NOT EXISTS pgcrypto;
|
||||||
|
CREATE EXTENSION IF NOT EXISTS pg_trgm;
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS users (
|
||||||
|
id BIGSERIAL PRIMARY KEY,
|
||||||
|
email TEXT NOT NULL UNIQUE,
|
||||||
|
username TEXT,
|
||||||
|
password_hash TEXT NOT NULL,
|
||||||
|
avatar_url TEXT,
|
||||||
|
bio TEXT,
|
||||||
|
role TEXT NOT NULL DEFAULT 'user',
|
||||||
|
permissions JSONB NOT NULL DEFAULT '{}'::jsonb,
|
||||||
|
disabled BOOLEAN NOT NULL DEFAULT FALSE,
|
||||||
|
totp_secret TEXT,
|
||||||
|
mfa_enabled BOOLEAN NOT NULL DEFAULT FALSE,
|
||||||
|
mfa_backup_codes JSONB,
|
||||||
|
password_reset_token TEXT,
|
||||||
|
password_reset_expires TIMESTAMPTZ,
|
||||||
|
last_login_at TIMESTAMPTZ,
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||||
|
);
|
||||||
|
ALTER TABLE users ADD COLUMN IF NOT EXISTS username TEXT;
|
||||||
|
ALTER TABLE users ADD COLUMN IF NOT EXISTS role TEXT NOT NULL DEFAULT 'user';
|
||||||
|
UPDATE users SET role = 'superadmin'
|
||||||
|
WHERE id = (SELECT id FROM users ORDER BY created_at, id LIMIT 1)
|
||||||
|
AND NOT EXISTS (SELECT 1 FROM users WHERE role = 'superadmin');
|
||||||
|
ALTER TABLE users ADD COLUMN IF NOT EXISTS permissions JSONB NOT NULL DEFAULT '{}'::jsonb;
|
||||||
|
ALTER TABLE users ADD COLUMN IF NOT EXISTS disabled BOOLEAN NOT NULL DEFAULT FALSE;
|
||||||
|
ALTER TABLE users ADD COLUMN IF NOT EXISTS last_login_at TIMESTAMPTZ;
|
||||||
|
CREATE UNIQUE INDEX IF NOT EXISTS users_username_unique ON users (LOWER(username)) WHERE username IS NOT NULL;
|
||||||
|
CREATE INDEX IF NOT EXISTS users_email_idx ON users (LOWER(email));
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS go_sessions (
|
||||||
|
token_hash TEXT PRIMARY KEY,
|
||||||
|
user_id BIGINT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||||
|
expires_at TIMESTAMPTZ NOT NULL,
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||||
|
);
|
||||||
|
CREATE INDEX IF NOT EXISTS go_sessions_expiry_idx ON go_sessions (expires_at);
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS media (
|
||||||
|
id BIGSERIAL PRIMARY KEY,
|
||||||
|
user_id BIGINT REFERENCES users(id) ON DELETE SET NULL,
|
||||||
|
media_key TEXT NOT NULL UNIQUE,
|
||||||
|
media_type TEXT NOT NULL DEFAULT 'unknown',
|
||||||
|
app TEXT,
|
||||||
|
source TEXT NOT NULL DEFAULT 'Filesystem',
|
||||||
|
title TEXT,
|
||||||
|
description TEXT,
|
||||||
|
category TEXT,
|
||||||
|
file_path TEXT,
|
||||||
|
original_filename TEXT,
|
||||||
|
active BOOLEAN NOT NULL DEFAULT TRUE,
|
||||||
|
metadata JSONB NOT NULL DEFAULT '{}'::jsonb,
|
||||||
|
width INT,
|
||||||
|
height INT,
|
||||||
|
duration_ms BIGINT,
|
||||||
|
size_bytes BIGINT,
|
||||||
|
is_vr BOOLEAN NOT NULL DEFAULT FALSE,
|
||||||
|
has_funscript BOOLEAN NOT NULL DEFAULT FALSE,
|
||||||
|
speed REAL,
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
|
modified_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||||
|
);
|
||||||
|
ALTER TABLE media ADD COLUMN IF NOT EXISTS file_path TEXT;
|
||||||
|
ALTER TABLE media ADD COLUMN IF NOT EXISTS source TEXT NOT NULL DEFAULT 'Filesystem';
|
||||||
|
ALTER TABLE media ADD COLUMN IF NOT EXISTS title TEXT;
|
||||||
|
ALTER TABLE media ADD COLUMN IF NOT EXISTS description TEXT;
|
||||||
|
ALTER TABLE media ADD COLUMN IF NOT EXISTS category TEXT;
|
||||||
|
ALTER TABLE media ADD COLUMN IF NOT EXISTS original_filename TEXT;
|
||||||
|
ALTER TABLE media ADD COLUMN IF NOT EXISTS active BOOLEAN NOT NULL DEFAULT TRUE;
|
||||||
|
ALTER TABLE media ADD COLUMN IF NOT EXISTS metadata JSONB NOT NULL DEFAULT '{}'::jsonb;
|
||||||
|
ALTER TABLE media ADD COLUMN IF NOT EXISTS created_at TIMESTAMPTZ NOT NULL DEFAULT NOW();
|
||||||
|
ALTER TABLE media ADD COLUMN IF NOT EXISTS media_type TEXT NOT NULL DEFAULT 'unknown';
|
||||||
|
ALTER TABLE media ADD COLUMN IF NOT EXISTS width INT;
|
||||||
|
ALTER TABLE media ADD COLUMN IF NOT EXISTS height INT;
|
||||||
|
ALTER TABLE media ADD COLUMN IF NOT EXISTS duration_ms BIGINT;
|
||||||
|
ALTER TABLE media ADD COLUMN IF NOT EXISTS size_bytes BIGINT;
|
||||||
|
ALTER TABLE media ADD COLUMN IF NOT EXISTS is_vr BOOLEAN NOT NULL DEFAULT FALSE;
|
||||||
|
ALTER TABLE media ADD COLUMN IF NOT EXISTS has_funscript BOOLEAN NOT NULL DEFAULT FALSE;
|
||||||
|
ALTER TABLE media ADD COLUMN IF NOT EXISTS speed REAL;
|
||||||
|
ALTER TABLE media ADD COLUMN IF NOT EXISTS modified_at TIMESTAMPTZ NOT NULL DEFAULT NOW();
|
||||||
|
CREATE INDEX IF NOT EXISTS media_active_idx ON media (active);
|
||||||
|
CREATE INDEX IF NOT EXISTS media_file_path_idx ON media (file_path);
|
||||||
|
CREATE INDEX IF NOT EXISTS media_search_idx ON media USING GIN (to_tsvector('simple', COALESCE(title, '') || ' ' || COALESCE(original_filename, '') || ' ' || COALESCE(file_path, '')));
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS media_stats (
|
||||||
|
id BIGSERIAL PRIMARY KEY,
|
||||||
|
media_id BIGINT REFERENCES media(id) ON DELETE CASCADE,
|
||||||
|
media_key TEXT NOT NULL,
|
||||||
|
user_id BIGINT REFERENCES users(id) ON DELETE SET NULL,
|
||||||
|
stat_type TEXT NOT NULL,
|
||||||
|
app TEXT,
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||||
|
);
|
||||||
|
ALTER TABLE media_stats ADD COLUMN IF NOT EXISTS media_id BIGINT;
|
||||||
|
ALTER TABLE media_stats ADD COLUMN IF NOT EXISTS media_key TEXT;
|
||||||
|
ALTER TABLE media_stats ADD COLUMN IF NOT EXISTS user_id BIGINT;
|
||||||
|
ALTER TABLE media_stats ADD COLUMN IF NOT EXISTS stat_type TEXT;
|
||||||
|
ALTER TABLE media_stats ADD COLUMN IF NOT EXISTS app TEXT;
|
||||||
|
ALTER TABLE media_stats ADD COLUMN IF NOT EXISTS created_at TIMESTAMPTZ NOT NULL DEFAULT NOW();
|
||||||
|
CREATE UNIQUE INDEX IF NOT EXISTS media_stats_like_unique ON media_stats (user_id, media_key) WHERE stat_type = 'like' AND user_id IS NOT NULL;
|
||||||
|
CREATE INDEX IF NOT EXISTS media_stats_key_idx ON media_stats (media_key, stat_type);
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS media_view_sessions (
|
||||||
|
id BIGSERIAL PRIMARY KEY,
|
||||||
|
media_id BIGINT REFERENCES media(id) ON DELETE CASCADE,
|
||||||
|
media_key TEXT NOT NULL,
|
||||||
|
user_id BIGINT REFERENCES users(id) ON DELETE SET NULL,
|
||||||
|
duration_ms BIGINT NOT NULL DEFAULT 0,
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS media_metrics (
|
||||||
|
id BIGSERIAL PRIMARY KEY,
|
||||||
|
media_id BIGINT REFERENCES media(id) ON DELETE CASCADE,
|
||||||
|
media_key TEXT NOT NULL,
|
||||||
|
user_id BIGINT REFERENCES users(id) ON DELETE SET NULL,
|
||||||
|
elapsed_ms BIGINT NOT NULL DEFAULT 0,
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS media_tags (
|
||||||
|
id BIGSERIAL PRIMARY KEY,
|
||||||
|
media_id BIGINT REFERENCES media(id) ON DELETE CASCADE,
|
||||||
|
media_key TEXT NOT NULL,
|
||||||
|
tag TEXT NOT NULL,
|
||||||
|
user_id BIGINT REFERENCES users(id) ON DELETE SET NULL,
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
|
UNIQUE (media_key, tag, user_id)
|
||||||
|
);
|
||||||
|
CREATE INDEX IF NOT EXISTS media_tags_tag_idx ON media_tags (LOWER(tag));
|
||||||
|
CREATE INDEX IF NOT EXISTS media_tags_media_idx ON media_tags (media_key);
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS media_tag_votes (
|
||||||
|
id BIGSERIAL PRIMARY KEY,
|
||||||
|
media_key TEXT NOT NULL,
|
||||||
|
tag TEXT NOT NULL,
|
||||||
|
user_id BIGINT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||||
|
vote SMALLINT NOT NULL CHECK (vote IN (-1, 1)),
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
|
UNIQUE (media_key, tag, user_id)
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS playlists (
|
||||||
|
id BIGSERIAL PRIMARY KEY,
|
||||||
|
user_id BIGINT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||||
|
name TEXT NOT NULL,
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
|
UNIQUE (user_id, name)
|
||||||
|
);
|
||||||
|
CREATE TABLE IF NOT EXISTS playlist_items (
|
||||||
|
id BIGSERIAL PRIMARY KEY,
|
||||||
|
playlist_id BIGINT NOT NULL REFERENCES playlists(id) ON DELETE CASCADE,
|
||||||
|
media_id BIGINT REFERENCES media(id) ON DELETE CASCADE,
|
||||||
|
media_key TEXT NOT NULL,
|
||||||
|
position INT,
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
|
UNIQUE (playlist_id, media_key)
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS settings (
|
||||||
|
key TEXT PRIMARY KEY,
|
||||||
|
value TEXT,
|
||||||
|
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||||
|
);
|
||||||
|
INSERT INTO settings (key, value)
|
||||||
|
VALUES ('auth_required', 'true')
|
||||||
|
ON CONFLICT (key) DO NOTHING;
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS media_worker_jobs (
|
||||||
|
id BIGSERIAL PRIMARY KEY,
|
||||||
|
media_id BIGINT REFERENCES media(id) ON DELETE SET NULL,
|
||||||
|
media_key TEXT,
|
||||||
|
file_path TEXT NOT NULL,
|
||||||
|
file_name TEXT NOT NULL DEFAULT '',
|
||||||
|
media_type TEXT NOT NULL DEFAULT 'unknown',
|
||||||
|
status TEXT NOT NULL DEFAULT 'queued',
|
||||||
|
progress INT NOT NULL DEFAULT 0,
|
||||||
|
queued_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
|
started_at TIMESTAMPTZ,
|
||||||
|
finished_at TIMESTAMPTZ,
|
||||||
|
duration_ms INT,
|
||||||
|
error_message TEXT,
|
||||||
|
extracted_data JSONB,
|
||||||
|
file_size_bytes BIGINT,
|
||||||
|
scan_batch_id TEXT,
|
||||||
|
tags TEXT[],
|
||||||
|
title TEXT,
|
||||||
|
description TEXT,
|
||||||
|
has_funscript BOOLEAN NOT NULL DEFAULT FALSE,
|
||||||
|
is_vr BOOLEAN NOT NULL DEFAULT FALSE,
|
||||||
|
vr_fov INT,
|
||||||
|
vr_stereo TEXT,
|
||||||
|
data_outcome TEXT,
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||||
|
);
|
||||||
|
CREATE INDEX IF NOT EXISTS media_worker_jobs_status_idx ON media_worker_jobs (status, queued_at DESC);
|
||||||
|
CREATE UNIQUE INDEX IF NOT EXISTS media_worker_jobs_file_path_unique ON media_worker_jobs (file_path);
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS generated_media (
|
||||||
|
id BIGSERIAL PRIMARY KEY,
|
||||||
|
media_id BIGINT REFERENCES media(id) ON DELETE SET NULL,
|
||||||
|
user_id BIGINT REFERENCES users(id) ON DELETE SET NULL,
|
||||||
|
workflow TEXT,
|
||||||
|
prompt TEXT,
|
||||||
|
parameters JSONB,
|
||||||
|
output_filename TEXT,
|
||||||
|
output_path TEXT,
|
||||||
|
elapsed_ms INT,
|
||||||
|
status TEXT NOT NULL DEFAULT 'completed',
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||||
|
);
|
||||||
|
CREATE TABLE IF NOT EXISTS downloaded_media (
|
||||||
|
id BIGSERIAL PRIMARY KEY,
|
||||||
|
media_id BIGINT REFERENCES media(id) ON DELETE SET NULL,
|
||||||
|
user_id BIGINT REFERENCES users(id) ON DELETE SET NULL,
|
||||||
|
job_id BIGINT,
|
||||||
|
source_url TEXT NOT NULL,
|
||||||
|
tool TEXT,
|
||||||
|
file_path TEXT,
|
||||||
|
file_name TEXT,
|
||||||
|
file_size_bytes BIGINT,
|
||||||
|
status TEXT NOT NULL DEFAULT 'completed',
|
||||||
|
error_message TEXT,
|
||||||
|
started_at TIMESTAMPTZ,
|
||||||
|
finished_at TIMESTAMPTZ,
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS workflow_jobs (
|
||||||
|
id TEXT PRIMARY KEY,
|
||||||
|
service TEXT NOT NULL,
|
||||||
|
tool TEXT NOT NULL,
|
||||||
|
status TEXT NOT NULL DEFAULT 'queued',
|
||||||
|
progress INT NOT NULL DEFAULT 0,
|
||||||
|
request JSONB NOT NULL DEFAULT '{}'::jsonb,
|
||||||
|
result JSONB NOT NULL DEFAULT '{}'::jsonb,
|
||||||
|
error_message TEXT,
|
||||||
|
user_id BIGINT REFERENCES users(id) ON DELETE SET NULL,
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
|
started_at TIMESTAMPTZ,
|
||||||
|
finished_at TIMESTAMPTZ
|
||||||
|
);
|
||||||
|
CREATE INDEX IF NOT EXISTS workflow_jobs_service_idx ON workflow_jobs (service, created_at DESC);
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS workflow_schedules (
|
||||||
|
id TEXT PRIMARY KEY,
|
||||||
|
service TEXT NOT NULL,
|
||||||
|
tool TEXT NOT NULL,
|
||||||
|
name TEXT NOT NULL,
|
||||||
|
interval_minutes INT NOT NULL DEFAULT 60,
|
||||||
|
enabled BOOLEAN NOT NULL DEFAULT TRUE,
|
||||||
|
settings JSONB NOT NULL DEFAULT '{}'::jsonb,
|
||||||
|
last_run_at TIMESTAMPTZ,
|
||||||
|
last_status TEXT,
|
||||||
|
next_run_at TIMESTAMPTZ,
|
||||||
|
user_id BIGINT REFERENCES users(id) ON DELETE CASCADE,
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
|
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS thumbnails (
|
||||||
|
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||||
|
media_id BIGINT REFERENCES media(id) ON DELETE SET NULL,
|
||||||
|
source_path TEXT UNIQUE,
|
||||||
|
width INT,
|
||||||
|
height INT,
|
||||||
|
file_size_bytes BIGINT,
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS mount_paths (
|
||||||
|
project TEXT NOT NULL,
|
||||||
|
function_name TEXT NOT NULL,
|
||||||
|
path TEXT NOT NULL,
|
||||||
|
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
|
PRIMARY KEY (project, function_name)
|
||||||
|
);
|
||||||
|
|
||||||
|
-- Per-step status tracking for metadata extraction and thumbnail generation, independent of the
|
||||||
|
-- legacy `status`/`error_message` columns above (which track the overall discovery row).
|
||||||
|
ALTER TABLE media_worker_jobs ADD COLUMN IF NOT EXISTS metadata_status TEXT NOT NULL DEFAULT 'queued';
|
||||||
|
ALTER TABLE media_worker_jobs ADD COLUMN IF NOT EXISTS metadata_error TEXT;
|
||||||
|
ALTER TABLE media_worker_jobs ADD COLUMN IF NOT EXISTS thumbnail_status TEXT NOT NULL DEFAULT 'queued';
|
||||||
|
ALTER TABLE media_worker_jobs ADD COLUMN IF NOT EXISTS thumbnail_error TEXT;
|
||||||
|
CREATE INDEX IF NOT EXISTS media_worker_jobs_metadata_status_idx ON media_worker_jobs (media_type, metadata_status);
|
||||||
|
CREATE INDEX IF NOT EXISTS media_worker_jobs_thumbnail_status_idx ON media_worker_jobs (media_type, thumbnail_status);
|
||||||
|
|
||||||
|
-- One row per (file, AI task) since a single image can have up to six independently toggleable
|
||||||
|
-- AI tasks (tags/title/description/age/gender/nsfw), which doesn't fit the one-row-per-file shape
|
||||||
|
-- of media_worker_jobs.
|
||||||
|
CREATE TABLE IF NOT EXISTS media_analysis_tasks (
|
||||||
|
id BIGSERIAL PRIMARY KEY,
|
||||||
|
media_key TEXT NOT NULL,
|
||||||
|
media_type TEXT NOT NULL,
|
||||||
|
task TEXT NOT NULL,
|
||||||
|
model TEXT NOT NULL,
|
||||||
|
status TEXT NOT NULL DEFAULT 'queued',
|
||||||
|
result JSONB,
|
||||||
|
error_message TEXT,
|
||||||
|
started_at TIMESTAMPTZ,
|
||||||
|
finished_at TIMESTAMPTZ,
|
||||||
|
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
|
UNIQUE (media_key, task)
|
||||||
|
);
|
||||||
|
CREATE INDEX IF NOT EXISTS media_analysis_tasks_status_idx ON media_analysis_tasks (media_type, status);
|
||||||
|
|
||||||
|
-- AI-attributed tags are inserted with user_id NULL; a plain UNIQUE(media_key, tag, user_id)
|
||||||
|
-- constraint does not dedupe NULLs against each other, so a dedicated partial index is required
|
||||||
|
-- to make repeated analysis runs idempotent instead of piling up duplicate tag rows.
|
||||||
|
CREATE UNIQUE INDEX IF NOT EXISTS media_tags_ai_tag_unique ON media_tags (media_key, tag) WHERE user_id IS NULL;
|
||||||
|
|
||||||
|
-- Speeds up the MediaAnalyzer dashboard/pipelines/history/live-status queries: analyzerStats and
|
||||||
|
-- analyzerPipelineBreakdown group active media by type (and join it against thumbnails), and
|
||||||
|
-- analyzerHistory sorts media_worker_jobs by queued_at with no status filter, none of which the
|
||||||
|
-- existing media/media_worker_jobs indexes above actually cover.
|
||||||
|
CREATE INDEX IF NOT EXISTS media_active_type_idx ON media (active, media_type);
|
||||||
|
CREATE INDEX IF NOT EXISTS media_worker_jobs_queued_at_idx ON media_worker_jobs (queued_at DESC);
|
||||||
|
CREATE INDEX IF NOT EXISTS media_worker_jobs_media_type_status_idx ON media_worker_jobs (media_type, status);
|
||||||
|
CREATE INDEX IF NOT EXISTS media_worker_jobs_funscript_status_idx ON media_worker_jobs (status) WHERE has_funscript = TRUE;
|
||||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,710 @@
|
|||||||
|
package server
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"image"
|
||||||
|
_ "image/gif"
|
||||||
|
_ "image/jpeg"
|
||||||
|
_ "image/png"
|
||||||
|
"io"
|
||||||
|
"log"
|
||||||
|
"net/http"
|
||||||
|
"os"
|
||||||
|
"os/exec"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
// analysisState tracks the currently-running AI analysis pass, mirroring thumbnailGenerationState.
|
||||||
|
type analysisState struct {
|
||||||
|
Running bool
|
||||||
|
State string
|
||||||
|
Total int
|
||||||
|
Completed int
|
||||||
|
Failed int
|
||||||
|
Current string
|
||||||
|
CurrentType string
|
||||||
|
StartedAt *time.Time
|
||||||
|
FinishedAt *time.Time
|
||||||
|
LastError string
|
||||||
|
}
|
||||||
|
|
||||||
|
// analyzerTasksByMediaType mirrors WebUI/src/lib/features/MediaTypePipeline.svelte's stagesForType -
|
||||||
|
// the set of AI tasks that exist for each media type.
|
||||||
|
var analyzerTasksByMediaType = map[string][]string{
|
||||||
|
"image": {"tags", "title", "description", "age", "gender", "nsfw"},
|
||||||
|
"video": {"tags"},
|
||||||
|
"audio": {"tags"},
|
||||||
|
"funscript": {},
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Server) analyzerAnalyzeStatus(w http.ResponseWriter, r *http.Request) {
|
||||||
|
s.analysisMu.Lock()
|
||||||
|
state := s.analysis
|
||||||
|
s.analysisMu.Unlock()
|
||||||
|
writeJSON(w, http.StatusOK, map[string]any{
|
||||||
|
"ok": true,
|
||||||
|
"status": map[string]any{
|
||||||
|
"running": state.Running,
|
||||||
|
"state": firstNonEmpty(state.State, "idle"),
|
||||||
|
"total": state.Total,
|
||||||
|
"completed": state.Completed,
|
||||||
|
"failed": state.Failed,
|
||||||
|
"current": state.Current,
|
||||||
|
"startedAt": state.StartedAt,
|
||||||
|
"finishedAt": state.FinishedAt,
|
||||||
|
"lastError": state.LastError,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Server) analyzerAnalyzeStart(w http.ResponseWriter, r *http.Request) {
|
||||||
|
selected := parseMediaTypesPayload(r, false)
|
||||||
|
s.analysisMu.Lock()
|
||||||
|
if s.analysis.Running {
|
||||||
|
s.analysisMu.Unlock()
|
||||||
|
writeError(w, http.StatusConflict, "AI analysis is already running")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
ctx, cancel := context.WithCancel(context.Background())
|
||||||
|
now := time.Now().UTC()
|
||||||
|
s.analysis = analysisState{Running: true, State: "running", StartedAt: &now}
|
||||||
|
s.analysisCancel = cancel
|
||||||
|
s.analysisMu.Unlock()
|
||||||
|
|
||||||
|
go s.runAiAnalysis(ctx, mediaTypesList(selected))
|
||||||
|
writeJSON(w, http.StatusAccepted, map[string]any{"ok": true, "state": "running"})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Server) analyzerAnalyzeStop(w http.ResponseWriter, r *http.Request) {
|
||||||
|
s.analysisMu.Lock()
|
||||||
|
cancel := s.analysisCancel
|
||||||
|
running := s.analysis.Running
|
||||||
|
s.analysisMu.Unlock()
|
||||||
|
if !running || cancel == nil {
|
||||||
|
writeJSON(w, http.StatusOK, map[string]any{"ok": true, "state": "idle"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
log.Printf("analyzer: AI analysis stop requested")
|
||||||
|
cancel()
|
||||||
|
writeJSON(w, http.StatusAccepted, map[string]any{"ok": true, "state": "stopping"})
|
||||||
|
}
|
||||||
|
|
||||||
|
// runAiAnalysis queues any AI task that isn't already completed under the currently-configured
|
||||||
|
// model, then works through everything queued. mediaTypeFilters scopes both stages to a subset of
|
||||||
|
// media types (empty means every type) - used both by the dashboard's media-type selector and by
|
||||||
|
// the per-media-type retry-errors action (which passes a single-element list) so a scoped run
|
||||||
|
// never kicks off a full-library pass.
|
||||||
|
func (s *Server) runAiAnalysis(ctx context.Context, mediaTypeFilters []string) {
|
||||||
|
if err := s.syncAnalysisTasks(ctx, mediaTypeFilters); err != nil && ctx.Err() == nil {
|
||||||
|
log.Printf("analyzer: AI analysis: failed to sync tasks: %v", err)
|
||||||
|
s.finishAnalysis(err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
s.processAnalysisTasks(ctx, mediaTypeFilters)
|
||||||
|
}
|
||||||
|
|
||||||
|
type modelStageConfig struct {
|
||||||
|
Primary string
|
||||||
|
Enabled bool
|
||||||
|
}
|
||||||
|
|
||||||
|
// parseModelStageConfig mirrors MediaTypePipeline.svelte's own leniency: older saves stored the
|
||||||
|
// model as a bare string rather than {primary, fallback, enabled}.
|
||||||
|
func parseModelStageConfig(raw json.RawMessage) modelStageConfig {
|
||||||
|
var asString string
|
||||||
|
if json.Unmarshal(raw, &asString) == nil {
|
||||||
|
if asString == "" || asString == "disabled" {
|
||||||
|
return modelStageConfig{}
|
||||||
|
}
|
||||||
|
return modelStageConfig{Primary: asString, Enabled: true}
|
||||||
|
}
|
||||||
|
var asObject struct {
|
||||||
|
Primary string `json:"primary"`
|
||||||
|
Enabled bool `json:"enabled"`
|
||||||
|
}
|
||||||
|
if json.Unmarshal(raw, &asObject) == nil {
|
||||||
|
return modelStageConfig{Primary: asObject.Primary, Enabled: asObject.Enabled}
|
||||||
|
}
|
||||||
|
return modelStageConfig{}
|
||||||
|
}
|
||||||
|
|
||||||
|
// enabledAnalysisTasks reads the analyzer_model_config setting (the same one the model-config
|
||||||
|
// endpoints already read/write) and returns, per media type, the task->model pairs the user has
|
||||||
|
// actually turned on.
|
||||||
|
func (s *Server) enabledAnalysisTasks(ctx context.Context, mediaTypeFilters []string) map[string]map[string]string {
|
||||||
|
value := s.settingValue(ctx, "analyzer_model_config", "{}")
|
||||||
|
var wrapper struct {
|
||||||
|
Config map[string]map[string]json.RawMessage `json:"config"`
|
||||||
|
}
|
||||||
|
if json.Unmarshal([]byte(value), &wrapper) != nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
filterSet := make(map[string]bool, len(mediaTypeFilters))
|
||||||
|
for _, mediaType := range mediaTypeFilters {
|
||||||
|
filterSet[mediaType] = true
|
||||||
|
}
|
||||||
|
result := make(map[string]map[string]string)
|
||||||
|
for mediaType, tasks := range analyzerTasksByMediaType {
|
||||||
|
if len(filterSet) > 0 && !filterSet[mediaType] {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
section, ok := wrapper.Config[mediaType]
|
||||||
|
if !ok {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
enabled := make(map[string]string)
|
||||||
|
for _, task := range tasks {
|
||||||
|
raw, ok := section[task]
|
||||||
|
if !ok {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
stage := parseModelStageConfig(raw)
|
||||||
|
if stage.Enabled && stage.Primary != "" && stage.Primary != "disabled" {
|
||||||
|
enabled[task] = stage.Primary
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(enabled) > 0 {
|
||||||
|
result[mediaType] = enabled
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return result
|
||||||
|
}
|
||||||
|
|
||||||
|
// syncAnalysisTasks upserts one media_analysis_tasks row per (active media file, enabled task).
|
||||||
|
// A file whose task previously errored, or whose configured model has since changed, is put back
|
||||||
|
// on the queue - mirroring how thumbnails/metadata already retry automatically on every run
|
||||||
|
// rather than requiring the dedicated retry-errors action.
|
||||||
|
func (s *Server) syncAnalysisTasks(ctx context.Context, mediaTypeFilters []string) error {
|
||||||
|
tasksByType := s.enabledAnalysisTasks(ctx, mediaTypeFilters)
|
||||||
|
if len(tasksByType) == 0 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
query := `SELECT media_key, LOWER(COALESCE(media_type, '')) FROM media WHERE active = TRUE`
|
||||||
|
args := []any{}
|
||||||
|
if len(mediaTypeFilters) > 0 {
|
||||||
|
query += ` AND LOWER(COALESCE(media_type, '')) = ANY($1)`
|
||||||
|
args = append(args, mediaTypeFilters)
|
||||||
|
}
|
||||||
|
rows, err := s.db.Query(ctx, query, args...)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
type mediaItem struct{ key, mediaType string }
|
||||||
|
items := make([]mediaItem, 0)
|
||||||
|
for rows.Next() {
|
||||||
|
var item mediaItem
|
||||||
|
if rows.Scan(&item.key, &item.mediaType) == nil {
|
||||||
|
items = append(items, item)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
rows.Close()
|
||||||
|
if err := rows.Err(); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, item := range items {
|
||||||
|
tasks, ok := tasksByType[item.mediaType]
|
||||||
|
if !ok {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
for task, model := range tasks {
|
||||||
|
if ctx.Err() != nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
_, _ = s.db.Exec(ctx, `
|
||||||
|
INSERT INTO media_analysis_tasks (media_key, media_type, task, model, status)
|
||||||
|
VALUES ($1,$2,$3,$4,'queued')
|
||||||
|
ON CONFLICT (media_key, task) DO UPDATE SET
|
||||||
|
model = EXCLUDED.model,
|
||||||
|
status = 'queued',
|
||||||
|
error_message = NULL,
|
||||||
|
updated_at = NOW()
|
||||||
|
WHERE media_analysis_tasks.status = 'error'
|
||||||
|
OR (media_analysis_tasks.status = 'completed' AND media_analysis_tasks.model <> EXCLUDED.model)`,
|
||||||
|
item.key, item.mediaType, task, model)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
type pendingAnalysisTask struct {
|
||||||
|
id int64
|
||||||
|
mediaKey, mediaType string
|
||||||
|
task, model, filePath string
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Server) processAnalysisTasks(ctx context.Context, mediaTypeFilters []string) {
|
||||||
|
query := `
|
||||||
|
SELECT t.id, t.media_key, t.media_type, t.task, t.model, COALESCE(NULLIF(m.file_path, ''), m.media_key)
|
||||||
|
FROM media_analysis_tasks t
|
||||||
|
JOIN media m ON m.media_key = t.media_key
|
||||||
|
WHERE t.status = 'queued' AND m.active = TRUE`
|
||||||
|
args := []any{}
|
||||||
|
if len(mediaTypeFilters) > 0 {
|
||||||
|
query += ` AND t.media_type = ANY($1)`
|
||||||
|
args = append(args, mediaTypeFilters)
|
||||||
|
}
|
||||||
|
query += ` ORDER BY t.id ASC`
|
||||||
|
|
||||||
|
rows, err := s.db.Query(ctx, query, args...)
|
||||||
|
if err != nil {
|
||||||
|
if ctx.Err() != nil {
|
||||||
|
s.finishAnalysis(nil)
|
||||||
|
} else {
|
||||||
|
log.Printf("analyzer: AI analysis: failed to load queued tasks: %v", err)
|
||||||
|
s.finishAnalysis(err)
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
items := make([]pendingAnalysisTask, 0)
|
||||||
|
for rows.Next() {
|
||||||
|
var item pendingAnalysisTask
|
||||||
|
if rows.Scan(&item.id, &item.mediaKey, &item.mediaType, &item.task, &item.model, &item.filePath) == nil {
|
||||||
|
items = append(items, item)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
rows.Close()
|
||||||
|
|
||||||
|
log.Printf("analyzer: AI analysis started: %d tasks queued", len(items))
|
||||||
|
|
||||||
|
s.analysisMu.Lock()
|
||||||
|
s.analysis.Total = len(items)
|
||||||
|
s.analysisMu.Unlock()
|
||||||
|
|
||||||
|
for _, item := range items {
|
||||||
|
if ctx.Err() != nil {
|
||||||
|
s.finishAnalysis(nil)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
s.analysisMu.Lock()
|
||||||
|
s.analysis.Current = item.filePath
|
||||||
|
s.analysis.CurrentType = item.mediaType
|
||||||
|
s.analysisMu.Unlock()
|
||||||
|
|
||||||
|
_, _ = s.db.Exec(ctx, `UPDATE media_analysis_tasks SET status='processing', started_at=NOW() WHERE id=$1`, item.id)
|
||||||
|
|
||||||
|
result, runErr := s.runAnalysisTask(ctx, item)
|
||||||
|
|
||||||
|
s.analysisMu.Lock()
|
||||||
|
if runErr != nil {
|
||||||
|
s.analysis.Failed++
|
||||||
|
s.analysis.LastError = runErr.Error()
|
||||||
|
} else {
|
||||||
|
s.analysis.Completed++
|
||||||
|
}
|
||||||
|
s.analysisMu.Unlock()
|
||||||
|
|
||||||
|
if runErr != nil {
|
||||||
|
_, _ = s.db.Exec(ctx, `UPDATE media_analysis_tasks SET status='error', error_message=$2, finished_at=NOW() WHERE id=$1`, item.id, runErr.Error())
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
_, _ = s.db.Exec(ctx, `UPDATE media_analysis_tasks SET status='completed', error_message=NULL, result=$2, finished_at=NOW() WHERE id=$1`, item.id, mustJSON(result))
|
||||||
|
s.applyAnalysisResult(ctx, item.mediaKey, result)
|
||||||
|
}
|
||||||
|
s.finishAnalysis(nil)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Server) finishAnalysis(runErr error) {
|
||||||
|
now := time.Now().UTC()
|
||||||
|
s.analysisMu.Lock()
|
||||||
|
defer s.analysisMu.Unlock()
|
||||||
|
s.analysis.Running = false
|
||||||
|
s.analysisCancel = nil
|
||||||
|
s.analysis.Current = ""
|
||||||
|
s.analysis.CurrentType = ""
|
||||||
|
s.analysis.FinishedAt = &now
|
||||||
|
if runErr != nil {
|
||||||
|
s.analysis.State = "error"
|
||||||
|
s.analysis.LastError = runErr.Error()
|
||||||
|
} else if s.analysis.Completed+s.analysis.Failed < s.analysis.Total {
|
||||||
|
s.analysis.State = "stopped"
|
||||||
|
} else if s.analysis.Failed > 0 {
|
||||||
|
s.analysis.State = "completed_with_errors"
|
||||||
|
} else {
|
||||||
|
s.analysis.State = "completed"
|
||||||
|
s.analysis.LastError = ""
|
||||||
|
}
|
||||||
|
log.Printf("analyzer: AI analysis finished: %d/%d done, %d failed, state=%s", s.analysis.Completed, s.analysis.Total, s.analysis.Failed, s.analysis.State)
|
||||||
|
if s.analysis.LastError != "" {
|
||||||
|
log.Printf("analyzer: AI analysis last error: %s", s.analysis.LastError)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// runAnalysisTask dispatches one (file, task, model) unit of work. Every model produces a fixed
|
||||||
|
// output shape regardless of which task slot it was assigned to in the UI (the model dropdown
|
||||||
|
// isn't filtered per task), so storage in applyAnalysisResult is driven by what a model actually
|
||||||
|
// returns, not by the task key it ran under.
|
||||||
|
func (s *Server) runAnalysisTask(ctx context.Context, item pendingAnalysisTask) (map[string]any, error) {
|
||||||
|
sourcePath := filepath.ToSlash(item.filePath)
|
||||||
|
|
||||||
|
// Video frames come from an existing thumbnail when possible (see videoAnalysisFrame) rather
|
||||||
|
// than always fetching the whole video across the wire to Servant just to grab one frame.
|
||||||
|
if item.mediaType == "video" && item.model != "laplacian" {
|
||||||
|
framePath, cleanup, err := s.videoAnalysisFrame(ctx, sourcePath)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if cleanup != nil {
|
||||||
|
defer cleanup()
|
||||||
|
}
|
||||||
|
return s.callAnalyzerModelsService(ctx, item.mediaType, item.task, item.model, framePath)
|
||||||
|
}
|
||||||
|
|
||||||
|
scratchPath, cleanup, err := s.fetchServantToScratch(ctx, "/media/"+urlPath(sourcePath), filepath.Ext(sourcePath))
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("fetch %s: %w", item.filePath, err)
|
||||||
|
}
|
||||||
|
defer cleanup()
|
||||||
|
|
||||||
|
if item.model == "laplacian" {
|
||||||
|
if item.mediaType != "image" {
|
||||||
|
return nil, fmt.Errorf("laplacian quality scoring only supports images")
|
||||||
|
}
|
||||||
|
variance, err := computeLaplacianVariance(scratchPath)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return map[string]any{"quality": map[string]any{"laplacianVariance": variance}}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
return s.callAnalyzerModelsService(ctx, item.mediaType, item.task, item.model, scratchPath)
|
||||||
|
}
|
||||||
|
|
||||||
|
// videoAnalysisFrame reuses an already-generated thumbnail as the representative frame for
|
||||||
|
// image-shaped models when one exists, fetching the source video and extracting a temporary
|
||||||
|
// frame otherwise so AI analysis doesn't depend on the thumbnails stage being enabled. Both paths
|
||||||
|
// return a scratch file the AnalyzerModels sidecar (co-located in this container - see
|
||||||
|
// callAnalyzerModelsService) can read directly.
|
||||||
|
func (s *Server) videoAnalysisFrame(ctx context.Context, sourcePath string) (string, func(), error) {
|
||||||
|
var thumbnailID string
|
||||||
|
if err := s.db.QueryRow(ctx, `SELECT id FROM thumbnails WHERE source_path = $1`, sourcePath).Scan(&thumbnailID); err == nil {
|
||||||
|
if scratchPath, cleanup, fetchErr := s.fetchServantToScratch(ctx, "/thumbnails/"+thumbnailID+".jpg", ".jpg"); fetchErr == nil {
|
||||||
|
return scratchPath, cleanup, nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
videoScratch, cleanupVideo, err := s.fetchServantToScratch(ctx, "/media/"+urlPath(sourcePath), filepath.Ext(sourcePath))
|
||||||
|
if err != nil {
|
||||||
|
return "", nil, fmt.Errorf("fetch %s: %w", sourcePath, err)
|
||||||
|
}
|
||||||
|
defer cleanupVideo()
|
||||||
|
|
||||||
|
temporary, err := os.CreateTemp("", "analysis-frame-*.jpg")
|
||||||
|
if err != nil {
|
||||||
|
return "", nil, fmt.Errorf("create temporary frame: %w", err)
|
||||||
|
}
|
||||||
|
temporaryPath := temporary.Name()
|
||||||
|
if err := temporary.Close(); err != nil {
|
||||||
|
_ = os.Remove(temporaryPath)
|
||||||
|
return "", nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
frameCtx, cancel := context.WithTimeout(ctx, 2*time.Minute)
|
||||||
|
defer cancel()
|
||||||
|
args := []string{"-hide_banner", "-loglevel", "error", "-y", "-ss", "0", "-i", videoScratch, "-vf", "scale=320:-2:force_original_aspect_ratio=decrease", "-frames:v", "1", "-q:v", "3", temporaryPath}
|
||||||
|
command := exec.CommandContext(frameCtx, s.cfg.FFmpeg, args...)
|
||||||
|
var stderr bytes.Buffer
|
||||||
|
command.Stderr = &stderr
|
||||||
|
if err := command.Run(); err != nil {
|
||||||
|
_ = os.Remove(temporaryPath)
|
||||||
|
detail := strings.TrimSpace(stderr.String())
|
||||||
|
if len(detail) > 300 {
|
||||||
|
detail = detail[len(detail)-300:]
|
||||||
|
}
|
||||||
|
if detail != "" {
|
||||||
|
return "", nil, fmt.Errorf("ffmpeg: %s", detail)
|
||||||
|
}
|
||||||
|
return "", nil, err
|
||||||
|
}
|
||||||
|
return temporaryPath, func() { _ = os.Remove(temporaryPath) }, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
type analysisSidecarRequest struct {
|
||||||
|
Task string `json:"task"`
|
||||||
|
Model string `json:"model"`
|
||||||
|
Path string `json:"path"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// callAnalyzerModelsService calls the AnalyzerModels sidecar (a separate process in the same
|
||||||
|
// container, not baked into this binary - see ANALYZER_MODELS_URL and MediaAnalyzer/Dockerfile),
|
||||||
|
// the same way executeGeneration already calls out to ComfyUI for image generation. Video frames
|
||||||
|
// are analyzed through the image endpoint since by the time this runs the video has already been
|
||||||
|
// reduced to a still frame.
|
||||||
|
func (s *Server) callAnalyzerModelsService(ctx context.Context, mediaType, task, model, path string) (map[string]any, error) {
|
||||||
|
endpoint, ok := map[string]string{"image": "/analyze/image", "video": "/analyze/image", "audio": "/analyze/audio"}[mediaType]
|
||||||
|
if !ok {
|
||||||
|
return nil, fmt.Errorf("unsupported media type for AI analysis: %s", mediaType)
|
||||||
|
}
|
||||||
|
body, err := json.Marshal(analysisSidecarRequest{Task: task, Model: model, Path: path})
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
// Some models (florence2 especially) run several seconds per file on CPU - generous timeout
|
||||||
|
// so a slow model doesn't get mistaken for a hung one.
|
||||||
|
requestCtx, cancel := context.WithTimeout(ctx, 5*time.Minute)
|
||||||
|
defer cancel()
|
||||||
|
request, err := http.NewRequestWithContext(requestCtx, http.MethodPost, s.cfg.AnalyzerModelsURL+endpoint, bytes.NewReader(body))
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
request.Header.Set("Content-Type", "application/json")
|
||||||
|
response, err := http.DefaultClient.Do(request)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("analyzer models service request failed: %w", err)
|
||||||
|
}
|
||||||
|
defer response.Body.Close()
|
||||||
|
var payload struct {
|
||||||
|
Result map[string]any `json:"result"`
|
||||||
|
// FastAPI's HTTPException serializes as {"detail": "..."} , not {"error": "..."}.
|
||||||
|
Detail string `json:"detail"`
|
||||||
|
}
|
||||||
|
if err := json.NewDecoder(io.LimitReader(response.Body, 1<<20)).Decode(&payload); err != nil {
|
||||||
|
return nil, fmt.Errorf("invalid analyzer models response: %w", err)
|
||||||
|
}
|
||||||
|
if response.StatusCode >= 300 {
|
||||||
|
if payload.Detail == "" {
|
||||||
|
payload.Detail = response.Status
|
||||||
|
}
|
||||||
|
return nil, fmt.Errorf("analyzer models service: %s", payload.Detail)
|
||||||
|
}
|
||||||
|
return payload.Result, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// applyAnalysisResult writes a completed task's output into the tables the rest of the app
|
||||||
|
// actually reads, not just the analyzer's own history - tags into media_tags (user_id NULL marks
|
||||||
|
// them as AI-attributed), title/description onto media (never overwriting a value that's already
|
||||||
|
// set, whether user-edited or from an earlier analysis run), everything else into media.metadata.
|
||||||
|
func (s *Server) applyAnalysisResult(ctx context.Context, mediaKey string, result map[string]any) {
|
||||||
|
if result == nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if tagsRaw, ok := result["tags"].([]any); ok {
|
||||||
|
for _, tagValue := range tagsRaw {
|
||||||
|
tag, ok := tagValue.(string)
|
||||||
|
tag = strings.ToLower(strings.TrimSpace(tag))
|
||||||
|
if !ok || tag == "" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
_, _ = s.db.Exec(ctx, `
|
||||||
|
INSERT INTO media_tags (media_key, tag, user_id) VALUES ($1, $2, NULL)
|
||||||
|
ON CONFLICT (media_key, tag) WHERE user_id IS NULL DO NOTHING`, mediaKey, tag)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
title, _ := result["title"].(string)
|
||||||
|
description, _ := result["description"].(string)
|
||||||
|
if strings.TrimSpace(title) != "" || strings.TrimSpace(description) != "" {
|
||||||
|
_, _ = s.db.Exec(ctx, `
|
||||||
|
UPDATE media SET
|
||||||
|
title = COALESCE(NULLIF(media.title, ''), NULLIF($2, '')),
|
||||||
|
description = COALESCE(NULLIF(media.description, ''), NULLIF($3, ''))
|
||||||
|
WHERE media_key = $1`, mediaKey, title, description)
|
||||||
|
}
|
||||||
|
|
||||||
|
extra := map[string]any{}
|
||||||
|
for _, key := range []string{"age", "gender", "nsfwLabel", "nsfwScore", "quality"} {
|
||||||
|
if value, ok := result[key]; ok {
|
||||||
|
extra[key] = value
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(extra) > 0 {
|
||||||
|
_, _ = s.db.Exec(ctx, `UPDATE media SET metadata = metadata || $2::jsonb WHERE media_key = $1`, mediaKey, mustJSON(extra))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// computeLaplacianVariance measures image sharpness/blur without any external model: convert to
|
||||||
|
// grayscale, convolve with the standard 4-neighbor Laplacian kernel, and take the variance of the
|
||||||
|
// result - a low variance means a flat/blurry image, a high variance means a lot of sharp edges.
|
||||||
|
// Only the image formats Go's standard library can decode (JPEG/PNG/GIF) are supported; anything
|
||||||
|
// else surfaces as a normal per-file error rather than silently skipping.
|
||||||
|
func computeLaplacianVariance(fullPath string) (float64, error) {
|
||||||
|
file, err := os.Open(fullPath)
|
||||||
|
if err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
defer file.Close()
|
||||||
|
|
||||||
|
img, _, err := image.Decode(file)
|
||||||
|
if err != nil {
|
||||||
|
return 0, fmt.Errorf("decode image: %w", err)
|
||||||
|
}
|
||||||
|
bounds := img.Bounds()
|
||||||
|
width, height := bounds.Dx(), bounds.Dy()
|
||||||
|
if width < 3 || height < 3 {
|
||||||
|
return 0, fmt.Errorf("image too small for quality analysis")
|
||||||
|
}
|
||||||
|
|
||||||
|
gray := make([]float64, width*height)
|
||||||
|
for y := 0; y < height; y++ {
|
||||||
|
for x := 0; x < width; x++ {
|
||||||
|
r, g, b, _ := img.At(bounds.Min.X+x, bounds.Min.Y+y).RGBA()
|
||||||
|
gray[y*width+x] = 0.299*float64(r>>8) + 0.587*float64(g>>8) + 0.114*float64(b>>8)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
at := func(x, y int) float64 {
|
||||||
|
if x < 0 {
|
||||||
|
x = 0
|
||||||
|
} else if x >= width {
|
||||||
|
x = width - 1
|
||||||
|
}
|
||||||
|
if y < 0 {
|
||||||
|
y = 0
|
||||||
|
} else if y >= height {
|
||||||
|
y = height - 1
|
||||||
|
}
|
||||||
|
return gray[y*width+x]
|
||||||
|
}
|
||||||
|
|
||||||
|
var sum, sumSquares float64
|
||||||
|
count := float64(width * height)
|
||||||
|
for y := 0; y < height; y++ {
|
||||||
|
for x := 0; x < width; x++ {
|
||||||
|
laplacian := at(x-1, y) + at(x+1, y) + at(x, y-1) + at(x, y+1) - 4*at(x, y)
|
||||||
|
sum += laplacian
|
||||||
|
sumSquares += laplacian * laplacian
|
||||||
|
}
|
||||||
|
}
|
||||||
|
mean := sum / count
|
||||||
|
return sumSquares/count - mean*mean, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// retryPipelineErrors resets one media type's failed items for one stage back onto the queue and
|
||||||
|
// immediately re-runs that stage for just that type, rather than requiring a full "Run pipeline".
|
||||||
|
func (s *Server) retryPipelineErrors(w http.ResponseWriter, r *http.Request, mediaType, stage string) {
|
||||||
|
ctx := r.Context()
|
||||||
|
log.Printf("analyzer: retry errors requested (mediaType=%s, stage=%s)", mediaType, stage)
|
||||||
|
switch stage {
|
||||||
|
case "metadata":
|
||||||
|
go s.retryMetadataErrors(mediaType)
|
||||||
|
case "thumbnails":
|
||||||
|
go s.retryThumbnailErrors(mediaType)
|
||||||
|
case "analyze":
|
||||||
|
go s.runAiAnalysis(context.Background(), []string{mediaType})
|
||||||
|
default:
|
||||||
|
writeError(w, http.StatusBadRequest, "unknown pipeline stage")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
_ = ctx
|
||||||
|
writeJSON(w, http.StatusAccepted, map[string]any{"ok": true, "mediaType": mediaType, "stage": stage, "started": true})
|
||||||
|
}
|
||||||
|
|
||||||
|
// mediaTypeErrorCondition returns a media_worker_jobs WHERE fragment for one media type, and the
|
||||||
|
// single arg it needs (if any) - the same "funscript" special-case analyzerHistory and
|
||||||
|
// parseMediaTypesPayload use, since it isn't a real media_type value on that table, just the
|
||||||
|
// has_funscript flag on a video/audio row.
|
||||||
|
func mediaTypeErrorCondition(mediaType string) (string, []any) {
|
||||||
|
if mediaType == "funscript" {
|
||||||
|
return "has_funscript = TRUE", nil
|
||||||
|
}
|
||||||
|
return "LOWER(COALESCE(media_type, '')) = $1", []any{mediaType}
|
||||||
|
}
|
||||||
|
|
||||||
|
type pipelineStageError struct {
|
||||||
|
FilePath string `json:"filePath"`
|
||||||
|
Error string `json:"error"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// pipelineStageErrors returns the most recent error messages recorded for one media type's one
|
||||||
|
// pipeline stage, so the "Show errors" button next to Retry (see PipelineFlowDiagram.svelte) can
|
||||||
|
// display what's actually failing instead of just the count already shown in the breakdown.
|
||||||
|
func (s *Server) pipelineStageErrors(w http.ResponseWriter, r *http.Request, mediaType, stage string) {
|
||||||
|
ctx := r.Context()
|
||||||
|
limit := optionalInt(r.URL.Query().Get("limit"), 20, 1, 100)
|
||||||
|
items := make([]pipelineStageError, 0)
|
||||||
|
|
||||||
|
var query string
|
||||||
|
var args []any
|
||||||
|
switch stage {
|
||||||
|
case "metadata":
|
||||||
|
condition, condArgs := mediaTypeErrorCondition(mediaType)
|
||||||
|
query = fmt.Sprintf(`SELECT file_path, COALESCE(metadata_error, '') FROM media_worker_jobs
|
||||||
|
WHERE metadata_status = 'error' AND %s ORDER BY finished_at DESC NULLS LAST LIMIT $%d`, condition, len(condArgs)+1)
|
||||||
|
args = append(condArgs, limit)
|
||||||
|
case "thumbnails":
|
||||||
|
condition, condArgs := mediaTypeErrorCondition(mediaType)
|
||||||
|
query = fmt.Sprintf(`SELECT file_path, COALESCE(thumbnail_error, '') FROM media_worker_jobs
|
||||||
|
WHERE thumbnail_status = 'error' AND %s ORDER BY finished_at DESC NULLS LAST LIMIT $%d`, condition, len(condArgs)+1)
|
||||||
|
args = append(condArgs, limit)
|
||||||
|
case "analyze":
|
||||||
|
query = `SELECT media_key, COALESCE(error_message, '') FROM media_analysis_tasks
|
||||||
|
WHERE status = 'error' AND LOWER(media_type) = $1 ORDER BY finished_at DESC NULLS LAST LIMIT $2`
|
||||||
|
args = []any{mediaType, limit}
|
||||||
|
default:
|
||||||
|
writeError(w, http.StatusBadRequest, "unknown pipeline stage")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
rows, err := s.db.Query(ctx, query, args...)
|
||||||
|
if err != nil {
|
||||||
|
writeError(w, http.StatusInternalServerError, "pipeline errors unavailable")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
for rows.Next() {
|
||||||
|
var item pipelineStageError
|
||||||
|
if rows.Scan(&item.FilePath, &item.Error) == nil && item.Error != "" {
|
||||||
|
items = append(items, item)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
writeJSON(w, http.StatusOK, map[string]any{"ok": true, "mediaType": mediaType, "stage": stage, "errors": items})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Server) retryMetadataErrors(mediaType string) {
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Minute)
|
||||||
|
defer cancel()
|
||||||
|
rows, err := s.db.Query(ctx, `
|
||||||
|
SELECT file_path FROM media_worker_jobs
|
||||||
|
WHERE LOWER(COALESCE(media_type, '')) = $1 AND metadata_status = 'error'`, mediaType)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
filePaths := make([]string, 0)
|
||||||
|
for rows.Next() {
|
||||||
|
var filePath string
|
||||||
|
if rows.Scan(&filePath) == nil {
|
||||||
|
filePaths = append(filePaths, filePath)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
rows.Close()
|
||||||
|
|
||||||
|
for _, filePath := range filePaths {
|
||||||
|
if ctx.Err() != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if probe, probeErr := s.servantProbe(ctx, filepath.ToSlash(filePath)); probeErr != nil {
|
||||||
|
_, _ = s.db.Exec(ctx, `UPDATE media_worker_jobs SET metadata_status='error', metadata_error=$2 WHERE file_path=$1`, filePath, probeErr.Error())
|
||||||
|
} else {
|
||||||
|
duration := nullableInt64(probe.DurationMs)
|
||||||
|
width, height := probe.Width, probe.Height
|
||||||
|
_, _ = s.db.Exec(ctx, `UPDATE media SET duration_ms = COALESCE($2, duration_ms), width = COALESCE($3, width), height = COALESCE($4, height) WHERE file_path = $1`, filePath, duration, nullableInt(width), nullableInt(height))
|
||||||
|
_, _ = s.db.Exec(ctx, `UPDATE media_worker_jobs SET metadata_status='completed', metadata_error=NULL WHERE file_path=$1`, filePath)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Server) retryThumbnailErrors(mediaType string) {
|
||||||
|
s.thumbnailMu.Lock()
|
||||||
|
if s.thumbnail.Running {
|
||||||
|
s.thumbnailMu.Unlock()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
ctx, cancel := context.WithCancel(context.Background())
|
||||||
|
now := time.Now().UTC()
|
||||||
|
s.thumbnail = thumbnailGenerationState{Running: true, State: "running", StartedAt: &now}
|
||||||
|
s.thumbnailCancel = cancel
|
||||||
|
s.thumbnailMu.Unlock()
|
||||||
|
|
||||||
|
candidates, err := s.thumbnailCandidatesWithErrors(ctx, mediaType)
|
||||||
|
if err != nil {
|
||||||
|
s.finishThumbnailGeneration(err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
s.runThumbnailCandidates(ctx, candidates)
|
||||||
|
}
|
||||||
@@ -0,0 +1,139 @@
|
|||||||
|
package server
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"log"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
// runAnalyzerScheduler polls due, enabled workflow_schedules for this service and runs them. It's
|
||||||
|
// deliberately a simple poll loop rather than a precise cron: schedules only ever run on
|
||||||
|
// minute-scale intervals, so "checked every 30s, run when due" is accurate enough and far simpler
|
||||||
|
// than tracking individual timers per schedule.
|
||||||
|
func (s *Server) runAnalyzerScheduler(ctx context.Context) {
|
||||||
|
ticker := time.NewTicker(30 * time.Second)
|
||||||
|
defer ticker.Stop()
|
||||||
|
for {
|
||||||
|
select {
|
||||||
|
case <-ctx.Done():
|
||||||
|
return
|
||||||
|
case <-ticker.C:
|
||||||
|
s.runDueAnalyzerSchedules(ctx)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Server) runDueAnalyzerSchedules(ctx context.Context) {
|
||||||
|
rows, err := s.db.Query(ctx, `
|
||||||
|
SELECT id, tool, settings
|
||||||
|
FROM workflow_schedules
|
||||||
|
WHERE service = $1 AND enabled = TRUE AND (next_run_at IS NULL OR next_run_at <= NOW())`, s.cfg.ServiceName)
|
||||||
|
if err != nil {
|
||||||
|
log.Printf("analyzer: schedule poll: failed to load due schedules: %v", err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
type due struct {
|
||||||
|
id, tool string
|
||||||
|
settings []byte
|
||||||
|
}
|
||||||
|
items := make([]due, 0)
|
||||||
|
for rows.Next() {
|
||||||
|
var item due
|
||||||
|
if rows.Scan(&item.id, &item.tool, &item.settings) == nil {
|
||||||
|
items = append(items, item)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
rows.Close()
|
||||||
|
|
||||||
|
for _, item := range items {
|
||||||
|
if ctx.Err() != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
var parsed struct {
|
||||||
|
Types []string `json:"types"`
|
||||||
|
}
|
||||||
|
_ = json.Unmarshal(item.settings, &parsed)
|
||||||
|
types := normalizeMediaTypes(parsed.Types, true)
|
||||||
|
|
||||||
|
status := "started"
|
||||||
|
started, err := s.startAnalyzerScheduledRun(item.tool, types)
|
||||||
|
switch {
|
||||||
|
case err != nil:
|
||||||
|
status = "error: " + err.Error()
|
||||||
|
case !started:
|
||||||
|
status = "skipped: busy"
|
||||||
|
}
|
||||||
|
log.Printf("analyzer: automation schedule %s fired (tool=%s): %s", item.id, item.tool, status)
|
||||||
|
// Always advance next_run_at, even on skip/error, so a busy or misconfigured schedule
|
||||||
|
// doesn't get retried on every single tick - it just waits for its normal interval instead.
|
||||||
|
_, _ = s.db.Exec(ctx, `
|
||||||
|
UPDATE workflow_schedules
|
||||||
|
SET last_run_at = NOW(), last_status = $2, next_run_at = NOW() + make_interval(mins => interval_minutes), updated_at = NOW()
|
||||||
|
WHERE id = $1`, item.id, status)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// startAnalyzerScheduledRun dispatches one schedule's action exactly the way its corresponding
|
||||||
|
// manual-trigger HTTP handler does: guard the relevant busy-state slot, then hand off to the same
|
||||||
|
// background worker function used everywhere else. "started" is false (not an error) when that
|
||||||
|
// slot was already busy - the schedule just waits for its next tick rather than queuing up or
|
||||||
|
// failing loudly, mirroring how the dashboard's own buttons behave under the same condition.
|
||||||
|
func (s *Server) startAnalyzerScheduledRun(tool string, types map[string]bool) (bool, error) {
|
||||||
|
now := time.Now().UTC()
|
||||||
|
switch tool {
|
||||||
|
case "discover":
|
||||||
|
s.scanMu.Lock()
|
||||||
|
if s.scan.Running {
|
||||||
|
s.scanMu.Unlock()
|
||||||
|
return false, nil
|
||||||
|
}
|
||||||
|
s.scan = scanState{Running: true, Mode: "discover", StartedAt: &now}
|
||||||
|
s.scanMu.Unlock()
|
||||||
|
go s.scanMediaFiles(types)
|
||||||
|
case "metadata":
|
||||||
|
s.scanMu.Lock()
|
||||||
|
if s.scan.Running {
|
||||||
|
s.scanMu.Unlock()
|
||||||
|
return false, nil
|
||||||
|
}
|
||||||
|
s.scan = scanState{Running: true, Mode: "metadata", StartedAt: &now}
|
||||||
|
s.scanMu.Unlock()
|
||||||
|
go s.refreshMetadataForTypes(types)
|
||||||
|
case "cleanup":
|
||||||
|
s.scanMu.Lock()
|
||||||
|
if s.scan.Running {
|
||||||
|
s.scanMu.Unlock()
|
||||||
|
return false, nil
|
||||||
|
}
|
||||||
|
s.scan = scanState{Running: true, Mode: "cleanup", StartedAt: &now}
|
||||||
|
s.scanMu.Unlock()
|
||||||
|
go s.cleanupStaleMedia()
|
||||||
|
case "thumbnails":
|
||||||
|
s.thumbnailMu.Lock()
|
||||||
|
if s.thumbnail.Running {
|
||||||
|
s.thumbnailMu.Unlock()
|
||||||
|
return false, nil
|
||||||
|
}
|
||||||
|
runCtx, cancel := context.WithCancel(context.Background())
|
||||||
|
s.thumbnail = thumbnailGenerationState{Running: true, State: "running", StartedAt: &now}
|
||||||
|
s.thumbnailCancel = cancel
|
||||||
|
s.thumbnailMu.Unlock()
|
||||||
|
go s.generateThumbnails(runCtx, types)
|
||||||
|
case "analyze":
|
||||||
|
s.analysisMu.Lock()
|
||||||
|
if s.analysis.Running {
|
||||||
|
s.analysisMu.Unlock()
|
||||||
|
return false, nil
|
||||||
|
}
|
||||||
|
runCtx, cancel := context.WithCancel(context.Background())
|
||||||
|
s.analysis = analysisState{Running: true, State: "running", StartedAt: &now}
|
||||||
|
s.analysisCancel = cancel
|
||||||
|
s.analysisMu.Unlock()
|
||||||
|
go s.runAiAnalysis(runCtx, mediaTypesList(types))
|
||||||
|
default:
|
||||||
|
return false, fmt.Errorf("unsupported schedule action: %s", tool)
|
||||||
|
}
|
||||||
|
return true, nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,195 @@
|
|||||||
|
package server
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"net/http"
|
||||||
|
"sort"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/coder/websocket"
|
||||||
|
"github.com/go-chi/chi/v5"
|
||||||
|
|
||||||
|
"mediacollection/internal/config"
|
||||||
|
)
|
||||||
|
|
||||||
|
type kioskMessage struct {
|
||||||
|
Type string `json:"type"`
|
||||||
|
QueueMode string `json:"queueMode,omitempty"`
|
||||||
|
DisplayDuration int64 `json:"displayDuration,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Server) kioskWebsocket(w http.ResponseWriter, r *http.Request) {
|
||||||
|
options := s.websocketAcceptOptions(r)
|
||||||
|
conn, err := websocket.Accept(w, r, options)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
defer conn.Close(websocket.StatusNormalClosure, "")
|
||||||
|
|
||||||
|
updates := make(chan []byte, 16)
|
||||||
|
s.kioskMu.Lock()
|
||||||
|
s.kioskClients[updates] = struct{}{}
|
||||||
|
latest := s.kioskLatest
|
||||||
|
s.kioskMu.Unlock()
|
||||||
|
defer func() {
|
||||||
|
s.kioskMu.Lock()
|
||||||
|
delete(s.kioskClients, updates)
|
||||||
|
s.kioskMu.Unlock()
|
||||||
|
}()
|
||||||
|
|
||||||
|
if latest != "" {
|
||||||
|
s.kioskSend(updates, map[string]any{"type": "new-image", "path": latest})
|
||||||
|
}
|
||||||
|
s.kioskSend(updates, map[string]any{
|
||||||
|
"type": "settings-updated",
|
||||||
|
"queueMode": s.settingValue(r.Context(), "kiosk_queue_mode", "client"),
|
||||||
|
"serverDisplayDuration": kioskDuration(s.settingValue(r.Context(), "server_display_duration", "5000")),
|
||||||
|
})
|
||||||
|
|
||||||
|
ctx := r.Context()
|
||||||
|
writeCtx, cancelWrite := context.WithCancel(ctx)
|
||||||
|
defer cancelWrite()
|
||||||
|
go func() {
|
||||||
|
for {
|
||||||
|
select {
|
||||||
|
case <-writeCtx.Done():
|
||||||
|
return
|
||||||
|
case data := <-updates:
|
||||||
|
if err := conn.Write(writeCtx, websocket.MessageText, data); err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
s.startKioskPoll()
|
||||||
|
for {
|
||||||
|
messageType, payload, readErr := conn.Read(ctx)
|
||||||
|
if readErr != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if messageType != websocket.MessageText {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
var message kioskMessage
|
||||||
|
if json.Unmarshal(payload, &message) != nil || message.Type != "update-settings" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if message.QueueMode != "" && (message.QueueMode == "client" || message.QueueMode == "server") {
|
||||||
|
_ = s.saveSetting(ctx, "kiosk_queue_mode", message.QueueMode)
|
||||||
|
}
|
||||||
|
if message.DisplayDuration >= 0 && message.DisplayDuration <= 24*60*60*1000 {
|
||||||
|
_ = s.saveSetting(ctx, "server_display_duration", formatInt(message.DisplayDuration))
|
||||||
|
}
|
||||||
|
s.kioskBroadcast(map[string]any{
|
||||||
|
"type": "settings-updated",
|
||||||
|
"queueMode": s.settingValue(ctx, "kiosk_queue_mode", "client"),
|
||||||
|
"serverDisplayDuration": kioskDuration(s.settingValue(ctx, "server_display_duration", "5000")),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Server) startKioskPoll() {
|
||||||
|
s.kioskMu.Lock()
|
||||||
|
if s.kioskPolling {
|
||||||
|
s.kioskMu.Unlock()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
s.kioskPolling = true
|
||||||
|
s.kioskMu.Unlock()
|
||||||
|
go s.kioskPoll(context.Background())
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Server) kioskPoll(ctx context.Context) {
|
||||||
|
if s.cfg.Service != config.Kiosk {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
ticker := time.NewTicker(3 * time.Second)
|
||||||
|
defer ticker.Stop()
|
||||||
|
for {
|
||||||
|
s.kioskPollOnce(ctx)
|
||||||
|
select {
|
||||||
|
case <-ctx.Done():
|
||||||
|
return
|
||||||
|
case <-ticker.C:
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Server) kioskPollOnce(ctx context.Context) {
|
||||||
|
files, err := s.servantListFiles(ctx, "", false, 0)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
images := make([]fileEntry, 0, len(files))
|
||||||
|
for _, file := range files {
|
||||||
|
if file.Type == "image" {
|
||||||
|
images = append(images, file)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(images) == 0 {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
sort.Slice(images, func(i, j int) bool { return images[i].Mtime > images[j].Mtime })
|
||||||
|
latest := images[0].Rel
|
||||||
|
s.kioskMu.Lock()
|
||||||
|
changed := latest != s.kioskLatest
|
||||||
|
s.kioskLatest = latest
|
||||||
|
s.kioskMu.Unlock()
|
||||||
|
if changed {
|
||||||
|
s.kioskBroadcast(map[string]any{"type": "new-image", "path": latest})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Server) kioskBroadcast(message any) {
|
||||||
|
data, err := json.Marshal(message)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
s.kioskMu.Lock()
|
||||||
|
defer s.kioskMu.Unlock()
|
||||||
|
for client := range s.kioskClients {
|
||||||
|
select {
|
||||||
|
case client <- data:
|
||||||
|
default:
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Server) kioskSend(client chan []byte, message any) {
|
||||||
|
data, err := json.Marshal(message)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
select {
|
||||||
|
case client <- data:
|
||||||
|
default:
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Server) kioskImage(w http.ResponseWriter, r *http.Request) {
|
||||||
|
relative := chi.URLParam(r, "*")
|
||||||
|
if relative == "" {
|
||||||
|
relative = strings.TrimPrefix(r.URL.Path, "/api/images/")
|
||||||
|
}
|
||||||
|
if !safeRelative(relative) || !isImagePath(relative) {
|
||||||
|
writeError(w, http.StatusNotFound, "image not found")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
s.proxyServant(w, r, "/media/"+urlPath(relative))
|
||||||
|
}
|
||||||
|
|
||||||
|
func kioskDuration(value string) int64 {
|
||||||
|
var duration int64
|
||||||
|
if _, err := fmt.Sscanf(value, "%d", &duration); err != nil || duration < 0 {
|
||||||
|
return 5000
|
||||||
|
}
|
||||||
|
return duration
|
||||||
|
}
|
||||||
|
|
||||||
|
func formatInt(value int64) string {
|
||||||
|
return strconv.FormatInt(value, 10)
|
||||||
|
}
|
||||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,83 @@
|
|||||||
|
package server
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestSafeRelativeRejectsTraversal(t *testing.T) {
|
||||||
|
for _, value := range []string{"", ".", "..", "../secret", `..\secret`, `/etc/passwd`, "a/../../b"} {
|
||||||
|
if safeRelative(value) {
|
||||||
|
t.Errorf("safeRelative(%q) = true", value)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, value := range []string{"video.mp4", "nested/image.webp", "funscript.json"} {
|
||||||
|
if !safeRelative(value) {
|
||||||
|
t.Errorf("safeRelative(%q) = false", value)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSameRealRootRejectsSymlinkEscape(t *testing.T) {
|
||||||
|
root := t.TempDir()
|
||||||
|
inside := filepath.Join(root, "inside.txt")
|
||||||
|
if err := os.WriteFile(inside, []byte("ok"), 0o600); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if !sameRealRoot(root, inside) {
|
||||||
|
t.Fatal("sameRealRoot rejected a file inside the root")
|
||||||
|
}
|
||||||
|
outside := t.TempDir()
|
||||||
|
outsideFile := filepath.Join(outside, "outside.txt")
|
||||||
|
if err := os.WriteFile(outsideFile, []byte("secret"), 0o600); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
link := filepath.Join(root, "link.txt")
|
||||||
|
if err := os.Symlink(outsideFile, link); err != nil {
|
||||||
|
t.Skipf("symlink unavailable: %v", err)
|
||||||
|
}
|
||||||
|
if sameRealRoot(root, link) {
|
||||||
|
t.Fatal("sameRealRoot accepted a symlink outside the root")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestConversionArgsDoNotAcceptArbitraryEncoderFlags(t *testing.T) {
|
||||||
|
args := strings.Join(conversionArgs("input.mp4", "output.mp4", "mp4", "-filter_complex malicious"), " ")
|
||||||
|
if strings.Contains(args, "malicious") || !strings.Contains(args, "libx264") {
|
||||||
|
t.Fatalf("conversion args = %q", args)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestHasFunscriptSidecar(t *testing.T) {
|
||||||
|
root := t.TempDir()
|
||||||
|
mediaPath := filepath.Join(root, "clip.mp4")
|
||||||
|
if os.WriteFile(mediaPath, []byte("media"), 0o600) != nil {
|
||||||
|
t.Fatal("could not create media fixture")
|
||||||
|
}
|
||||||
|
if hasFunscriptSidecar(mediaPath) {
|
||||||
|
t.Fatal("media without a sidecar was marked as having a funscript")
|
||||||
|
}
|
||||||
|
if os.WriteFile(filepath.Join(root, "clip.funscript"), []byte("{}"), 0o600) != nil {
|
||||||
|
t.Fatal("could not create funscript fixture")
|
||||||
|
}
|
||||||
|
if !hasFunscriptSidecar(mediaPath) {
|
||||||
|
t.Fatal("funscript sidecar was not detected")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestDownloadURLValidation(t *testing.T) {
|
||||||
|
for _, value := range []string{"file:///etc/passwd", "http://127.0.0.1/x", "http://169.254.169.254/", "https://user:pass@example.com/x"} {
|
||||||
|
if err := validateDownloadURL(value); err == nil {
|
||||||
|
t.Errorf("validateDownloadURL(%q) succeeded", value)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if err := validateDownloadURL("https://example.com/video"); err != nil {
|
||||||
|
t.Fatalf("public URL rejected: %v", err)
|
||||||
|
}
|
||||||
|
if !isPrivateIP(net.ParseIP("127.0.0.1")) {
|
||||||
|
t.Fatal("loopback was not classified as private")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,331 @@
|
|||||||
|
package server
|
||||||
|
|
||||||
|
// Servant client: every non-Servant service serves and stores media by calling MediaServant's
|
||||||
|
// HTTP API through the helpers in this file instead of touching MediaRoots/ThumbnailRoot/
|
||||||
|
// OutputRoot/DownloadsRoot/InputRoot/CopyRoot locally. Servant's own handlers keep using those
|
||||||
|
// roots directly (see media.go, admin_storage.go) - this file is never called from Servant's
|
||||||
|
// own code path.
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"net/http"
|
||||||
|
"net/url"
|
||||||
|
"os"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
// servantHTTPClient has no blanket timeout since it streams large media files; callers bound
|
||||||
|
// individual calls with a context deadline instead.
|
||||||
|
var servantHTTPClient = &http.Client{}
|
||||||
|
|
||||||
|
func (s *Server) servantClient() *http.Client {
|
||||||
|
return servantHTTPClient
|
||||||
|
}
|
||||||
|
|
||||||
|
// servantBaseURL is configured in MediaConfig and stored in the settings table (key
|
||||||
|
// "mediaservant_url", the same "{projectKey}_url" convention ConfigWorkspace.svelte uses for
|
||||||
|
// every project's connection URL) - not a static env var, so a change in MediaConfig takes
|
||||||
|
// effect on every service's very next request without a restart. SERVANT_URL is only the
|
||||||
|
// bootstrap fallback before that setting has ever been saved.
|
||||||
|
func (s *Server) servantBaseURL(ctx context.Context) string {
|
||||||
|
return strings.TrimRight(s.settingValue(ctx, "mediaservant_url", s.cfg.ServantURL), "/")
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Server) newServantRequest(ctx context.Context, method, path string, body io.Reader) (*http.Request, error) {
|
||||||
|
request, err := http.NewRequestWithContext(ctx, method, s.servantBaseURL(ctx)+path, body)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if s.cfg.InternalServiceSecret != "" {
|
||||||
|
request.Header.Set("X-Internal-Auth", s.cfg.InternalServiceSecret)
|
||||||
|
}
|
||||||
|
return request, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
var servantForwardRequestHeaders = []string{"Range", "If-Modified-Since", "If-None-Match", "If-Range"}
|
||||||
|
var servantForwardResponseHeaders = []string{"Content-Type", "Content-Length", "Content-Range", "Accept-Ranges", "Last-Modified", "ETag", "Content-Disposition"}
|
||||||
|
|
||||||
|
// proxyServant streams a Servant response straight through to the original client, preserving
|
||||||
|
// range/conditional-request semantics so video scrubbing keeps working without reimplementing
|
||||||
|
// http.ServeContent on this side.
|
||||||
|
func (s *Server) proxyServant(w http.ResponseWriter, r *http.Request, servantPath string) {
|
||||||
|
request, err := s.newServantRequest(r.Context(), r.Method, servantPath, nil)
|
||||||
|
if err != nil {
|
||||||
|
writeError(w, http.StatusBadGateway, "media service unavailable")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
for _, header := range servantForwardRequestHeaders {
|
||||||
|
if value := r.Header.Get(header); value != "" {
|
||||||
|
request.Header.Set(header, value)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
response, err := s.servantClient().Do(request)
|
||||||
|
if err != nil {
|
||||||
|
writeError(w, http.StatusBadGateway, "media service unavailable")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
defer response.Body.Close()
|
||||||
|
for _, header := range servantForwardResponseHeaders {
|
||||||
|
if value := response.Header.Get(header); value != "" {
|
||||||
|
w.Header().Set(header, value)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
w.WriteHeader(response.StatusCode)
|
||||||
|
if r.Method != http.MethodHead {
|
||||||
|
_, _ = io.Copy(w, response.Body)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// probeServant checks whether a Servant-served path exists without fetching its bytes.
|
||||||
|
// A 404 is reported as exists=false with a nil error, not a failure - only transport/5xx
|
||||||
|
// problems are surfaced as errors.
|
||||||
|
func (s *Server) probeServant(ctx context.Context, servantPath string) (bool, int64, time.Time, error) {
|
||||||
|
request, err := s.newServantRequest(ctx, http.MethodHead, servantPath, nil)
|
||||||
|
if err != nil {
|
||||||
|
return false, 0, time.Time{}, err
|
||||||
|
}
|
||||||
|
response, err := s.servantClient().Do(request)
|
||||||
|
if err != nil {
|
||||||
|
return false, 0, time.Time{}, err
|
||||||
|
}
|
||||||
|
defer response.Body.Close()
|
||||||
|
if response.StatusCode == http.StatusNotFound {
|
||||||
|
return false, 0, time.Time{}, nil
|
||||||
|
}
|
||||||
|
if response.StatusCode >= 400 {
|
||||||
|
return false, 0, time.Time{}, fmt.Errorf("servant probe failed: %s", response.Status)
|
||||||
|
}
|
||||||
|
size, _ := strconv.ParseInt(response.Header.Get("Content-Length"), 10, 64)
|
||||||
|
modTime, _ := http.ParseTime(response.Header.Get("Last-Modified"))
|
||||||
|
return true, size, modTime, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// fetchServantToScratch downloads a Servant-served path into an ephemeral temp file for local
|
||||||
|
// processing (ffmpeg/ffprobe/yt-dlp all need a real file handle). Callers must invoke the
|
||||||
|
// returned cleanup once done; it removes the scratch file unconditionally.
|
||||||
|
func (s *Server) fetchServantToScratch(ctx context.Context, servantPath, suffix string) (string, func(), error) {
|
||||||
|
request, err := s.newServantRequest(ctx, http.MethodGet, servantPath, nil)
|
||||||
|
if err != nil {
|
||||||
|
return "", nil, err
|
||||||
|
}
|
||||||
|
response, err := s.servantClient().Do(request)
|
||||||
|
if err != nil {
|
||||||
|
return "", nil, err
|
||||||
|
}
|
||||||
|
defer response.Body.Close()
|
||||||
|
if response.StatusCode != http.StatusOK {
|
||||||
|
return "", nil, fmt.Errorf("servant fetch failed: %s", response.Status)
|
||||||
|
}
|
||||||
|
scratch, err := os.CreateTemp("", "servant-src-*"+suffix)
|
||||||
|
if err != nil {
|
||||||
|
return "", nil, err
|
||||||
|
}
|
||||||
|
cleanup := func() { _ = os.Remove(scratch.Name()) }
|
||||||
|
if _, err := io.Copy(scratch, response.Body); err != nil {
|
||||||
|
scratch.Close()
|
||||||
|
cleanup()
|
||||||
|
return "", nil, err
|
||||||
|
}
|
||||||
|
if err := scratch.Close(); err != nil {
|
||||||
|
cleanup()
|
||||||
|
return "", nil, err
|
||||||
|
}
|
||||||
|
return scratch.Name(), cleanup, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// pushToServant streams a local file as the request body without buffering it in memory.
|
||||||
|
func (s *Server) pushToServant(ctx context.Context, method, servantPath, localPath string) (*http.Response, error) {
|
||||||
|
file, err := os.Open(localPath)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
defer file.Close()
|
||||||
|
request, err := s.newServantRequest(ctx, method, servantPath, file)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if info, statErr := file.Stat(); statErr == nil {
|
||||||
|
request.ContentLength = info.Size()
|
||||||
|
}
|
||||||
|
response, err := s.servantClient().Do(request)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if response.StatusCode >= 400 {
|
||||||
|
body, _ := io.ReadAll(io.LimitReader(response.Body, 4096))
|
||||||
|
response.Body.Close()
|
||||||
|
return nil, fmt.Errorf("servant push failed: %s: %s", response.Status, string(body))
|
||||||
|
}
|
||||||
|
return response, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func servantPushedSize(response *http.Response) int64 {
|
||||||
|
defer response.Body.Close()
|
||||||
|
var payload struct {
|
||||||
|
Size int64 `json:"size"`
|
||||||
|
}
|
||||||
|
_ = json.NewDecoder(response.Body).Decode(&payload)
|
||||||
|
return payload.Size
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Server) servantPushThumbnail(ctx context.Context, id, localPath string) (int64, error) {
|
||||||
|
response, err := s.pushToServant(ctx, http.MethodPost, "/api/thumbnails/"+url.PathEscape(id), localPath)
|
||||||
|
if err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
return servantPushedSize(response), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Server) servantDeleteThumbnail(ctx context.Context, id string) error {
|
||||||
|
request, err := s.newServantRequest(ctx, http.MethodDelete, "/api/thumbnails/"+url.PathEscape(id), nil)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
response, err := s.servantClient().Do(request)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
defer response.Body.Close()
|
||||||
|
if response.StatusCode >= 400 && response.StatusCode != http.StatusNotFound {
|
||||||
|
return fmt.Errorf("servant delete thumbnail failed: %s", response.Status)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Server) servantPushOutput(ctx context.Context, name, localPath string) (int64, error) {
|
||||||
|
response, err := s.pushToServant(ctx, http.MethodPost, "/api/outputs/"+url.PathEscape(name), localPath)
|
||||||
|
if err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
return servantPushedSize(response), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Server) servantPushInput(ctx context.Context, name, localPath string) (int64, error) {
|
||||||
|
response, err := s.pushToServant(ctx, http.MethodPost, "/api/inputs/"+url.PathEscape(name), localPath)
|
||||||
|
if err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
return servantPushedSize(response), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Server) servantPushCopy(ctx context.Context, name, localPath string) (int64, error) {
|
||||||
|
response, err := s.pushToServant(ctx, http.MethodPost, "/api/copies/"+url.PathEscape(name), localPath)
|
||||||
|
if err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
return servantPushedSize(response), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// servantUploadDownload streams a locally-produced file (e.g. a completed yt-dlp download
|
||||||
|
// staged in a scratch dir) into Servant's DownloadsRoot via its existing raw-upload endpoint.
|
||||||
|
func (s *Server) servantUploadDownload(ctx context.Context, localPath, filename string) (map[string]any, error) {
|
||||||
|
response, err := s.pushToServant(ctx, http.MethodPost, "/api/upload?filename="+url.QueryEscape(filename), localPath)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
defer response.Body.Close()
|
||||||
|
var payload map[string]any
|
||||||
|
_ = json.NewDecoder(response.Body).Decode(&payload)
|
||||||
|
return payload, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// servantStoreDownload catalogs an already-uploaded file into Servant's media/downloaded_media
|
||||||
|
// tables via its existing /api/store endpoint - callers should stop duplicating that DB write
|
||||||
|
// locally once they migrate to this.
|
||||||
|
func (s *Server) servantStoreDownload(ctx context.Context, filePath, sourceURL, tool, status string) (map[string]any, error) {
|
||||||
|
body, err := json.Marshal(map[string]any{"filePath": filePath, "sourceUrl": sourceURL, "tool": tool, "status": status})
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
request, err := s.newServantRequest(ctx, http.MethodPost, "/api/store", bytes.NewReader(body))
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
request.Header.Set("Content-Type", "application/json")
|
||||||
|
response, err := s.servantClient().Do(request)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
defer response.Body.Close()
|
||||||
|
if response.StatusCode >= 400 {
|
||||||
|
errorBody, _ := io.ReadAll(io.LimitReader(response.Body, 4096))
|
||||||
|
return nil, fmt.Errorf("servant store failed: %s: %s", response.Status, string(errorBody))
|
||||||
|
}
|
||||||
|
var payload map[string]any
|
||||||
|
_ = json.NewDecoder(response.Body).Decode(&payload)
|
||||||
|
return payload, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// servantListFiles lists files under Servant's MediaRoots via its existing /api/files(/recent)
|
||||||
|
// endpoints - the replacement for a local filepath.WalkDir over MediaRoots.
|
||||||
|
func (s *Server) servantListFiles(ctx context.Context, relative string, recent bool, limit int) ([]fileEntry, error) {
|
||||||
|
endpoint := "/api/files"
|
||||||
|
if recent {
|
||||||
|
endpoint = "/api/files/recent"
|
||||||
|
}
|
||||||
|
query := url.Values{}
|
||||||
|
if relative != "" {
|
||||||
|
query.Set("path", relative)
|
||||||
|
}
|
||||||
|
if limit > 0 {
|
||||||
|
query.Set("limit", strconv.Itoa(limit))
|
||||||
|
}
|
||||||
|
if encoded := query.Encode(); encoded != "" {
|
||||||
|
endpoint += "?" + encoded
|
||||||
|
}
|
||||||
|
request, err := s.newServantRequest(ctx, http.MethodGet, endpoint, nil)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
response, err := s.servantClient().Do(request)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
defer response.Body.Close()
|
||||||
|
if response.StatusCode != http.StatusOK {
|
||||||
|
return nil, fmt.Errorf("servant file listing failed: %s", response.Status)
|
||||||
|
}
|
||||||
|
var payload struct {
|
||||||
|
Files []fileEntry `json:"files"`
|
||||||
|
}
|
||||||
|
if err := json.NewDecoder(response.Body).Decode(&payload); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return payload.Files, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
type servantProbeResult struct {
|
||||||
|
DurationMs int64 `json:"durationMs"`
|
||||||
|
Width int `json:"width"`
|
||||||
|
Height int `json:"height"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// servantProbe runs ffprobe on Servant against a MediaRoots-relative path and returns just the
|
||||||
|
// metadata fields - bytes never leave Servant, unlike every other helper in this file.
|
||||||
|
func (s *Server) servantProbe(ctx context.Context, relative string) (servantProbeResult, error) {
|
||||||
|
query := url.Values{}
|
||||||
|
query.Set("path", relative)
|
||||||
|
request, err := s.newServantRequest(ctx, http.MethodGet, "/api/probe?"+query.Encode(), nil)
|
||||||
|
if err != nil {
|
||||||
|
return servantProbeResult{}, err
|
||||||
|
}
|
||||||
|
response, err := s.servantClient().Do(request)
|
||||||
|
if err != nil {
|
||||||
|
return servantProbeResult{}, err
|
||||||
|
}
|
||||||
|
defer response.Body.Close()
|
||||||
|
if response.StatusCode != http.StatusOK {
|
||||||
|
return servantProbeResult{}, fmt.Errorf("servant probe failed: %s", response.Status)
|
||||||
|
}
|
||||||
|
var result servantProbeResult
|
||||||
|
if err := json.NewDecoder(response.Body).Decode(&result); err != nil {
|
||||||
|
return servantProbeResult{}, err
|
||||||
|
}
|
||||||
|
return result, nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,433 @@
|
|||||||
|
package server
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"io/fs"
|
||||||
|
"log"
|
||||||
|
"net/http"
|
||||||
|
"os"
|
||||||
|
"path"
|
||||||
|
"runtime"
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/go-chi/chi/v5"
|
||||||
|
chimiddleware "github.com/go-chi/chi/v5/middleware"
|
||||||
|
"github.com/jackc/pgx/v5/pgxpool"
|
||||||
|
|
||||||
|
"mediacollection/internal/auth"
|
||||||
|
"mediacollection/internal/config"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Server struct {
|
||||||
|
cfg *config.Config
|
||||||
|
db *pgxpool.Pool
|
||||||
|
auth *auth.Service
|
||||||
|
startedAt time.Time
|
||||||
|
mediaMu sync.RWMutex
|
||||||
|
media map[string]MediaRecord
|
||||||
|
jobsMu sync.RWMutex
|
||||||
|
jobs map[string]*WorkflowJob
|
||||||
|
workflowSem chan struct{}
|
||||||
|
sync *syncHub
|
||||||
|
thumbnailMu sync.Mutex
|
||||||
|
thumbnail thumbnailGenerationState
|
||||||
|
thumbnailCancel context.CancelFunc
|
||||||
|
clearMu sync.Mutex
|
||||||
|
clear databaseClearState
|
||||||
|
scanMu sync.Mutex
|
||||||
|
scan scanState
|
||||||
|
scanCancel context.CancelFunc
|
||||||
|
analysisMu sync.Mutex
|
||||||
|
analysis analysisState
|
||||||
|
analysisCancel context.CancelFunc
|
||||||
|
kioskMu sync.Mutex
|
||||||
|
kioskClients map[chan []byte]struct{}
|
||||||
|
kioskLatest string
|
||||||
|
kioskPolling bool
|
||||||
|
}
|
||||||
|
|
||||||
|
type MediaRecord struct {
|
||||||
|
ID int64
|
||||||
|
MediaKey string
|
||||||
|
MediaType string
|
||||||
|
Title *string
|
||||||
|
Description *string
|
||||||
|
FilePath string
|
||||||
|
OriginalName string
|
||||||
|
Source string
|
||||||
|
Width *int
|
||||||
|
Height *int
|
||||||
|
DurationMs *int64
|
||||||
|
SizeBytes *int64
|
||||||
|
IsVR bool
|
||||||
|
HasFunscript bool
|
||||||
|
Speed *float32
|
||||||
|
ModifiedAt time.Time
|
||||||
|
}
|
||||||
|
|
||||||
|
type WorkflowJob struct {
|
||||||
|
ID string `json:"id"`
|
||||||
|
Service string `json:"service"`
|
||||||
|
Tool string `json:"tool"`
|
||||||
|
Status string `json:"status"`
|
||||||
|
Progress int `json:"progress"`
|
||||||
|
Request map[string]any `json:"request,omitempty"`
|
||||||
|
Result map[string]any `json:"result,omitempty"`
|
||||||
|
Error string `json:"error,omitempty"`
|
||||||
|
CreatedAt time.Time `json:"createdAt"`
|
||||||
|
StartedAt *time.Time `json:"startedAt,omitempty"`
|
||||||
|
FinishedAt *time.Time `json:"finishedAt,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type thumbnailGenerationState struct {
|
||||||
|
Running bool
|
||||||
|
State string
|
||||||
|
Total int
|
||||||
|
Completed int
|
||||||
|
Failed int
|
||||||
|
Current string
|
||||||
|
CurrentType string
|
||||||
|
StartedAt *time.Time
|
||||||
|
FinishedAt *time.Time
|
||||||
|
LastError string
|
||||||
|
}
|
||||||
|
|
||||||
|
// databaseClearState tracks a dashboard/per-media-type reset so it can be reported through the
|
||||||
|
// same live status endpoint as the analyzer workers. The reset itself is deliberately kept
|
||||||
|
// synchronous from the HTTP caller's perspective, but large libraries still need an honest state
|
||||||
|
// while their thumbnail files and database rows are being removed.
|
||||||
|
type databaseClearState struct {
|
||||||
|
Running bool
|
||||||
|
State string
|
||||||
|
Total int
|
||||||
|
Completed int
|
||||||
|
Failed int
|
||||||
|
Current string
|
||||||
|
CurrentType string
|
||||||
|
StartedAt *time.Time
|
||||||
|
FinishedAt *time.Time
|
||||||
|
LastError string
|
||||||
|
}
|
||||||
|
|
||||||
|
// scanState tracks the currently-running discover/metadata walk so the analyzer UI can show
|
||||||
|
// which media type is actively being indexed right now - scanMediaFiles has no separate queue,
|
||||||
|
// it indexes (and, per pipelineStageEnabled, extracts metadata for) each file synchronously as
|
||||||
|
// it's found, so "active" here is the closest honest signal to a live "processing" state.
|
||||||
|
type scanState struct {
|
||||||
|
Running bool
|
||||||
|
Mode string // "discover" (filesystem walk), "metadata" (refresh), or "cleanup" (stale sweep)
|
||||||
|
CurrentType string
|
||||||
|
CurrentFile string
|
||||||
|
FilesIndexed int64
|
||||||
|
// Total is only known upfront for metadata/cleanup - both pre-fetch their full row list before
|
||||||
|
// looping. discover has no total (a live filesystem walk doesn't know its own size in advance)
|
||||||
|
// and leaves this at zero, which the UI treats as "not available".
|
||||||
|
Total int64
|
||||||
|
StartedAt *time.Time
|
||||||
|
// LastError survives the end-of-run reset (unlike every other field here) so a run that
|
||||||
|
// failed fast - e.g. MediaServant unreachable - doesn't just look like it silently reverted
|
||||||
|
// to idle; analyzerStatus reports it until the next run overwrites or clears it.
|
||||||
|
LastError string
|
||||||
|
}
|
||||||
|
|
||||||
|
func New(cfg *config.Config, db *pgxpool.Pool) *Server {
|
||||||
|
return &Server{
|
||||||
|
cfg: cfg,
|
||||||
|
db: db,
|
||||||
|
auth: auth.New(db, cfg.SessionCookie, cfg.SecureCookies),
|
||||||
|
startedAt: time.Now(),
|
||||||
|
media: make(map[string]MediaRecord),
|
||||||
|
jobs: make(map[string]*WorkflowJob),
|
||||||
|
workflowSem: make(chan struct{}, 2),
|
||||||
|
sync: newSyncHub(),
|
||||||
|
thumbnail: thumbnailGenerationState{State: "idle"},
|
||||||
|
analysis: analysisState{State: "idle"},
|
||||||
|
kioskClients: make(map[chan []byte]struct{}),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Server) Handler() http.Handler {
|
||||||
|
router := chi.NewRouter()
|
||||||
|
router.Use(chimiddleware.RequestID)
|
||||||
|
router.Use(chimiddleware.Recoverer)
|
||||||
|
router.Use(s.securityHeadersMiddleware)
|
||||||
|
router.Use(s.cors)
|
||||||
|
|
||||||
|
router.Get("/healthz", s.health)
|
||||||
|
router.Get("/health", s.health)
|
||||||
|
router.Get("/ready", s.ready)
|
||||||
|
router.With(s.auth.RequireIfLoginRequired).Get("/api/tech-stack", s.techStack)
|
||||||
|
router.Get("/__cache-policy", s.cachePolicy)
|
||||||
|
|
||||||
|
router.Route("/auth", func(r chi.Router) {
|
||||||
|
r.Post("/signup", s.auth.Signup)
|
||||||
|
r.Post("/login", s.auth.Login)
|
||||||
|
r.Post("/logout", s.auth.Logout)
|
||||||
|
r.Post("/reset/request", s.auth.RequestAdminReset)
|
||||||
|
r.Post("/reset/confirm", s.auth.ConfirmAdminReset)
|
||||||
|
r.Get("/me", s.auth.Me)
|
||||||
|
r.With(s.auth.Require).Put("/me", s.auth.UpdateMe)
|
||||||
|
r.Get("/status", s.auth.Status)
|
||||||
|
r.Get("/bootstrap/admin-needed", s.auth.AdminNeeded)
|
||||||
|
})
|
||||||
|
router.Route("/api/auth", func(r chi.Router) {
|
||||||
|
manager := r.With(s.auth.RequireUserManager)
|
||||||
|
manager.Get("/access", s.auth.AccessSettings)
|
||||||
|
manager.Put("/access", s.auth.UpdateAccessSettings)
|
||||||
|
manager.Get("/users", s.auth.ManagedUsers)
|
||||||
|
manager.Post("/users", s.auth.ManagedCreateUser)
|
||||||
|
manager.Put("/users/{id}", s.auth.ManagedUpdateUser)
|
||||||
|
manager.Patch("/users/{id}", s.auth.ManagedUpdateUser)
|
||||||
|
manager.Delete("/users/{id}", s.auth.ManagedDeleteUser)
|
||||||
|
})
|
||||||
|
router.Route("/api", func(r chi.Router) {
|
||||||
|
s.mountServiceRoutes(r)
|
||||||
|
})
|
||||||
|
|
||||||
|
if s.cfg.Service == config.Kiosk {
|
||||||
|
s.mountKioskSocket(router)
|
||||||
|
}
|
||||||
|
if s.cfg.Service != config.Kiosk {
|
||||||
|
router.HandleFunc("/ws", s.syncWebsocket)
|
||||||
|
}
|
||||||
|
if s.cfg.Service == config.Servant {
|
||||||
|
internal := s.internalServiceAuth
|
||||||
|
router.Handle("/media/downloads/*", internal(http.HandlerFunc(s.servantDownloadMedia)))
|
||||||
|
router.Handle("/mount/generated/*", internal(http.HandlerFunc(s.servantGeneratedMedia)))
|
||||||
|
router.Handle("/mount/inputs/*", internal(http.HandlerFunc(s.servantInputMedia)))
|
||||||
|
router.Handle("/mount/copies/*", internal(http.HandlerFunc(s.servantCopyMedia)))
|
||||||
|
router.Handle("/media/*", internal(http.HandlerFunc(s.servantMedia)))
|
||||||
|
router.Handle("/thumbnails/*", internal(http.HandlerFunc(s.servantThumbnail)))
|
||||||
|
}
|
||||||
|
|
||||||
|
router.NotFound(s.staticHandler)
|
||||||
|
return router
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Server) mountServiceRoutes(r chi.Router) {
|
||||||
|
s.mountSharedRoutes(r)
|
||||||
|
switch s.cfg.Service {
|
||||||
|
case config.Viewer:
|
||||||
|
s.mountViewerRoutes(r)
|
||||||
|
case config.Tools:
|
||||||
|
s.mountToolsRoutes(r)
|
||||||
|
case config.Analyzer:
|
||||||
|
s.mountAnalyzerRoutes(r)
|
||||||
|
case config.ConfigService:
|
||||||
|
s.mountConfigRoutes(r)
|
||||||
|
case config.Moderator:
|
||||||
|
s.mountModeratorRoutes(r)
|
||||||
|
case config.Kiosk:
|
||||||
|
s.mountKioskRoutes(r)
|
||||||
|
case config.Servant:
|
||||||
|
s.mountServantRoutes(r)
|
||||||
|
case config.Desktop:
|
||||||
|
s.mountDesktopRoutes(r)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Server) securityHeadersMiddleware(next http.Handler) http.Handler {
|
||||||
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
w.Header().Set("X-Content-Type-Options", "nosniff")
|
||||||
|
w.Header().Set("X-Frame-Options", "DENY")
|
||||||
|
w.Header().Set("Referrer-Policy", "same-origin")
|
||||||
|
w.Header().Set("Permissions-Policy", "camera=(), microphone=(), geolocation=()")
|
||||||
|
w.Header().Set("Content-Security-Policy", "default-src 'self'; base-uri 'self'; object-src 'none'; frame-ancestors 'none'; img-src 'self' data: blob:; media-src 'self' blob:; style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline'; connect-src 'self' ws: wss:")
|
||||||
|
next.ServeHTTP(w, r)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Server) cors(next http.Handler) http.Handler {
|
||||||
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
origin := r.Header.Get("Origin")
|
||||||
|
if origin != "" && (s.cfg.AllowedOrigin == "*" || origin == s.cfg.AllowedOrigin) {
|
||||||
|
w.Header().Set("Access-Control-Allow-Origin", origin)
|
||||||
|
w.Header().Set("Access-Control-Allow-Credentials", "true")
|
||||||
|
w.Header().Add("Vary", "Origin")
|
||||||
|
}
|
||||||
|
if r.Method == http.MethodOptions {
|
||||||
|
w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, PATCH, DELETE, OPTIONS")
|
||||||
|
w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization, X-Internal-Auth")
|
||||||
|
w.WriteHeader(http.StatusNoContent)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
next.ServeHTTP(w, r)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Server) health(w http.ResponseWriter, _ *http.Request) {
|
||||||
|
writeJSON(w, http.StatusOK, map[string]any{"ok": true, "service": s.cfg.ServiceName, "uptimeSeconds": int(time.Since(s.startedAt).Seconds())})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Server) ready(w http.ResponseWriter, r *http.Request) {
|
||||||
|
if s.db == nil {
|
||||||
|
writeJSON(w, http.StatusServiceUnavailable, map[string]any{"ok": false, "service": s.cfg.ServiceName, "error": "database unavailable"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
ctx, cancel := context.WithTimeout(r.Context(), 2*time.Second)
|
||||||
|
defer cancel()
|
||||||
|
if err := s.db.Ping(ctx); err != nil {
|
||||||
|
writeJSON(w, http.StatusServiceUnavailable, map[string]any{"ok": false, "service": s.cfg.ServiceName, "error": "database unavailable"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
writeJSON(w, http.StatusOK, map[string]any{"ok": true, "service": s.cfg.ServiceName})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Server) techStack(w http.ResponseWriter, _ *http.Request) {
|
||||||
|
appVersion := os.Getenv("APP_VERSION")
|
||||||
|
if appVersion == "" {
|
||||||
|
appVersion = "go-rewrite"
|
||||||
|
}
|
||||||
|
writeJSON(w, http.StatusOK, map[string]any{
|
||||||
|
"appVersion": appVersion,
|
||||||
|
"stack": []map[string]string{
|
||||||
|
{"label": "Runtime", "value": runtime.Version()},
|
||||||
|
{"label": "HTTP", "value": "net/http + chi"},
|
||||||
|
{"label": "Database", "value": "PostgreSQL + pgx"},
|
||||||
|
{"label": "Authentication", "value": "bcrypt + PostgreSQL sessions"},
|
||||||
|
},
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Server) cachePolicy(w http.ResponseWriter, _ *http.Request) {
|
||||||
|
writeJSON(w, http.StatusOK, map[string]any{"service": s.cfg.ServiceName, "policies": map[string]string{"static": "public, max-age=3600", "media": "private, max-age=0, must-revalidate"}})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Server) staticHandler(w http.ResponseWriter, r *http.Request) {
|
||||||
|
root := os.DirFS(s.cfg.WebRoot)
|
||||||
|
if _, err := fs.Stat(root, "."); err != nil {
|
||||||
|
writeJSON(w, http.StatusNotFound, map[string]string{"error": "frontend build not found"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
requested := strings.TrimPrefix(path.Clean("/"+r.URL.Path), "/")
|
||||||
|
if requested == "." || requested == "" {
|
||||||
|
requested = "index.html"
|
||||||
|
}
|
||||||
|
if info, err := fs.Stat(root, requested); err == nil && !info.IsDir() {
|
||||||
|
http.FileServer(http.FS(root)).ServeHTTP(w, r)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if path.Ext(requested) != "" {
|
||||||
|
http.NotFound(w, r)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
index, err := fs.ReadFile(root, "index.html")
|
||||||
|
if err != nil {
|
||||||
|
http.NotFound(w, r)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||||
|
_, _ = w.Write(index)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Server) listenAndServe(ctx context.Context) error {
|
||||||
|
server := &http.Server{Addr: ":" + s.cfg.Port, Handler: s.Handler(), ReadHeaderTimeout: 10 * time.Second, ReadTimeout: 30 * time.Second, WriteTimeout: 0, IdleTimeout: 60 * time.Second}
|
||||||
|
go func() {
|
||||||
|
<-ctx.Done()
|
||||||
|
shutdownCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||||
|
defer cancel()
|
||||||
|
_ = server.Shutdown(shutdownCtx)
|
||||||
|
}()
|
||||||
|
log.Printf("%s listening on http://:%s (Go)", s.cfg.ServiceName, s.cfg.Port)
|
||||||
|
if s.cfg.TLSCertFile != "" {
|
||||||
|
return server.ListenAndServeTLS(s.cfg.TLSCertFile, s.cfg.TLSKeyFile)
|
||||||
|
}
|
||||||
|
return server.ListenAndServe()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Server) Run(ctx context.Context) error {
|
||||||
|
go s.resumeWorkflowJobs(ctx)
|
||||||
|
if s.cfg.Service == config.Analyzer {
|
||||||
|
go s.runAnalyzerScheduler(ctx)
|
||||||
|
}
|
||||||
|
return s.listenAndServe(ctx)
|
||||||
|
}
|
||||||
|
|
||||||
|
func writeJSON(w http.ResponseWriter, status int, value any) {
|
||||||
|
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||||
|
w.WriteHeader(status)
|
||||||
|
_ = json.NewEncoder(w).Encode(value)
|
||||||
|
}
|
||||||
|
|
||||||
|
func writeError(w http.ResponseWriter, status int, message string) {
|
||||||
|
writeJSON(w, status, map[string]string{"error": message, "message": message})
|
||||||
|
}
|
||||||
|
|
||||||
|
func stringValue(value *string) string {
|
||||||
|
if value == nil {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
return *value
|
||||||
|
}
|
||||||
|
|
||||||
|
func intValue(value *int) any {
|
||||||
|
if value == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return *value
|
||||||
|
}
|
||||||
|
|
||||||
|
func int64Value(value *int64) any {
|
||||||
|
if value == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return *value
|
||||||
|
}
|
||||||
|
|
||||||
|
func floatValue(value *float32) any {
|
||||||
|
if value == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return *value
|
||||||
|
}
|
||||||
|
|
||||||
|
func boolQuery(value string) *bool {
|
||||||
|
switch strings.ToLower(strings.TrimSpace(value)) {
|
||||||
|
case "1", "true", "yes", "on":
|
||||||
|
result := true
|
||||||
|
return &result
|
||||||
|
case "0", "false", "no", "off":
|
||||||
|
result := false
|
||||||
|
return &result
|
||||||
|
default:
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Server) internalServiceAuth(next http.Handler) http.Handler {
|
||||||
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
if s.cfg.InternalServiceSecret == "" || r.Header.Get("X-Internal-Auth") != s.cfg.InternalServiceSecret {
|
||||||
|
writeError(w, http.StatusUnauthorized, "internal service authentication required")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
next.ServeHTTP(w, r)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Server) requireAdminOrInternal(next http.Handler) http.Handler {
|
||||||
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
if auth.IsAdmin(auth.UserFromContext(r.Context())) || (s.cfg.InternalServiceSecret != "" && r.Header.Get("X-Internal-Auth") == s.cfg.InternalServiceSecret) {
|
||||||
|
next.ServeHTTP(w, r)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
writeError(w, http.StatusUnauthorized, "administrator or internal service authentication required")
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func optionalInt(value string, fallback, minimum, maximum int) int {
|
||||||
|
var parsed int
|
||||||
|
if _, err := fmt.Sscanf(strings.TrimSpace(value), "%d", &parsed); err != nil {
|
||||||
|
return fallback
|
||||||
|
}
|
||||||
|
if parsed < minimum {
|
||||||
|
return minimum
|
||||||
|
}
|
||||||
|
if parsed > maximum {
|
||||||
|
return maximum
|
||||||
|
}
|
||||||
|
return parsed
|
||||||
|
}
|
||||||
@@ -0,0 +1,541 @@
|
|||||||
|
package server
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"math"
|
||||||
|
"net/http"
|
||||||
|
"net/url"
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/coder/websocket"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
maxSyncIdentifier = 128
|
||||||
|
maxSyncSessions = 1000
|
||||||
|
)
|
||||||
|
|
||||||
|
type syncPeer struct {
|
||||||
|
conn *websocket.Conn
|
||||||
|
writeMu sync.Mutex
|
||||||
|
clientID string
|
||||||
|
sessionID string
|
||||||
|
userAgent string
|
||||||
|
ipAddress string
|
||||||
|
remoteControlEnabled bool
|
||||||
|
uiView string
|
||||||
|
uiMediaID any
|
||||||
|
uiMediaIDSet bool
|
||||||
|
}
|
||||||
|
|
||||||
|
type syncHub struct {
|
||||||
|
mu sync.Mutex
|
||||||
|
peers map[*syncPeer]struct{}
|
||||||
|
states map[string]map[string]any
|
||||||
|
playAt map[string]string
|
||||||
|
playAtLocalMs map[string]int64
|
||||||
|
capturedAtMs map[string]int64
|
||||||
|
controlOwners map[string]string
|
||||||
|
}
|
||||||
|
|
||||||
|
func newSyncHub() *syncHub {
|
||||||
|
return &syncHub{
|
||||||
|
peers: make(map[*syncPeer]struct{}),
|
||||||
|
states: make(map[string]map[string]any),
|
||||||
|
playAt: make(map[string]string),
|
||||||
|
playAtLocalMs: make(map[string]int64),
|
||||||
|
capturedAtMs: make(map[string]int64),
|
||||||
|
controlOwners: make(map[string]string),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *syncHub) add(peer *syncPeer) {
|
||||||
|
h.mu.Lock()
|
||||||
|
h.peers[peer] = struct{}{}
|
||||||
|
h.mu.Unlock()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *syncHub) remove(peer *syncPeer) string {
|
||||||
|
h.mu.Lock()
|
||||||
|
defer h.mu.Unlock()
|
||||||
|
delete(h.peers, peer)
|
||||||
|
if peer.clientID != "" && !h.hasClientLocked(peer.clientID) {
|
||||||
|
delete(h.controlOwners, peer.clientID)
|
||||||
|
for targetID, ownerID := range h.controlOwners {
|
||||||
|
if ownerID == peer.clientID {
|
||||||
|
delete(h.controlOwners, targetID)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return peer.sessionID
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *syncHub) hasClientLocked(clientID string) bool {
|
||||||
|
for peer := range h.peers {
|
||||||
|
if peer.clientID == clientID {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *syncHub) updatePeer(peer *syncPeer, clientID, sessionID string) {
|
||||||
|
h.mu.Lock()
|
||||||
|
if clientID != "" {
|
||||||
|
peer.clientID = clientID
|
||||||
|
}
|
||||||
|
if sessionID != "" {
|
||||||
|
peer.sessionID = sessionID
|
||||||
|
}
|
||||||
|
h.mu.Unlock()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *syncHub) clientStatus(peer *syncPeer, sessionID, view string, mediaID any, mediaIDSet bool, remoteSet, remote bool) {
|
||||||
|
h.mu.Lock()
|
||||||
|
defer h.mu.Unlock()
|
||||||
|
if sessionID != "" {
|
||||||
|
peer.sessionID = sessionID
|
||||||
|
}
|
||||||
|
if view != "" {
|
||||||
|
peer.uiView = view
|
||||||
|
}
|
||||||
|
if mediaIDSet {
|
||||||
|
peer.uiMediaID = mediaID
|
||||||
|
peer.uiMediaIDSet = true
|
||||||
|
}
|
||||||
|
if remoteSet {
|
||||||
|
peer.remoteControlEnabled = remote
|
||||||
|
if !remote && h.controlOwners[peer.clientID] != "" {
|
||||||
|
delete(h.controlOwners, peer.clientID)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *syncHub) clientsLocked(sessionID string) []map[string]any {
|
||||||
|
byID := make(map[string]map[string]any)
|
||||||
|
for peer := range h.peers {
|
||||||
|
if peer.sessionID != sessionID || peer.clientID == "" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
entry, exists := byID[peer.clientID]
|
||||||
|
if !exists {
|
||||||
|
entry = map[string]any{
|
||||||
|
"clientId": peer.clientID,
|
||||||
|
"userAgent": peer.userAgent,
|
||||||
|
"ipAddress": peer.ipAddress,
|
||||||
|
"remoteControlEnabled": peer.remoteControlEnabled,
|
||||||
|
"controlOwnerClientId": nil,
|
||||||
|
}
|
||||||
|
byID[peer.clientID] = entry
|
||||||
|
} else if peer.remoteControlEnabled {
|
||||||
|
entry["remoteControlEnabled"] = true
|
||||||
|
}
|
||||||
|
if peer.uiView != "" {
|
||||||
|
entry["uiView"] = peer.uiView
|
||||||
|
}
|
||||||
|
if peer.uiMediaIDSet {
|
||||||
|
entry["uiMediaId"] = peer.uiMediaID
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for clientID, entry := range byID {
|
||||||
|
if owner := h.controlOwners[clientID]; owner != "" {
|
||||||
|
entry["controlOwnerClientId"] = owner
|
||||||
|
}
|
||||||
|
}
|
||||||
|
clients := make([]map[string]any, 0, len(byID))
|
||||||
|
for _, entry := range byID {
|
||||||
|
clients = append(clients, entry)
|
||||||
|
}
|
||||||
|
return clients
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *syncHub) stateLocked(sessionID string) map[string]any {
|
||||||
|
state, ok := h.states[sessionID]
|
||||||
|
if !ok {
|
||||||
|
return map[string]any{
|
||||||
|
"sessionId": sessionID,
|
||||||
|
"mediaId": nil,
|
||||||
|
"timeMs": int64(0),
|
||||||
|
"paused": true,
|
||||||
|
"fps": 30,
|
||||||
|
"frame": int64(0),
|
||||||
|
"fromClientId": "",
|
||||||
|
"updatedAt": time.Unix(0, 0).UTC().Format(time.RFC3339Nano),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return cloneMap(state)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *syncHub) httpState(sessionID string) map[string]any {
|
||||||
|
h.mu.Lock()
|
||||||
|
defer h.mu.Unlock()
|
||||||
|
return h.timingLocked(sessionID, h.stateLocked(sessionID))
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *syncHub) setHTTPState(sessionID string, state map[string]any) {
|
||||||
|
h.mu.Lock()
|
||||||
|
defer h.mu.Unlock()
|
||||||
|
h.states[sessionID] = cloneMap(state)
|
||||||
|
if len(h.states) > maxSyncSessions {
|
||||||
|
for key := range h.states {
|
||||||
|
delete(h.states, key)
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *syncHub) timingLocked(sessionID string, state map[string]any) map[string]any {
|
||||||
|
paused, _ := state["paused"].(bool)
|
||||||
|
if !paused {
|
||||||
|
if value := h.playAt[sessionID]; value != "" {
|
||||||
|
state["playAt"] = value
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if value, ok := h.playAtLocalMs[sessionID]; ok {
|
||||||
|
state["playAtLocalMs"] = value
|
||||||
|
}
|
||||||
|
if value, ok := h.capturedAtMs[sessionID]; ok {
|
||||||
|
state["capturedAtLocalMs"] = value
|
||||||
|
}
|
||||||
|
return state
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *syncHub) broadcast(sessionID string) {
|
||||||
|
h.mu.Lock()
|
||||||
|
state := h.timingLocked(sessionID, h.stateLocked(sessionID))
|
||||||
|
clients := h.clientsLocked(sessionID)
|
||||||
|
peers := make([]*syncPeer, 0)
|
||||||
|
for peer := range h.peers {
|
||||||
|
if peer.sessionID == sessionID {
|
||||||
|
peers = append(peers, peer)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
h.mu.Unlock()
|
||||||
|
|
||||||
|
message := map[string]any{"type": "sync:state", "state": state, "clients": clients}
|
||||||
|
for _, peer := range peers {
|
||||||
|
if err := peer.send(message); err != nil {
|
||||||
|
_ = peer.conn.Close(websocket.StatusGoingAway, "write failed")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (peer *syncPeer) send(message any) error {
|
||||||
|
data, err := json.Marshal(message)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
peer.writeMu.Lock()
|
||||||
|
defer peer.writeMu.Unlock()
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
|
||||||
|
defer cancel()
|
||||||
|
return peer.conn.Write(ctx, websocket.MessageText, data)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Server) websocketAcceptOptions(r *http.Request) *websocket.AcceptOptions {
|
||||||
|
options := &websocket.AcceptOptions{}
|
||||||
|
if s.cfg.AllowedOrigin == "*" {
|
||||||
|
options.InsecureSkipVerify = true
|
||||||
|
return options
|
||||||
|
}
|
||||||
|
|
||||||
|
patterns := make([]string, 0, 2)
|
||||||
|
addOrigin := func(value string) {
|
||||||
|
parsed, err := url.Parse(strings.TrimSpace(value))
|
||||||
|
if err == nil && parsed.Scheme != "" && parsed.Host != "" {
|
||||||
|
patterns = append(patterns, parsed.Scheme+"://"+parsed.Host)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
addOrigin(s.cfg.AllowedOrigin)
|
||||||
|
scheme := "http"
|
||||||
|
if r.TLS != nil {
|
||||||
|
scheme = "https"
|
||||||
|
}
|
||||||
|
addOrigin(scheme + "://" + r.Host)
|
||||||
|
options.OriginPatterns = patterns
|
||||||
|
return options
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Server) syncWebsocket(w http.ResponseWriter, r *http.Request) {
|
||||||
|
conn, err := websocket.Accept(w, r, s.websocketAcceptOptions(r))
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
peer := &syncPeer{
|
||||||
|
conn: conn,
|
||||||
|
userAgent: firstNonEmpty(r.Header.Get("User-Agent"), "Unknown"),
|
||||||
|
ipAddress: firstNonEmpty(strings.Split(r.Header.Get("X-Forwarded-For"), ",")[0], r.RemoteAddr, "Unknown"),
|
||||||
|
}
|
||||||
|
s.sync.add(peer)
|
||||||
|
defer func() {
|
||||||
|
sessionID := s.sync.remove(peer)
|
||||||
|
_ = conn.Close(websocket.StatusNormalClosure, "")
|
||||||
|
if sessionID != "" {
|
||||||
|
s.sync.broadcast(sessionID)
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
|
||||||
|
_ = peer.send(map[string]any{"type": "hello", "ts": time.Now().UnixMilli()})
|
||||||
|
for {
|
||||||
|
messageType, payload, readErr := conn.Read(r.Context())
|
||||||
|
if readErr != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if messageType != websocket.MessageText {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
var message map[string]any
|
||||||
|
if json.Unmarshal(payload, &message) != nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
s.handleSyncMessage(peer, message)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Server) handleSyncMessage(peer *syncPeer, message map[string]any) {
|
||||||
|
typ, _ := message["type"].(string)
|
||||||
|
switch typ {
|
||||||
|
case "ws:ping":
|
||||||
|
_ = peer.send(map[string]any{
|
||||||
|
"type": "ws:pong",
|
||||||
|
"nonce": syncString(message, "nonce"),
|
||||||
|
"clientSentAt": syncNumberValue(message, "clientSentAt"),
|
||||||
|
"serverReceivedAt": time.Now().UnixMilli(),
|
||||||
|
})
|
||||||
|
case "sync:hello":
|
||||||
|
clientID := boundedSyncString(syncString(message, "clientId"))
|
||||||
|
sessionID := boundedSyncString(firstNonEmpty(syncString(message, "sessionId"), "default"))
|
||||||
|
if clientID == "" || sessionID == "" {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
s.sync.updatePeer(peer, clientID, sessionID)
|
||||||
|
s.sync.broadcast(sessionID)
|
||||||
|
case "client:status":
|
||||||
|
clientID := boundedSyncString(firstNonEmpty(syncString(message, "clientId"), peer.clientID))
|
||||||
|
sessionID := boundedSyncString(firstNonEmpty(syncString(message, "sessionId"), peer.sessionID, "default"))
|
||||||
|
if clientID == "" {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
s.sync.updatePeer(peer, clientID, sessionID)
|
||||||
|
mediaID, mediaIDSet := syncMediaID(message)
|
||||||
|
remote, remoteSet := message["remoteControlEnabled"].(bool)
|
||||||
|
s.sync.clientStatus(peer, sessionID, boundedSyncString(syncString(message, "uiView")), mediaID, mediaIDSet, remoteSet, remote)
|
||||||
|
s.sync.broadcast(sessionID)
|
||||||
|
case "control:claim", "control:release":
|
||||||
|
s.handleControlMessage(peer, typ, message)
|
||||||
|
case "sync:update":
|
||||||
|
s.handleSyncUpdate(peer, message)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Server) handleControlMessage(peer *syncPeer, typ string, message map[string]any) {
|
||||||
|
requesterID := boundedSyncString(firstNonEmpty(syncString(message, "clientId"), peer.clientID))
|
||||||
|
sessionID := boundedSyncString(firstNonEmpty(syncString(message, "sessionId"), peer.sessionID, "default"))
|
||||||
|
targetID := boundedSyncString(syncString(message, "targetClientId"))
|
||||||
|
if requesterID == "" || targetID == "" || requesterID != peer.clientID {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
s.sync.mu.Lock()
|
||||||
|
owner := s.sync.controlOwners[targetID]
|
||||||
|
ok := false
|
||||||
|
reason := ""
|
||||||
|
if typ == "control:claim" {
|
||||||
|
enabled := false
|
||||||
|
for candidate := range s.sync.peers {
|
||||||
|
if candidate.clientID == targetID && candidate.remoteControlEnabled {
|
||||||
|
enabled = true
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
switch {
|
||||||
|
case !enabled:
|
||||||
|
reason = "disabled"
|
||||||
|
case owner != "" && owner != requesterID:
|
||||||
|
reason = "busy"
|
||||||
|
default:
|
||||||
|
s.sync.controlOwners[targetID] = requesterID
|
||||||
|
owner = requesterID
|
||||||
|
ok = true
|
||||||
|
}
|
||||||
|
} else if owner != "" && owner != requesterID {
|
||||||
|
reason = "not-owner"
|
||||||
|
} else {
|
||||||
|
delete(s.sync.controlOwners, targetID)
|
||||||
|
owner = ""
|
||||||
|
ok = true
|
||||||
|
}
|
||||||
|
s.sync.mu.Unlock()
|
||||||
|
|
||||||
|
_ = peer.send(map[string]any{
|
||||||
|
"type": "control:ack",
|
||||||
|
"ok": ok,
|
||||||
|
"action": strings.TrimPrefix(typ, "control:"),
|
||||||
|
"targetClientId": targetID,
|
||||||
|
"ownerClientId": nullableString(owner),
|
||||||
|
"reason": nullableString(reason),
|
||||||
|
})
|
||||||
|
s.sync.broadcast(sessionID)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Server) handleSyncUpdate(peer *syncPeer, message map[string]any) {
|
||||||
|
clientID := boundedSyncString(firstNonEmpty(syncString(message, "clientId"), peer.clientID))
|
||||||
|
sessionID := boundedSyncString(firstNonEmpty(syncString(message, "sessionId"), peer.sessionID, "default"))
|
||||||
|
if clientID == "" || clientID != peer.clientID {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
mediaID, _ := syncMediaID(message)
|
||||||
|
paused := syncBool(message, "paused")
|
||||||
|
state := map[string]any{
|
||||||
|
"sessionId": sessionID,
|
||||||
|
"mediaId": mediaID,
|
||||||
|
"timeMs": syncInt(message, "timeMs", 0),
|
||||||
|
"paused": paused,
|
||||||
|
"fps": syncFPS(message),
|
||||||
|
"frame": syncInt(message, "frame", 0),
|
||||||
|
"fromClientId": clientID,
|
||||||
|
"updatedAt": time.Now().UTC().Format(time.RFC3339Nano),
|
||||||
|
}
|
||||||
|
for _, key := range []string{"openInUi", "seekToken", "seekPhase", "seekWantPlay", "seekTargetClientId", "fullscreen", "goToGrid"} {
|
||||||
|
if value, ok := message[key]; ok {
|
||||||
|
state[key] = value
|
||||||
|
}
|
||||||
|
}
|
||||||
|
toClientID := boundedSyncString(syncString(message, "toClientId"))
|
||||||
|
playAtRaw, hasPlayAt := message["playAt"]
|
||||||
|
|
||||||
|
s.sync.mu.Lock()
|
||||||
|
if paused || !hasPlayAt || strings.TrimSpace(syncStringValue(playAtRaw)) == "" {
|
||||||
|
delete(s.sync.playAt, sessionID)
|
||||||
|
delete(s.sync.playAtLocalMs, sessionID)
|
||||||
|
} else if parsed, err := time.Parse(time.RFC3339Nano, strings.TrimSpace(syncStringValue(playAtRaw))); err == nil {
|
||||||
|
s.sync.playAt[sessionID] = parsed.UTC().Format(time.RFC3339Nano)
|
||||||
|
if local := syncInt(message, "playAtLocalMs", 0); local > 0 {
|
||||||
|
s.sync.playAtLocalMs[sessionID] = local
|
||||||
|
} else {
|
||||||
|
delete(s.sync.playAtLocalMs, sessionID)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if captured := syncInt(message, "capturedAtLocalMs", 0); captured > 0 {
|
||||||
|
s.sync.capturedAtMs[sessionID] = captured
|
||||||
|
}
|
||||||
|
if toClientID == "" {
|
||||||
|
s.sync.states[sessionID] = cloneMap(state)
|
||||||
|
if len(s.sync.states) > maxSyncSessions {
|
||||||
|
for key := range s.sync.states {
|
||||||
|
delete(s.sync.states, key)
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
state = s.sync.timingLocked(sessionID, state)
|
||||||
|
clients := s.sync.clientsLocked(sessionID)
|
||||||
|
peers := make([]*syncPeer, 0)
|
||||||
|
if toClientID != "" {
|
||||||
|
for candidate := range s.sync.peers {
|
||||||
|
if candidate.sessionID == sessionID && candidate.clientID == toClientID {
|
||||||
|
peers = append(peers, candidate)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
s.sync.mu.Unlock()
|
||||||
|
|
||||||
|
messageOut := map[string]any{"type": "sync:state", "state": state, "clients": clients}
|
||||||
|
if toClientID != "" {
|
||||||
|
for _, target := range peers {
|
||||||
|
if err := target.send(messageOut); err != nil {
|
||||||
|
_ = target.conn.Close(websocket.StatusGoingAway, "write failed")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
s.sync.broadcast(sessionID)
|
||||||
|
}
|
||||||
|
|
||||||
|
func syncMediaID(message map[string]any) (any, bool) {
|
||||||
|
value, ok := message["mediaId"]
|
||||||
|
if !ok {
|
||||||
|
return nil, false
|
||||||
|
}
|
||||||
|
if value == nil {
|
||||||
|
return nil, true
|
||||||
|
}
|
||||||
|
return boundedSyncString(syncStringValue(value)), true
|
||||||
|
}
|
||||||
|
|
||||||
|
func syncString(message map[string]any, key string) string {
|
||||||
|
return syncStringValue(message[key])
|
||||||
|
}
|
||||||
|
|
||||||
|
func syncStringValue(value any) string {
|
||||||
|
if value == nil {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
if text, ok := value.(string); ok {
|
||||||
|
return strings.TrimSpace(text)
|
||||||
|
}
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
|
||||||
|
func boundedSyncString(value string) string {
|
||||||
|
value = strings.TrimSpace(value)
|
||||||
|
if len(value) > maxSyncIdentifier {
|
||||||
|
return value[:maxSyncIdentifier]
|
||||||
|
}
|
||||||
|
return value
|
||||||
|
}
|
||||||
|
|
||||||
|
func syncBool(message map[string]any, key string) bool {
|
||||||
|
value, _ := message[key].(bool)
|
||||||
|
return value
|
||||||
|
}
|
||||||
|
|
||||||
|
func syncNumberValue(message map[string]any, key string) any {
|
||||||
|
if value, ok := message[key]; ok {
|
||||||
|
return value
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func syncInt(message map[string]any, key string, fallback int64) int64 {
|
||||||
|
value, ok := message[key].(float64)
|
||||||
|
if !ok || math.IsNaN(value) || math.IsInf(value, 0) {
|
||||||
|
return fallback
|
||||||
|
}
|
||||||
|
if value < 0 {
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
if value > float64(^uint64(0)>>1) {
|
||||||
|
return int64(^uint64(0) >> 1)
|
||||||
|
}
|
||||||
|
return int64(math.Round(value))
|
||||||
|
}
|
||||||
|
|
||||||
|
func syncFPS(message map[string]any) int64 {
|
||||||
|
fps := syncInt(message, "fps", 30)
|
||||||
|
if fps < 1 {
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
if fps > 240 {
|
||||||
|
return 240
|
||||||
|
}
|
||||||
|
return fps
|
||||||
|
}
|
||||||
|
|
||||||
|
func nullableString(value string) any {
|
||||||
|
if value == "" {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return value
|
||||||
|
}
|
||||||
|
|
||||||
|
func cloneMap(value map[string]any) map[string]any {
|
||||||
|
result := make(map[string]any, len(value))
|
||||||
|
for key, item := range value {
|
||||||
|
result[key] = item
|
||||||
|
}
|
||||||
|
return result
|
||||||
|
}
|
||||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,3 @@
|
|||||||
|
.svelte-kit/
|
||||||
|
build/
|
||||||
|
node_modules/
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
# MediaCollection WebUI
|
||||||
|
|
||||||
|
The browser-facing MediaCollection services share one SvelteKit application. The
|
||||||
|
service variant is selected at build time with `VITE_MEDIA_APP` and uses the same
|
||||||
|
Svelte 5, Tailwind CSS v4, bits-ui-compatible component patterns, Lucide icons,
|
||||||
|
semantic tokens, responsive shell, and static adapter as the other projects.
|
||||||
|
|
||||||
|
From this directory:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
npm install
|
||||||
|
npm run build:all
|
||||||
|
```
|
||||||
|
|
||||||
|
`build:all` creates ignored `.webui/` directories in each service. Docker builds
|
||||||
|
compile the requested variant in a dedicated frontend stage and set
|
||||||
|
`MEDIA_UI_DIR` to the generated output. The existing JSON, media, WebSocket,
|
||||||
|
Socket.IO, and service-to-service routes remain owned by each backend.
|
||||||
@@ -0,0 +1,62 @@
|
|||||||
|
import js from '@eslint/js'
|
||||||
|
import globals from 'globals'
|
||||||
|
import svelte from 'eslint-plugin-svelte'
|
||||||
|
import prettierConfig from 'eslint-config-prettier'
|
||||||
|
import tseslint from 'typescript-eslint'
|
||||||
|
|
||||||
|
export default tseslint.config(
|
||||||
|
{ ignores: ['build', '.svelte-kit', 'node_modules'] },
|
||||||
|
js.configs.recommended,
|
||||||
|
...tseslint.configs.recommended,
|
||||||
|
...svelte.configs.recommended,
|
||||||
|
{
|
||||||
|
files: ['**/*.ts', '**/*.svelte'],
|
||||||
|
languageOptions: {
|
||||||
|
ecmaVersion: 2022,
|
||||||
|
globals: {
|
||||||
|
...globals.browser,
|
||||||
|
__MEDIA_APP__: 'readonly',
|
||||||
|
__FRONTEND_TECH_STACK__: 'readonly',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
rules: {
|
||||||
|
'no-console': 'error',
|
||||||
|
'@typescript-eslint/no-unused-vars': ['warn', { argsIgnorePattern: '^_' }],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
files: ['**/*.{js,mjs,cjs}'],
|
||||||
|
languageOptions: {
|
||||||
|
ecmaVersion: 2022,
|
||||||
|
globals: globals.node,
|
||||||
|
},
|
||||||
|
rules: {},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
files: ['**/*.svelte'],
|
||||||
|
languageOptions: {
|
||||||
|
parserOptions: {
|
||||||
|
parser: tseslint.parser,
|
||||||
|
extraFileExtensions: ['.svelte'],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
rules: {
|
||||||
|
'prefer-const': 'off',
|
||||||
|
'svelte/no-navigation-without-resolve': 'off',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
prettierConfig,
|
||||||
|
...svelte.configs.prettier,
|
||||||
|
{
|
||||||
|
files: ['**/*.svelte.ts'],
|
||||||
|
languageOptions: {
|
||||||
|
parser: tseslint.parser,
|
||||||
|
ecmaVersion: 2022,
|
||||||
|
globals: {
|
||||||
|
...globals.browser,
|
||||||
|
__MEDIA_APP__: 'readonly',
|
||||||
|
__FRONTEND_TECH_STACK__: 'readonly',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
)
|
||||||
@@ -0,0 +1,53 @@
|
|||||||
|
{
|
||||||
|
"name": "@gabriel20xx/media-collection-webui",
|
||||||
|
"private": true,
|
||||||
|
"version": "1.0.0",
|
||||||
|
"type": "module",
|
||||||
|
"scripts": {
|
||||||
|
"dev": "vite dev",
|
||||||
|
"build": "vite build",
|
||||||
|
"build:all": "node scripts/build-all.mjs",
|
||||||
|
"build:viewer": "node scripts/build-all.mjs viewer",
|
||||||
|
"build:tools": "node scripts/build-all.mjs tools",
|
||||||
|
"build:analyzer": "node scripts/build-all.mjs analyzer",
|
||||||
|
"build:config": "node scripts/build-all.mjs config",
|
||||||
|
"build:moderator": "node scripts/build-all.mjs moderator",
|
||||||
|
"build:kiosk": "node scripts/build-all.mjs kiosk",
|
||||||
|
"build:servant": "node scripts/build-all.mjs servant",
|
||||||
|
"build:desktop": "node scripts/build-all.mjs desktop",
|
||||||
|
"check": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json",
|
||||||
|
"lint": "eslint .",
|
||||||
|
"format": "prettier --write .",
|
||||||
|
"format:check": "prettier --check ."
|
||||||
|
},
|
||||||
|
"dependencies": {
|
||||||
|
"@gabriel20xx/web-ui": "file:../shared/packages/web-ui",
|
||||||
|
"@lucide/svelte": "1.28.0",
|
||||||
|
"@tanstack/svelte-query": "6.1.38",
|
||||||
|
"bits-ui": "2.18.1",
|
||||||
|
"class-variance-authority": "0.7.1",
|
||||||
|
"clsx": "2.1.1",
|
||||||
|
"tailwind-merge": "3.6.0"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"@eslint/js": "10.0.1",
|
||||||
|
"@sveltejs/adapter-static": "3.0.10",
|
||||||
|
"@sveltejs/kit": "2.70.2",
|
||||||
|
"@sveltejs/vite-plugin-svelte": "7.2.0",
|
||||||
|
"@tailwindcss/vite": "4.3.3",
|
||||||
|
"@types/node": "26.1.2",
|
||||||
|
"eslint": "10.8.0",
|
||||||
|
"eslint-config-prettier": "10.1.8",
|
||||||
|
"eslint-plugin-svelte": "3.22.0",
|
||||||
|
"globals": "17.9.0",
|
||||||
|
"prettier": "3.9.6",
|
||||||
|
"prettier-plugin-svelte": "4.1.1",
|
||||||
|
"svelte": "5.56.8",
|
||||||
|
"svelte-check": "4.7.4",
|
||||||
|
"tailwindcss": "4.3.3",
|
||||||
|
"tw-animate-css": "1.4.0",
|
||||||
|
"typescript": "6.0.3",
|
||||||
|
"typescript-eslint": "8.65.0",
|
||||||
|
"vite": "8.2.0"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
/** @type {import('prettier').Config} */
|
||||||
|
export default {
|
||||||
|
plugins: ['prettier-plugin-svelte'],
|
||||||
|
semi: false,
|
||||||
|
singleQuote: true,
|
||||||
|
trailingComma: 'all',
|
||||||
|
printWidth: 120,
|
||||||
|
svelteSortOrder: 'options-scripts-markup-styles',
|
||||||
|
}
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
{
|
||||||
|
"viewer": { "name": "MediaViewer", "icon": "play" },
|
||||||
|
"tools": { "name": "MediaTools", "icon": "wand-sparkles" },
|
||||||
|
"analyzer": { "name": "MediaAnalyzer", "icon": "scan-search" },
|
||||||
|
"config": { "name": "MediaConfig", "icon": "settings-2" },
|
||||||
|
"moderator": { "name": "MediaModerator", "icon": "shield-check" },
|
||||||
|
"kiosk": { "name": "MediaKiosk", "icon": "image" },
|
||||||
|
"servant": { "name": "MediaServant", "icon": "server" },
|
||||||
|
"desktop": { "name": "MediaViewer Desktop", "icon": "monitor-play" }
|
||||||
|
}
|
||||||
@@ -0,0 +1,49 @@
|
|||||||
|
import { cp, mkdir, rm } from 'node:fs/promises'
|
||||||
|
import path from 'node:path'
|
||||||
|
import { spawn } from 'node:child_process'
|
||||||
|
|
||||||
|
const webUiDir = path.resolve(import.meta.dirname, '..')
|
||||||
|
const collectionDir = path.resolve(webUiDir, '..')
|
||||||
|
const targets = {
|
||||||
|
viewer: 'MediaViewer',
|
||||||
|
tools: 'MediaTools',
|
||||||
|
analyzer: 'MediaAnalyzer',
|
||||||
|
config: 'MediaConfig',
|
||||||
|
moderator: 'MediaModerator',
|
||||||
|
kiosk: 'MediaKiosk',
|
||||||
|
servant: 'MediaServant',
|
||||||
|
desktop: 'MediaDesktop',
|
||||||
|
}
|
||||||
|
|
||||||
|
const requested = process.argv.slice(2)
|
||||||
|
const apps = requested.length ? requested : Object.keys(targets)
|
||||||
|
const unknown = apps.filter((app) => !targets[app])
|
||||||
|
if (unknown.length) {
|
||||||
|
console.error(`Unknown MediaCollection WebUI app: ${unknown.join(', ')}`)
|
||||||
|
process.exit(1)
|
||||||
|
}
|
||||||
|
|
||||||
|
function runBuild(app) {
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
const child = spawn(process.platform === 'win32' ? 'npm.cmd' : 'npm', ['run', 'build'], {
|
||||||
|
cwd: webUiDir,
|
||||||
|
env: { ...process.env, VITE_MEDIA_APP: app },
|
||||||
|
shell: process.platform === 'win32',
|
||||||
|
stdio: 'inherit',
|
||||||
|
})
|
||||||
|
child.on('error', reject)
|
||||||
|
child.on('exit', (code) => {
|
||||||
|
if (code === 0) resolve()
|
||||||
|
else reject(new Error(`WebUI build failed for ${app} with exit code ${code}`))
|
||||||
|
})
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
for (const app of apps) {
|
||||||
|
await runBuild(app)
|
||||||
|
const target = path.join(collectionDir, targets[app], '.webui')
|
||||||
|
await rm(target, { recursive: true, force: true })
|
||||||
|
await mkdir(target, { recursive: true })
|
||||||
|
await cp(path.join(webUiDir, 'build'), target, { recursive: true })
|
||||||
|
console.log(`[webui] ${app} -> ${path.relative(collectionDir, target)}`)
|
||||||
|
}
|
||||||
@@ -0,0 +1,49 @@
|
|||||||
|
import fs from 'node:fs'
|
||||||
|
import path from 'node:path'
|
||||||
|
|
||||||
|
const webUiDir = path.resolve(import.meta.dirname, '..')
|
||||||
|
|
||||||
|
/** @typedef {{ name: string, icon: string }} ProjectIconConfig */
|
||||||
|
/** @typedef {[string, Record<string, string | number>]} IconNode */
|
||||||
|
|
||||||
|
/** @type {Record<string, ProjectIconConfig>} */
|
||||||
|
const projectIcons = JSON.parse(fs.readFileSync(path.join(webUiDir, 'project-icons.json'), 'utf8'))
|
||||||
|
const lucideIconsDir = path.join(webUiDir, 'node_modules', '@lucide', 'svelte', 'dist', 'icons')
|
||||||
|
|
||||||
|
/** @param {unknown} value */
|
||||||
|
function escapeAttribute(value) {
|
||||||
|
return String(value)
|
||||||
|
.replaceAll('&', '&')
|
||||||
|
.replaceAll('"', '"')
|
||||||
|
.replaceAll('<', '<')
|
||||||
|
.replaceAll('>', '>')
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @param {string} iconName @returns {IconNode[]} */
|
||||||
|
function getIconNode(iconName) {
|
||||||
|
const source = fs.readFileSync(path.join(lucideIconsDir, `${iconName}.svelte`), 'utf8')
|
||||||
|
const match = source.match(/const iconNode = (\[[\s\S]*?\]);/)
|
||||||
|
if (!match) throw new Error(`Unable to read Lucide icon node for ${iconName}`)
|
||||||
|
return /** @type {IconNode[]} */ (JSON.parse(match[1]))
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @param {IconNode} node */
|
||||||
|
function renderIconNode([tag, attributes]) {
|
||||||
|
const renderedAttributes = Object.entries(attributes)
|
||||||
|
.map(([name, value]) => `${name}="${escapeAttribute(value)}"`)
|
||||||
|
.join(' ')
|
||||||
|
return ` <${tag} ${renderedAttributes} />`
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @param {string} appId */
|
||||||
|
export function renderProjectFavicon(appId) {
|
||||||
|
const project = projectIcons[appId]
|
||||||
|
if (!project) throw new Error(`Unknown MediaCollection project: ${appId}`)
|
||||||
|
|
||||||
|
const iconNode = getIconNode(project.icon)
|
||||||
|
return `<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="#5b8cff" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" role="img" aria-labelledby="favicon-title">
|
||||||
|
<title id="favicon-title">${escapeAttribute(project.name)}</title>
|
||||||
|
${iconNode.map(renderIconNode).join('\n')}
|
||||||
|
</svg>
|
||||||
|
`
|
||||||
|
}
|
||||||
@@ -0,0 +1,167 @@
|
|||||||
|
@import 'tailwindcss';
|
||||||
|
@import 'tw-animate-css';
|
||||||
|
|
||||||
|
:root,
|
||||||
|
[data-theme='dark'] {
|
||||||
|
--color-bg: #0b0f14;
|
||||||
|
--color-surface: #131820;
|
||||||
|
--color-surface-hover: #1c2330;
|
||||||
|
--color-border: #2a3140;
|
||||||
|
--color-fg: #e6e9ef;
|
||||||
|
--color-muted-fg: #8b95a5;
|
||||||
|
--color-primary: #5b8cff;
|
||||||
|
--color-primary-fg: #06122b;
|
||||||
|
--color-secondary: #2563eb;
|
||||||
|
--color-secondary-fg: #ffffff;
|
||||||
|
--color-accent: #5b8cff;
|
||||||
|
--color-accent-fg: #06122b;
|
||||||
|
--color-danger: #ef4444;
|
||||||
|
--color-danger-fg: #450a0a;
|
||||||
|
--color-success: #22c55e;
|
||||||
|
--color-success-fg: #052e14;
|
||||||
|
--color-warning: #f59e0b;
|
||||||
|
--color-warning-fg: #2a1a00;
|
||||||
|
--color-ring: #5b8cff;
|
||||||
|
color-scheme: dark;
|
||||||
|
}
|
||||||
|
|
||||||
|
[data-theme='light'] {
|
||||||
|
--color-bg: #f5f7fb;
|
||||||
|
--color-surface: #ffffff;
|
||||||
|
--color-surface-hover: #eef1f7;
|
||||||
|
--color-border: #dbe1ea;
|
||||||
|
--color-fg: #10151f;
|
||||||
|
--color-muted-fg: #5b6472;
|
||||||
|
--color-primary: #2f5fe0;
|
||||||
|
--color-primary-fg: #ffffff;
|
||||||
|
--color-secondary: #1e3fae;
|
||||||
|
--color-secondary-fg: #ffffff;
|
||||||
|
--color-accent: #2f5fe0;
|
||||||
|
--color-accent-fg: #ffffff;
|
||||||
|
--color-danger: #dc2626;
|
||||||
|
--color-danger-fg: #ffffff;
|
||||||
|
--color-success: #059669;
|
||||||
|
--color-success-fg: #ffffff;
|
||||||
|
--color-warning: #b45309;
|
||||||
|
--color-warning-fg: #ffffff;
|
||||||
|
--color-ring: #2f5fe0;
|
||||||
|
color-scheme: light;
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (prefers-color-scheme: light) {
|
||||||
|
:root:not([data-theme]) {
|
||||||
|
--color-bg: #f5f7fb;
|
||||||
|
--color-surface: #ffffff;
|
||||||
|
--color-surface-hover: #eef1f7;
|
||||||
|
--color-border: #dbe1ea;
|
||||||
|
--color-fg: #10151f;
|
||||||
|
--color-muted-fg: #5b6472;
|
||||||
|
--color-primary: #2f5fe0;
|
||||||
|
--color-primary-fg: #ffffff;
|
||||||
|
--color-secondary: #1e3fae;
|
||||||
|
--color-secondary-fg: #ffffff;
|
||||||
|
--color-accent: #2f5fe0;
|
||||||
|
--color-accent-fg: #ffffff;
|
||||||
|
--color-danger: #dc2626;
|
||||||
|
--color-danger-fg: #ffffff;
|
||||||
|
--color-success: #059669;
|
||||||
|
--color-success-fg: #ffffff;
|
||||||
|
--color-warning: #b45309;
|
||||||
|
--color-warning-fg: #ffffff;
|
||||||
|
--color-ring: #2f5fe0;
|
||||||
|
color-scheme: light;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@theme inline {
|
||||||
|
--color-bg: var(--color-bg);
|
||||||
|
--color-surface: var(--color-surface);
|
||||||
|
--color-surface-hover: var(--color-surface-hover);
|
||||||
|
--color-border: var(--color-border);
|
||||||
|
--color-fg: var(--color-fg);
|
||||||
|
--color-muted-fg: var(--color-muted-fg);
|
||||||
|
--color-primary: var(--color-primary);
|
||||||
|
--color-primary-fg: var(--color-primary-fg);
|
||||||
|
--color-secondary: var(--color-secondary);
|
||||||
|
--color-secondary-fg: var(--color-secondary-fg);
|
||||||
|
--color-accent: var(--color-accent);
|
||||||
|
--color-accent-fg: var(--color-accent-fg);
|
||||||
|
--color-danger: var(--color-danger);
|
||||||
|
--color-danger-fg: var(--color-danger-fg);
|
||||||
|
--color-success: var(--color-success);
|
||||||
|
--color-success-fg: var(--color-success-fg);
|
||||||
|
--color-warning: var(--color-warning);
|
||||||
|
--color-warning-fg: var(--color-warning-fg);
|
||||||
|
--color-ring: var(--color-ring);
|
||||||
|
--font-sans: 'Inter', ui-sans-serif, system-ui, -apple-system, sans-serif;
|
||||||
|
--font-mono: 'JetBrains Mono', 'Fira Code', Consolas, monospace;
|
||||||
|
}
|
||||||
|
|
||||||
|
html,
|
||||||
|
body {
|
||||||
|
min-height: 100%;
|
||||||
|
}
|
||||||
|
|
||||||
|
body {
|
||||||
|
margin: 0;
|
||||||
|
background: var(--color-bg);
|
||||||
|
color: var(--color-fg);
|
||||||
|
font-family: var(--font-sans);
|
||||||
|
font-size: 14px;
|
||||||
|
line-height: 1.5;
|
||||||
|
transition:
|
||||||
|
background-color 150ms ease,
|
||||||
|
color 150ms ease;
|
||||||
|
}
|
||||||
|
|
||||||
|
button,
|
||||||
|
input,
|
||||||
|
select,
|
||||||
|
textarea {
|
||||||
|
font: inherit;
|
||||||
|
}
|
||||||
|
|
||||||
|
.field {
|
||||||
|
width: 100%;
|
||||||
|
height: 2.5rem;
|
||||||
|
border: 1px solid var(--color-border);
|
||||||
|
border-radius: 0.375rem;
|
||||||
|
background: var(--color-bg);
|
||||||
|
padding: 0 0.75rem;
|
||||||
|
color: var(--color-fg);
|
||||||
|
outline: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.field:focus-visible {
|
||||||
|
box-shadow: 0 0 0 2px color-mix(in srgb, var(--color-ring) 35%, transparent);
|
||||||
|
}
|
||||||
|
|
||||||
|
* {
|
||||||
|
scrollbar-width: thin;
|
||||||
|
scrollbar-color: var(--color-border) transparent;
|
||||||
|
}
|
||||||
|
|
||||||
|
::selection {
|
||||||
|
background: var(--color-primary);
|
||||||
|
color: var(--color-primary-fg);
|
||||||
|
}
|
||||||
|
|
||||||
|
.media-shimmer {
|
||||||
|
background: linear-gradient(
|
||||||
|
90deg,
|
||||||
|
var(--color-surface) 25%,
|
||||||
|
var(--color-surface-hover) 50%,
|
||||||
|
var(--color-surface) 75%
|
||||||
|
);
|
||||||
|
background-size: 200% 100%;
|
||||||
|
animation: media-shimmer 1.5s infinite;
|
||||||
|
}
|
||||||
|
|
||||||
|
@keyframes media-shimmer {
|
||||||
|
0% {
|
||||||
|
background-position: -200% 0;
|
||||||
|
}
|
||||||
|
100% {
|
||||||
|
background-position: 200% 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
Vendored
+2
@@ -0,0 +1,2 @@
|
|||||||
|
declare const __MEDIA_APP__: string
|
||||||
|
declare const __FRONTEND_TECH_STACK__: Array<{ name: string; version: string }>
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
<!doctype html>
|
||||||
|
<html lang="en">
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8" />
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" />
|
||||||
|
<meta name="theme-color" content="#0b0f14" />
|
||||||
|
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
|
||||||
|
<title>MediaCollection</title>
|
||||||
|
%sveltekit.head%
|
||||||
|
</head>
|
||||||
|
<body data-sveltekit-preload-data="hover">
|
||||||
|
<div style="display: contents">%sveltekit.body%</div>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
@@ -0,0 +1,55 @@
|
|||||||
|
import type { ApiError } from './types'
|
||||||
|
|
||||||
|
export class ApiRequestError extends Error {
|
||||||
|
status: number
|
||||||
|
payload: ApiError | null
|
||||||
|
|
||||||
|
constructor(message: string, status: number, payload: ApiError | null = null) {
|
||||||
|
super(message)
|
||||||
|
this.name = 'ApiRequestError'
|
||||||
|
this.status = status
|
||||||
|
this.payload = payload
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function request<T>(path: string, init: RequestInit = {}): Promise<T> {
|
||||||
|
const response = await fetch(path, {
|
||||||
|
credentials: 'include',
|
||||||
|
...init,
|
||||||
|
headers: {
|
||||||
|
...(init.body && !(init.body instanceof FormData) ? { 'content-type': 'application/json' } : {}),
|
||||||
|
...(init.headers || {}),
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
const contentType = response.headers.get('content-type') || ''
|
||||||
|
const payload = contentType.includes('json') ? await response.json().catch(() => null) : null
|
||||||
|
if (!response.ok) {
|
||||||
|
const error = payload as ApiError | null
|
||||||
|
throw new ApiRequestError(
|
||||||
|
error?.error || error?.message || error?.detail || response.statusText,
|
||||||
|
response.status,
|
||||||
|
error,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
return (payload ?? (await response.text())) as T
|
||||||
|
}
|
||||||
|
|
||||||
|
export function get<T>(path: string) {
|
||||||
|
return request<T>(path)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function post<T>(path: string, body?: unknown) {
|
||||||
|
return request<T>(path, {
|
||||||
|
method: 'POST',
|
||||||
|
...(body === undefined ? {} : { body: body instanceof FormData ? body : JSON.stringify(body) }),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
export function put<T>(path: string, body: unknown) {
|
||||||
|
return request<T>(path, { method: 'PUT', body: JSON.stringify(body) })
|
||||||
|
}
|
||||||
|
|
||||||
|
export function del<T>(path: string) {
|
||||||
|
return request<T>(path, { method: 'DELETE' })
|
||||||
|
}
|
||||||
@@ -0,0 +1,286 @@
|
|||||||
|
import projectIcons from '../../project-icons.json'
|
||||||
|
import type { AppConfig, AppId } from './types'
|
||||||
|
import type { ProjectIconName } from './types'
|
||||||
|
|
||||||
|
function projectIcon(id: AppId): ProjectIconName {
|
||||||
|
return projectIcons[id].icon as ProjectIconName
|
||||||
|
}
|
||||||
|
|
||||||
|
const configs: Record<AppId, AppConfig> = {
|
||||||
|
viewer: {
|
||||||
|
id: 'viewer',
|
||||||
|
name: 'MediaViewer',
|
||||||
|
icon: projectIcon('viewer'),
|
||||||
|
eyebrow: 'Immersive media library',
|
||||||
|
description: 'Browse, search, and play your media collection from one calm workspace.',
|
||||||
|
nav: [
|
||||||
|
{
|
||||||
|
label: 'Library',
|
||||||
|
panel: 'library',
|
||||||
|
path: '/',
|
||||||
|
icon: 'gallery-horizontal-end',
|
||||||
|
description: 'Browse, search, and play your media collection.',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: 'Feed',
|
||||||
|
panel: 'view',
|
||||||
|
path: '/feed',
|
||||||
|
icon: 'monitor-play',
|
||||||
|
description: 'View a focused stream of media from your collection.',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: 'Tags',
|
||||||
|
panel: 'tags',
|
||||||
|
path: '/tags',
|
||||||
|
icon: 'tags',
|
||||||
|
description: 'Explore media by tags and related items.',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: 'Playlists',
|
||||||
|
panel: 'playlists',
|
||||||
|
path: '/playlists',
|
||||||
|
icon: 'list-video',
|
||||||
|
description: 'Organize media into playlists for convenient playback.',
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
tools: {
|
||||||
|
id: 'tools',
|
||||||
|
name: 'MediaTools',
|
||||||
|
icon: projectIcon('tools'),
|
||||||
|
eyebrow: 'Media workflow studio',
|
||||||
|
description: 'Generate, download, convert, and schedule media jobs in one place.',
|
||||||
|
nav: [
|
||||||
|
{
|
||||||
|
label: 'Generator',
|
||||||
|
panel: 'generator',
|
||||||
|
path: '/',
|
||||||
|
icon: 'wand-sparkles',
|
||||||
|
description: 'Generate new media and monitor generation jobs.',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: 'Downloader',
|
||||||
|
panel: 'downloader',
|
||||||
|
path: '/downloader',
|
||||||
|
icon: 'cloud-download',
|
||||||
|
description: 'Download media from configured sources.',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: 'Converter',
|
||||||
|
panel: 'converter',
|
||||||
|
path: '/converter',
|
||||||
|
icon: 'refresh-cw',
|
||||||
|
description: 'Convert media between supported formats.',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: 'Schedules',
|
||||||
|
panel: 'schedules',
|
||||||
|
path: '/schedules',
|
||||||
|
icon: 'activity',
|
||||||
|
description: 'Schedule recurring media tools and maintenance jobs.',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: 'Library',
|
||||||
|
panel: 'library',
|
||||||
|
path: '/library',
|
||||||
|
icon: 'image',
|
||||||
|
description: 'Inspect media produced by the tools workspace.',
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
analyzer: {
|
||||||
|
id: 'analyzer',
|
||||||
|
name: 'MediaAnalyzer',
|
||||||
|
icon: projectIcon('analyzer'),
|
||||||
|
eyebrow: 'Processing operations',
|
||||||
|
description: 'Monitor discovery and define per-type processing pipelines and automation queues.',
|
||||||
|
nav: [
|
||||||
|
{
|
||||||
|
label: 'Dashboard',
|
||||||
|
panel: 'dashboard',
|
||||||
|
path: '/',
|
||||||
|
icon: 'layout-dashboard',
|
||||||
|
description: 'Monitor processing queues, progress, and recent history.',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: 'Discover',
|
||||||
|
panel: 'discover',
|
||||||
|
path: '/discover',
|
||||||
|
icon: 'folder-open',
|
||||||
|
description: 'Discover and register media from configured locations.',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: 'Images',
|
||||||
|
panel: 'images',
|
||||||
|
path: '/images',
|
||||||
|
icon: 'image',
|
||||||
|
description: 'Define the image pipeline: thumbnails, metadata extraction, and AI analysis.',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: 'Videos',
|
||||||
|
panel: 'videos',
|
||||||
|
path: '/videos',
|
||||||
|
icon: 'monitor-play',
|
||||||
|
description: 'Define the video pipeline: thumbnails, metadata extraction, and AI analysis.',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: 'Audios',
|
||||||
|
panel: 'audios',
|
||||||
|
path: '/audios',
|
||||||
|
icon: 'audio-lines',
|
||||||
|
description: 'Define the audio pipeline: thumbnails, metadata extraction, and AI analysis.',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: 'Funscripts',
|
||||||
|
panel: 'funscripts',
|
||||||
|
path: '/funscripts',
|
||||||
|
icon: 'scroll-text',
|
||||||
|
description: 'Define the funscript pipeline: thumbnails, metadata extraction, and AI analysis.',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: 'Schedules',
|
||||||
|
panel: 'schedules',
|
||||||
|
path: '/schedules',
|
||||||
|
icon: 'activity',
|
||||||
|
description: 'Configure recurring analyzer operations.',
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
config: {
|
||||||
|
id: 'config',
|
||||||
|
name: 'MediaConfig',
|
||||||
|
icon: projectIcon('config'),
|
||||||
|
eyebrow: 'Platform configuration',
|
||||||
|
description: 'Connect services, configure mounts, and tune shared processing parameters.',
|
||||||
|
nav: [
|
||||||
|
{
|
||||||
|
label: 'Mounts',
|
||||||
|
panel: 'mounts',
|
||||||
|
path: '/',
|
||||||
|
icon: 'hard-drive',
|
||||||
|
description: 'Configure collection mounts and connected storage.',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: 'Parameters',
|
||||||
|
panel: 'parameters',
|
||||||
|
path: '/parameters',
|
||||||
|
icon: 'sliders-horizontal',
|
||||||
|
description: 'Tune shared processing and service parameters.',
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
moderator: {
|
||||||
|
id: 'moderator',
|
||||||
|
name: 'MediaModerator',
|
||||||
|
icon: projectIcon('moderator'),
|
||||||
|
eyebrow: 'Administration and safety',
|
||||||
|
description: 'Review users, media, tags, visibility, and platform health.',
|
||||||
|
nav: [
|
||||||
|
{
|
||||||
|
label: 'Dashboard',
|
||||||
|
panel: 'dashboard',
|
||||||
|
path: '/',
|
||||||
|
icon: 'bar-chart-3',
|
||||||
|
description: 'Review moderation activity and platform health.',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: 'Users',
|
||||||
|
panel: 'users',
|
||||||
|
path: '/users',
|
||||||
|
icon: 'users',
|
||||||
|
description: 'Manage accounts, roles, and access.',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: 'Media',
|
||||||
|
panel: 'media',
|
||||||
|
path: '/media',
|
||||||
|
icon: 'shield-check',
|
||||||
|
description: 'Review media visibility and moderation status.',
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
kiosk: {
|
||||||
|
id: 'kiosk',
|
||||||
|
name: 'MediaKiosk',
|
||||||
|
icon: projectIcon('kiosk'),
|
||||||
|
eyebrow: 'Ambient display',
|
||||||
|
description: 'Show the latest collection output in a focused, full-screen canvas.',
|
||||||
|
nav: [
|
||||||
|
{
|
||||||
|
label: 'Kiosk',
|
||||||
|
panel: 'kiosk',
|
||||||
|
path: '/',
|
||||||
|
icon: 'monitor-play',
|
||||||
|
description: 'Show the latest collection output in a focused display.',
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
servant: {
|
||||||
|
id: 'servant',
|
||||||
|
name: 'MediaServant',
|
||||||
|
icon: projectIcon('servant'),
|
||||||
|
eyebrow: 'Storage and delivery',
|
||||||
|
description: 'Inspect mounts, file activity, bandwidth, and media delivery health.',
|
||||||
|
nav: [
|
||||||
|
{
|
||||||
|
label: 'Overview',
|
||||||
|
panel: 'overview',
|
||||||
|
path: '/',
|
||||||
|
icon: 'server',
|
||||||
|
description: 'Inspect storage, delivery, and service health.',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: 'Files',
|
||||||
|
panel: 'files',
|
||||||
|
path: '/files',
|
||||||
|
icon: 'folder-open',
|
||||||
|
description: 'Review recent files and media activity.',
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
desktop: {
|
||||||
|
id: 'desktop',
|
||||||
|
name: 'MediaViewer Desktop',
|
||||||
|
icon: projectIcon('desktop'),
|
||||||
|
eyebrow: 'Connected player',
|
||||||
|
description: 'Control playback, funscripts, and connected devices from your desktop.',
|
||||||
|
nav: [
|
||||||
|
{
|
||||||
|
label: 'Player',
|
||||||
|
panel: 'player',
|
||||||
|
path: '/',
|
||||||
|
icon: 'monitor-play',
|
||||||
|
description: 'Control playback and connected desktop devices.',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: 'Devices',
|
||||||
|
panel: 'devices',
|
||||||
|
path: '/devices',
|
||||||
|
icon: 'box',
|
||||||
|
description: 'Manage connected playback and funscript devices.',
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getAppConfig(id: string): AppConfig {
|
||||||
|
return configs[(id as AppId) in configs ? (id as AppId) : 'viewer']
|
||||||
|
}
|
||||||
|
|
||||||
|
function normalizePathname(pathname: string): string {
|
||||||
|
const normalized = String(pathname || '/').replace(/\/+$/, '')
|
||||||
|
return normalized || '/'
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getPanelForPath(app: AppConfig, pathname: string): string {
|
||||||
|
const normalizedPath = normalizePathname(pathname)
|
||||||
|
const matchingItem = app.nav.find((item) => {
|
||||||
|
if (item.path === '/') return normalizedPath === '/'
|
||||||
|
return normalizedPath === item.path || normalizedPath.startsWith(`${item.path}/`)
|
||||||
|
})
|
||||||
|
return matchingItem?.panel || app.nav[0]?.panel || ''
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getPathForPanel(app: AppConfig, panel: string): string {
|
||||||
|
return app.nav.find((item) => item.panel === panel)?.path || app.nav[0]?.path || '/'
|
||||||
|
}
|
||||||
@@ -0,0 +1,211 @@
|
|||||||
|
<script lang="ts">
|
||||||
|
import { onMount } from 'svelte'
|
||||||
|
import { get } from '$lib/api'
|
||||||
|
import EmptyState from '$lib/components/EmptyState.svelte'
|
||||||
|
import SectionTitle from '$lib/components/SectionTitle.svelte'
|
||||||
|
import Badge from '$lib/components/ui/badge.svelte'
|
||||||
|
import Button from '$lib/components/ui/button.svelte'
|
||||||
|
import Card from '$lib/components/ui/card.svelte'
|
||||||
|
|
||||||
|
type Json = Record<string, unknown>
|
||||||
|
type MediaType = 'image' | 'video' | 'audio' | 'funscript'
|
||||||
|
|
||||||
|
// mediaType fixes the card to one media type and hides the type filter entirely - used by the
|
||||||
|
// Images/Videos/Audios/Funscripts tabs, which have no business filtering across types. Every
|
||||||
|
// other page (dashboard, schedules, discover) omits it and gets the full type filter instead.
|
||||||
|
let {
|
||||||
|
mediaType,
|
||||||
|
title = 'Processing history',
|
||||||
|
description = 'Recently processed elements and their results.',
|
||||||
|
pageSize = 10,
|
||||||
|
}: {
|
||||||
|
mediaType?: MediaType
|
||||||
|
title?: string
|
||||||
|
description?: string
|
||||||
|
pageSize?: number
|
||||||
|
} = $props()
|
||||||
|
|
||||||
|
const TYPE_OPTIONS: { value: string; label: string }[] = [
|
||||||
|
{ value: '', label: 'All types' },
|
||||||
|
{ value: 'image', label: 'Images' },
|
||||||
|
{ value: 'video', label: 'Videos' },
|
||||||
|
{ value: 'audio', label: 'Audios' },
|
||||||
|
{ value: 'funscript', label: 'Funscripts' },
|
||||||
|
]
|
||||||
|
const STATUS_OPTIONS: { value: string; label: string }[] = [
|
||||||
|
{ value: '', label: 'All statuses' },
|
||||||
|
{ value: 'queued', label: 'Queued' },
|
||||||
|
{ value: 'processing', label: 'Processing' },
|
||||||
|
{ value: 'done', label: 'Done' },
|
||||||
|
{ value: 'error', label: 'Error' },
|
||||||
|
]
|
||||||
|
|
||||||
|
let typeFilter = $state('')
|
||||||
|
let statusFilter = $state('')
|
||||||
|
let currentPage = $state(1)
|
||||||
|
let entries = $state<Json[]>([])
|
||||||
|
let total = $state(0)
|
||||||
|
let loading = $state(true)
|
||||||
|
let error = $state('')
|
||||||
|
|
||||||
|
// The type filter is only ever shown (and only ever meaningful) when the parent hasn't already
|
||||||
|
// fixed one - once it's fixed, the fixed value always wins over whatever's left in the dropdown
|
||||||
|
// state from a previous type-agnostic usage of this same component instance.
|
||||||
|
const effectiveType = $derived(mediaType ?? typeFilter)
|
||||||
|
|
||||||
|
function firstValue(entry: Json, keys: string[], fallback: string) {
|
||||||
|
for (const key of keys) {
|
||||||
|
const value = entry[key]
|
||||||
|
if (value !== undefined && value !== null && String(value).trim() !== '') {
|
||||||
|
return String(value)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return fallback
|
||||||
|
}
|
||||||
|
|
||||||
|
function statusTone(status: string): 'neutral' | 'primary' | 'success' | 'warning' | 'danger' {
|
||||||
|
const normalized = status.toLowerCase()
|
||||||
|
if (normalized.includes('error') || normalized.includes('fail')) return 'danger'
|
||||||
|
if (normalized.includes('process') || normalized.includes('running')) return 'primary'
|
||||||
|
if (normalized.includes('queue') || normalized.includes('pending')) return 'warning'
|
||||||
|
if (normalized.includes('done') || normalized.includes('complete') || normalized.includes('success'))
|
||||||
|
return 'success'
|
||||||
|
return 'neutral'
|
||||||
|
}
|
||||||
|
|
||||||
|
async function load({ background = false } = {}) {
|
||||||
|
if (!background) loading = true
|
||||||
|
error = ''
|
||||||
|
try {
|
||||||
|
const params: [string, string][] = [
|
||||||
|
['limit', String(pageSize)],
|
||||||
|
['offset', String((currentPage - 1) * pageSize)],
|
||||||
|
]
|
||||||
|
if (effectiveType) params.push(['mediaType', effectiveType])
|
||||||
|
if (statusFilter) params.push(['status', statusFilter])
|
||||||
|
const query = params.map(([key, value]) => `${key}=${encodeURIComponent(value)}`).join('&')
|
||||||
|
const response = await get<Json>(`/api/history?${query}`)
|
||||||
|
const rawEntries = response.items || response.history || response.rows
|
||||||
|
entries = Array.isArray(rawEntries) ? (rawEntries as Json[]) : []
|
||||||
|
total = Number(response.total ?? entries.length) || 0
|
||||||
|
} catch (reason) {
|
||||||
|
error = reason instanceof Error ? reason.message : 'Unable to load processing history.'
|
||||||
|
entries = []
|
||||||
|
total = 0
|
||||||
|
} finally {
|
||||||
|
if (!background) loading = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function goToPage(next: number) {
|
||||||
|
const target = Math.max(1, next)
|
||||||
|
if (target === currentPage) return
|
||||||
|
currentPage = target
|
||||||
|
void load()
|
||||||
|
}
|
||||||
|
|
||||||
|
function applyTypeFilter(value: string) {
|
||||||
|
typeFilter = value
|
||||||
|
currentPage = 1
|
||||||
|
void load()
|
||||||
|
}
|
||||||
|
|
||||||
|
function applyStatusFilter(value: string) {
|
||||||
|
statusFilter = value
|
||||||
|
currentPage = 1
|
||||||
|
void load()
|
||||||
|
}
|
||||||
|
|
||||||
|
// Re-fetches whenever the mediaType *prop* changes - the Images/Videos/Audios/Funscripts tabs
|
||||||
|
// all reuse one component instance across tab switches (same position in the parent's template),
|
||||||
|
// so this is what makes switching tabs actually reload that tab's own history instead of still
|
||||||
|
// showing the previous tab's entries. Also covers the initial load on mount.
|
||||||
|
$effect(() => {
|
||||||
|
void mediaType
|
||||||
|
currentPage = 1
|
||||||
|
void load()
|
||||||
|
})
|
||||||
|
|
||||||
|
onMount(() => {
|
||||||
|
const timer = window.setInterval(() => void load({ background: true }), 10_000)
|
||||||
|
return () => window.clearInterval(timer)
|
||||||
|
})
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<Card class="space-y-4">
|
||||||
|
<SectionTitle {title} {description} />
|
||||||
|
<div class="flex flex-wrap items-center gap-3">
|
||||||
|
{#if !mediaType}
|
||||||
|
<select
|
||||||
|
class="field h-8 w-40 text-sm"
|
||||||
|
value={typeFilter}
|
||||||
|
onchange={(event) => applyTypeFilter(event.currentTarget.value)}
|
||||||
|
>
|
||||||
|
{#each TYPE_OPTIONS as option (option.value)}
|
||||||
|
<option value={option.value}>{option.label}</option>
|
||||||
|
{/each}
|
||||||
|
</select>
|
||||||
|
{/if}
|
||||||
|
<select
|
||||||
|
class="field h-8 w-40 text-sm"
|
||||||
|
value={statusFilter}
|
||||||
|
onchange={(event) => applyStatusFilter(event.currentTarget.value)}
|
||||||
|
>
|
||||||
|
{#each STATUS_OPTIONS as option (option.value)}
|
||||||
|
<option value={option.value}>{option.label}</option>
|
||||||
|
{/each}
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
{#if error}
|
||||||
|
<p class="rounded-md border border-danger/30 bg-danger/10 p-3 text-xs text-danger">{error}</p>
|
||||||
|
{/if}
|
||||||
|
{#if loading}
|
||||||
|
<p class="text-sm text-muted-fg">Loading history…</p>
|
||||||
|
{:else if entries.length === 0}
|
||||||
|
<EmptyState title="No processed elements" message="Processed files and their results will appear here." />
|
||||||
|
{:else}
|
||||||
|
<div class="space-y-2">
|
||||||
|
{#each entries as entry, index (String(entry.id || entry.file_path || index))}
|
||||||
|
{@const name = firstValue(entry, ['file_name', 'fileName', 'file', 'type', 'action'], 'Processed element')}
|
||||||
|
{@const path = firstValue(entry, ['file_path', 'filePath', 'path'], '')}
|
||||||
|
{@const entryMediaType = firstValue(entry, ['media_type', 'mediaType', 'type'], '')}
|
||||||
|
{@const status = firstValue(entry, ['status', 'state'], 'recorded')}
|
||||||
|
{@const progress = firstValue(entry, ['progress'], '')}
|
||||||
|
{@const timestamp = firstValue(
|
||||||
|
entry,
|
||||||
|
['finished_at', 'finishedAt', 'created_at', 'createdAt', 'queued_at', 'queuedAt', 'timestamp'],
|
||||||
|
'',
|
||||||
|
)}
|
||||||
|
{@const message = firstValue(entry, ['error', 'error_message', 'message'], '')}
|
||||||
|
<div class="rounded-md border border-border bg-bg p-3">
|
||||||
|
<div class="flex items-start justify-between gap-3">
|
||||||
|
<div class="min-w-0">
|
||||||
|
<p class="truncate text-sm font-medium text-fg">{name}</p>
|
||||||
|
{#if path}<p class="mt-1 truncate text-xs text-muted-fg">{path}</p>{/if}
|
||||||
|
</div>
|
||||||
|
<Badge tone={statusTone(status)}>{status}</Badge>
|
||||||
|
</div>
|
||||||
|
<div class="mt-2 flex flex-wrap gap-x-3 gap-y-1 text-xs text-muted-fg">
|
||||||
|
{#if entryMediaType}<span>{entryMediaType}</span>{/if}
|
||||||
|
{#if progress}<span>{progress}% complete</span>{/if}
|
||||||
|
{#if timestamp}<span>{timestamp}</span>{/if}
|
||||||
|
</div>
|
||||||
|
{#if message}<p class="mt-2 truncate text-xs text-danger">{message}</p>{/if}
|
||||||
|
</div>
|
||||||
|
{/each}
|
||||||
|
</div>
|
||||||
|
<div class="flex items-center justify-between border-t border-border pt-3">
|
||||||
|
<p class="text-xs text-muted-fg">Showing {entries.length} of {total.toLocaleString()}</p>
|
||||||
|
<div class="flex gap-2">
|
||||||
|
<Button variant="secondary" size="sm" disabled={currentPage <= 1} onclick={() => goToPage(currentPage - 1)}
|
||||||
|
>Previous</Button
|
||||||
|
><Button
|
||||||
|
variant="secondary"
|
||||||
|
size="sm"
|
||||||
|
disabled={currentPage * pageSize >= total}
|
||||||
|
onclick={() => goToPage(currentPage + 1)}>Next</Button
|
||||||
|
>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
|
</Card>
|
||||||
@@ -0,0 +1,212 @@
|
|||||||
|
<script lang="ts">
|
||||||
|
import { notify } from '@gabriel20xx/web-ui'
|
||||||
|
import { post } from '$lib/api'
|
||||||
|
import SectionTitle from '$lib/components/SectionTitle.svelte'
|
||||||
|
import Badge from '$lib/components/ui/badge.svelte'
|
||||||
|
import Button from '$lib/components/ui/button.svelte'
|
||||||
|
import Card from '$lib/components/ui/card.svelte'
|
||||||
|
|
||||||
|
type Json = Record<string, unknown>
|
||||||
|
type StatusTone = 'neutral' | 'primary' | 'success' | 'warning' | 'danger'
|
||||||
|
|
||||||
|
let {
|
||||||
|
status = {},
|
||||||
|
stats = {},
|
||||||
|
loading = false,
|
||||||
|
description = 'Current analyzer worker state.',
|
||||||
|
}: { status?: Json; stats?: Json; loading?: boolean; description?: string } = $props()
|
||||||
|
|
||||||
|
// discovering/extracting/cleaning all share one backend scan slot (see scanCancel on the Go
|
||||||
|
// side), so they stop through the same endpoint; generate/analyze/the legacy extract worker
|
||||||
|
// each have their own. "clearing" (database clear) has no entry - that reset runs synchronously
|
||||||
|
// on the request that started it, so there's nothing separate left to cancel.
|
||||||
|
const STOP_ENDPOINTS: Record<string, string> = {
|
||||||
|
discovering: 'scan/stop',
|
||||||
|
extracting: 'scan/stop',
|
||||||
|
cleaning: 'scan/stop',
|
||||||
|
generating: 'generate/stop',
|
||||||
|
analyzing: 'analyze/stop',
|
||||||
|
processing: 'extract/stop',
|
||||||
|
}
|
||||||
|
|
||||||
|
let stopping = $state(false)
|
||||||
|
|
||||||
|
function asRecord(value: unknown): Json {
|
||||||
|
return value && typeof value === 'object' && !Array.isArray(value) ? (value as Json) : {}
|
||||||
|
}
|
||||||
|
|
||||||
|
function firstRecord(...values: unknown[]): Json {
|
||||||
|
for (const value of values) {
|
||||||
|
const record = asRecord(value)
|
||||||
|
if (Object.keys(record).length > 0) return record
|
||||||
|
}
|
||||||
|
return {}
|
||||||
|
}
|
||||||
|
|
||||||
|
function numeric(source: Json, key: string, fallback = 0) {
|
||||||
|
const value = Number(source[key] ?? fallback)
|
||||||
|
return Number.isFinite(value) ? value : fallback
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatTimestamp(value: unknown) {
|
||||||
|
if (value === null || value === undefined) return '—'
|
||||||
|
|
||||||
|
if (value instanceof Date) {
|
||||||
|
return Number.isNaN(value.getTime()) ? '—' : value.toLocaleString()
|
||||||
|
}
|
||||||
|
|
||||||
|
const raw = String(value).trim()
|
||||||
|
if (!raw) return '—'
|
||||||
|
|
||||||
|
const numericValue = Number(raw)
|
||||||
|
const timestamp =
|
||||||
|
Number.isFinite(numericValue) && /^-?\d+(?:\.\d+)?$/.test(raw)
|
||||||
|
? Math.abs(numericValue) < 100_000_000_000
|
||||||
|
? numericValue * 1000
|
||||||
|
: numericValue
|
||||||
|
: Date.parse(raw)
|
||||||
|
|
||||||
|
if (!Number.isFinite(timestamp) || timestamp <= 0) return '—'
|
||||||
|
return new Date(timestamp).toLocaleString()
|
||||||
|
}
|
||||||
|
|
||||||
|
function stateTone(label: string, running: boolean, paused: boolean): StatusTone {
|
||||||
|
if (running) return paused ? 'warning' : 'primary'
|
||||||
|
if (label.includes('error') || label.includes('failed')) return 'danger'
|
||||||
|
if (['idle', 'completed', 'complete', 'done'].includes(label)) return 'success'
|
||||||
|
return 'neutral'
|
||||||
|
}
|
||||||
|
|
||||||
|
const extractionProgress = $derived(asRecord(status.extractionProgress))
|
||||||
|
const queue = $derived(firstRecord(status.queue, extractionProgress, stats, status))
|
||||||
|
const currentJob = $derived(asRecord(status.current))
|
||||||
|
const stateLabel = $derived(
|
||||||
|
String(
|
||||||
|
status.state ||
|
||||||
|
status.status ||
|
||||||
|
(status.running === true ? (status.paused === true ? 'paused' : 'running') : 'idle'),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
const stateKey = $derived(stateLabel.toLowerCase())
|
||||||
|
const running = $derived(
|
||||||
|
status.running === true ||
|
||||||
|
status.extracting === true ||
|
||||||
|
status.processing === true ||
|
||||||
|
['running', 'extracting', 'processing', 'discovering', 'generating', 'analyzing', 'cleaning', 'clearing'].includes(
|
||||||
|
stateKey,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
const paused = $derived(status.paused === true || stateKey.includes('paused'))
|
||||||
|
// `status.queue` (a raw media_worker_jobs count) is misleading here: those rows go straight to
|
||||||
|
// "done" on discovery and never actually sit in "queued"/"processing", so that count is always
|
||||||
|
// 0 regardless of how much metadata/thumbnail/AI-analysis work is really pending. `stats` -
|
||||||
|
// summed from the same per-stage pipeline breakdown the dashboard/discover pages render below
|
||||||
|
// this card - is the real number, so it takes priority; the job-table queue is just a fallback
|
||||||
|
// for callers that only ever pass `status`.
|
||||||
|
const queued = $derived(numeric(stats, 'queued', numeric(queue, 'queued', numeric(status, 'queued'))))
|
||||||
|
const processing = $derived(
|
||||||
|
numeric(stats, 'processing', numeric(queue, 'processing', numeric(status, 'processing'))),
|
||||||
|
)
|
||||||
|
const total = $derived(numeric(status, 'total', numeric(extractionProgress, 'total')))
|
||||||
|
const completed = $derived(
|
||||||
|
numeric(
|
||||||
|
status,
|
||||||
|
'completed',
|
||||||
|
numeric(queue, 'completed', numeric(queue, 'done', numeric(extractionProgress, 'extracted'))),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
const failed = $derived(numeric(status, 'failed', numeric(queue, 'failed')))
|
||||||
|
const progressCompleted = $derived(completed + failed)
|
||||||
|
const progressPercent = $derived(total > 0 ? Math.min(100, (progressCompleted / total) * 100) : 0)
|
||||||
|
const current = $derived(
|
||||||
|
typeof status.current === 'string'
|
||||||
|
? status.current
|
||||||
|
: String(currentJob.fileName || currentJob.file_name || currentJob.filePath || currentJob.file_path || '—'),
|
||||||
|
)
|
||||||
|
const worker = $derived(String(status.worker || status.activeWorker || '—'))
|
||||||
|
const lastUpdate = $derived(
|
||||||
|
formatTimestamp(status.updatedAt || status.updated_at || status.timestamp || status.finishedAt),
|
||||||
|
)
|
||||||
|
const lastError = $derived(String(status.lastError || status.error || ''))
|
||||||
|
const tone = $derived(stateTone(stateKey, running, paused))
|
||||||
|
const stopEndpoint = $derived(STOP_ENDPOINTS[stateKey])
|
||||||
|
const canStop = $derived(running && !!stopEndpoint)
|
||||||
|
|
||||||
|
async function stopAction() {
|
||||||
|
if (!stopEndpoint) return
|
||||||
|
stopping = true
|
||||||
|
try {
|
||||||
|
await post(`/api/${stopEndpoint}`)
|
||||||
|
notify.success('Stop requested.')
|
||||||
|
} catch (reason) {
|
||||||
|
notify.error(reason instanceof Error ? reason.message : 'Unable to stop the running action.')
|
||||||
|
} finally {
|
||||||
|
stopping = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<Card class="space-y-4">
|
||||||
|
<SectionTitle title="Live status" {description} />
|
||||||
|
{#if loading}
|
||||||
|
<p class="text-sm text-muted-fg">Loading status…</p>
|
||||||
|
{:else}
|
||||||
|
<div class="space-y-3" aria-live="polite">
|
||||||
|
<div class="flex items-center justify-between gap-3">
|
||||||
|
<span class="text-sm text-muted-fg">State</span>
|
||||||
|
<div class="flex items-center gap-2">
|
||||||
|
<Badge {tone}>{stateLabel}</Badge>
|
||||||
|
{#if canStop}
|
||||||
|
<Button variant="danger" size="sm" disabled={stopping} onclick={() => void stopAction()}>
|
||||||
|
{stopping ? 'Stopping…' : 'Stop'}
|
||||||
|
</Button>
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="flex items-center justify-between">
|
||||||
|
<span class="text-sm text-muted-fg">Pending</span>
|
||||||
|
<span class="text-sm text-fg">{queued}</span>
|
||||||
|
</div>
|
||||||
|
<div class="flex items-center justify-between">
|
||||||
|
<span class="text-sm text-muted-fg">Processing</span>
|
||||||
|
<span class="text-sm text-fg">{processing}</span>
|
||||||
|
</div>
|
||||||
|
<div class="flex items-center justify-between">
|
||||||
|
<span class="text-sm text-muted-fg">Worker</span>
|
||||||
|
<span class="text-sm text-fg">{worker}</span>
|
||||||
|
</div>
|
||||||
|
<div class="flex items-center justify-between gap-3">
|
||||||
|
<span class="text-sm text-muted-fg">Current item</span>
|
||||||
|
<span class="max-w-52 truncate text-right text-xs text-muted-fg">{current}</span>
|
||||||
|
</div>
|
||||||
|
{#if total > 0}
|
||||||
|
<div>
|
||||||
|
<div class="mb-1 flex justify-between text-xs text-muted-fg">
|
||||||
|
<span>Progress</span>
|
||||||
|
<span>{progressCompleted} / {total}</span>
|
||||||
|
</div>
|
||||||
|
<div class="h-2 overflow-hidden rounded-full bg-surface-hover">
|
||||||
|
<div class="h-full rounded-full bg-primary transition-[width]" style={`width: ${progressPercent}%`}></div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{:else if running && progressCompleted > 0}
|
||||||
|
<div>
|
||||||
|
<div class="mb-1 flex justify-between text-xs text-muted-fg">
|
||||||
|
<span>Progress</span>
|
||||||
|
<span>{progressCompleted} processed</span>
|
||||||
|
</div>
|
||||||
|
<div class="h-2 overflow-hidden rounded-full bg-surface-hover">
|
||||||
|
<div class="h-full w-1/3 animate-pulse rounded-full bg-primary"></div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
|
<div class="flex items-center justify-between gap-3">
|
||||||
|
<span class="text-sm text-muted-fg">Last update</span>
|
||||||
|
<span class="max-w-52 truncate text-right text-xs text-muted-fg">{lastUpdate}</span>
|
||||||
|
</div>
|
||||||
|
{#if lastError}
|
||||||
|
<p class="rounded-md border border-danger/30 bg-danger/10 p-3 text-xs text-danger">{lastError}</p>
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
|
</Card>
|
||||||
@@ -0,0 +1,85 @@
|
|||||||
|
<script lang="ts">
|
||||||
|
import SectionTitle from '$lib/components/SectionTitle.svelte'
|
||||||
|
import Card from '$lib/components/ui/card.svelte'
|
||||||
|
|
||||||
|
type Json = Record<string, unknown>
|
||||||
|
|
||||||
|
const mediaTypes = [
|
||||||
|
{ key: 'image', label: 'Images' },
|
||||||
|
{ key: 'video', label: 'Videos' },
|
||||||
|
{ key: 'audio', label: 'Audios' },
|
||||||
|
{ key: 'funscript', label: 'Funscripts' },
|
||||||
|
]
|
||||||
|
// 'convert' is left out - that stage was retired along with the Convert tab, and the
|
||||||
|
// backend's breakdown map still carries it (always zero) only for backward compatibility.
|
||||||
|
// 'discover' is left out too - it's not a per-file processing stage, just the media count
|
||||||
|
// itself, which is already shown via total() in the card header.
|
||||||
|
const processStages = [
|
||||||
|
{ key: 'extract', label: 'Metadata' },
|
||||||
|
{ key: 'generate', label: 'Thumbnails' },
|
||||||
|
{ key: 'analyze', label: 'AI analysis' },
|
||||||
|
]
|
||||||
|
|
||||||
|
let { pipeline = {} }: { pipeline?: Json } = $props()
|
||||||
|
|
||||||
|
// Thumbnails only ever run for images and videos, and AI analysis has no stages at all for
|
||||||
|
// funscript - skip those rows rather than showing counts that can only ever read zero.
|
||||||
|
function stagesFor(mediaTypeKey: string) {
|
||||||
|
return processStages.filter((stage) => {
|
||||||
|
if (stage.key === 'generate') return mediaTypeKey === 'image' || mediaTypeKey === 'video'
|
||||||
|
if (stage.key === 'analyze') return mediaTypeKey !== 'funscript'
|
||||||
|
return true
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
function count(stage: string, mediaType: string, status: string) {
|
||||||
|
const stageData = pipeline[stage]
|
||||||
|
if (!stageData || typeof stageData !== 'object' || Array.isArray(stageData)) return 0
|
||||||
|
const mediaData = (stageData as Json)[mediaType]
|
||||||
|
if (!mediaData || typeof mediaData !== 'object' || Array.isArray(mediaData)) return 0
|
||||||
|
const value = Number((mediaData as Json)[status] ?? 0)
|
||||||
|
return Number.isFinite(value) ? value : 0
|
||||||
|
}
|
||||||
|
|
||||||
|
// The "discover" stage's "completed" bucket is a straight count of active media rows of that type
|
||||||
|
// (funscripts counted via has_funscript rather than their own media_type) - already exactly the
|
||||||
|
// per-type total, so there's no need for a separate stats prop just to show it in the header.
|
||||||
|
function total(mediaTypeKey: string) {
|
||||||
|
return count('discover', mediaTypeKey, 'completed')
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<Card class="space-y-4">
|
||||||
|
<SectionTitle
|
||||||
|
title="Pipeline breakdown"
|
||||||
|
description="Pending, completed, and error counts for every media type and processing stage."
|
||||||
|
/>
|
||||||
|
<div class="grid gap-4 md:grid-cols-2">
|
||||||
|
{#each mediaTypes as mediaType (mediaType.key)}
|
||||||
|
<div class="overflow-hidden rounded-md border border-border">
|
||||||
|
<div class="flex items-center justify-between border-b border-border bg-bg px-4 py-3">
|
||||||
|
<h3 class="text-sm font-semibold text-fg">{mediaType.label}</h3>
|
||||||
|
<span class="text-xs text-muted-fg">{total(mediaType.key).toLocaleString()} total</span>
|
||||||
|
</div>
|
||||||
|
<div class="grid grid-cols-[minmax(0,1fr)_4.5rem_4.5rem_4.5rem] items-center gap-x-2 px-4 py-2 text-xs">
|
||||||
|
<span class="text-muted-fg">Process stage</span>
|
||||||
|
<span class="text-right text-warning">Pending</span>
|
||||||
|
<span class="text-right text-success">Done</span>
|
||||||
|
<span class="text-right text-danger">Errors</span>
|
||||||
|
{#each stagesFor(mediaType.key) as stage (stage.key)}
|
||||||
|
<span class="border-t border-border py-2 text-sm text-fg">{stage.label}</span>
|
||||||
|
<span class="border-t border-border py-2 text-right text-sm text-warning"
|
||||||
|
>{count(stage.key, mediaType.key, 'queued')}</span
|
||||||
|
>
|
||||||
|
<span class="border-t border-border py-2 text-right text-sm text-success"
|
||||||
|
>{count(stage.key, mediaType.key, 'completed')}</span
|
||||||
|
>
|
||||||
|
<span class="border-t border-border py-2 text-right text-sm text-danger"
|
||||||
|
>{count(stage.key, mediaType.key, 'errors')}</span
|
||||||
|
>
|
||||||
|
{/each}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{/each}
|
||||||
|
</div>
|
||||||
|
</Card>
|
||||||
@@ -0,0 +1,292 @@
|
|||||||
|
<script lang="ts">
|
||||||
|
import { goto } from '$app/navigation'
|
||||||
|
import { page } from '$app/state'
|
||||||
|
import { onMount } from 'svelte'
|
||||||
|
import AuthPage from '$lib/components/AuthPage.svelte'
|
||||||
|
import ProjectIcon from '$lib/components/ProjectIcon.svelte'
|
||||||
|
import AboutWorkspace from '$lib/features/AboutWorkspace.svelte'
|
||||||
|
import { AboutDialog, AdminDialog, Header, NotificationStack, PageHeader, ProfileDialog } from '@gabriel20xx/web-ui'
|
||||||
|
import type {
|
||||||
|
AuthLoginInput,
|
||||||
|
AuthSetupInput,
|
||||||
|
ManagedUser,
|
||||||
|
ProfileUpdateInput,
|
||||||
|
UserCreateInput,
|
||||||
|
UserId,
|
||||||
|
UserRole,
|
||||||
|
UserUpdateInput,
|
||||||
|
} from '@gabriel20xx/web-ui'
|
||||||
|
import SettingsDialog from '$lib/components/SettingsDialog.svelte'
|
||||||
|
import { getPanelForPath } from '$lib/app-config'
|
||||||
|
import { pageActions } from '$lib/stores/page-actions.svelte'
|
||||||
|
import { del, get, post, put } from '$lib/api'
|
||||||
|
import '$lib/language.svelte'
|
||||||
|
import type { AppConfig, AuthState, AuthUser } from '$lib/types'
|
||||||
|
import type { Snippet } from 'svelte'
|
||||||
|
|
||||||
|
let { app, children }: { app: AppConfig; children: Snippet } = $props()
|
||||||
|
|
||||||
|
let auth = $state<AuthState>({
|
||||||
|
user: null,
|
||||||
|
authRequired: true,
|
||||||
|
setupRequired: true,
|
||||||
|
loading: true,
|
||||||
|
error: null,
|
||||||
|
})
|
||||||
|
let settingsOpen = $state(false)
|
||||||
|
let aboutOpen = $state(false)
|
||||||
|
let profileOpen = $state(false)
|
||||||
|
let adminOpen = $state(false)
|
||||||
|
|
||||||
|
// Header only renders its profile/settings menu when username is truthy - with login not
|
||||||
|
// required and nobody signed in, auth.user is legitimately null (there's no session to read
|
||||||
|
// it from), which silently hid Settings (and with it, the only UI path back to re-enabling
|
||||||
|
// login) behind a button that never appeared. Falls back to a placeholder identity in that
|
||||||
|
// one case so the menu - and Settings - stays reachable.
|
||||||
|
const displayName = $derived(auth.user?.username || auth.user?.email || (auth.authRequired ? '' : 'Admin'))
|
||||||
|
const homePath = $derived(app.nav[0]?.path || '/')
|
||||||
|
const navItems = $derived(
|
||||||
|
app.nav.map((item) => ({
|
||||||
|
href: item.path,
|
||||||
|
label: item.label,
|
||||||
|
icon: item.icon,
|
||||||
|
description: item.description,
|
||||||
|
})),
|
||||||
|
)
|
||||||
|
const activeNavItem = $derived(
|
||||||
|
app.nav.find((item) => item.panel === getPanelForPath(app, page.url.pathname)) || app.nav[0],
|
||||||
|
)
|
||||||
|
const currentRole = $derived<UserRole>(
|
||||||
|
auth.user?.role === 'superadmin' || auth.user?.role === 'admin' ? auth.user.role : 'user',
|
||||||
|
)
|
||||||
|
const currentUserId = $derived<UserId | undefined>(auth.user?.id)
|
||||||
|
const isAdmin = $derived(currentRole === 'admin' || currentRole === 'superadmin')
|
||||||
|
|
||||||
|
function openSettings() {
|
||||||
|
settingsOpen = true
|
||||||
|
}
|
||||||
|
|
||||||
|
function openAbout() {
|
||||||
|
aboutOpen = true
|
||||||
|
}
|
||||||
|
|
||||||
|
function openProfile() {
|
||||||
|
profileOpen = true
|
||||||
|
}
|
||||||
|
|
||||||
|
function openAdmin() {
|
||||||
|
adminOpen = true
|
||||||
|
}
|
||||||
|
|
||||||
|
function closeSettings() {
|
||||||
|
settingsOpen = false
|
||||||
|
if (page.url.pathname === '/settings') void goto(homePath)
|
||||||
|
}
|
||||||
|
|
||||||
|
function closeAbout() {
|
||||||
|
aboutOpen = false
|
||||||
|
if (page.url.pathname === '/about') void goto(homePath)
|
||||||
|
}
|
||||||
|
|
||||||
|
function currentPageToken() {
|
||||||
|
if (typeof window === 'undefined') return '/'
|
||||||
|
return `${window.location.pathname}${window.location.search}` || '/'
|
||||||
|
}
|
||||||
|
|
||||||
|
async function loadAuth() {
|
||||||
|
try {
|
||||||
|
const data = await get<{ user: AuthUser | null; authRequired?: boolean }>(
|
||||||
|
`/auth/me?page=${encodeURIComponent(currentPageToken())}`,
|
||||||
|
)
|
||||||
|
let setupRequired = false
|
||||||
|
try {
|
||||||
|
const bootstrap = await get<{ adminNeeded?: boolean }>('/auth/bootstrap/admin-needed')
|
||||||
|
setupRequired = bootstrap.adminNeeded === true
|
||||||
|
} catch {
|
||||||
|
// The auth status remains usable if the optional bootstrap check is unavailable.
|
||||||
|
}
|
||||||
|
auth = {
|
||||||
|
user: data.user || null,
|
||||||
|
authRequired: data.authRequired !== false,
|
||||||
|
setupRequired,
|
||||||
|
loading: false,
|
||||||
|
error: null,
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
auth = {
|
||||||
|
...auth,
|
||||||
|
loading: false,
|
||||||
|
error: error instanceof Error ? error.message : 'Unable to load authentication state.',
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function login(input: AuthLoginInput) {
|
||||||
|
const data = await post<{ user: AuthUser }>('/auth/login', {
|
||||||
|
identifier: input.identifier,
|
||||||
|
password: input.password,
|
||||||
|
totpToken: input.totpToken,
|
||||||
|
})
|
||||||
|
auth = { ...auth, user: data.user, setupRequired: false, loading: false, error: null }
|
||||||
|
}
|
||||||
|
|
||||||
|
async function setup(input: AuthSetupInput) {
|
||||||
|
const data = await post<{ user: AuthUser }>('/auth/signup', {
|
||||||
|
email: input.email,
|
||||||
|
username: input.username,
|
||||||
|
password: input.password,
|
||||||
|
})
|
||||||
|
auth = { ...auth, user: data.user, setupRequired: false, loading: false, error: null }
|
||||||
|
}
|
||||||
|
|
||||||
|
const requestReset = () => post('/auth/reset/request')
|
||||||
|
|
||||||
|
async function confirmReset(code: string) {
|
||||||
|
await post('/auth/reset/confirm', { code })
|
||||||
|
window.location.reload()
|
||||||
|
}
|
||||||
|
|
||||||
|
async function logout() {
|
||||||
|
try {
|
||||||
|
await post('/auth/logout')
|
||||||
|
auth.user = null
|
||||||
|
} catch (error) {
|
||||||
|
auth.error = error instanceof Error ? error.message : 'Logout failed.'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function updateProfile(input: ProfileUpdateInput) {
|
||||||
|
const data = await put<{ user: AuthUser }>('/auth/me', input)
|
||||||
|
auth = { ...auth, user: data.user, error: null }
|
||||||
|
}
|
||||||
|
|
||||||
|
async function listUsers(): Promise<ManagedUser[]> {
|
||||||
|
return get<ManagedUser[]>('/api/auth/users')
|
||||||
|
}
|
||||||
|
|
||||||
|
async function createUser(input: UserCreateInput): Promise<void | ManagedUser> {
|
||||||
|
return post<ManagedUser>('/api/auth/users', input)
|
||||||
|
}
|
||||||
|
|
||||||
|
async function updateUser(id: UserId, input: UserUpdateInput): Promise<void | ManagedUser> {
|
||||||
|
return put<ManagedUser>(`/api/auth/users/${encodeURIComponent(String(id))}`, input)
|
||||||
|
}
|
||||||
|
|
||||||
|
async function deleteUser(id: UserId): Promise<void> {
|
||||||
|
await del<{ ok: boolean }>(`/api/auth/users/${encodeURIComponent(String(id))}`)
|
||||||
|
}
|
||||||
|
|
||||||
|
async function updateLoginRequired(loginRequired: boolean) {
|
||||||
|
await put<{ loginRequired: boolean }>('/api/auth/access', { loginRequired })
|
||||||
|
auth = { ...auth, authRequired: loginRequired }
|
||||||
|
}
|
||||||
|
|
||||||
|
onMount(() => {
|
||||||
|
void loadAuth()
|
||||||
|
})
|
||||||
|
|
||||||
|
$effect(() => {
|
||||||
|
if (page.url.pathname === '/settings') settingsOpen = true
|
||||||
|
if (page.url.pathname === '/about') aboutOpen = true
|
||||||
|
})
|
||||||
|
</script>
|
||||||
|
|
||||||
|
{#if auth.loading || auth.error || auth.setupRequired || (auth.authRequired && !auth.user)}
|
||||||
|
<AuthPage
|
||||||
|
{app}
|
||||||
|
setupRequired={auth.setupRequired}
|
||||||
|
loading={auth.loading}
|
||||||
|
error={auth.error || ''}
|
||||||
|
onLogin={login}
|
||||||
|
onSetup={setup}
|
||||||
|
onRequestReset={requestReset}
|
||||||
|
onConfirmReset={confirmReset}
|
||||||
|
/>
|
||||||
|
{:else}
|
||||||
|
<div class="sc-root sc-app-shell min-h-screen bg-bg text-fg mediacollection-shell">
|
||||||
|
<NotificationStack />
|
||||||
|
|
||||||
|
<Header
|
||||||
|
brand={app.name}
|
||||||
|
brandHref={homePath}
|
||||||
|
currentPath={page.url.pathname}
|
||||||
|
faviconHref="/favicon.svg"
|
||||||
|
{navItems}
|
||||||
|
onAbout={openAbout}
|
||||||
|
onAdmin={isAdmin ? openAdmin : undefined}
|
||||||
|
onLogout={logout}
|
||||||
|
onProfile={openProfile}
|
||||||
|
onSettings={openSettings}
|
||||||
|
username={displayName}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<main class="mx-auto w-full max-w-7xl px-4 pt-4 pb-8">
|
||||||
|
<PageHeader
|
||||||
|
title={activeNavItem?.label || app.name}
|
||||||
|
description={activeNavItem?.description || app.description}
|
||||||
|
actions={pageActions.snippet ?? undefined}
|
||||||
|
/>
|
||||||
|
{@render children?.()}
|
||||||
|
</main>
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
|
|
||||||
|
<SettingsDialog bind:open={settingsOpen} onClose={closeSettings} />
|
||||||
|
<AdminDialog
|
||||||
|
bind:open={adminOpen}
|
||||||
|
{currentRole}
|
||||||
|
{currentUserId}
|
||||||
|
onListUsers={listUsers}
|
||||||
|
onCreateUser={createUser}
|
||||||
|
onUpdateUser={updateUser}
|
||||||
|
onDeleteUser={deleteUser}
|
||||||
|
loginRequired={auth.authRequired}
|
||||||
|
onLoginRequiredChange={updateLoginRequired}
|
||||||
|
/>
|
||||||
|
<AboutDialog bind:open={aboutOpen} brand={app.name} description={app.description} onClose={closeAbout}>
|
||||||
|
{#snippet icon()}
|
||||||
|
<ProjectIcon icon={app.icon} class="size-8 text-primary" />
|
||||||
|
{/snippet}
|
||||||
|
<AboutWorkspace />
|
||||||
|
</AboutDialog>
|
||||||
|
<ProfileDialog
|
||||||
|
bind:open={profileOpen}
|
||||||
|
currentEmail={auth.user?.email || ''}
|
||||||
|
currentUsername={auth.user?.username || ''}
|
||||||
|
onSave={updateProfile}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<style>
|
||||||
|
/* The shared component library (header, page title box, dialogs, buttons, ...) otherwise
|
||||||
|
renders in its own generic default palette instead of this app's own branding - remap its
|
||||||
|
--sc-* tokens onto this app's own --color-* palette so every shared component follows suit.
|
||||||
|
--sc-secondary is a subtle tinted-surface color for low-emphasis buttons, a different role
|
||||||
|
than this app's own saturated --color-secondary, so it's derived instead of mapped directly. */
|
||||||
|
:global(.mediacollection-shell) {
|
||||||
|
--sc-bg: var(--color-bg);
|
||||||
|
--sc-surface: var(--color-surface);
|
||||||
|
--sc-surface-raised: var(--color-surface);
|
||||||
|
--sc-surface-hover: var(--color-surface-hover);
|
||||||
|
--sc-border: var(--color-border);
|
||||||
|
--sc-border-strong: var(--color-border);
|
||||||
|
--sc-fg: var(--color-fg);
|
||||||
|
--sc-muted-fg: var(--color-muted-fg);
|
||||||
|
--sc-subtle-fg: var(--color-muted-fg);
|
||||||
|
--sc-primary: var(--color-primary);
|
||||||
|
--sc-primary-hover: var(--color-secondary);
|
||||||
|
--sc-primary-fg: var(--color-primary-fg);
|
||||||
|
--sc-secondary: color-mix(in srgb, var(--color-primary) 12%, var(--color-surface));
|
||||||
|
--sc-secondary-hover: color-mix(in srgb, var(--color-primary) 20%, var(--color-surface));
|
||||||
|
--sc-secondary-fg: var(--color-fg);
|
||||||
|
--sc-accent: var(--color-accent);
|
||||||
|
--sc-accent-fg: var(--color-accent-fg);
|
||||||
|
--sc-danger: var(--color-danger);
|
||||||
|
--sc-danger-hover: color-mix(in srgb, var(--color-danger) 90%, black);
|
||||||
|
--sc-danger-fg: var(--color-danger-fg);
|
||||||
|
--sc-success: var(--color-success);
|
||||||
|
--sc-success-fg: var(--color-success-fg);
|
||||||
|
--sc-warning: var(--color-warning);
|
||||||
|
--sc-warning-fg: var(--color-warning-fg);
|
||||||
|
--sc-ring: var(--color-ring);
|
||||||
|
}
|
||||||
|
</style>
|
||||||
@@ -0,0 +1,43 @@
|
|||||||
|
<script lang="ts">
|
||||||
|
import {
|
||||||
|
AuthPage as SharedAuthPage,
|
||||||
|
type AuthLoginInput,
|
||||||
|
type AuthResetConfirm,
|
||||||
|
type AuthResetRequest,
|
||||||
|
type AuthSetupInput,
|
||||||
|
} from '@gabriel20xx/web-ui'
|
||||||
|
import type { AppConfig } from '$lib/types'
|
||||||
|
|
||||||
|
let {
|
||||||
|
app,
|
||||||
|
error = '',
|
||||||
|
loading = false,
|
||||||
|
onConfirmReset,
|
||||||
|
onLogin,
|
||||||
|
onRequestReset,
|
||||||
|
onSetup,
|
||||||
|
setupRequired,
|
||||||
|
}: {
|
||||||
|
app: AppConfig
|
||||||
|
error?: string
|
||||||
|
loading?: boolean
|
||||||
|
onConfirmReset: AuthResetConfirm
|
||||||
|
onLogin: (input: AuthLoginInput) => void | Promise<void>
|
||||||
|
onRequestReset: AuthResetRequest
|
||||||
|
onSetup: (input: AuthSetupInput) => void | Promise<void>
|
||||||
|
setupRequired: boolean
|
||||||
|
} = $props()
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<SharedAuthPage
|
||||||
|
brand={app.name}
|
||||||
|
tagline={app.eyebrow}
|
||||||
|
{setupRequired}
|
||||||
|
{loading}
|
||||||
|
{error}
|
||||||
|
showTotp
|
||||||
|
{onLogin}
|
||||||
|
{onSetup}
|
||||||
|
{onRequestReset}
|
||||||
|
{onConfirmReset}
|
||||||
|
/>
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
<script lang="ts">
|
||||||
|
import { Inbox } from '@lucide/svelte'
|
||||||
|
let { title, message }: { title: string; message: string } = $props()
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<div
|
||||||
|
class="flex min-h-40 flex-col items-center justify-center gap-3 rounded-lg border border-dashed border-border bg-surface/50 px-5 py-8 text-center"
|
||||||
|
>
|
||||||
|
<Inbox class="size-8 text-muted-fg" />
|
||||||
|
<div>
|
||||||
|
<p class="text-sm font-medium text-fg">{title}</p>
|
||||||
|
<p class="mt-1 max-w-sm text-xs text-muted-fg">{message}</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
@@ -0,0 +1,352 @@
|
|||||||
|
<script lang="ts">
|
||||||
|
import { ArrowDown, ArrowRight, ChevronDown, FileCog, Image as ImageIcon, Search, Sparkles } from '@lucide/svelte'
|
||||||
|
import Badge from '$lib/components/ui/badge.svelte'
|
||||||
|
import { cn } from '$lib/utils/cn'
|
||||||
|
|
||||||
|
type StageStatus = { pending: number; processing: number; processed: number; errors: number; active: boolean }
|
||||||
|
type AiStage = { key: string; label: string; model: string; enabled: boolean }
|
||||||
|
type StageErrorItem = { filePath: string; error: string }
|
||||||
|
type StageKey = 'metadata' | 'thumbnails' | 'analyze'
|
||||||
|
|
||||||
|
let {
|
||||||
|
discovered,
|
||||||
|
discoveredLabel,
|
||||||
|
metadataEnabled,
|
||||||
|
metadataStatus,
|
||||||
|
metadataDescription,
|
||||||
|
metadataDetails,
|
||||||
|
onToggleMetadata,
|
||||||
|
thumbnailsSupported,
|
||||||
|
thumbnailsEnabled,
|
||||||
|
thumbnailsStatus,
|
||||||
|
thumbnailsDescription,
|
||||||
|
thumbnailsDetails,
|
||||||
|
onToggleThumbnails,
|
||||||
|
aiStages,
|
||||||
|
modelOptions,
|
||||||
|
hasAiModel,
|
||||||
|
analysisStatus,
|
||||||
|
onToggleStage,
|
||||||
|
onModelChange,
|
||||||
|
onRetryErrors,
|
||||||
|
onShowErrors,
|
||||||
|
disabled = false,
|
||||||
|
}: {
|
||||||
|
discovered: number
|
||||||
|
discoveredLabel: string
|
||||||
|
metadataEnabled: boolean
|
||||||
|
metadataStatus: StageStatus
|
||||||
|
metadataDescription: string
|
||||||
|
metadataDetails: string
|
||||||
|
onToggleMetadata: (enabled: boolean) => void
|
||||||
|
thumbnailsSupported: boolean
|
||||||
|
thumbnailsEnabled: boolean
|
||||||
|
thumbnailsStatus: StageStatus
|
||||||
|
thumbnailsDescription: string
|
||||||
|
thumbnailsDetails: string
|
||||||
|
onToggleThumbnails: (enabled: boolean) => void
|
||||||
|
aiStages: AiStage[]
|
||||||
|
modelOptions: string[]
|
||||||
|
hasAiModel: boolean
|
||||||
|
analysisStatus: StageStatus
|
||||||
|
onToggleStage: (stage: string, enabled: boolean) => void
|
||||||
|
onModelChange: (stage: string, model: string) => void
|
||||||
|
onRetryErrors: (stage: StageKey) => void
|
||||||
|
onShowErrors: (stage: StageKey) => Promise<StageErrorItem[]>
|
||||||
|
disabled?: boolean
|
||||||
|
} = $props()
|
||||||
|
|
||||||
|
// Short, model-agnostic descriptions of what each AI backend actually produces - shown in the
|
||||||
|
// AI analysis stage's expandable details rather than making users guess from the model name.
|
||||||
|
const MODEL_DETAILS: Record<string, string> = {
|
||||||
|
nsfwjs: 'NSFWJS - classifies the frame as safe or not-safe-for-work.',
|
||||||
|
wdtagger: 'WD Tagger - predicts weighted Danbooru-style content tags.',
|
||||||
|
faceapi: 'face-api.js - detects faces and estimates apparent gender.',
|
||||||
|
onnxage: 'ONNX Age - estimates the apparent age of detected faces.',
|
||||||
|
florence2: 'Florence-2 - vision-language model used for captions and descriptions.',
|
||||||
|
laplacian: 'Laplacian variance - measures image sharpness/blur as a quality signal.',
|
||||||
|
whisper: 'Whisper - transcribes spoken audio to text.',
|
||||||
|
clap: 'CLAP - audio-text embedding model used for zero-shot audio tagging.',
|
||||||
|
}
|
||||||
|
|
||||||
|
const showAiAnalysis = $derived(aiStages.length > 0)
|
||||||
|
const aiActive = $derived(hasAiModel && aiStages.some((stage) => stage.enabled))
|
||||||
|
|
||||||
|
let metadataDetailsOpen = $state(false)
|
||||||
|
let thumbnailsDetailsOpen = $state(false)
|
||||||
|
let aiDetailsOpen = $state(false)
|
||||||
|
|
||||||
|
// Keyed by stage so each of the three error panels (metadata/thumbnails/analyze) opens,
|
||||||
|
// loads, and closes independently. Errors are fetched on open rather than eagerly for every
|
||||||
|
// stage up front - most stages never have any, and the count alone (already shown) is enough
|
||||||
|
// until the user actually asks to see what failed.
|
||||||
|
let errorPanels = $state<Record<string, { open: boolean; loading: boolean; items: StageErrorItem[] }>>({})
|
||||||
|
|
||||||
|
async function toggleErrors(stage: StageKey) {
|
||||||
|
const current = errorPanels[stage]
|
||||||
|
if (current?.open) {
|
||||||
|
errorPanels = { ...errorPanels, [stage]: { ...current, open: false } }
|
||||||
|
return
|
||||||
|
}
|
||||||
|
errorPanels = { ...errorPanels, [stage]: { open: true, loading: true, items: current?.items ?? [] } }
|
||||||
|
const items = await onShowErrors(stage)
|
||||||
|
errorPanels = { ...errorPanels, [stage]: { open: true, loading: false, items } }
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
{#snippet connector(active: boolean)}
|
||||||
|
<div class="flex items-center justify-center py-1 lg:px-1 lg:py-0">
|
||||||
|
<ArrowDown class={cn('size-5 shrink-0 lg:hidden', active ? 'animate-pulse text-primary' : 'text-muted-fg/40')} />
|
||||||
|
<ArrowRight
|
||||||
|
class={cn('hidden size-5 shrink-0 lg:block', active ? 'animate-pulse text-primary' : 'text-muted-fg/40')}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
{/snippet}
|
||||||
|
|
||||||
|
{#snippet toggle(enabled: boolean, onToggle: (value: boolean) => void, toggleLabel: string)}
|
||||||
|
<label
|
||||||
|
class="mt-auto flex items-center justify-between gap-2 border-t border-border pt-3 text-xs font-medium text-muted-fg"
|
||||||
|
>
|
||||||
|
{toggleLabel}
|
||||||
|
<span
|
||||||
|
class={cn(
|
||||||
|
'relative inline-flex h-6 w-11 shrink-0 items-center rounded-full transition-colors',
|
||||||
|
enabled ? 'bg-primary' : 'bg-border',
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
<input
|
||||||
|
type="checkbox"
|
||||||
|
class="peer absolute inset-0 size-full cursor-pointer opacity-0"
|
||||||
|
checked={enabled}
|
||||||
|
{disabled}
|
||||||
|
aria-label={toggleLabel}
|
||||||
|
onchange={(event) => onToggle((event.currentTarget as HTMLInputElement).checked)}
|
||||||
|
/>
|
||||||
|
<span
|
||||||
|
class={cn(
|
||||||
|
'pointer-events-none inline-block size-4 translate-x-1 rounded-full bg-white shadow transition-transform',
|
||||||
|
enabled && 'translate-x-6',
|
||||||
|
)}
|
||||||
|
></span>
|
||||||
|
</span>
|
||||||
|
</label>
|
||||||
|
{/snippet}
|
||||||
|
|
||||||
|
{#snippet detailsToggle(open: boolean, onClick: () => void)}
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
class="flex items-center gap-1 self-start text-[11px] font-medium text-muted-fg hover:text-fg"
|
||||||
|
onclick={onClick}
|
||||||
|
>
|
||||||
|
<ChevronDown class={cn('size-3 transition-transform', open && 'rotate-180')} />
|
||||||
|
{open ? 'Hide details' : 'Show details'}
|
||||||
|
</button>
|
||||||
|
{/snippet}
|
||||||
|
|
||||||
|
{#snippet statusGrid(status: StageStatus, stage: StageKey, onRetry: () => void)}
|
||||||
|
{@const panel = errorPanels[stage]}
|
||||||
|
<div class="grid grid-cols-3 gap-2 text-center text-xs">
|
||||||
|
<div>
|
||||||
|
<p class="text-base font-semibold text-warning">{status.pending}</p>
|
||||||
|
<p class="text-muted-fg">Pending</p>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<p class="text-base font-semibold text-primary">{status.processing}</p>
|
||||||
|
<p class="text-muted-fg">Processing</p>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<p class="text-base font-semibold text-success">{status.processed}</p>
|
||||||
|
<p class="text-muted-fg">Processed</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{#if status.errors > 0}
|
||||||
|
<div class="flex items-center justify-between gap-2 rounded-md bg-danger/10 px-2 py-1.5 text-xs text-danger">
|
||||||
|
<span>{status.errors} error{status.errors === 1 ? '' : 's'}</span>
|
||||||
|
<div class="flex items-center gap-3">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
class="font-medium underline decoration-dotted hover:text-danger/80 disabled:opacity-50"
|
||||||
|
{disabled}
|
||||||
|
onclick={() => void toggleErrors(stage)}
|
||||||
|
>
|
||||||
|
{panel?.open ? 'Hide text' : 'Show text'}
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
class="font-medium underline decoration-dotted hover:text-danger/80 disabled:opacity-50"
|
||||||
|
{disabled}
|
||||||
|
onclick={onRetry}
|
||||||
|
>
|
||||||
|
Retry
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{#if panel?.open}
|
||||||
|
<div class="max-h-40 space-y-1 overflow-y-auto rounded-md bg-bg p-2 text-[11px] text-danger">
|
||||||
|
{#if panel.loading}
|
||||||
|
<p class="text-muted-fg">Loading errors…</p>
|
||||||
|
{:else if panel.items.length === 0}
|
||||||
|
<p class="text-muted-fg">No recent error text available.</p>
|
||||||
|
{:else}
|
||||||
|
{#each panel.items as item (item.filePath)}
|
||||||
|
<p><span class="font-medium text-fg">{item.filePath}:</span> {item.error}</p>
|
||||||
|
{/each}
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
|
{/if}
|
||||||
|
{/snippet}
|
||||||
|
|
||||||
|
<div class="flex flex-col lg:flex-row lg:items-stretch">
|
||||||
|
<div
|
||||||
|
class="flex flex-1 flex-col items-center justify-center gap-2 rounded-lg border border-border bg-surface p-4 text-center"
|
||||||
|
>
|
||||||
|
<Search class="size-5 text-muted-fg" />
|
||||||
|
<p class="text-2xl font-semibold text-fg">{discovered}</p>
|
||||||
|
<p class="text-xs font-medium uppercase tracking-wide text-muted-fg">{discoveredLabel} discovered</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{@render connector(metadataStatus.active)}
|
||||||
|
|
||||||
|
<div
|
||||||
|
class={cn(
|
||||||
|
'flex flex-1 flex-col gap-3 rounded-lg border p-4 transition-opacity',
|
||||||
|
metadataEnabled ? 'border-border bg-surface' : 'border-border/60 bg-surface/40 opacity-70',
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
<div class="flex items-center justify-between gap-2">
|
||||||
|
<div class="flex items-center gap-2">
|
||||||
|
<FileCog class="size-4 text-muted-fg" />
|
||||||
|
<span class="text-sm font-semibold text-fg">Metadata</span>
|
||||||
|
</div>
|
||||||
|
{#if metadataStatus.active}
|
||||||
|
<Badge tone="primary" class="animate-pulse">Active</Badge>
|
||||||
|
{:else}
|
||||||
|
<Badge tone="neutral">Idle</Badge>
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
|
<p class="text-xs text-muted-fg">{metadataDescription}</p>
|
||||||
|
{@render detailsToggle(metadataDetailsOpen, () => (metadataDetailsOpen = !metadataDetailsOpen))}
|
||||||
|
{#if metadataDetailsOpen}
|
||||||
|
<p class="rounded-md bg-bg p-2 text-[11px] text-muted-fg">{metadataDetails}</p>
|
||||||
|
{/if}
|
||||||
|
{@render statusGrid(metadataStatus, 'metadata', () => onRetryErrors('metadata'))}
|
||||||
|
{@render toggle(metadataEnabled, onToggleMetadata, 'Enabled')}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{#if thumbnailsSupported}
|
||||||
|
{@render connector(thumbnailsStatus.active)}
|
||||||
|
|
||||||
|
<div
|
||||||
|
class={cn(
|
||||||
|
'flex flex-1 flex-col gap-3 rounded-lg border p-4 transition-opacity',
|
||||||
|
thumbnailsEnabled ? 'border-border bg-surface' : 'border-border/60 bg-surface/40 opacity-70',
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
<div class="flex items-center justify-between gap-2">
|
||||||
|
<div class="flex items-center gap-2">
|
||||||
|
<ImageIcon class="size-4 text-muted-fg" />
|
||||||
|
<span class="text-sm font-semibold text-fg">Thumbnails</span>
|
||||||
|
</div>
|
||||||
|
{#if thumbnailsStatus.active}
|
||||||
|
<Badge tone="primary" class="animate-pulse">Active</Badge>
|
||||||
|
{:else}
|
||||||
|
<Badge tone="neutral">Idle</Badge>
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
|
<p class="text-xs text-muted-fg">{thumbnailsDescription}</p>
|
||||||
|
{@render detailsToggle(thumbnailsDetailsOpen, () => (thumbnailsDetailsOpen = !thumbnailsDetailsOpen))}
|
||||||
|
{#if thumbnailsDetailsOpen}
|
||||||
|
<p class="rounded-md bg-bg p-2 text-[11px] text-muted-fg">{thumbnailsDetails}</p>
|
||||||
|
{/if}
|
||||||
|
{@render statusGrid(thumbnailsStatus, 'thumbnails', () => onRetryErrors('thumbnails'))}
|
||||||
|
{@render toggle(thumbnailsEnabled, onToggleThumbnails, 'Enabled')}
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
|
|
||||||
|
{#if showAiAnalysis}
|
||||||
|
{@render connector(analysisStatus.active)}
|
||||||
|
|
||||||
|
<div
|
||||||
|
class={cn(
|
||||||
|
'flex flex-1 flex-col gap-3 rounded-lg border p-4 transition-opacity',
|
||||||
|
aiActive ? 'border-border bg-surface' : 'border-border/60 bg-surface/40 opacity-70',
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
<div class="flex items-center justify-between gap-2">
|
||||||
|
<div class="flex items-center gap-2">
|
||||||
|
<Sparkles class="size-4 text-muted-fg" />
|
||||||
|
<span class="text-sm font-semibold text-fg">AI analysis</span>
|
||||||
|
</div>
|
||||||
|
{#if analysisStatus.active}
|
||||||
|
<Badge tone="primary" class="animate-pulse">Active</Badge>
|
||||||
|
{:else}
|
||||||
|
<Badge tone="neutral">Idle</Badge>
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
|
<p class="text-xs text-muted-fg">
|
||||||
|
{hasAiModel
|
||||||
|
? 'Toggle a task on, then choose which model handles it. Runs as part of the pipeline alongside metadata and thumbnails.'
|
||||||
|
: 'No AI model is available for this media type yet.'}
|
||||||
|
</p>
|
||||||
|
{#if hasAiModel}
|
||||||
|
{@render detailsToggle(aiDetailsOpen, () => (aiDetailsOpen = !aiDetailsOpen))}
|
||||||
|
{#if aiDetailsOpen}
|
||||||
|
<div class="flex flex-col gap-1 rounded-md bg-bg p-2 text-[11px] text-muted-fg">
|
||||||
|
{#each aiStages as stage (stage.key)}
|
||||||
|
<p><span class="font-medium text-fg">{stage.label}:</span> {MODEL_DETAILS[stage.model] ?? 'No description available for this model.'}</p>
|
||||||
|
{/each}
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
|
{/if}
|
||||||
|
<div class="flex flex-col gap-2">
|
||||||
|
{#each aiStages as stage (stage.key)}
|
||||||
|
<div
|
||||||
|
class={cn(
|
||||||
|
'flex flex-col gap-2 rounded-md border p-2 transition-opacity',
|
||||||
|
stage.enabled ? 'border-border' : 'border-border/60 opacity-70',
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
<div class="flex items-center justify-between gap-2 text-[11px] font-medium text-muted-fg">
|
||||||
|
{stage.label}
|
||||||
|
<span
|
||||||
|
class={cn(
|
||||||
|
'relative inline-flex h-5 w-9 shrink-0 items-center rounded-full transition-colors',
|
||||||
|
stage.enabled ? 'bg-primary' : 'bg-border',
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
<input
|
||||||
|
type="checkbox"
|
||||||
|
class="peer absolute inset-0 size-full cursor-pointer opacity-0"
|
||||||
|
checked={stage.enabled}
|
||||||
|
disabled={!hasAiModel || disabled}
|
||||||
|
aria-label={`${stage.label} enabled`}
|
||||||
|
onchange={(event) => onToggleStage(stage.key, (event.currentTarget as HTMLInputElement).checked)}
|
||||||
|
/>
|
||||||
|
<span
|
||||||
|
class={cn(
|
||||||
|
'pointer-events-none inline-block size-3.5 translate-x-1 rounded-full bg-white shadow transition-transform',
|
||||||
|
stage.enabled && 'translate-x-4',
|
||||||
|
)}
|
||||||
|
></span>
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<select
|
||||||
|
value={stage.model}
|
||||||
|
disabled={!hasAiModel || disabled || !stage.enabled}
|
||||||
|
onchange={(event) => onModelChange(stage.key, (event.currentTarget as HTMLSelectElement).value)}
|
||||||
|
class="h-9 w-full rounded-md border border-border bg-surface px-2 text-xs font-normal text-fg outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:opacity-50"
|
||||||
|
>
|
||||||
|
{#each modelOptions as model (model)}
|
||||||
|
<option value={model}>{model}</option>
|
||||||
|
{/each}
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
{/each}
|
||||||
|
</div>
|
||||||
|
{#if hasAiModel}
|
||||||
|
{@render statusGrid(analysisStatus, 'analyze', () => onRetryErrors('analyze'))}
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
<script lang="ts">
|
||||||
|
import { Image, MonitorPlay, Play, ScanSearch, Server, Settings2, ShieldCheck, WandSparkles } from '@lucide/svelte'
|
||||||
|
import type { ProjectIconName } from '$lib/types'
|
||||||
|
|
||||||
|
const icons: Record<ProjectIconName, typeof Play> = {
|
||||||
|
image: Image,
|
||||||
|
'monitor-play': MonitorPlay,
|
||||||
|
play: Play,
|
||||||
|
'scan-search': ScanSearch,
|
||||||
|
server: Server,
|
||||||
|
'settings-2': Settings2,
|
||||||
|
'shield-check': ShieldCheck,
|
||||||
|
'wand-sparkles': WandSparkles,
|
||||||
|
}
|
||||||
|
|
||||||
|
let { icon, class: className = '' }: { icon: ProjectIconName; class?: string } = $props()
|
||||||
|
const Icon = $derived(icons[icon])
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<Icon class={className} aria-hidden="true" />
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
<script lang="ts">
|
||||||
|
let { title, description = '' }: { title: string; description?: string } = $props()
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<div class="flex items-start justify-between gap-3">
|
||||||
|
<div>
|
||||||
|
<h2 class="text-sm font-semibold text-fg">{title}</h2>
|
||||||
|
{#if description}<p class="mt-1 text-xs text-muted-fg">{description}</p>{/if}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
@@ -0,0 +1,97 @@
|
|||||||
|
<script lang="ts">
|
||||||
|
import { Moon, Sun, SunMoon } from '@lucide/svelte'
|
||||||
|
import Button from '$lib/components/ui/button.svelte'
|
||||||
|
import { currentLanguage, languages, setLanguage } from '$lib/language.svelte'
|
||||||
|
import { themeState } from '$lib/theme.svelte'
|
||||||
|
|
||||||
|
let {
|
||||||
|
open = $bindable(false),
|
||||||
|
onClose,
|
||||||
|
}: {
|
||||||
|
open?: boolean
|
||||||
|
onClose?: () => void
|
||||||
|
} = $props()
|
||||||
|
|
||||||
|
const languageItems = languages.map((language) => ({ value: language.id, label: language.label }))
|
||||||
|
let wasOpen = false
|
||||||
|
|
||||||
|
$effect(() => {
|
||||||
|
if (wasOpen && !open) onClose?.()
|
||||||
|
wasOpen = open
|
||||||
|
})
|
||||||
|
</script>
|
||||||
|
|
||||||
|
{#if open}
|
||||||
|
<div
|
||||||
|
class="fixed inset-0 z-50 grid place-items-center bg-black/70 p-4 backdrop-blur-sm"
|
||||||
|
role="presentation"
|
||||||
|
onclick={(event) => {
|
||||||
|
if (event.target === event.currentTarget) open = false
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<div
|
||||||
|
class="w-full max-w-lg rounded-xl border border-border bg-surface p-6 shadow-xl"
|
||||||
|
role="dialog"
|
||||||
|
aria-modal="true"
|
||||||
|
aria-label="Settings"
|
||||||
|
tabindex="-1"
|
||||||
|
>
|
||||||
|
<div class="flex items-start justify-between gap-4">
|
||||||
|
<h2 class="text-xl font-semibold">Settings</h2>
|
||||||
|
<button
|
||||||
|
class="rounded-md px-2 py-1 text-2xl leading-none text-muted-fg hover:bg-surface-hover hover:text-fg"
|
||||||
|
type="button"
|
||||||
|
aria-label="Close"
|
||||||
|
onclick={() => (open = false)}>×</button
|
||||||
|
>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="mt-6 space-y-5">
|
||||||
|
<div>
|
||||||
|
<span class="mb-2 block text-sm font-medium">Theme</span>
|
||||||
|
<div class="flex w-full rounded-md border border-border p-1">
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant={themeState.mode === 'light' ? 'secondary' : 'ghost'}
|
||||||
|
size="sm"
|
||||||
|
class="flex-1 gap-1.5"
|
||||||
|
onclick={() => themeState.setMode('light')}
|
||||||
|
>
|
||||||
|
<Sun class="size-4" />
|
||||||
|
Light
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant={themeState.mode === 'dark' ? 'secondary' : 'ghost'}
|
||||||
|
size="sm"
|
||||||
|
class="flex-1 gap-1.5"
|
||||||
|
onclick={() => themeState.setMode('dark')}
|
||||||
|
>
|
||||||
|
<Moon class="size-4" />
|
||||||
|
Dark
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant={themeState.mode === 'system' ? 'secondary' : 'ghost'}
|
||||||
|
size="sm"
|
||||||
|
class="flex-1 gap-1.5"
|
||||||
|
onclick={() => themeState.setMode('system')}
|
||||||
|
>
|
||||||
|
<SunMoon class="size-4" />
|
||||||
|
System
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<label class="block">
|
||||||
|
<span class="mb-2 block text-sm font-medium">Language</span>
|
||||||
|
<select class="field" value={currentLanguage()} onchange={(event) => setLanguage(event.currentTarget.value)}>
|
||||||
|
{#each languageItems as item (item.value)}
|
||||||
|
<option value={item.value}>{item.label}</option>
|
||||||
|
{/each}
|
||||||
|
</select>
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
@@ -0,0 +1,102 @@
|
|||||||
|
<script lang="ts">
|
||||||
|
import { AlertCircle, AlertTriangle, CheckCircle2, CircleHelp, LoaderCircle, RefreshCw, X } from '@lucide/svelte'
|
||||||
|
import Button from '$lib/components/ui/button.svelte'
|
||||||
|
import type { StatusProbe, StatusSnapshot } from '$lib/status'
|
||||||
|
|
||||||
|
let {
|
||||||
|
open = $bindable(false),
|
||||||
|
status,
|
||||||
|
onRefresh,
|
||||||
|
}: {
|
||||||
|
open?: boolean
|
||||||
|
status: StatusSnapshot
|
||||||
|
onRefresh: () => Promise<void>
|
||||||
|
} = $props()
|
||||||
|
|
||||||
|
const levelLabel = {
|
||||||
|
checking: 'Checking',
|
||||||
|
healthy: 'Healthy',
|
||||||
|
degraded: 'Degraded',
|
||||||
|
offline: 'Offline',
|
||||||
|
}
|
||||||
|
|
||||||
|
const levelClass = {
|
||||||
|
checking: 'text-muted-fg',
|
||||||
|
healthy: 'text-success',
|
||||||
|
degraded: 'text-warning',
|
||||||
|
offline: 'text-danger',
|
||||||
|
}
|
||||||
|
|
||||||
|
function probeLabel(probe: StatusProbe | null) {
|
||||||
|
if (!probe) return 'Not checked'
|
||||||
|
if (probe.ok) return 'OK'
|
||||||
|
if (probe.error) return probe.error
|
||||||
|
return probe.httpStatus ? `HTTP ${probe.httpStatus}` : 'Unavailable'
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
{#if open}
|
||||||
|
<div
|
||||||
|
class="fixed inset-0 z-50 grid place-items-center bg-black/70 px-4"
|
||||||
|
role="presentation"
|
||||||
|
onclick={(event) => event.target === event.currentTarget && (open = false)}
|
||||||
|
>
|
||||||
|
<div
|
||||||
|
class="w-full max-w-lg rounded-xl border border-border bg-bg p-6 text-fg shadow-2xl"
|
||||||
|
role="dialog"
|
||||||
|
aria-modal="true"
|
||||||
|
aria-labelledby="status-dialog-title"
|
||||||
|
>
|
||||||
|
<div class="mb-5 flex items-start justify-between gap-3">
|
||||||
|
<div>
|
||||||
|
<h2 id="status-dialog-title" class="text-xl font-semibold">Service status</h2>
|
||||||
|
<p class="mt-1 text-sm text-muted-fg">Live liveness and database readiness checks.</p>
|
||||||
|
</div>
|
||||||
|
<Button variant="ghost" size="icon" aria-label="Close" onclick={() => (open = false)}>
|
||||||
|
<X class="size-4" />
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="mb-5 flex items-center gap-3 rounded-lg border border-border bg-surface p-3" aria-live="polite">
|
||||||
|
{#if status.loading && status.level === 'checking'}
|
||||||
|
<LoaderCircle class="size-5 animate-spin text-muted-fg" />
|
||||||
|
{:else if status.level === 'healthy'}
|
||||||
|
<CheckCircle2 class="size-5 text-success" />
|
||||||
|
{:else if status.level === 'degraded'}
|
||||||
|
<AlertTriangle class="size-5 text-warning" />
|
||||||
|
{:else if status.level === 'offline'}
|
||||||
|
<AlertCircle class="size-5 text-danger" />
|
||||||
|
{:else}
|
||||||
|
<CircleHelp class="size-5 text-muted-fg" />
|
||||||
|
{/if}
|
||||||
|
<span class={`font-medium ${levelClass[status.level]}`}>{levelLabel[status.level]}</span>
|
||||||
|
{#if status.checkedAt}
|
||||||
|
<span class="ml-auto text-xs text-muted-fg">{new Date(status.checkedAt).toLocaleTimeString()}</span>
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="space-y-2 text-sm">
|
||||||
|
{#each [{ label: 'Liveness', probe: status.health }, { label: 'Readiness / database', probe: status.readiness }] as item (item.label)}
|
||||||
|
<div class="flex items-center justify-between gap-4 rounded-md border border-border px-3 py-2">
|
||||||
|
<span>{item.label}</span>
|
||||||
|
<span class={item.probe?.ok ? 'text-success' : 'text-danger'}>{probeLabel(item.probe)}</span>
|
||||||
|
</div>
|
||||||
|
{/each}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{#if status.health?.service || status.readiness?.service}
|
||||||
|
<p class="mt-4 text-xs text-muted-fg">
|
||||||
|
Service: {status.health?.service || status.readiness?.service}
|
||||||
|
</p>
|
||||||
|
{/if}
|
||||||
|
|
||||||
|
<div class="mt-6 flex justify-end gap-2">
|
||||||
|
<Button variant="outline" disabled={status.loading} onclick={() => void onRefresh()}>
|
||||||
|
<RefreshCw class={status.loading ? 'animate-spin' : ''} />
|
||||||
|
Refresh
|
||||||
|
</Button>
|
||||||
|
<Button variant="secondary" onclick={() => (open = false)}>Dismiss</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
@@ -0,0 +1,97 @@
|
|||||||
|
<script lang="ts">
|
||||||
|
import { AlertCircle, AlertTriangle, CheckCircle2, CircleHelp, LoaderCircle } from '@lucide/svelte'
|
||||||
|
import { onMount } from 'svelte'
|
||||||
|
import Button from '$lib/components/ui/button.svelte'
|
||||||
|
import StatusDialog from '$lib/components/StatusDialog.svelte'
|
||||||
|
import type { StatusProbe, StatusSnapshot } from '$lib/status'
|
||||||
|
|
||||||
|
const initialStatus: StatusSnapshot = {
|
||||||
|
level: 'checking',
|
||||||
|
health: null,
|
||||||
|
readiness: null,
|
||||||
|
checkedAt: null,
|
||||||
|
loading: false,
|
||||||
|
}
|
||||||
|
|
||||||
|
let status = $state<StatusSnapshot>(initialStatus)
|
||||||
|
let open = $state(false)
|
||||||
|
let requestInFlight = false
|
||||||
|
|
||||||
|
async function probe(path: string): Promise<StatusProbe> {
|
||||||
|
try {
|
||||||
|
const response = await fetch(path, {
|
||||||
|
credentials: 'include',
|
||||||
|
headers: { Accept: 'application/json' },
|
||||||
|
})
|
||||||
|
const payload = (await response.json().catch(() => null)) as {
|
||||||
|
ok?: boolean
|
||||||
|
service?: string
|
||||||
|
error?: string
|
||||||
|
} | null
|
||||||
|
return {
|
||||||
|
path,
|
||||||
|
ok: response.ok && payload?.ok !== false,
|
||||||
|
httpStatus: response.status,
|
||||||
|
service: payload?.service || null,
|
||||||
|
error: response.ok ? null : payload?.error || response.statusText || `HTTP ${response.status}`,
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
return {
|
||||||
|
path,
|
||||||
|
ok: false,
|
||||||
|
httpStatus: null,
|
||||||
|
service: null,
|
||||||
|
error: error instanceof Error ? error.message : 'Unavailable',
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function refresh() {
|
||||||
|
if (requestInFlight) return
|
||||||
|
requestInFlight = true
|
||||||
|
status = { ...status, loading: true, level: status.health || status.readiness ? status.level : 'checking' }
|
||||||
|
|
||||||
|
try {
|
||||||
|
const [health, readiness] = await Promise.all([probe('/healthz'), probe('/ready')])
|
||||||
|
const level = health.ok && readiness.ok ? 'healthy' : health.ok ? 'degraded' : 'offline'
|
||||||
|
status = {
|
||||||
|
level,
|
||||||
|
health,
|
||||||
|
readiness,
|
||||||
|
checkedAt: new Date().toISOString(),
|
||||||
|
loading: false,
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
requestInFlight = false
|
||||||
|
if (status.loading) status = { ...status, loading: false }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
onMount(() => {
|
||||||
|
void refresh()
|
||||||
|
const timer = window.setInterval(() => void refresh(), 15_000)
|
||||||
|
return () => window.clearInterval(timer)
|
||||||
|
})
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<Button
|
||||||
|
variant="ghost"
|
||||||
|
size="icon"
|
||||||
|
aria-label="Service status"
|
||||||
|
title={`Service status: ${status.level}`}
|
||||||
|
onclick={() => (open = true)}
|
||||||
|
>
|
||||||
|
{#if status.loading && status.level === 'checking'}
|
||||||
|
<LoaderCircle class="size-5 animate-spin text-muted-fg" />
|
||||||
|
{:else if status.level === 'healthy'}
|
||||||
|
<CheckCircle2 class="size-5 text-success" />
|
||||||
|
{:else if status.level === 'degraded'}
|
||||||
|
<AlertTriangle class="size-5 text-warning" />
|
||||||
|
{:else if status.level === 'offline'}
|
||||||
|
<AlertCircle class="size-5 text-danger" />
|
||||||
|
{:else}
|
||||||
|
<CircleHelp class="size-5 text-muted-fg" />
|
||||||
|
{/if}
|
||||||
|
</Button>
|
||||||
|
|
||||||
|
<StatusDialog bind:open {status} onRefresh={refresh} />
|
||||||
@@ -0,0 +1,87 @@
|
|||||||
|
<script lang="ts">
|
||||||
|
import { page } from '$app/state'
|
||||||
|
import { getAppConfig, getPanelForPath, getPathForPanel } from '$lib/app-config'
|
||||||
|
import AnalyzerWorkspace from '$lib/features/AnalyzerWorkspace.svelte'
|
||||||
|
import ConfigWorkspace from '$lib/features/ConfigWorkspace.svelte'
|
||||||
|
import DesktopWorkspace from '$lib/features/DesktopWorkspace.svelte'
|
||||||
|
import FeedWorkspace from '$lib/features/FeedWorkspace.svelte'
|
||||||
|
import KioskWorkspace from '$lib/features/KioskWorkspace.svelte'
|
||||||
|
import MediaTypePipeline from '$lib/features/MediaTypePipeline.svelte'
|
||||||
|
import ModeratorWorkspace from '$lib/features/ModeratorWorkspace.svelte'
|
||||||
|
import ServantWorkspace from '$lib/features/ServantWorkspace.svelte'
|
||||||
|
import TagsWorkspace from '$lib/features/TagsWorkspace.svelte'
|
||||||
|
import VideoPage from '$lib/features/VideoPage.svelte'
|
||||||
|
import ToolsWorkspace from '$lib/features/ToolsWorkspace.svelte'
|
||||||
|
import ViewerWorkspace from '$lib/features/ViewerWorkspace.svelte'
|
||||||
|
|
||||||
|
const analyzerMediaTypePanels: Record<
|
||||||
|
string,
|
||||||
|
{ mediaType: 'image' | 'video' | 'audio' | 'funscript'; label: string }
|
||||||
|
> = {
|
||||||
|
images: { mediaType: 'image', label: 'Images' },
|
||||||
|
videos: { mediaType: 'video', label: 'Videos' },
|
||||||
|
audios: { mediaType: 'audio', label: 'Audios' },
|
||||||
|
funscripts: { mediaType: 'funscript', label: 'Funscripts' },
|
||||||
|
}
|
||||||
|
|
||||||
|
const app = getAppConfig(__MEDIA_APP__)
|
||||||
|
const requestedPanel = $derived(page.url.searchParams.get('panel') || getPanelForPath(app, page.url.pathname))
|
||||||
|
const panel = $derived(app.id === 'viewer' && requestedPanel === 'search' ? 'library' : requestedPanel)
|
||||||
|
const videoId = $derived(app.id === 'viewer' ? getVideoId(page.url.pathname) : '')
|
||||||
|
|
||||||
|
function getVideoId(pathname: string) {
|
||||||
|
const match = pathname.match(/^\/video\/([^/]+)\/?$/i)
|
||||||
|
if (!match?.[1]) return ''
|
||||||
|
try {
|
||||||
|
return decodeURIComponent(match[1])
|
||||||
|
} catch {
|
||||||
|
return ''
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
$effect(() => {
|
||||||
|
const legacyPanel = page.url.searchParams.get('panel')
|
||||||
|
if (typeof window === 'undefined' || !legacyPanel || !app.nav.some((item) => item.panel === legacyPanel)) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
const query = Array.from(page.url.searchParams.entries())
|
||||||
|
.filter(([key]) => key !== 'panel')
|
||||||
|
.map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(value)}`)
|
||||||
|
.join('&')
|
||||||
|
const target = `${getPathForPanel(app, legacyPanel)}${query ? `?${query}` : ''}`
|
||||||
|
const current = `${page.url.pathname}${page.url.search}`
|
||||||
|
if (target !== current) {
|
||||||
|
window.location.replace(target)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
</script>
|
||||||
|
|
||||||
|
{#if app.id === 'viewer' && videoId}
|
||||||
|
<VideoPage id={videoId} />
|
||||||
|
{:else if app.id === 'viewer' && panel === 'view'}
|
||||||
|
<FeedWorkspace />
|
||||||
|
{:else if app.id === 'viewer' && panel === 'tags'}
|
||||||
|
<TagsWorkspace />
|
||||||
|
{:else if app.id === 'viewer'}
|
||||||
|
<ViewerWorkspace {panel} />
|
||||||
|
{:else if app.id === 'analyzer' && panel in analyzerMediaTypePanels}
|
||||||
|
<MediaTypePipeline
|
||||||
|
mediaType={analyzerMediaTypePanels[panel].mediaType}
|
||||||
|
label={analyzerMediaTypePanels[panel].label}
|
||||||
|
/>
|
||||||
|
{:else if app.id === 'tools'}
|
||||||
|
<ToolsWorkspace {panel} />
|
||||||
|
{:else if app.id === 'analyzer'}
|
||||||
|
<AnalyzerWorkspace {panel} />
|
||||||
|
{:else if app.id === 'config'}
|
||||||
|
<ConfigWorkspace {panel} />
|
||||||
|
{:else if app.id === 'moderator'}
|
||||||
|
<ModeratorWorkspace {panel} />
|
||||||
|
{:else if app.id === 'kiosk'}
|
||||||
|
<KioskWorkspace {panel} />
|
||||||
|
{:else if app.id === 'servant'}
|
||||||
|
<ServantWorkspace {panel} />
|
||||||
|
{:else}
|
||||||
|
<DesktopWorkspace {panel} />
|
||||||
|
{/if}
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
<script lang="ts">
|
||||||
|
import type { HTMLAttributes } from 'svelte/elements'
|
||||||
|
import { cn } from '$lib/utils/cn'
|
||||||
|
|
||||||
|
let {
|
||||||
|
class: className,
|
||||||
|
tone = 'neutral',
|
||||||
|
children,
|
||||||
|
...rest
|
||||||
|
}: HTMLAttributes<HTMLSpanElement> & {
|
||||||
|
tone?: 'neutral' | 'primary' | 'success' | 'warning' | 'danger'
|
||||||
|
children?: import('svelte').Snippet
|
||||||
|
} = $props()
|
||||||
|
const toneClasses = {
|
||||||
|
neutral: 'border-border bg-surface-hover text-muted-fg',
|
||||||
|
primary: 'border-primary/30 bg-primary/15 text-primary',
|
||||||
|
success: 'border-success/30 bg-success/15 text-success',
|
||||||
|
warning: 'border-warning/30 bg-warning/15 text-warning',
|
||||||
|
danger: 'border-danger/30 bg-danger/15 text-danger',
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<span
|
||||||
|
class={cn(
|
||||||
|
'inline-flex items-center rounded-full border px-2 py-0.5 text-xs font-medium',
|
||||||
|
toneClasses[tone],
|
||||||
|
className,
|
||||||
|
)}
|
||||||
|
{...rest}
|
||||||
|
>
|
||||||
|
{@render children?.()}
|
||||||
|
</span>
|
||||||
@@ -0,0 +1,43 @@
|
|||||||
|
<script lang="ts">
|
||||||
|
import { cva, type VariantProps } from 'class-variance-authority'
|
||||||
|
import type { HTMLButtonAttributes } from 'svelte/elements'
|
||||||
|
import { cn } from '$lib/utils/cn'
|
||||||
|
|
||||||
|
export const buttonVariants = cva(
|
||||||
|
'inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50 [&_svg]:size-4 [&_svg]:shrink-0',
|
||||||
|
{
|
||||||
|
variants: {
|
||||||
|
variant: {
|
||||||
|
default: 'bg-primary text-primary-fg hover:opacity-90',
|
||||||
|
secondary: 'border border-border bg-surface text-fg hover:bg-surface-hover',
|
||||||
|
outline: 'border border-border bg-transparent text-fg hover:bg-surface-hover',
|
||||||
|
ghost: 'text-fg hover:bg-surface-hover',
|
||||||
|
danger: 'bg-danger text-danger-fg hover:opacity-90',
|
||||||
|
success: 'bg-success text-success-fg hover:opacity-90',
|
||||||
|
link: 'text-primary underline-offset-4 hover:underline',
|
||||||
|
},
|
||||||
|
size: {
|
||||||
|
default: 'h-9 px-4 py-2',
|
||||||
|
sm: 'h-8 rounded-md px-3 text-xs',
|
||||||
|
lg: 'h-10 rounded-md px-6',
|
||||||
|
icon: 'h-9 w-9',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
defaultVariants: { variant: 'default', size: 'default' },
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
type Variant = VariantProps<typeof buttonVariants>
|
||||||
|
let {
|
||||||
|
class: className,
|
||||||
|
variant = 'default',
|
||||||
|
size = 'default',
|
||||||
|
type = 'button',
|
||||||
|
children,
|
||||||
|
...rest
|
||||||
|
}: HTMLButtonAttributes & Variant & { children?: import('svelte').Snippet } = $props()
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<button {type} class={cn(buttonVariants({ variant, size }), className)} {...rest}>
|
||||||
|
{@render children?.()}
|
||||||
|
</button>
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
<script lang="ts">
|
||||||
|
import type { HTMLAttributes } from 'svelte/elements'
|
||||||
|
import { cn } from '$lib/utils/cn'
|
||||||
|
|
||||||
|
let {
|
||||||
|
class: className,
|
||||||
|
children,
|
||||||
|
...rest
|
||||||
|
}: HTMLAttributes<HTMLDivElement> & { children?: import('svelte').Snippet } = $props()
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<div class={cn('rounded-lg border border-border bg-surface p-4 shadow-sm', className)} {...rest}>
|
||||||
|
{@render children?.()}
|
||||||
|
</div>
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
<script lang="ts">
|
||||||
|
import { cn } from '$lib/utils/cn'
|
||||||
|
|
||||||
|
let {
|
||||||
|
label,
|
||||||
|
value,
|
||||||
|
detail = '',
|
||||||
|
tone = 'default',
|
||||||
|
}: {
|
||||||
|
label: string
|
||||||
|
value: string | number
|
||||||
|
detail?: string
|
||||||
|
tone?: 'default' | 'primary' | 'success' | 'warning' | 'danger'
|
||||||
|
} = $props()
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<div class="rounded-lg border border-border bg-surface p-4">
|
||||||
|
<p class="text-xs font-medium uppercase tracking-wider text-muted-fg">{label}</p>
|
||||||
|
<p
|
||||||
|
class={cn(
|
||||||
|
'mt-2 text-2xl font-semibold tracking-tight',
|
||||||
|
tone === 'primary' && 'text-primary',
|
||||||
|
tone === 'success' && 'text-success',
|
||||||
|
tone === 'warning' && 'text-warning',
|
||||||
|
tone === 'danger' && 'text-danger',
|
||||||
|
tone === 'default' && 'text-fg',
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
{value}
|
||||||
|
</p>
|
||||||
|
{#if detail}<p class="mt-1 text-xs text-muted-fg">{detail}</p>{/if}
|
||||||
|
</div>
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
<script lang="ts">
|
||||||
|
import TechStackSection from '$lib/features/about/TechStackSection.svelte'
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<TechStackSection />
|
||||||
@@ -0,0 +1,626 @@
|
|||||||
|
<script lang="ts">
|
||||||
|
import { AlertTriangle, Play, Plus, RefreshCw, Trash2 } from '@lucide/svelte'
|
||||||
|
import { onMount } from 'svelte'
|
||||||
|
import { SvelteSet } from 'svelte/reactivity'
|
||||||
|
import { notify } from '@gabriel20xx/web-ui'
|
||||||
|
import { del, get, post } from '$lib/api'
|
||||||
|
import AnalyzerHistory from '$lib/components/AnalyzerHistory.svelte'
|
||||||
|
import AnalyzerLiveStatus from '$lib/components/AnalyzerLiveStatus.svelte'
|
||||||
|
import AnalyzerPipelineBreakdown from '$lib/components/AnalyzerPipelineBreakdown.svelte'
|
||||||
|
import SectionTitle from '$lib/components/SectionTitle.svelte'
|
||||||
|
import Card from '$lib/components/ui/card.svelte'
|
||||||
|
import Button from '$lib/components/ui/button.svelte'
|
||||||
|
import Badge from '$lib/components/ui/badge.svelte'
|
||||||
|
import Metric from '$lib/components/ui/metric.svelte'
|
||||||
|
import EmptyState from '$lib/components/EmptyState.svelte'
|
||||||
|
import { cn } from '$lib/utils/cn'
|
||||||
|
|
||||||
|
type Json = Record<string, unknown>
|
||||||
|
let { panel = 'dashboard' }: { panel?: string } = $props()
|
||||||
|
let stats = $state<Json>({})
|
||||||
|
let status = $state<Json>({})
|
||||||
|
let schedules = $state<Json[]>([])
|
||||||
|
let loading = $state(true)
|
||||||
|
let error = $state('')
|
||||||
|
|
||||||
|
const DISCOVER_TYPES: { key: 'image' | 'video' | 'audio' | 'funscript'; label: string; statsKey: string }[] = [
|
||||||
|
{ key: 'image', label: 'Images', statsKey: 'images' },
|
||||||
|
{ key: 'video', label: 'Videos', statsKey: 'videos' },
|
||||||
|
{ key: 'audio', label: 'Audios', statsKey: 'audio' },
|
||||||
|
{ key: 'funscript', label: 'Funscripts', statsKey: 'funscripts' },
|
||||||
|
]
|
||||||
|
const selectedDiscoverTypes = new SvelteSet<string>(DISCOVER_TYPES.map((type) => type.key))
|
||||||
|
const allDiscoverTypesSelected = $derived(DISCOVER_TYPES.every((type) => selectedDiscoverTypes.has(type.key)))
|
||||||
|
|
||||||
|
function toggleDiscoverType(key: string) {
|
||||||
|
if (selectedDiscoverTypes.has(key)) selectedDiscoverTypes.delete(key)
|
||||||
|
else selectedDiscoverTypes.add(key)
|
||||||
|
}
|
||||||
|
|
||||||
|
function selectAllDiscoverTypes() {
|
||||||
|
for (const type of DISCOVER_TYPES) selectedDiscoverTypes.add(type.key)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Pipeline controls (dashboard panel): an independent media-type selection from the discover
|
||||||
|
// panel's own one above, since they're two separate controls that happen to share a type list.
|
||||||
|
const selectedPipelineTypes = new SvelteSet<string>(DISCOVER_TYPES.map((type) => type.key))
|
||||||
|
const allPipelineTypesSelected = $derived(DISCOVER_TYPES.every((type) => selectedPipelineTypes.has(type.key)))
|
||||||
|
|
||||||
|
function togglePipelineType(key: string) {
|
||||||
|
if (selectedPipelineTypes.has(key)) selectedPipelineTypes.delete(key)
|
||||||
|
else selectedPipelineTypes.add(key)
|
||||||
|
}
|
||||||
|
|
||||||
|
function selectAllPipelineTypes() {
|
||||||
|
for (const type of DISCOVER_TYPES) selectedPipelineTypes.add(type.key)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Mirrors the pipeline stages modeled everywhere else (AnalyzerPipelineBreakdown, the per-type
|
||||||
|
// Images/Videos/Audios/Funscripts tabs): discover, extract metadata, generate thumbnails, and
|
||||||
|
// run AI analysis. Each maps to its own backend action, scoped by the selected media types.
|
||||||
|
const PIPELINE_ACTIONS: { key: 'discover' | 'metadata' | 'thumbnails' | 'analyze'; label: string; endpoint: string }[] = [
|
||||||
|
{ key: 'discover', label: 'Discovery', endpoint: 'extract/discover' },
|
||||||
|
{ key: 'metadata', label: 'Metadata', endpoint: 'metadata/start' },
|
||||||
|
{ key: 'thumbnails', label: 'Thumbnails', endpoint: 'generate/start' },
|
||||||
|
{ key: 'analyze', label: 'AI analysis', endpoint: 'analyze/start' },
|
||||||
|
]
|
||||||
|
const selectedPipelineActions = new SvelteSet<string>(PIPELINE_ACTIONS.map((action) => action.key))
|
||||||
|
const allPipelineActionsSelected = $derived(PIPELINE_ACTIONS.every((action) => selectedPipelineActions.has(action.key)))
|
||||||
|
|
||||||
|
function togglePipelineAction(key: string) {
|
||||||
|
if (selectedPipelineActions.has(key)) selectedPipelineActions.delete(key)
|
||||||
|
else selectedPipelineActions.add(key)
|
||||||
|
}
|
||||||
|
|
||||||
|
function selectAllPipelineActions() {
|
||||||
|
for (const action of PIPELINE_ACTIONS) selectedPipelineActions.add(action.key)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Schedules: recurring runs of the same five pipeline actions, on the backend's own poll-based
|
||||||
|
// scheduler (see runAnalyzerScheduler on the Go side) rather than anything client-driven. Cleanup
|
||||||
|
// always sweeps the whole library, so it's the one action here with no media-type scoping.
|
||||||
|
const SCHEDULE_TOOLS: { key: 'discover' | 'metadata' | 'thumbnails' | 'analyze' | 'cleanup'; label: string; usesTypes: boolean }[] =
|
||||||
|
[
|
||||||
|
{ key: 'discover', label: 'Discovery', usesTypes: true },
|
||||||
|
{ key: 'metadata', label: 'Metadata', usesTypes: true },
|
||||||
|
{ key: 'thumbnails', label: 'Thumbnails', usesTypes: true },
|
||||||
|
{ key: 'analyze', label: 'AI analysis', usesTypes: true },
|
||||||
|
{ key: 'cleanup', label: 'Cleanup', usesTypes: false },
|
||||||
|
]
|
||||||
|
|
||||||
|
let scheduleName = $state('')
|
||||||
|
let scheduleTool = $state<(typeof SCHEDULE_TOOLS)[number]['key']>('discover')
|
||||||
|
const scheduleTypes = new SvelteSet<string>(DISCOVER_TYPES.map((type) => type.key))
|
||||||
|
let scheduleIntervalMinutes = $state(60)
|
||||||
|
let scheduleEnabled = $state(true)
|
||||||
|
let creatingSchedule = $state(false)
|
||||||
|
|
||||||
|
const selectedScheduleTool = $derived(SCHEDULE_TOOLS.find((tool) => tool.key === scheduleTool)!)
|
||||||
|
const allScheduleTypesSelected = $derived(DISCOVER_TYPES.every((type) => scheduleTypes.has(type.key)))
|
||||||
|
|
||||||
|
function toggleScheduleType(key: string) {
|
||||||
|
if (scheduleTypes.has(key)) scheduleTypes.delete(key)
|
||||||
|
else scheduleTypes.add(key)
|
||||||
|
}
|
||||||
|
|
||||||
|
function selectAllScheduleTypes() {
|
||||||
|
for (const type of DISCOVER_TYPES) scheduleTypes.add(type.key)
|
||||||
|
}
|
||||||
|
|
||||||
|
async function createSchedule() {
|
||||||
|
if (selectedScheduleTool.usesTypes && scheduleTypes.size === 0) return
|
||||||
|
creatingSchedule = true
|
||||||
|
try {
|
||||||
|
await post('/api/automation-schedules', {
|
||||||
|
tool: scheduleTool,
|
||||||
|
name: scheduleName.trim() || `${selectedScheduleTool.label} schedule`,
|
||||||
|
intervalMinutes: scheduleIntervalMinutes,
|
||||||
|
enabled: scheduleEnabled,
|
||||||
|
settings: selectedScheduleTool.usesTypes ? { types: Array.from(scheduleTypes) } : {},
|
||||||
|
})
|
||||||
|
notify.success('Schedule created.')
|
||||||
|
scheduleName = ''
|
||||||
|
await load({ background: true })
|
||||||
|
} catch (reason) {
|
||||||
|
notify.error(reason instanceof Error ? reason.message : 'Unable to create schedule.')
|
||||||
|
} finally {
|
||||||
|
creatingSchedule = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function runScheduleNow(id: string) {
|
||||||
|
try {
|
||||||
|
await post(`/api/automation-schedules/${id}/run`)
|
||||||
|
notify.success('Schedule run started.')
|
||||||
|
await load({ background: true })
|
||||||
|
} catch (reason) {
|
||||||
|
notify.error(reason instanceof Error ? reason.message : 'Unable to run that schedule.')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function deleteSchedule(id: string) {
|
||||||
|
try {
|
||||||
|
await del(`/api/automation-schedules/${id}`)
|
||||||
|
notify.success('Schedule deleted.')
|
||||||
|
await load({ background: true })
|
||||||
|
} catch (reason) {
|
||||||
|
notify.error(reason instanceof Error ? reason.message : 'Unable to delete that schedule.')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function numeric(key: string, fallback = 0) {
|
||||||
|
const value = Number(stats[key] ?? status[key])
|
||||||
|
return Number.isFinite(value) ? value : fallback
|
||||||
|
}
|
||||||
|
|
||||||
|
function asRecord(value: unknown): Json {
|
||||||
|
return value && typeof value === 'object' && !Array.isArray(value) ? (value as Json) : {}
|
||||||
|
}
|
||||||
|
|
||||||
|
let loadGeneration = 0
|
||||||
|
// Tracks the last analyzer-reported failure we've already toasted, so a lingering lastError
|
||||||
|
// (it persists in status until the next run starts or clears it) doesn't re-notify on every
|
||||||
|
// background poll - only a new/changed error should interrupt the user.
|
||||||
|
let lastNotifiedError = ''
|
||||||
|
|
||||||
|
async function load({ background = false } = {}) {
|
||||||
|
if (!background) loading = true
|
||||||
|
error = ''
|
||||||
|
const generation = ++loadGeneration
|
||||||
|
try {
|
||||||
|
const responses = await Promise.all([
|
||||||
|
get<Json>('/api/stats').catch(() => ({})),
|
||||||
|
get<Json>('/api/status').catch(() => ({})),
|
||||||
|
get<Json>('/api/automation-schedules').catch(() => ({})),
|
||||||
|
])
|
||||||
|
// A newer load() may have been triggered (e.g. by a start-action) and already resolved while
|
||||||
|
// this one was still in flight - applying this stale response would clobber the fresher state.
|
||||||
|
if (generation !== loadGeneration) return
|
||||||
|
const statsResponse = responses[0] as Json
|
||||||
|
const nestedStats = statsResponse.stats
|
||||||
|
stats =
|
||||||
|
nestedStats && typeof nestedStats === 'object' && !Array.isArray(nestedStats)
|
||||||
|
? (nestedStats as Json)
|
||||||
|
: statsResponse
|
||||||
|
const statusResponse = responses[1] as Json
|
||||||
|
const nestedStatus = statusResponse.status
|
||||||
|
status =
|
||||||
|
nestedStatus && typeof nestedStatus === 'object' && !Array.isArray(nestedStatus)
|
||||||
|
? (nestedStatus as Json)
|
||||||
|
: statusResponse
|
||||||
|
const lastError = typeof status.lastError === 'string' ? status.lastError : ''
|
||||||
|
if (lastError && lastError !== lastNotifiedError) notify.error(lastError)
|
||||||
|
lastNotifiedError = lastError
|
||||||
|
const schedulesResponse = responses[2] as Json
|
||||||
|
const rawSchedules = schedulesResponse.schedules || schedulesResponse.items
|
||||||
|
schedules = Array.isArray(rawSchedules) ? (rawSchedules as Json[]) : []
|
||||||
|
} catch (reason) {
|
||||||
|
if (generation !== loadGeneration) return
|
||||||
|
error = reason instanceof Error ? reason.message : 'Unable to load analyzer state.'
|
||||||
|
} finally {
|
||||||
|
if (!background) loading = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// The backend sets its Running flag synchronously before responding to a start request, so this
|
||||||
|
// is normally redundant - but the very next status poll still has to round-trip over the
|
||||||
|
// network, and a small/near-empty library can finish a run in well under that time. Patching
|
||||||
|
// `status` immediately gives instant feedback that the click was received, and the next real
|
||||||
|
// poll (below) overwrites it with the authoritative value moments later either way.
|
||||||
|
const OPTIMISTIC_STATUS: Record<string, Json> = {
|
||||||
|
'extract/discover': { running: true, state: 'discovering', worker: 'Discovery' },
|
||||||
|
'metadata/start': { running: true, state: 'extracting', worker: 'Metadata extraction' },
|
||||||
|
'generate/start': { running: true, state: 'generating', worker: 'Thumbnail generation' },
|
||||||
|
'analyze/start': { running: true, state: 'analyzing', worker: 'AI analysis' },
|
||||||
|
'cleanup/start': { running: true, state: 'cleaning', worker: 'Cleanup' },
|
||||||
|
'pipeline/clear': { running: true, state: 'clearing', worker: 'Database cleanup', total: 1, completed: 0 },
|
||||||
|
}
|
||||||
|
|
||||||
|
function applyOptimisticStatus(action: string) {
|
||||||
|
const patch = OPTIMISTIC_STATUS[action]
|
||||||
|
if (patch) status = { ...status, ...patch }
|
||||||
|
}
|
||||||
|
|
||||||
|
function clearProgressTotal(types: string[], stages: string[]) {
|
||||||
|
let total = 0
|
||||||
|
for (const type of types) {
|
||||||
|
if (stages.includes('discover')) {
|
||||||
|
total += 1
|
||||||
|
} else if (type === 'funscript') {
|
||||||
|
total += stages.includes('metadata') ? 1 : 0
|
||||||
|
} else {
|
||||||
|
total += stages.filter((stage) => stage === 'metadata' || stage === 'thumbnails' || stage === 'analyze').length
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return total
|
||||||
|
}
|
||||||
|
|
||||||
|
async function runAction(action: string, label = action) {
|
||||||
|
try {
|
||||||
|
await post(`/api/${action}`)
|
||||||
|
applyOptimisticStatus(action)
|
||||||
|
notify.success(`${label} started.`)
|
||||||
|
await load({ background: true })
|
||||||
|
} catch (reason) {
|
||||||
|
notify.error(reason instanceof Error ? reason.message : `Unable to start ${label.toLowerCase()}.`)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let pipelineRunning = $state(false)
|
||||||
|
|
||||||
|
async function runSelectedPipeline() {
|
||||||
|
if (selectedPipelineTypes.size === 0 || selectedPipelineActions.size === 0) return
|
||||||
|
pipelineRunning = true
|
||||||
|
try {
|
||||||
|
const types = Array.from(selectedPipelineTypes)
|
||||||
|
// Discovery and the standalone metadata refresh share one worker slot on the backend (both
|
||||||
|
// walk/probe files synchronously) and can't run at once - discovery already re-probes
|
||||||
|
// metadata for the exact same files as a side effect, so when both are picked, discovery
|
||||||
|
// wins and the separate metadata call is skipped rather than failing with a conflict.
|
||||||
|
const runDiscover = selectedPipelineActions.has('discover')
|
||||||
|
const stages = PIPELINE_ACTIONS.filter(
|
||||||
|
(action) => selectedPipelineActions.has(action.key) && !(action.key === 'metadata' && runDiscover),
|
||||||
|
)
|
||||||
|
const started: string[] = []
|
||||||
|
const failed: string[] = []
|
||||||
|
for (const stage of stages) {
|
||||||
|
try {
|
||||||
|
await post(`/api/${stage.endpoint}`, { types })
|
||||||
|
applyOptimisticStatus(stage.endpoint)
|
||||||
|
started.push(stage.label)
|
||||||
|
} catch (reason) {
|
||||||
|
failed.push(`${stage.label} (${reason instanceof Error ? reason.message : 'failed to start'})`)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (started.length > 0) notify.success(`${started.join(', ')} started.`)
|
||||||
|
if (failed.length > 0) notify.error(`Unable to start: ${failed.join(', ')}.`)
|
||||||
|
await load({ background: true })
|
||||||
|
} finally {
|
||||||
|
pipelineRunning = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let clearingDatabase = $state(false)
|
||||||
|
|
||||||
|
async function clearSelectedPipeline() {
|
||||||
|
if (selectedPipelineTypes.size === 0 || selectedPipelineActions.size === 0) return
|
||||||
|
const types = Array.from(selectedPipelineTypes)
|
||||||
|
const stages = PIPELINE_ACTIONS.filter((action) => selectedPipelineActions.has(action.key))
|
||||||
|
if (
|
||||||
|
!window.confirm(
|
||||||
|
`Clear ${stages.map((stage) => stage.label.toLowerCase()).join(', ')} data for ${types.join(', ')}? This can't be undone, though everything will be regenerated on the next run.`,
|
||||||
|
)
|
||||||
|
) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
clearingDatabase = true
|
||||||
|
const clearRequest = post<Json>('/api/pipeline/clear', { types, stages: stages.map((stage) => stage.key) })
|
||||||
|
status = {
|
||||||
|
...status,
|
||||||
|
...OPTIMISTIC_STATUS['pipeline/clear'],
|
||||||
|
total: clearProgressTotal(types, stages.map((stage) => stage.key)),
|
||||||
|
}
|
||||||
|
// Fetch the authoritative progress immediately as well as through the normal polling loop;
|
||||||
|
// a large thumbnail cleanup can outlive the next scheduled poll interval.
|
||||||
|
void load({ background: true })
|
||||||
|
try {
|
||||||
|
const response = await clearRequest
|
||||||
|
notify.success('Selected pipeline data cleared.')
|
||||||
|
const progress = asRecord(response.progress)
|
||||||
|
await load({ background: true })
|
||||||
|
if (Object.keys(progress).length > 0) {
|
||||||
|
status = {
|
||||||
|
...status,
|
||||||
|
running: false,
|
||||||
|
state: 'completed',
|
||||||
|
worker: 'Database cleanup',
|
||||||
|
total: Number(progress.total) || 0,
|
||||||
|
completed: Number(progress.completed) || 0,
|
||||||
|
failed: Number(progress.failed) || 0,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (reason) {
|
||||||
|
notify.error(reason instanceof Error ? reason.message : 'Unable to clear the selected pipeline data.')
|
||||||
|
} finally {
|
||||||
|
clearingDatabase = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function startDiscover() {
|
||||||
|
if (selectedDiscoverTypes.size === 0) return
|
||||||
|
try {
|
||||||
|
await post('/api/extract/discover', { types: Array.from(selectedDiscoverTypes) })
|
||||||
|
applyOptimisticStatus('extract/discover')
|
||||||
|
notify.success('Discovery started.')
|
||||||
|
await load({ background: true })
|
||||||
|
} catch (reason) {
|
||||||
|
notify.error(reason instanceof Error ? reason.message : 'Unable to start discovery.')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
onMount(() => {
|
||||||
|
let timer: number
|
||||||
|
let cancelled = false
|
||||||
|
const tick = async () => {
|
||||||
|
await load({ background: true })
|
||||||
|
if (!cancelled) timer = window.setTimeout(() => void tick(), status.running === true ? 3_000 : 10_000)
|
||||||
|
}
|
||||||
|
void load().then(() => {
|
||||||
|
if (!cancelled) timer = window.setTimeout(() => void tick(), status.running === true ? 3_000 : 10_000)
|
||||||
|
})
|
||||||
|
return () => {
|
||||||
|
cancelled = true
|
||||||
|
window.clearTimeout(timer)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
</script>
|
||||||
|
|
||||||
|
{#snippet chipGroup(
|
||||||
|
items: { key: string; label: string }[],
|
||||||
|
isSelected: (key: string) => boolean,
|
||||||
|
onToggle: (key: string) => void,
|
||||||
|
allSelected: boolean,
|
||||||
|
onSelectAll: () => void,
|
||||||
|
)}
|
||||||
|
<div class="flex flex-wrap gap-2">
|
||||||
|
{#each items as item (item.key)}
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
class={cn(
|
||||||
|
'rounded-full border px-3 py-1.5 text-sm font-medium transition-colors',
|
||||||
|
isSelected(item.key)
|
||||||
|
? 'border-primary bg-primary text-primary-fg'
|
||||||
|
: 'border-border bg-surface text-fg hover:bg-surface-hover',
|
||||||
|
)}
|
||||||
|
aria-pressed={isSelected(item.key)}
|
||||||
|
onclick={() => onToggle(item.key)}
|
||||||
|
>
|
||||||
|
{item.label}
|
||||||
|
</button>
|
||||||
|
{/each}
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
class={cn(
|
||||||
|
'rounded-full border px-3 py-1.5 text-sm font-medium transition-colors',
|
||||||
|
allSelected
|
||||||
|
? 'border-primary bg-primary text-primary-fg'
|
||||||
|
: 'border-border bg-surface text-fg hover:bg-surface-hover',
|
||||||
|
)}
|
||||||
|
aria-pressed={allSelected}
|
||||||
|
onclick={onSelectAll}
|
||||||
|
>
|
||||||
|
All
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
{/snippet}
|
||||||
|
|
||||||
|
<div class="space-y-4">
|
||||||
|
{#if error}<div
|
||||||
|
class="flex items-center gap-2 rounded-md border border-danger/30 bg-danger/10 px-4 py-3 text-sm text-danger"
|
||||||
|
>
|
||||||
|
<AlertTriangle class="size-4" />{error}
|
||||||
|
</div>{/if}
|
||||||
|
|
||||||
|
{#if panel === 'dashboard'}
|
||||||
|
<div class="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
|
||||||
|
<Metric
|
||||||
|
label="Pending"
|
||||||
|
value={numeric('queued', numeric('queueLength'))}
|
||||||
|
detail="Waiting for a worker"
|
||||||
|
tone="warning"
|
||||||
|
/><Metric
|
||||||
|
label="Processing"
|
||||||
|
value={numeric('processing', numeric('activeJobs'))}
|
||||||
|
detail="Active jobs"
|
||||||
|
tone="primary"
|
||||||
|
/><Metric
|
||||||
|
label="Completed"
|
||||||
|
value={numeric('completed', numeric('processed'))}
|
||||||
|
detail="Current history window"
|
||||||
|
tone="success"
|
||||||
|
/><Metric label="Errors" value={numeric('errors', numeric('failed'))} detail="Needs attention" tone="danger" />
|
||||||
|
</div>
|
||||||
|
<AnalyzerPipelineBreakdown pipeline={asRecord(stats.pipeline)} />
|
||||||
|
<div class="grid gap-4 lg:grid-cols-[minmax(0,1.25fr)_minmax(280px,.75fr)]">
|
||||||
|
<Card class="space-y-5"
|
||||||
|
><SectionTitle
|
||||||
|
title="Pipeline controls"
|
||||||
|
description="Pick media types and pipeline stages, then run just that combination. Each type's own Images/Videos/Audios/Funscripts tab still holds the detailed thumbnails/metadata/AI model settings."
|
||||||
|
/>
|
||||||
|
<div class="space-y-2">
|
||||||
|
<p class="text-xs font-medium uppercase tracking-wide text-muted-fg">Media types</p>
|
||||||
|
{@render chipGroup(
|
||||||
|
DISCOVER_TYPES,
|
||||||
|
(key: string) => selectedPipelineTypes.has(key),
|
||||||
|
togglePipelineType,
|
||||||
|
allPipelineTypesSelected,
|
||||||
|
selectAllPipelineTypes,
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<div class="space-y-2">
|
||||||
|
<p class="text-xs font-medium uppercase tracking-wide text-muted-fg">Stages</p>
|
||||||
|
{@render chipGroup(
|
||||||
|
PIPELINE_ACTIONS,
|
||||||
|
(key: string) => selectedPipelineActions.has(key),
|
||||||
|
togglePipelineAction,
|
||||||
|
allPipelineActionsSelected,
|
||||||
|
selectAllPipelineActions,
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<div class="flex flex-wrap items-center gap-3">
|
||||||
|
<Button
|
||||||
|
disabled={
|
||||||
|
pipelineRunning || clearingDatabase || selectedPipelineTypes.size === 0 || selectedPipelineActions.size === 0
|
||||||
|
}
|
||||||
|
onclick={() => void runSelectedPipeline()}
|
||||||
|
><Play class="size-4" />{pipelineRunning ? 'Starting…' : 'Run selected'}</Button
|
||||||
|
><Button variant="outline" disabled={clearingDatabase} onclick={() => void runAction('cleanup/start', 'Cleanup')}
|
||||||
|
><RefreshCw class="size-4" />Clean stale entries</Button
|
||||||
|
><Button
|
||||||
|
variant="danger"
|
||||||
|
disabled={clearingDatabase || pipelineRunning || selectedPipelineTypes.size === 0 || selectedPipelineActions.size === 0}
|
||||||
|
onclick={() => void clearSelectedPipeline()}
|
||||||
|
><Trash2 class="size-4" />{clearingDatabase ? 'Clearing…' : 'Clear database'}</Button
|
||||||
|
>
|
||||||
|
</div>
|
||||||
|
</Card>
|
||||||
|
<AnalyzerLiveStatus {status} {stats} {loading} description="Last response from the analyzer service." />
|
||||||
|
</div>
|
||||||
|
<AnalyzerHistory
|
||||||
|
title="Recent processing history"
|
||||||
|
description="Every discovered, extracted, and analyzed element is recorded here."
|
||||||
|
/>
|
||||||
|
{:else if panel === 'schedules'}
|
||||||
|
<div class="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
|
||||||
|
<Metric
|
||||||
|
label="Pending"
|
||||||
|
value={numeric('queued', numeric('queueLength'))}
|
||||||
|
detail="Waiting for a worker"
|
||||||
|
tone="warning"
|
||||||
|
/><Metric
|
||||||
|
label="Processing"
|
||||||
|
value={numeric('processing', numeric('activeJobs'))}
|
||||||
|
detail="Active jobs"
|
||||||
|
tone="primary"
|
||||||
|
/><Metric
|
||||||
|
label="Completed"
|
||||||
|
value={numeric('completed', numeric('processed'))}
|
||||||
|
detail="Current history window"
|
||||||
|
tone="success"
|
||||||
|
/><Metric label="Errors" value={numeric('errors', numeric('failed'))} detail="Needs attention" tone="danger" />
|
||||||
|
</div>
|
||||||
|
<AnalyzerLiveStatus {status} {stats} {loading} description="Current analyzer schedule and worker state." />
|
||||||
|
<Card class="space-y-5"
|
||||||
|
><SectionTitle
|
||||||
|
title="New schedule"
|
||||||
|
description="Run a pipeline action automatically on a recurring interval."
|
||||||
|
/>
|
||||||
|
<div class="grid gap-3 sm:grid-cols-2 lg:grid-cols-4">
|
||||||
|
<label class="space-y-1 text-sm"
|
||||||
|
><span class="text-muted-fg">Name</span><input
|
||||||
|
class="field h-9"
|
||||||
|
type="text"
|
||||||
|
placeholder={`${selectedScheduleTool.label} schedule`}
|
||||||
|
bind:value={scheduleName}
|
||||||
|
/></label
|
||||||
|
>
|
||||||
|
<label class="space-y-1 text-sm"
|
||||||
|
><span class="text-muted-fg">Action</span><select class="field h-9" bind:value={scheduleTool}>
|
||||||
|
{#each SCHEDULE_TOOLS as tool (tool.key)}
|
||||||
|
<option value={tool.key}>{tool.label}</option>
|
||||||
|
{/each}
|
||||||
|
</select></label
|
||||||
|
>
|
||||||
|
<label class="space-y-1 text-sm"
|
||||||
|
><span class="text-muted-fg">Every (minutes)</span><input
|
||||||
|
class="field h-9"
|
||||||
|
type="number"
|
||||||
|
min="5"
|
||||||
|
step="5"
|
||||||
|
bind:value={scheduleIntervalMinutes}
|
||||||
|
/></label
|
||||||
|
>
|
||||||
|
<label class="flex items-end gap-2 pb-2 text-sm"
|
||||||
|
><input type="checkbox" bind:checked={scheduleEnabled} /><span class="text-muted-fg">Enabled</span></label
|
||||||
|
>
|
||||||
|
</div>
|
||||||
|
{#if selectedScheduleTool.usesTypes}
|
||||||
|
<div class="space-y-2">
|
||||||
|
<p class="text-xs font-medium uppercase tracking-wide text-muted-fg">Media types</p>
|
||||||
|
{@render chipGroup(
|
||||||
|
DISCOVER_TYPES,
|
||||||
|
(key: string) => scheduleTypes.has(key),
|
||||||
|
toggleScheduleType,
|
||||||
|
allScheduleTypesSelected,
|
||||||
|
selectAllScheduleTypes,
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
|
<Button
|
||||||
|
disabled={creatingSchedule || (selectedScheduleTool.usesTypes && scheduleTypes.size === 0)}
|
||||||
|
onclick={() => void createSchedule()}
|
||||||
|
><Plus class="size-4" />{creatingSchedule ? 'Creating…' : 'Create schedule'}</Button
|
||||||
|
></Card
|
||||||
|
>
|
||||||
|
<Card class="space-y-5"
|
||||||
|
><SectionTitle
|
||||||
|
title="Schedules"
|
||||||
|
description="Recurring analyzer jobs and their current state."
|
||||||
|
/>{#if schedules.length === 0}<EmptyState
|
||||||
|
title="No automation schedules"
|
||||||
|
message="Create one above; it will appear here with its next run."
|
||||||
|
/>{:else}<div class="divide-y divide-border">
|
||||||
|
{#each schedules as schedule, index (String(schedule.id || index))}<div
|
||||||
|
class="flex items-center justify-between gap-3 py-3"
|
||||||
|
>
|
||||||
|
<div class="min-w-0">
|
||||||
|
<p class="truncate text-sm font-medium text-fg">
|
||||||
|
{String(schedule.name || schedule.tool || 'Analyzer schedule')}
|
||||||
|
</p>
|
||||||
|
<p class="mt-1 text-xs text-muted-fg">
|
||||||
|
{String(schedule.tool || '—')} · every {String(schedule.intervalMinutes ?? '?')}m · Next run: {String(
|
||||||
|
schedule.nextRunAt || schedule.next_run_at || '—',
|
||||||
|
)}
|
||||||
|
</p>
|
||||||
|
{#if schedule.lastStatus}<p class="mt-1 text-xs text-muted-fg">
|
||||||
|
Last run: {String(schedule.lastStatus)}
|
||||||
|
</p>{/if}
|
||||||
|
</div>
|
||||||
|
<div class="flex shrink-0 items-center gap-2">
|
||||||
|
<Badge tone={schedule.enabled === false ? 'neutral' : 'success'}
|
||||||
|
>{schedule.enabled === false ? 'Paused' : 'Enabled'}</Badge
|
||||||
|
><Button variant="outline" size="sm" onclick={() => void runScheduleNow(String(schedule.id))}
|
||||||
|
>Run now</Button
|
||||||
|
><Button variant="danger" size="sm" onclick={() => void deleteSchedule(String(schedule.id))}
|
||||||
|
><Trash2 class="size-4" /></Button
|
||||||
|
>
|
||||||
|
</div>
|
||||||
|
</div>{/each}
|
||||||
|
</div>{/if}</Card
|
||||||
|
>
|
||||||
|
<AnalyzerHistory
|
||||||
|
title="Processing history"
|
||||||
|
description="Elements processed while scheduled analyzer work runs."
|
||||||
|
/>
|
||||||
|
{:else}
|
||||||
|
<div class="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
|
||||||
|
{#each DISCOVER_TYPES as type (type.key)}
|
||||||
|
<Metric label={type.label} value={numeric(type.statsKey)} detail="Discovered" />
|
||||||
|
{/each}
|
||||||
|
</div>
|
||||||
|
<div class="grid gap-4 lg:grid-cols-[minmax(0,1.25fr)_minmax(280px,.75fr)]">
|
||||||
|
<Card class="space-y-5"
|
||||||
|
><SectionTitle
|
||||||
|
title="Discovery controls"
|
||||||
|
description="Choose which media types to walk the configured media roots for, then watch the unified run history below."
|
||||||
|
/>
|
||||||
|
{@render chipGroup(
|
||||||
|
DISCOVER_TYPES,
|
||||||
|
(key: string) => selectedDiscoverTypes.has(key),
|
||||||
|
toggleDiscoverType,
|
||||||
|
allDiscoverTypesSelected,
|
||||||
|
selectAllDiscoverTypes,
|
||||||
|
)}
|
||||||
|
<div class="flex flex-wrap gap-3">
|
||||||
|
<Button disabled={selectedDiscoverTypes.size === 0} onclick={() => void startDiscover()}
|
||||||
|
><Play class="size-4" />Start discover</Button
|
||||||
|
><Button variant="secondary" onclick={() => void runAction('cleanup/start', 'Cleanup')}
|
||||||
|
><RefreshCw class="size-4" />Cleanup</Button
|
||||||
|
>
|
||||||
|
</div>
|
||||||
|
<div class="rounded-md border border-border bg-bg p-4">
|
||||||
|
<p class="text-sm font-medium text-fg">Stage guidance</p>
|
||||||
|
<p class="mt-1 text-sm text-muted-fg">
|
||||||
|
Discovered files are indexed immediately. Visit each media type's own tab (Images, Videos, Audios,
|
||||||
|
Funscripts) to configure thumbnails, metadata extraction, and AI analysis for what discovery finds.
|
||||||
|
</p>
|
||||||
|
</div></Card
|
||||||
|
>
|
||||||
|
<AnalyzerLiveStatus {status} {stats} {loading} description="Current discovery run, including the file it's on." />
|
||||||
|
</div>
|
||||||
|
<AnalyzerHistory
|
||||||
|
title="Discovery history"
|
||||||
|
description="Discovered elements, statuses, and results."
|
||||||
|
/>
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,99 @@
|
|||||||
|
<script lang="ts">
|
||||||
|
import { Bluetooth, Cable, CheckCircle2, MonitorPlay, Settings2, SlidersHorizontal } from '@lucide/svelte'
|
||||||
|
import SectionTitle from '$lib/components/SectionTitle.svelte'
|
||||||
|
import Card from '$lib/components/ui/card.svelte'
|
||||||
|
import Button from '$lib/components/ui/button.svelte'
|
||||||
|
import Badge from '$lib/components/ui/badge.svelte'
|
||||||
|
import EmptyState from '$lib/components/EmptyState.svelte'
|
||||||
|
|
||||||
|
let { panel = 'player' }: { panel?: string } = $props()
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<div class="space-y-4">
|
||||||
|
{#if panel === 'devices'}
|
||||||
|
<div class="grid gap-4 lg:grid-cols-2">
|
||||||
|
<Card class="space-y-5"
|
||||||
|
><SectionTitle title="Device connections" description="Connect hardware through the native desktop bridge." />
|
||||||
|
<div class="space-y-3">
|
||||||
|
<div class="flex items-center gap-3 rounded-md border border-border bg-bg p-3">
|
||||||
|
<Cable class="size-4 text-primary" />
|
||||||
|
<div class="flex-1">
|
||||||
|
<p class="text-sm font-medium text-fg">Serial / TCode</p>
|
||||||
|
<p class="text-xs text-muted-fg">Waiting for a local driver</p>
|
||||||
|
</div>
|
||||||
|
<Badge>Offline</Badge>
|
||||||
|
</div>
|
||||||
|
<div class="flex items-center gap-3 rounded-md border border-border bg-bg p-3">
|
||||||
|
<Bluetooth class="size-4 text-primary" />
|
||||||
|
<div class="flex-1">
|
||||||
|
<p class="text-sm font-medium text-fg">Bluetooth devices</p>
|
||||||
|
<p class="text-xs text-muted-fg">Native discovery is available after launch</p>
|
||||||
|
</div>
|
||||||
|
<Badge>Offline</Badge>
|
||||||
|
</div>
|
||||||
|
</div></Card
|
||||||
|
><Card class="space-y-5"
|
||||||
|
><SectionTitle
|
||||||
|
title="Safety"
|
||||||
|
description="The desktop client keeps device output disabled until a connection is explicitly enabled."
|
||||||
|
/>
|
||||||
|
<div class="flex items-start gap-3 rounded-md border border-success/25 bg-success/10 p-3">
|
||||||
|
<CheckCircle2 class="mt-0.5 size-4 text-success" />
|
||||||
|
<p class="text-sm leading-6 text-fg">
|
||||||
|
No device is currently receiving output. Connect a driver from the native controls to enable playback
|
||||||
|
synchronization.
|
||||||
|
</p>
|
||||||
|
</div></Card
|
||||||
|
>
|
||||||
|
</div>
|
||||||
|
{:else if panel === 'settings'}
|
||||||
|
<Card class="space-y-5"
|
||||||
|
><SectionTitle
|
||||||
|
title="Application preferences"
|
||||||
|
description="Native renderer settings remain available from the desktop client bridge."
|
||||||
|
/>
|
||||||
|
<div class="grid gap-4 sm:grid-cols-2">
|
||||||
|
<label class="space-y-2 text-sm"
|
||||||
|
><span class="font-medium text-fg">Theme</span><select class="field"
|
||||||
|
><option>System</option><option>Dark</option><option>Light</option></select
|
||||||
|
></label
|
||||||
|
><label class="space-y-2 text-sm"
|
||||||
|
><span class="font-medium text-fg">Control mode</span><select class="field"
|
||||||
|
><option>Local player</option><option>Remote player</option></select
|
||||||
|
></label
|
||||||
|
>
|
||||||
|
</div>
|
||||||
|
<Button variant="secondary"><Settings2 class="size-4" />Open native preferences</Button></Card
|
||||||
|
>
|
||||||
|
{:else}
|
||||||
|
<div class="grid gap-4 xl:grid-cols-[minmax(0,1fr)_340px]">
|
||||||
|
<Card class="space-y-5"
|
||||||
|
><SectionTitle
|
||||||
|
title="Embedded player"
|
||||||
|
description="The desktop shell embeds MediaViewer when a server is connected."
|
||||||
|
/>
|
||||||
|
<div class="flex min-h-[420px] items-center justify-center rounded-lg border border-dashed border-border bg-bg">
|
||||||
|
<EmptyState
|
||||||
|
title="Connect a MediaViewer server"
|
||||||
|
message="Enter a server URL in the native desktop panel to load the library and player."
|
||||||
|
/>
|
||||||
|
</div></Card
|
||||||
|
><Card class="space-y-5"
|
||||||
|
><SectionTitle
|
||||||
|
title="Playback status"
|
||||||
|
description="The native bridge reports the active media and sync state here."
|
||||||
|
/>
|
||||||
|
<div class="space-y-3">
|
||||||
|
<div class="flex items-center gap-3 rounded-md border border-border bg-bg p-3">
|
||||||
|
<MonitorPlay class="size-4 text-primary" />
|
||||||
|
<div>
|
||||||
|
<p class="text-sm font-medium text-fg">No active media</p>
|
||||||
|
<p class="text-xs text-muted-fg">Player status will appear after connection.</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<Button variant="secondary" class="w-full"><SlidersHorizontal class="size-4" />Open player controls</Button>
|
||||||
|
</div></Card
|
||||||
|
>
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
@@ -0,0 +1,116 @@
|
|||||||
|
<script lang="ts">
|
||||||
|
import { page } from '$app/state'
|
||||||
|
import { Film, Music2, Play } from '@lucide/svelte'
|
||||||
|
import { get } from '$lib/api'
|
||||||
|
import EmptyState from '$lib/components/EmptyState.svelte'
|
||||||
|
import Badge from '$lib/components/ui/badge.svelte'
|
||||||
|
import Button from '$lib/components/ui/button.svelte'
|
||||||
|
import Card from '$lib/components/ui/card.svelte'
|
||||||
|
|
||||||
|
interface FeedItem {
|
||||||
|
mediaKey?: string
|
||||||
|
url?: string
|
||||||
|
thumbnail?: string
|
||||||
|
name?: string
|
||||||
|
filename?: string
|
||||||
|
mediaType?: string
|
||||||
|
title?: string | null
|
||||||
|
category?: string | null
|
||||||
|
}
|
||||||
|
|
||||||
|
let item = $state<FeedItem | null>(null)
|
||||||
|
let loading = $state(true)
|
||||||
|
let error = $state('')
|
||||||
|
let reloadToken = $state(0)
|
||||||
|
let loadSequence = 0
|
||||||
|
|
||||||
|
const exactMedia = $derived(page.url.searchParams.get('video')?.trim() || '')
|
||||||
|
|
||||||
|
async function loadFeed(exact: string) {
|
||||||
|
const sequence = ++loadSequence
|
||||||
|
loading = true
|
||||||
|
error = ''
|
||||||
|
|
||||||
|
try {
|
||||||
|
const query = exact ? `?exact=${encodeURIComponent(exact)}` : ''
|
||||||
|
const response = await get<{ data?: FeedItem }>(`/api/media/random/all${query}`)
|
||||||
|
if (sequence !== loadSequence) return
|
||||||
|
item = response.data || null
|
||||||
|
if (!item) error = 'No media found.'
|
||||||
|
} catch (reason) {
|
||||||
|
if (sequence !== loadSequence) return
|
||||||
|
item = null
|
||||||
|
error = reason instanceof Error ? reason.message : 'Unable to load the media feed.'
|
||||||
|
} finally {
|
||||||
|
if (sequence === loadSequence) loading = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
$effect(() => {
|
||||||
|
const exact = exactMedia
|
||||||
|
const token = reloadToken
|
||||||
|
void token
|
||||||
|
void loadFeed(exact)
|
||||||
|
})
|
||||||
|
|
||||||
|
function nextItem() {
|
||||||
|
if (exactMedia) window.location.href = '/feed'
|
||||||
|
else reloadToken += 1
|
||||||
|
}
|
||||||
|
|
||||||
|
function isImage(media: FeedItem) {
|
||||||
|
return media.mediaType === 'static' || media.mediaType === 'image'
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
{#if loading}
|
||||||
|
<div class="media-shimmer mx-auto h-[min(70dvh,48rem)] max-w-4xl rounded-xl border border-border"></div>
|
||||||
|
{:else if error}
|
||||||
|
<div class="rounded-md border border-danger/30 bg-danger/10 px-4 py-3 text-sm text-danger">{error}</div>
|
||||||
|
{:else if !item}
|
||||||
|
<EmptyState title="No media found" message="The feed will appear once media has been indexed." />
|
||||||
|
{:else}
|
||||||
|
<Card class="mx-auto max-w-4xl overflow-hidden p-0">
|
||||||
|
<div class="relative flex min-h-[min(70dvh,48rem)] items-center justify-center overflow-hidden bg-black">
|
||||||
|
{#if isImage(item)}
|
||||||
|
<img
|
||||||
|
src={item.url || item.thumbnail || ''}
|
||||||
|
alt={item.title || item.name || item.filename || 'Media'}
|
||||||
|
class="max-h-[min(70dvh,48rem)] max-w-full object-contain"
|
||||||
|
/>
|
||||||
|
{:else if item.url}
|
||||||
|
<video
|
||||||
|
src={item.url}
|
||||||
|
poster={item.thumbnail}
|
||||||
|
controls
|
||||||
|
autoplay
|
||||||
|
playsinline
|
||||||
|
class="max-h-[min(70dvh,48rem)] max-w-full object-contain"
|
||||||
|
>
|
||||||
|
<track kind="captions" srclang="en" label="Captions" src="data:text/vtt,WEBVTT" />
|
||||||
|
</video>
|
||||||
|
{:else}
|
||||||
|
<div class="flex flex-col items-center gap-3 text-muted-fg">
|
||||||
|
{#if item.mediaType === 'audio'}<Music2 class="size-12" />{:else}<Film class="size-12" />{/if}
|
||||||
|
<span>Preview unavailable</span>
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="flex flex-col gap-3 border-t border-border p-4 sm:flex-row sm:items-center sm:justify-between">
|
||||||
|
<div class="min-w-0">
|
||||||
|
<p class="truncate text-sm font-medium text-fg">
|
||||||
|
{item.title || item.name || item.filename || 'Untitled media'}
|
||||||
|
</p>
|
||||||
|
<div class="mt-1 flex flex-wrap items-center gap-2 text-xs text-muted-fg">
|
||||||
|
{#if item.mediaType}<Badge tone="neutral">{item.mediaType}</Badge>{/if}
|
||||||
|
{#if item.category}<span>{item.category}</span>{/if}
|
||||||
|
{#if item.filename}<span class="truncate">{item.filename}</span>{/if}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<Button size="sm" onclick={() => void nextItem()} disabled={loading}><Play />Next item</Button>
|
||||||
|
</div>
|
||||||
|
</Card>
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
@@ -0,0 +1,231 @@
|
|||||||
|
<script lang="ts">
|
||||||
|
import { Maximize2, Pause, Play, Settings2, Wifi, WifiOff } from '@lucide/svelte'
|
||||||
|
import { onMount } from 'svelte'
|
||||||
|
import { get } from '$lib/api'
|
||||||
|
import SectionTitle from '$lib/components/SectionTitle.svelte'
|
||||||
|
import Card from '$lib/components/ui/card.svelte'
|
||||||
|
import Button from '$lib/components/ui/button.svelte'
|
||||||
|
import Badge from '$lib/components/ui/badge.svelte'
|
||||||
|
import Metric from '$lib/components/ui/metric.svelte'
|
||||||
|
|
||||||
|
type KioskConfig = {
|
||||||
|
defaultDisplayDuration?: number
|
||||||
|
defaultPreloadCount?: number
|
||||||
|
defaultQueueMode?: string
|
||||||
|
defaultProgressVisibility?: string
|
||||||
|
currentQueueMode?: string
|
||||||
|
currentServerDisplayDuration?: number
|
||||||
|
}
|
||||||
|
|
||||||
|
let { panel = 'kiosk' }: { panel?: string } = $props()
|
||||||
|
let config = $state<KioskConfig>({})
|
||||||
|
let latestImage = $state('')
|
||||||
|
let queueLength = $state(0)
|
||||||
|
let connected = $state(false)
|
||||||
|
let paused = $state(false)
|
||||||
|
let loading = $state(true)
|
||||||
|
let error = $state('')
|
||||||
|
let duration = $state(5000)
|
||||||
|
let queueMode = $state('client')
|
||||||
|
let socket: WebSocket | null = null
|
||||||
|
let mediaDisplay: HTMLDivElement | undefined
|
||||||
|
|
||||||
|
const imageUrl = $derived(
|
||||||
|
latestImage ? `/api/images/${latestImage.split('/').map(encodeURIComponent).join('/')}` : '',
|
||||||
|
)
|
||||||
|
const durationLabel = $derived(duration >= 1000 ? `${Math.round(duration / 100) / 10}s` : `${duration}ms`)
|
||||||
|
|
||||||
|
function updateQueue(next: unknown) {
|
||||||
|
queueLength = Number.isFinite(Number(next)) ? Math.max(0, Number(next)) : queueLength
|
||||||
|
}
|
||||||
|
|
||||||
|
async function loadConfig() {
|
||||||
|
loading = true
|
||||||
|
error = ''
|
||||||
|
try {
|
||||||
|
config = await get<KioskConfig>('/api/config')
|
||||||
|
duration = Number(config.currentServerDisplayDuration || config.defaultDisplayDuration || 5000)
|
||||||
|
queueMode = String(config.currentQueueMode || config.defaultQueueMode || 'client')
|
||||||
|
} catch (reason) {
|
||||||
|
error = reason instanceof Error ? reason.message : 'Unable to load kiosk settings.'
|
||||||
|
} finally {
|
||||||
|
loading = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function togglePause() {
|
||||||
|
paused = !paused
|
||||||
|
if (paused) queueLength = 0
|
||||||
|
}
|
||||||
|
|
||||||
|
function changeQueueMode(value: string) {
|
||||||
|
queueMode = value
|
||||||
|
sendSocket({ type: 'update-settings', queueMode: value })
|
||||||
|
}
|
||||||
|
|
||||||
|
function changeDuration(value: string) {
|
||||||
|
const next = Math.max(0, Number(value) || 0)
|
||||||
|
duration = next
|
||||||
|
sendSocket({ type: 'update-settings', displayDuration: next })
|
||||||
|
}
|
||||||
|
|
||||||
|
function sendSocket(message: Record<string, unknown>) {
|
||||||
|
if (socket?.readyState === WebSocket.OPEN) socket.send(JSON.stringify(message))
|
||||||
|
}
|
||||||
|
|
||||||
|
async function fullscreen() {
|
||||||
|
if (document.fullscreenElement) {
|
||||||
|
await document.exitFullscreen().catch(() => undefined)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if (mediaDisplay) await mediaDisplay.requestFullscreen().catch(() => undefined)
|
||||||
|
}
|
||||||
|
|
||||||
|
onMount(() => {
|
||||||
|
void loadConfig()
|
||||||
|
const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:'
|
||||||
|
socket = new WebSocket(`${protocol}//${window.location.host}/ws`)
|
||||||
|
socket.addEventListener('open', () => (connected = true))
|
||||||
|
socket.addEventListener('close', () => (connected = false))
|
||||||
|
socket.addEventListener('message', (event) => {
|
||||||
|
try {
|
||||||
|
const message = JSON.parse(String(event.data)) as {
|
||||||
|
type?: string
|
||||||
|
path?: string
|
||||||
|
queueMode?: string
|
||||||
|
displayDuration?: number
|
||||||
|
serverDisplayDuration?: number
|
||||||
|
value?: number
|
||||||
|
queueLength?: number
|
||||||
|
}
|
||||||
|
if (message.type === 'new-image') {
|
||||||
|
if (paused) return
|
||||||
|
latestImage = String(message.path || '')
|
||||||
|
queueLength = Math.max(0, queueLength - 1)
|
||||||
|
} else if (message.type === 'settings-updated') {
|
||||||
|
if (message.queueMode) queueMode = message.queueMode
|
||||||
|
const nextDuration = message.displayDuration || message.serverDisplayDuration
|
||||||
|
if (nextDuration) duration = Number(nextDuration)
|
||||||
|
} else if (message.type === 'queue-size') {
|
||||||
|
updateQueue(message.value ?? message.queueLength)
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
// Ignore malformed broadcast messages.
|
||||||
|
}
|
||||||
|
})
|
||||||
|
return () => {
|
||||||
|
socket?.close()
|
||||||
|
socket = null
|
||||||
|
}
|
||||||
|
})
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<div class="space-y-4">
|
||||||
|
<div
|
||||||
|
class="flex flex-wrap justify-end gap-2"
|
||||||
|
aria-label={panel === 'kiosk' ? 'Kiosk controls' : 'Kiosk display controls'}
|
||||||
|
>
|
||||||
|
<Badge tone={connected ? 'success' : 'warning'}
|
||||||
|
>{#if connected}<Wifi class="mr-1 size-3" />Connected{:else}<WifiOff class="mr-1 size-3" />Waiting{/if}</Badge
|
||||||
|
>
|
||||||
|
<Button variant="secondary" size="sm" onclick={() => void fullscreen()}
|
||||||
|
><Maximize2 class="size-4" />Fullscreen</Button
|
||||||
|
>
|
||||||
|
</div>
|
||||||
|
{#if error}<div class="rounded-md border border-danger/30 bg-danger/10 px-4 py-3 text-sm text-danger">
|
||||||
|
{error}
|
||||||
|
</div>{/if}
|
||||||
|
<div class="grid gap-4 sm:grid-cols-3">
|
||||||
|
<Metric label="Queue" value={queueLength} detail="Images waiting to display" tone="primary" /><Metric
|
||||||
|
label="Display time"
|
||||||
|
value={durationLabel}
|
||||||
|
detail="Current server interval"
|
||||||
|
/><Metric label="Mode" value={queueMode} detail={loading ? 'Loading configuration' : 'Socket-controlled'} />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="grid gap-4 xl:grid-cols-[minmax(0,1fr)_340px]">
|
||||||
|
<Card class="overflow-hidden p-0">
|
||||||
|
<div
|
||||||
|
bind:this={mediaDisplay}
|
||||||
|
class="kiosk-media-display relative flex min-h-[min(65vh,680px)] items-center justify-center overflow-hidden bg-black"
|
||||||
|
>
|
||||||
|
{#if imageUrl}<img
|
||||||
|
src={imageUrl}
|
||||||
|
alt="Latest kiosk output"
|
||||||
|
class="max-h-[65vh] w-full object-contain"
|
||||||
|
/>{:else}<div class="flex flex-col items-center gap-3 px-6 text-center text-white/60">
|
||||||
|
<svg
|
||||||
|
class="size-12 text-primary/60"
|
||||||
|
viewBox="0 0 24 24"
|
||||||
|
fill="none"
|
||||||
|
stroke="currentColor"
|
||||||
|
stroke-width="1.5"
|
||||||
|
aria-hidden="true"
|
||||||
|
><rect x="3" y="4" width="18" height="13" rx="2" /><path
|
||||||
|
d="M8 21h8M12 17v4M7 9h.01M11 9h6M7 13h10"
|
||||||
|
/></svg
|
||||||
|
>
|
||||||
|
<p class="text-sm">Waiting for the next image from MediaServant.</p>
|
||||||
|
<p class="text-xs text-white/40">The canvas will update automatically over WebSocket.</p>
|
||||||
|
</div>{/if}
|
||||||
|
<div
|
||||||
|
class="absolute inset-x-4 bottom-4 flex items-center justify-between gap-3 rounded-lg border border-white/10 bg-black/60 px-3 py-2 text-xs text-white backdrop-blur"
|
||||||
|
>
|
||||||
|
<span class="truncate">{latestImage || 'No image received yet'}</span><Button
|
||||||
|
variant="ghost"
|
||||||
|
size="icon"
|
||||||
|
class="text-white hover:bg-white/15 hover:text-white"
|
||||||
|
aria-label={paused ? 'Resume kiosk' : 'Pause kiosk'}
|
||||||
|
onclick={togglePause}
|
||||||
|
>{#if paused}<Play class="size-4" />{:else}<Pause class="size-4" />{/if}</Button
|
||||||
|
>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</Card>
|
||||||
|
|
||||||
|
<Card class="space-y-5"
|
||||||
|
><SectionTitle
|
||||||
|
title="Display controls"
|
||||||
|
description="These settings mirror the kiosk API and live WebSocket controls."
|
||||||
|
/><label class="space-y-2 text-sm"
|
||||||
|
><span class="font-medium text-fg">Display duration</span><input
|
||||||
|
class="field"
|
||||||
|
type="number"
|
||||||
|
min="0"
|
||||||
|
step="100"
|
||||||
|
value={duration}
|
||||||
|
oninput={(event) => changeDuration(event.currentTarget.value)}
|
||||||
|
/><span class="block text-xs text-muted-fg">{durationLabel} per image</span></label
|
||||||
|
><label class="space-y-2 text-sm"
|
||||||
|
><span class="font-medium text-fg">Queue mode</span><select
|
||||||
|
class="field"
|
||||||
|
value={queueMode}
|
||||||
|
onchange={(event) => changeQueueMode(event.currentTarget.value)}
|
||||||
|
><option value="client">Client side</option><option value="server">Server side</option></select
|
||||||
|
></label
|
||||||
|
>
|
||||||
|
<div class="rounded-md border border-border bg-bg p-3">
|
||||||
|
<div class="flex items-center gap-2 text-sm font-medium text-fg">
|
||||||
|
<Settings2 class="size-4 text-primary" />Live session
|
||||||
|
</div>
|
||||||
|
<p class="mt-2 text-xs leading-5 text-muted-fg">
|
||||||
|
Use fullscreen for a clean installation display. The media display expands to fill the screen while its
|
||||||
|
controls remain available.
|
||||||
|
</p>
|
||||||
|
</div></Card
|
||||||
|
>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<style>
|
||||||
|
.kiosk-media-display:fullscreen {
|
||||||
|
width: 100vw;
|
||||||
|
height: 100vh;
|
||||||
|
min-height: 100vh;
|
||||||
|
}
|
||||||
|
|
||||||
|
.kiosk-media-display:fullscreen img {
|
||||||
|
max-height: 100vh;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
@@ -0,0 +1,490 @@
|
|||||||
|
<script lang="ts">
|
||||||
|
import { AlertTriangle, Play, RefreshCw, Trash2 } from '@lucide/svelte'
|
||||||
|
import { onDestroy, onMount } from 'svelte'
|
||||||
|
import { SvelteSet } from 'svelte/reactivity'
|
||||||
|
import { notify } from '@gabriel20xx/web-ui'
|
||||||
|
import { get, post } from '$lib/api'
|
||||||
|
import AnalyzerHistory from '$lib/components/AnalyzerHistory.svelte'
|
||||||
|
import PipelineFlowDiagram from '$lib/components/PipelineFlowDiagram.svelte'
|
||||||
|
import SectionTitle from '$lib/components/SectionTitle.svelte'
|
||||||
|
import Card from '$lib/components/ui/card.svelte'
|
||||||
|
import Button from '$lib/components/ui/button.svelte'
|
||||||
|
import Metric from '$lib/components/ui/metric.svelte'
|
||||||
|
import { cn } from '$lib/utils/cn'
|
||||||
|
|
||||||
|
type MediaType = 'image' | 'video' | 'audio' | 'funscript'
|
||||||
|
type Json = Record<string, unknown>
|
||||||
|
|
||||||
|
let { mediaType, label }: { mediaType: MediaType; label: string } = $props()
|
||||||
|
|
||||||
|
// Mirrors AnalyzerModelSettings.svelte's fallback lists - funscript has no real model to run
|
||||||
|
// yet, so its only real choice is "Disabled".
|
||||||
|
const modelFallbacks: Record<MediaType, string[]> = {
|
||||||
|
image: ['nsfwjs', 'wdtagger', 'faceapi', 'onnxage', 'florence2', 'laplacian'],
|
||||||
|
video: ['nsfwjs', 'wdtagger', 'florence2'],
|
||||||
|
audio: ['whisper', 'clap', 'florence2'],
|
||||||
|
funscript: [],
|
||||||
|
}
|
||||||
|
|
||||||
|
// Tags apply to every media type that has AI models at all; the rest of these generation
|
||||||
|
// tasks only make sense for still images, so only image gets the full set.
|
||||||
|
const stagesForType: Record<MediaType, { key: string; label: string }[]> = {
|
||||||
|
image: [
|
||||||
|
{ key: 'tags', label: 'Tags' },
|
||||||
|
{ key: 'title', label: 'Title' },
|
||||||
|
{ key: 'description', label: 'Description' },
|
||||||
|
{ key: 'age', label: 'Age' },
|
||||||
|
{ key: 'gender', label: 'Gender' },
|
||||||
|
{ key: 'nsfw', label: 'NSFW' },
|
||||||
|
],
|
||||||
|
video: [{ key: 'tags', label: 'Tags' }],
|
||||||
|
audio: [{ key: 'tags', label: 'Tags' }],
|
||||||
|
funscript: [],
|
||||||
|
}
|
||||||
|
const defaultStageModel: Record<MediaType, Record<string, string>> = {
|
||||||
|
image: {
|
||||||
|
tags: 'wdtagger',
|
||||||
|
title: 'florence2',
|
||||||
|
description: 'florence2',
|
||||||
|
age: 'onnxage',
|
||||||
|
gender: 'faceapi',
|
||||||
|
nsfw: 'nsfwjs',
|
||||||
|
},
|
||||||
|
video: { tags: 'wdtagger' },
|
||||||
|
audio: { tags: 'clap' },
|
||||||
|
funscript: {},
|
||||||
|
}
|
||||||
|
const statsKey: Record<MediaType, string> = {
|
||||||
|
image: 'images',
|
||||||
|
video: 'videos',
|
||||||
|
audio: 'audio',
|
||||||
|
funscript: 'funscripts',
|
||||||
|
}
|
||||||
|
|
||||||
|
// The full multi-type blobs, kept in full and saved back in full - matching the read-modify
|
||||||
|
// -write pattern AnalyzerModelSettings.svelte already used for model-config, so a save from
|
||||||
|
// this one type's tab can never clobber the other three types' settings.
|
||||||
|
let pipelineConfig = $state<Json>({})
|
||||||
|
let modelConfig = $state<Json>({})
|
||||||
|
let modelOptions = $state<string[]>([])
|
||||||
|
|
||||||
|
let thumbnailsEnabled = $state(true)
|
||||||
|
let metadataEnabled = $state(true)
|
||||||
|
let stageModels = $state<Record<string, string>>({})
|
||||||
|
let stageEnabled = $state<Record<string, boolean>>({})
|
||||||
|
|
||||||
|
let stats = $state<Json>({})
|
||||||
|
|
||||||
|
let loading = $state(true)
|
||||||
|
let saving = $state(false)
|
||||||
|
let running = $state(false)
|
||||||
|
let clearing = $state(false)
|
||||||
|
let error = $state('')
|
||||||
|
|
||||||
|
function asRecord(value: unknown): Json {
|
||||||
|
return value && typeof value === 'object' && !Array.isArray(value) ? (value as Json) : {}
|
||||||
|
}
|
||||||
|
|
||||||
|
function numeric(value: unknown, fallback = 0) {
|
||||||
|
const n = Number(value ?? fallback)
|
||||||
|
return Number.isFinite(n) ? n : fallback
|
||||||
|
}
|
||||||
|
|
||||||
|
function pipelineCount(stage: string, status: string): number {
|
||||||
|
const stageData = asRecord(asRecord(stats.pipeline)[stage])
|
||||||
|
return numeric(asRecord(stageData[mediaType])[status])
|
||||||
|
}
|
||||||
|
|
||||||
|
// Thumbnails are only ever generated for images and videos (see the backend's
|
||||||
|
// thumbnailCandidates query) - audio and funscript never get one of their own.
|
||||||
|
const thumbnailsSupported = $derived(mediaType === 'image' || mediaType === 'video')
|
||||||
|
const hasAiModel = $derived(modelOptions.length > 0)
|
||||||
|
const aiStages = $derived(
|
||||||
|
stagesForType[mediaType].map((stage) => ({
|
||||||
|
...stage,
|
||||||
|
model: stageModels[stage.key] ?? defaultStageModel[mediaType][stage.key],
|
||||||
|
enabled: stageEnabled[stage.key] ?? false,
|
||||||
|
})),
|
||||||
|
)
|
||||||
|
|
||||||
|
// Mirrors AnalyzerWorkspace.svelte's dashboard "Pipeline controls" panel, scoped to this one
|
||||||
|
// page's fixed media type instead of a type selector. Selection is deliberately never reset on
|
||||||
|
// tab switch (same as the dashboard's own selection) - runSelectedStages filters by both
|
||||||
|
// selection and applicability, so a stage picked on one tab that doesn't apply to another
|
||||||
|
// (e.g. Thumbnails while on Funscripts) just never fires there instead of needing a reset.
|
||||||
|
const STAGE_ACTIONS: { key: 'discover' | 'metadata' | 'thumbnails' | 'analyze'; label: string; endpoint: string }[] = [
|
||||||
|
{ key: 'discover', label: 'Discovery', endpoint: 'extract/discover' },
|
||||||
|
{ key: 'metadata', label: 'Metadata', endpoint: 'metadata/start' },
|
||||||
|
{ key: 'thumbnails', label: 'Thumbnails', endpoint: 'generate/start' },
|
||||||
|
{ key: 'analyze', label: 'AI analysis', endpoint: 'analyze/start' },
|
||||||
|
]
|
||||||
|
const availableStageActions = $derived(
|
||||||
|
STAGE_ACTIONS.filter((action) => {
|
||||||
|
if (action.key === 'thumbnails') return thumbnailsSupported
|
||||||
|
if (action.key === 'analyze') return hasAiModel
|
||||||
|
return true
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
const selectedStages = new SvelteSet<string>(STAGE_ACTIONS.map((action) => action.key))
|
||||||
|
const allStagesSelected = $derived(availableStageActions.every((action) => selectedStages.has(action.key)))
|
||||||
|
|
||||||
|
function toggleStageAction(key: string) {
|
||||||
|
if (selectedStages.has(key)) selectedStages.delete(key)
|
||||||
|
else selectedStages.add(key)
|
||||||
|
}
|
||||||
|
|
||||||
|
function selectAllStageActions() {
|
||||||
|
for (const action of availableStageActions) selectedStages.add(action.key)
|
||||||
|
}
|
||||||
|
|
||||||
|
const stageSummaries = $derived(
|
||||||
|
[
|
||||||
|
{ key: 'extract', label: 'Metadata' },
|
||||||
|
{ key: 'generate', label: 'Thumbnails' },
|
||||||
|
{ key: 'analyze', label: 'AI analysis' },
|
||||||
|
].map((stage) => ({
|
||||||
|
...stage,
|
||||||
|
pending: pipelineCount(stage.key, 'queued'),
|
||||||
|
processing: pipelineCount(stage.key, 'processing'),
|
||||||
|
processed: pipelineCount(stage.key, 'completed'),
|
||||||
|
errors: pipelineCount(stage.key, 'errors'),
|
||||||
|
active: pipelineCount(stage.key, 'active') > 0,
|
||||||
|
})),
|
||||||
|
)
|
||||||
|
const metadataStatus = $derived(stageSummaries.find((stage) => stage.key === 'extract')!)
|
||||||
|
const thumbnailsStatus = $derived(stageSummaries.find((stage) => stage.key === 'generate')!)
|
||||||
|
const analysisStatus = $derived(stageSummaries.find((stage) => stage.key === 'analyze')!)
|
||||||
|
const metadataDescription = $derived(
|
||||||
|
mediaType === 'funscript'
|
||||||
|
? 'Detect .funscript sidecar files during discovery.'
|
||||||
|
: 'Read duration and dimensions with ffprobe during discovery.',
|
||||||
|
)
|
||||||
|
const thumbnailsDescription = 'Generate a preview thumbnail once this file is discovered.'
|
||||||
|
|
||||||
|
const metadataDetails = $derived(
|
||||||
|
mediaType === 'funscript'
|
||||||
|
? 'Looks for a sidecar file next to the source video named "<name>.funscript" or "<name>.json" - no ffprobe involved, just a file existence check.'
|
||||||
|
: mediaType === 'image'
|
||||||
|
? 'Runs ffprobe to read pixel width and height. Still images have no duration, so only dimensions are stored.'
|
||||||
|
: mediaType === 'audio'
|
||||||
|
? 'Runs ffprobe to read duration in milliseconds. Width/height are only stored if the file has an embedded video stream, such as cover art.'
|
||||||
|
: 'Runs ffprobe to read duration in milliseconds plus pixel width and height from the first video stream.',
|
||||||
|
)
|
||||||
|
const thumbnailsDetails =
|
||||||
|
'Captures a single frame with ffmpeg, scaled to 320px wide (height auto-scaled to preserve aspect ratio), saved as a JPEG at quality level 3 (ffmpeg -q:v 3). Videos seek to timestamp 0 before capturing.'
|
||||||
|
|
||||||
|
async function load({ background = false } = {}) {
|
||||||
|
if (!background) loading = true
|
||||||
|
error = ''
|
||||||
|
try {
|
||||||
|
const [pipelineResponse, modelResponse, statsResponse] = await Promise.all([
|
||||||
|
get<{ config?: unknown }>('/api/pipeline-config').catch(() => ({}) as Json),
|
||||||
|
get<{ config?: unknown; options?: unknown }>('/api/model-config').catch(() => ({}) as Json),
|
||||||
|
get<Json>('/api/stats').catch(() => ({}) as Json),
|
||||||
|
])
|
||||||
|
|
||||||
|
pipelineConfig = asRecord(pipelineResponse.config)
|
||||||
|
const typeConfig = asRecord(pipelineConfig[mediaType])
|
||||||
|
thumbnailsEnabled = thumbnailsSupported && typeConfig.thumbnails !== false
|
||||||
|
metadataEnabled = typeConfig.metadata !== false
|
||||||
|
|
||||||
|
const rawModelConfig = asRecord(modelResponse.config)
|
||||||
|
const nestedModelConfig = asRecord(rawModelConfig.config)
|
||||||
|
modelConfig = Object.keys(nestedModelConfig).length > 0 ? nestedModelConfig : rawModelConfig
|
||||||
|
const options = asRecord(modelResponse.options)
|
||||||
|
modelOptions = Array.isArray(options[mediaType]) ? (options[mediaType] as string[]) : modelFallbacks[mediaType]
|
||||||
|
const section = asRecord(modelConfig[mediaType])
|
||||||
|
const nextStageModels: Record<string, string> = {}
|
||||||
|
const nextStageEnabled: Record<string, boolean> = {}
|
||||||
|
for (const stage of stagesForType[mediaType]) {
|
||||||
|
// Older saves stored the single "tags" model as a bare string rather than {primary,
|
||||||
|
// fallback} - keep reading that shape so pre-existing configs don't reset silently.
|
||||||
|
const stored = asRecord(section[stage.key])
|
||||||
|
const primary = typeof section[stage.key] === 'string' ? section[stage.key] : stored.primary
|
||||||
|
// Older saves also had no dedicated "enabled" toggle - disabling a stage meant setting its
|
||||||
|
// model to the "disabled" sentinel. Keep honoring that as the enabled=false fallback so
|
||||||
|
// pre-existing configs don't silently flip on, then fall back to the real default model.
|
||||||
|
const resolvedPrimary = typeof primary === 'string' && primary ? primary : 'disabled'
|
||||||
|
nextStageModels[stage.key] =
|
||||||
|
resolvedPrimary === 'disabled' ? defaultStageModel[mediaType][stage.key] : resolvedPrimary
|
||||||
|
nextStageEnabled[stage.key] = typeof stored.enabled === 'boolean' ? stored.enabled : resolvedPrimary !== 'disabled'
|
||||||
|
}
|
||||||
|
stageModels = nextStageModels
|
||||||
|
stageEnabled = nextStageEnabled
|
||||||
|
|
||||||
|
const statsResult = asRecord(statsResponse)
|
||||||
|
const nestedStats = asRecord(statsResult.stats)
|
||||||
|
stats = Object.keys(nestedStats).length > 0 ? nestedStats : statsResult
|
||||||
|
} catch (reason) {
|
||||||
|
error = reason instanceof Error ? reason.message : `Unable to load the ${label.toLowerCase()} pipeline.`
|
||||||
|
} finally {
|
||||||
|
if (!background) loading = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let saveTimer: ReturnType<typeof setTimeout> | undefined
|
||||||
|
|
||||||
|
// Coalesces rapid successive toggle/dropdown changes into a single save instead of firing one
|
||||||
|
// request per keystroke-like change.
|
||||||
|
function scheduleSave() {
|
||||||
|
if (saveTimer) clearTimeout(saveTimer)
|
||||||
|
saveTimer = setTimeout(() => void save(), 400)
|
||||||
|
}
|
||||||
|
|
||||||
|
onDestroy(() => {
|
||||||
|
if (saveTimer) clearTimeout(saveTimer)
|
||||||
|
})
|
||||||
|
|
||||||
|
async function save() {
|
||||||
|
saving = true
|
||||||
|
try {
|
||||||
|
const nextPipelineConfig = {
|
||||||
|
...pipelineConfig,
|
||||||
|
[mediaType]: { thumbnails: thumbnailsEnabled, metadata: metadataEnabled },
|
||||||
|
}
|
||||||
|
pipelineConfig = nextPipelineConfig
|
||||||
|
await post('/api/pipeline-config', { config: nextPipelineConfig })
|
||||||
|
|
||||||
|
if (hasAiModel) {
|
||||||
|
const nextModelConfig = { ...modelConfig }
|
||||||
|
const section = asRecord(nextModelConfig[mediaType])
|
||||||
|
const nextSection = { ...section }
|
||||||
|
for (const stage of stagesForType[mediaType]) {
|
||||||
|
nextSection[stage.key] = {
|
||||||
|
primary: stageModels[stage.key] ?? defaultStageModel[mediaType][stage.key],
|
||||||
|
fallback: 'none',
|
||||||
|
enabled: stageEnabled[stage.key] ?? false,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
nextModelConfig[mediaType] = nextSection
|
||||||
|
modelConfig = nextModelConfig
|
||||||
|
await post('/api/model-config', { config: nextModelConfig })
|
||||||
|
}
|
||||||
|
|
||||||
|
notify.success(`${label} pipeline saved.`)
|
||||||
|
} catch (reason) {
|
||||||
|
notify.error(reason instanceof Error ? reason.message : 'Unable to save the pipeline.')
|
||||||
|
} finally {
|
||||||
|
saving = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function runSelectedStages() {
|
||||||
|
if (selectedStages.size === 0) return
|
||||||
|
running = true
|
||||||
|
try {
|
||||||
|
// Discovery and the standalone metadata refresh share one worker slot on the backend (both
|
||||||
|
// walk/probe files synchronously) and can't run at once - discovery already re-probes
|
||||||
|
// metadata for the exact same files as a side effect, so when both are picked, discovery
|
||||||
|
// wins and the separate metadata call is skipped rather than failing with a conflict.
|
||||||
|
// Mirrors AnalyzerWorkspace.svelte's runSelectedPipeline.
|
||||||
|
const runDiscover = selectedStages.has('discover')
|
||||||
|
const stages = availableStageActions.filter(
|
||||||
|
(action) => selectedStages.has(action.key) && !(action.key === 'metadata' && runDiscover),
|
||||||
|
)
|
||||||
|
const started: string[] = []
|
||||||
|
const failed: string[] = []
|
||||||
|
for (const stage of stages) {
|
||||||
|
try {
|
||||||
|
await post(`/api/${stage.endpoint}`, { types: [mediaType] })
|
||||||
|
started.push(stage.label)
|
||||||
|
} catch (reason) {
|
||||||
|
failed.push(`${stage.label} (${reason instanceof Error ? reason.message : 'failed to start'})`)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (started.length > 0) notify.success(`${started.join(', ')} started.`)
|
||||||
|
if (failed.length > 0) notify.error(`Unable to start: ${failed.join(', ')}.`)
|
||||||
|
await load({ background: true })
|
||||||
|
} finally {
|
||||||
|
running = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function clearAndReprocess() {
|
||||||
|
if (
|
||||||
|
!window.confirm(
|
||||||
|
`Clear all processed ${label.toLowerCase()} metadata and thumbnails and reprocess from scratch? This can't be undone, though everything will be regenerated.`,
|
||||||
|
)
|
||||||
|
) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
clearing = true
|
||||||
|
try {
|
||||||
|
await post(`/api/pipeline/${mediaType}/clear`)
|
||||||
|
// Same discover+generate+analyze calls "Run pipeline" uses - the clear above is what makes
|
||||||
|
// them redo this type's work instead of skipping already-processed files.
|
||||||
|
await post('/api/extract/discover')
|
||||||
|
await post('/api/generate/start').catch(() => undefined)
|
||||||
|
await post('/api/analyze/start').catch(() => undefined)
|
||||||
|
notify.success(`${label} cleared and reprocessing started.`)
|
||||||
|
await load({ background: true })
|
||||||
|
} catch (reason) {
|
||||||
|
notify.error(reason instanceof Error ? reason.message : 'Unable to clear and reprocess this media type.')
|
||||||
|
} finally {
|
||||||
|
clearing = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function retryErrors(stage: 'metadata' | 'thumbnails' | 'analyze') {
|
||||||
|
try {
|
||||||
|
await post(`/api/pipeline/${mediaType}/retry-errors/${stage}`)
|
||||||
|
notify.success(`Retrying ${label.toLowerCase()} ${stage} errors.`)
|
||||||
|
await load({ background: true })
|
||||||
|
} catch (reason) {
|
||||||
|
notify.error(reason instanceof Error ? reason.message : `Unable to retry ${stage} errors.`)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function fetchStageErrors(stage: 'metadata' | 'thumbnails' | 'analyze') {
|
||||||
|
try {
|
||||||
|
const response = await get<Json>(`/api/pipeline/${mediaType}/errors/${stage}`)
|
||||||
|
const items = response.errors
|
||||||
|
return Array.isArray(items) ? (items as { filePath: string; error: string }[]) : []
|
||||||
|
} catch (reason) {
|
||||||
|
notify.error(reason instanceof Error ? reason.message : `Unable to load ${stage} errors.`)
|
||||||
|
return []
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// WorkspacePage.svelte renders this component from a single shared branch for all four media
|
||||||
|
// types, so Svelte reuses the same instance across tab switches - an effect keyed on mediaType
|
||||||
|
// (rather than onMount alone) is what makes switching tabs actually reload that type's data.
|
||||||
|
$effect(() => {
|
||||||
|
void mediaType
|
||||||
|
void load()
|
||||||
|
})
|
||||||
|
|
||||||
|
onMount(() => {
|
||||||
|
const timer = window.setInterval(() => void load({ background: true }), 10_000)
|
||||||
|
return () => window.clearInterval(timer)
|
||||||
|
})
|
||||||
|
</script>
|
||||||
|
|
||||||
|
{#snippet chipGroup(
|
||||||
|
items: { key: string; label: string }[],
|
||||||
|
isSelected: (key: string) => boolean,
|
||||||
|
onToggle: (key: string) => void,
|
||||||
|
allSelected: boolean,
|
||||||
|
onSelectAll: () => void,
|
||||||
|
)}
|
||||||
|
<div class="flex flex-wrap gap-2">
|
||||||
|
{#each items as item (item.key)}
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
class={cn(
|
||||||
|
'rounded-full border px-3 py-1.5 text-sm font-medium transition-colors',
|
||||||
|
isSelected(item.key)
|
||||||
|
? 'border-primary bg-primary text-primary-fg'
|
||||||
|
: 'border-border bg-surface text-fg hover:bg-surface-hover',
|
||||||
|
)}
|
||||||
|
aria-pressed={isSelected(item.key)}
|
||||||
|
onclick={() => onToggle(item.key)}
|
||||||
|
>
|
||||||
|
{item.label}
|
||||||
|
</button>
|
||||||
|
{/each}
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
class={cn(
|
||||||
|
'rounded-full border px-3 py-1.5 text-sm font-medium transition-colors',
|
||||||
|
allSelected
|
||||||
|
? 'border-primary bg-primary text-primary-fg'
|
||||||
|
: 'border-border bg-surface text-fg hover:bg-surface-hover',
|
||||||
|
)}
|
||||||
|
aria-pressed={allSelected}
|
||||||
|
onclick={onSelectAll}
|
||||||
|
>
|
||||||
|
All
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
{/snippet}
|
||||||
|
|
||||||
|
<div class="space-y-4">
|
||||||
|
{#if error}
|
||||||
|
<div class="flex items-center gap-2 rounded-md border border-danger/30 bg-danger/10 px-4 py-3 text-sm text-danger">
|
||||||
|
<AlertTriangle class="size-4" />{error}
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
|
|
||||||
|
<div class="grid gap-4 sm:grid-cols-2">
|
||||||
|
<Metric {label} value={numeric(stats[statsKey[mediaType]])} detail="Discovered" />
|
||||||
|
<Metric
|
||||||
|
label="Errors"
|
||||||
|
value={stageSummaries.reduce((sum, stage) => sum + stage.errors, 0)}
|
||||||
|
detail="Needs attention"
|
||||||
|
tone="danger"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<Card class="space-y-5">
|
||||||
|
<SectionTitle
|
||||||
|
title={`${label} pipeline`}
|
||||||
|
description="Click a stage to enable or disable it. The diagram updates live and reflects what's currently running."
|
||||||
|
/>
|
||||||
|
|
||||||
|
{#if loading}
|
||||||
|
<p class="text-sm text-muted-fg">Loading pipeline settings…</p>
|
||||||
|
{:else}
|
||||||
|
<PipelineFlowDiagram
|
||||||
|
discovered={numeric(stats[statsKey[mediaType]])}
|
||||||
|
discoveredLabel={label}
|
||||||
|
{metadataEnabled}
|
||||||
|
{metadataStatus}
|
||||||
|
{metadataDescription}
|
||||||
|
{metadataDetails}
|
||||||
|
onToggleMetadata={(value) => {
|
||||||
|
metadataEnabled = value
|
||||||
|
scheduleSave()
|
||||||
|
}}
|
||||||
|
{thumbnailsSupported}
|
||||||
|
{thumbnailsEnabled}
|
||||||
|
{thumbnailsStatus}
|
||||||
|
{thumbnailsDescription}
|
||||||
|
{thumbnailsDetails}
|
||||||
|
onToggleThumbnails={(value) => {
|
||||||
|
thumbnailsEnabled = value
|
||||||
|
scheduleSave()
|
||||||
|
}}
|
||||||
|
{aiStages}
|
||||||
|
{modelOptions}
|
||||||
|
{hasAiModel}
|
||||||
|
{analysisStatus}
|
||||||
|
onToggleStage={(stage, value) => {
|
||||||
|
stageEnabled = { ...stageEnabled, [stage]: value }
|
||||||
|
scheduleSave()
|
||||||
|
}}
|
||||||
|
onModelChange={(stage, value) => {
|
||||||
|
stageModels = { ...stageModels, [stage]: value }
|
||||||
|
scheduleSave()
|
||||||
|
}}
|
||||||
|
onRetryErrors={(stage) => void retryErrors(stage)}
|
||||||
|
onShowErrors={(stage) => fetchStageErrors(stage)}
|
||||||
|
disabled={saving}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<div class="space-y-2 border-t border-border pt-4">
|
||||||
|
<p class="text-xs font-medium uppercase tracking-wide text-muted-fg">Stages</p>
|
||||||
|
{@render chipGroup(availableStageActions, (key) => selectedStages.has(key), toggleStageAction, allStagesSelected, selectAllStageActions)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="flex flex-wrap items-center gap-3">
|
||||||
|
<Button disabled={running || clearing || selectedStages.size === 0} onclick={() => void runSelectedStages()}>
|
||||||
|
<Play class="size-4" />{running ? 'Starting…' : 'Run selected'}
|
||||||
|
</Button>
|
||||||
|
<Button variant="outline" disabled={loading || clearing} onclick={() => void load()}>
|
||||||
|
<RefreshCw class="size-4" />Refresh
|
||||||
|
</Button>
|
||||||
|
<Button variant="danger" disabled={clearing || running} onclick={() => void clearAndReprocess()}>
|
||||||
|
<Trash2 class="size-4" />{clearing ? 'Clearing…' : 'Clear & reprocess'}
|
||||||
|
</Button>
|
||||||
|
{#if saving}<span class="text-xs text-muted-fg">Saving…</span>{/if}
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
|
</Card>
|
||||||
|
|
||||||
|
<AnalyzerHistory
|
||||||
|
{mediaType}
|
||||||
|
title={`Recent ${label.toLowerCase()} history`}
|
||||||
|
description="Elements of this media type processed by the pipeline."
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
@@ -0,0 +1,502 @@
|
|||||||
|
<script lang="ts">
|
||||||
|
import { BarChart3, Check, Pencil, ShieldCheck, Trash2, UserCheck, Users } from '@lucide/svelte'
|
||||||
|
import { onMount } from 'svelte'
|
||||||
|
import { notify } from '@gabriel20xx/web-ui'
|
||||||
|
import { get, post, put } from '$lib/api'
|
||||||
|
import SectionTitle from '$lib/components/SectionTitle.svelte'
|
||||||
|
import Card from '$lib/components/ui/card.svelte'
|
||||||
|
import Button from '$lib/components/ui/button.svelte'
|
||||||
|
import Badge from '$lib/components/ui/badge.svelte'
|
||||||
|
import Metric from '$lib/components/ui/metric.svelte'
|
||||||
|
import EmptyState from '$lib/components/EmptyState.svelte'
|
||||||
|
|
||||||
|
interface UserRow {
|
||||||
|
id: string | number
|
||||||
|
email?: string
|
||||||
|
username?: string
|
||||||
|
role?: string
|
||||||
|
disabled?: boolean
|
||||||
|
mfaEnabled?: boolean
|
||||||
|
createdAt?: string
|
||||||
|
}
|
||||||
|
interface UserForm {
|
||||||
|
email: string
|
||||||
|
username: string
|
||||||
|
password: string
|
||||||
|
role: string
|
||||||
|
}
|
||||||
|
interface MediaRow {
|
||||||
|
id: string | number
|
||||||
|
mediaKey?: string
|
||||||
|
title?: string
|
||||||
|
active?: boolean
|
||||||
|
source?: string
|
||||||
|
mediaType?: string
|
||||||
|
createdAt?: string
|
||||||
|
generatorUsername?: string
|
||||||
|
}
|
||||||
|
let { panel = 'dashboard' }: { panel?: string } = $props()
|
||||||
|
let users = $state<UserRow[]>([])
|
||||||
|
let media = $state<MediaRow[]>([])
|
||||||
|
let selectedUsers = $state<string[]>([])
|
||||||
|
let selectedMedia = $state<string[]>([])
|
||||||
|
let search = $state('')
|
||||||
|
let loading = $state(true)
|
||||||
|
let error = $state('')
|
||||||
|
let editingUser = $state<UserRow | null>(null)
|
||||||
|
let savingUser = $state(false)
|
||||||
|
let createForm = $state<UserForm>({ email: '', username: '', password: '', role: 'user' })
|
||||||
|
let editForm = $state<UserForm>({ email: '', username: '', password: '', role: 'user' })
|
||||||
|
|
||||||
|
async function load() {
|
||||||
|
loading = true
|
||||||
|
error = ''
|
||||||
|
try {
|
||||||
|
const [usersResponse, mediaResponse] = await Promise.all([
|
||||||
|
get<{ users?: UserRow[] }>(`/api/admin/users?search=${encodeURIComponent(search)}`).catch(() => ({
|
||||||
|
users: [],
|
||||||
|
})),
|
||||||
|
get<{ media?: MediaRow[] }>(`/api/admin/media?search=${encodeURIComponent(search)}`).catch(() => ({
|
||||||
|
media: [],
|
||||||
|
})),
|
||||||
|
])
|
||||||
|
users = Array.isArray(usersResponse.users) ? usersResponse.users : []
|
||||||
|
media = Array.isArray(mediaResponse.media) ? mediaResponse.media : []
|
||||||
|
} catch (reason) {
|
||||||
|
error = reason instanceof Error ? reason.message : 'Unable to load moderation data.'
|
||||||
|
} finally {
|
||||||
|
loading = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function toggle(list: string[], id: string, kind: 'users' | 'media') {
|
||||||
|
const next = list.includes(id) ? list.filter((value) => value !== id) : [...list, id]
|
||||||
|
if (kind === 'users') selectedUsers = next
|
||||||
|
else selectedMedia = next
|
||||||
|
}
|
||||||
|
|
||||||
|
async function userAction(action: string) {
|
||||||
|
if (!selectedUsers.length) return
|
||||||
|
try {
|
||||||
|
await post('/api/admin/users/actions', { action, ids: selectedUsers })
|
||||||
|
notify.success(`${action} applied to ${selectedUsers.length} user(s).`)
|
||||||
|
selectedUsers = []
|
||||||
|
await load()
|
||||||
|
} catch (reason) {
|
||||||
|
notify.error(reason instanceof Error ? reason.message : 'User action failed.')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function createUser() {
|
||||||
|
if (!createForm.email.trim() || !createForm.password) {
|
||||||
|
notify.error('Email and password are required.')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if (createForm.password.length < 8) {
|
||||||
|
notify.error('Password must be at least 8 characters.')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
savingUser = true
|
||||||
|
try {
|
||||||
|
await post('/api/admin/users', {
|
||||||
|
email: createForm.email.trim(),
|
||||||
|
username: createForm.username.trim(),
|
||||||
|
password: createForm.password,
|
||||||
|
role: createForm.role,
|
||||||
|
})
|
||||||
|
notify.success('User created.')
|
||||||
|
createForm = { email: '', username: '', password: '', role: 'user' }
|
||||||
|
await load()
|
||||||
|
} catch (reason) {
|
||||||
|
notify.error(reason instanceof Error ? reason.message : 'Unable to create user.')
|
||||||
|
} finally {
|
||||||
|
savingUser = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function openUserEditor(user: UserRow) {
|
||||||
|
editingUser = user
|
||||||
|
editForm = {
|
||||||
|
email: user.email || '',
|
||||||
|
username: user.username || '',
|
||||||
|
password: '',
|
||||||
|
role: user.role || 'user',
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function closeUserEditor() {
|
||||||
|
if (!savingUser) editingUser = null
|
||||||
|
}
|
||||||
|
|
||||||
|
async function saveUser() {
|
||||||
|
if (!editingUser) return
|
||||||
|
if (!editForm.email.trim()) {
|
||||||
|
notify.error('Email is required.')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if (editForm.password && editForm.password.length < 8) {
|
||||||
|
notify.error('Password must be at least 8 characters.')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
savingUser = true
|
||||||
|
try {
|
||||||
|
const body: Record<string, string> = {
|
||||||
|
email: editForm.email.trim(),
|
||||||
|
username: editForm.username.trim(),
|
||||||
|
role: editForm.role,
|
||||||
|
}
|
||||||
|
if (editForm.password) body.password = editForm.password
|
||||||
|
await put(`/api/admin/users/${encodeURIComponent(String(editingUser.id))}`, body)
|
||||||
|
notify.success('User updated.')
|
||||||
|
editingUser = null
|
||||||
|
await load()
|
||||||
|
} catch (reason) {
|
||||||
|
notify.error(reason instanceof Error ? reason.message : 'Unable to update user.')
|
||||||
|
} finally {
|
||||||
|
savingUser = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function mediaAction(action: string) {
|
||||||
|
if (!selectedMedia.length) return
|
||||||
|
try {
|
||||||
|
await post('/api/admin/media/actions', { action, ids: selectedMedia })
|
||||||
|
notify.success(`${action} applied to ${selectedMedia.length} media item(s).`)
|
||||||
|
selectedMedia = []
|
||||||
|
await load()
|
||||||
|
} catch (reason) {
|
||||||
|
notify.error(reason instanceof Error ? reason.message : 'Media action failed.')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
onMount(() => void load())
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<div class="space-y-4">
|
||||||
|
{#if error}<div class="rounded-md border border-danger/30 bg-danger/10 px-4 py-3 text-sm text-danger">
|
||||||
|
{error}
|
||||||
|
</div>{/if}
|
||||||
|
{#if panel === 'dashboard'}
|
||||||
|
<div class="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
|
||||||
|
<Metric label="Users" value={users.length} detail="Loaded from admin catalog" /><Metric
|
||||||
|
label="Active users"
|
||||||
|
value={users.filter((user) => !user.disabled).length}
|
||||||
|
tone="success"
|
||||||
|
/><Metric label="Media records" value={media.length} detail="Catalog window" /><Metric
|
||||||
|
label="Flagged / inactive"
|
||||||
|
value={media.filter((item) => item.active === false).length}
|
||||||
|
tone="warning"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div class="grid gap-4 lg:grid-cols-2">
|
||||||
|
<Card class="space-y-4"
|
||||||
|
><SectionTitle title="Access posture" description="Account state at a glance." />
|
||||||
|
<div class="flex items-center gap-3 rounded-md border border-border bg-bg p-4">
|
||||||
|
<ShieldCheck class="size-6 text-success" />
|
||||||
|
<div>
|
||||||
|
<p class="text-sm font-medium text-fg">Moderation controls available</p>
|
||||||
|
<p class="mt-1 text-xs text-muted-fg">
|
||||||
|
Use Users and Media for scoped actions; every write remains protected by the existing admin API.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</div></Card
|
||||||
|
><Card class="space-y-4"
|
||||||
|
><SectionTitle title="Next actions" />
|
||||||
|
<div class="grid gap-3 sm:grid-cols-2">
|
||||||
|
<a href="/users" class="rounded-md border border-border bg-bg p-4 transition hover:border-primary/60"
|
||||||
|
><Users class="size-5 text-primary" />
|
||||||
|
<p class="mt-3 text-sm font-medium text-fg">Review users</p>
|
||||||
|
<p class="mt-1 text-xs text-muted-fg">Disable, enable, reset, or change roles.</p></a
|
||||||
|
><a href="/media" class="rounded-md border border-border bg-bg p-4 transition hover:border-primary/60"
|
||||||
|
><BarChart3 class="size-5 text-primary" />
|
||||||
|
<p class="mt-3 text-sm font-medium text-fg">Moderate media</p>
|
||||||
|
<p class="mt-1 text-xs text-muted-fg">Hide, restore, delete, or rename catalog items.</p></a
|
||||||
|
>
|
||||||
|
</div></Card
|
||||||
|
>
|
||||||
|
</div>
|
||||||
|
{:else if panel === 'users'}
|
||||||
|
<Card class="space-y-5"
|
||||||
|
><div class="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
|
||||||
|
<SectionTitle title="Users" description="Create accounts, edit account details, or apply a bulk action." />
|
||||||
|
<div class="flex gap-2">
|
||||||
|
<input
|
||||||
|
bind:value={search}
|
||||||
|
onkeydown={(event) => event.key === 'Enter' && void load()}
|
||||||
|
placeholder="Search users"
|
||||||
|
class="h-9 w-48 rounded-md border border-border bg-bg px-3 text-sm text-fg outline-none focus-visible:ring-2 focus-visible:ring-ring"
|
||||||
|
/><Button size="sm" variant="secondary" onclick={() => void load()}>Search</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="flex flex-wrap gap-2 border-y border-border py-3">
|
||||||
|
<Badge tone="primary">{selectedUsers.length} selected</Badge><Button
|
||||||
|
size="sm"
|
||||||
|
variant="secondary"
|
||||||
|
disabled={!selectedUsers.length}
|
||||||
|
onclick={() => void userAction('enable')}><UserCheck class="size-4" />Enable</Button
|
||||||
|
><Button
|
||||||
|
size="sm"
|
||||||
|
variant="secondary"
|
||||||
|
disabled={!selectedUsers.length}
|
||||||
|
onclick={() => void userAction('disable')}>Disable</Button
|
||||||
|
><Button size="sm" variant="danger" disabled={!selectedUsers.length} onclick={() => void userAction('delete')}
|
||||||
|
><Trash2 class="size-4" />Delete</Button
|
||||||
|
>
|
||||||
|
</div>
|
||||||
|
<form
|
||||||
|
class="grid gap-3 rounded-md border border-border bg-bg p-4 sm:grid-cols-2 lg:grid-cols-5"
|
||||||
|
onsubmit={(event) => {
|
||||||
|
event.preventDefault()
|
||||||
|
void createUser()
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<div class="sm:col-span-2 lg:col-span-1">
|
||||||
|
<label for="new-user-email" class="mb-1 block text-xs font-medium text-muted-fg">Email</label>
|
||||||
|
<input
|
||||||
|
id="new-user-email"
|
||||||
|
type="email"
|
||||||
|
required
|
||||||
|
bind:value={createForm.email}
|
||||||
|
autocomplete="email"
|
||||||
|
placeholder="user@example.com"
|
||||||
|
class="h-9 w-full rounded-md border border-border bg-surface px-3 text-sm text-fg outline-none focus-visible:ring-2 focus-visible:ring-ring"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label for="new-user-username" class="mb-1 block text-xs font-medium text-muted-fg">Username</label>
|
||||||
|
<input
|
||||||
|
id="new-user-username"
|
||||||
|
bind:value={createForm.username}
|
||||||
|
autocomplete="username"
|
||||||
|
placeholder="Optional"
|
||||||
|
class="h-9 w-full rounded-md border border-border bg-surface px-3 text-sm text-fg outline-none focus-visible:ring-2 focus-visible:ring-ring"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label for="new-user-password" class="mb-1 block text-xs font-medium text-muted-fg">Password</label>
|
||||||
|
<input
|
||||||
|
id="new-user-password"
|
||||||
|
type="password"
|
||||||
|
required
|
||||||
|
minlength="8"
|
||||||
|
bind:value={createForm.password}
|
||||||
|
autocomplete="new-password"
|
||||||
|
placeholder="At least 8 characters"
|
||||||
|
class="h-9 w-full rounded-md border border-border bg-surface px-3 text-sm text-fg outline-none focus-visible:ring-2 focus-visible:ring-ring"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label for="new-user-role" class="mb-1 block text-xs font-medium text-muted-fg">Role</label>
|
||||||
|
<select
|
||||||
|
id="new-user-role"
|
||||||
|
bind:value={createForm.role}
|
||||||
|
class="h-9 w-full rounded-md border border-border bg-surface px-3 text-sm text-fg outline-none focus-visible:ring-2 focus-visible:ring-ring"
|
||||||
|
>
|
||||||
|
<option value="user">user</option>
|
||||||
|
<option value="moderator">moderator</option>
|
||||||
|
<option value="admin">admin</option>
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
<div class="flex items-end">
|
||||||
|
<Button type="submit" class="w-full" disabled={savingUser}>Create user</Button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
{#if loading}<p class="py-8 text-center text-sm text-muted-fg">
|
||||||
|
Loading users…
|
||||||
|
</p>{:else if users.length === 0}<EmptyState
|
||||||
|
title="No users found"
|
||||||
|
message="Try a different search or create a user above."
|
||||||
|
/>{:else}<div class="overflow-x-auto">
|
||||||
|
<table class="w-full min-w-[760px] text-left">
|
||||||
|
<thead
|
||||||
|
><tr class="border-b border-border text-xs uppercase tracking-wider text-muted-fg"
|
||||||
|
><th class="w-10 py-3"></th><th class="py-3">User</th><th class="py-3">Role</th><th class="py-3"
|
||||||
|
>Status</th
|
||||||
|
><th class="py-3">Security</th><th class="py-3 text-right">Actions</th></tr
|
||||||
|
></thead
|
||||||
|
><tbody class="divide-y divide-border"
|
||||||
|
>{#each users as user (user.id)}<tr class="hover:bg-surface-hover/50"
|
||||||
|
><td class="py-3"
|
||||||
|
><input
|
||||||
|
type="checkbox"
|
||||||
|
checked={selectedUsers.includes(String(user.id))}
|
||||||
|
onchange={() => toggle(selectedUsers, String(user.id), 'users')}
|
||||||
|
class="size-4 accent-primary"
|
||||||
|
/></td
|
||||||
|
><td class="py-3"
|
||||||
|
><p class="text-sm font-medium text-fg">{user.username || user.email || `User ${user.id}`}</p>
|
||||||
|
<p class="mt-1 text-xs text-muted-fg">{user.email || 'No email'}</p></td
|
||||||
|
><td class="py-3"
|
||||||
|
><Badge tone={user.role === 'admin' || user.role === 'superadmin' ? 'primary' : 'neutral'}
|
||||||
|
>{user.role || 'user'}</Badge
|
||||||
|
></td
|
||||||
|
><td class="py-3"
|
||||||
|
><Badge tone={user.disabled ? 'danger' : 'success'}>{user.disabled ? 'Disabled' : 'Active'}</Badge
|
||||||
|
></td
|
||||||
|
><td class="py-3 text-xs text-muted-fg">{user.mfaEnabled ? 'MFA enabled' : 'MFA not enabled'}</td><td
|
||||||
|
class="py-3 text-right"
|
||||||
|
>
|
||||||
|
<Button size="sm" variant="secondary" onclick={() => openUserEditor(user)}
|
||||||
|
><Pencil class="size-4" />Edit</Button
|
||||||
|
></td
|
||||||
|
></tr
|
||||||
|
>{/each}</tbody
|
||||||
|
>
|
||||||
|
</table>
|
||||||
|
</div>{/if}</Card
|
||||||
|
>
|
||||||
|
{#if editingUser}
|
||||||
|
<div
|
||||||
|
class="fixed inset-0 z-50 flex items-center justify-center bg-black/60 p-4"
|
||||||
|
role="presentation"
|
||||||
|
onclick={(event) => event.target === event.currentTarget && closeUserEditor()}
|
||||||
|
>
|
||||||
|
<div
|
||||||
|
role="dialog"
|
||||||
|
aria-modal="true"
|
||||||
|
aria-labelledby="edit-user-title"
|
||||||
|
class="w-full max-w-xl rounded-lg border border-border bg-surface p-5 shadow-xl"
|
||||||
|
>
|
||||||
|
<div class="flex items-start justify-between gap-4">
|
||||||
|
<div>
|
||||||
|
<h2 id="edit-user-title" class="text-lg font-semibold text-fg">Edit user</h2>
|
||||||
|
<p class="mt-1 text-xs text-muted-fg">
|
||||||
|
Update the account details for {editingUser.username || editingUser.email || `User ${editingUser.id}`}.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<Button variant="ghost" size="sm" onclick={closeUserEditor} disabled={savingUser}>Close</Button>
|
||||||
|
</div>
|
||||||
|
<form
|
||||||
|
class="mt-5 space-y-4"
|
||||||
|
onsubmit={(event) => {
|
||||||
|
event.preventDefault()
|
||||||
|
void saveUser()
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<div class="grid gap-4 sm:grid-cols-2">
|
||||||
|
<div>
|
||||||
|
<label for="edit-user-email" class="mb-1 block text-xs font-medium text-muted-fg">Email</label>
|
||||||
|
<input
|
||||||
|
id="edit-user-email"
|
||||||
|
type="email"
|
||||||
|
required
|
||||||
|
bind:value={editForm.email}
|
||||||
|
autocomplete="email"
|
||||||
|
class="h-9 w-full rounded-md border border-border bg-bg px-3 text-sm text-fg outline-none focus-visible:ring-2 focus-visible:ring-ring"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label for="edit-user-username" class="mb-1 block text-xs font-medium text-muted-fg">Username</label>
|
||||||
|
<input
|
||||||
|
id="edit-user-username"
|
||||||
|
bind:value={editForm.username}
|
||||||
|
autocomplete="username"
|
||||||
|
placeholder="Optional"
|
||||||
|
class="h-9 w-full rounded-md border border-border bg-bg px-3 text-sm text-fg outline-none focus-visible:ring-2 focus-visible:ring-ring"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label for="edit-user-password" class="mb-1 block text-xs font-medium text-muted-fg">New password</label>
|
||||||
|
<input
|
||||||
|
id="edit-user-password"
|
||||||
|
type="password"
|
||||||
|
minlength="8"
|
||||||
|
bind:value={editForm.password}
|
||||||
|
autocomplete="new-password"
|
||||||
|
placeholder="Leave blank to keep the current password"
|
||||||
|
class="h-9 w-full rounded-md border border-border bg-bg px-3 text-sm text-fg outline-none focus-visible:ring-2 focus-visible:ring-ring"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label for="edit-user-role" class="mb-1 block text-xs font-medium text-muted-fg">Role</label>
|
||||||
|
<select
|
||||||
|
id="edit-user-role"
|
||||||
|
bind:value={editForm.role}
|
||||||
|
class="h-9 w-full rounded-md border border-border bg-bg px-3 text-sm text-fg outline-none focus-visible:ring-2 focus-visible:ring-ring"
|
||||||
|
>
|
||||||
|
<option value="user">user</option>
|
||||||
|
<option value="moderator">moderator</option>
|
||||||
|
<option value="admin">admin</option>
|
||||||
|
<option value="superadmin">superadmin</option>
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
<div class="flex justify-end gap-2">
|
||||||
|
<Button type="button" variant="secondary" onclick={closeUserEditor} disabled={savingUser}>Cancel</Button>
|
||||||
|
<Button type="submit" disabled={savingUser}>{savingUser ? 'Saving…' : 'Save changes'}</Button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
|
{:else}
|
||||||
|
<Card class="space-y-5"
|
||||||
|
><div class="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
|
||||||
|
<SectionTitle title="Media catalog" description="Select catalog rows and apply visibility actions." />
|
||||||
|
<div class="flex gap-2">
|
||||||
|
<input
|
||||||
|
bind:value={search}
|
||||||
|
onkeydown={(event) => event.key === 'Enter' && void load()}
|
||||||
|
placeholder="Search media"
|
||||||
|
class="h-9 w-48 rounded-md border border-border bg-bg px-3 text-sm text-fg outline-none focus-visible:ring-2 focus-visible:ring-ring"
|
||||||
|
/><Button size="sm" variant="secondary" onclick={() => void load()}>Search</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="flex flex-wrap gap-2 border-y border-border py-3">
|
||||||
|
<Badge tone="primary">{selectedMedia.length} selected</Badge><Button
|
||||||
|
size="sm"
|
||||||
|
variant="secondary"
|
||||||
|
disabled={!selectedMedia.length}
|
||||||
|
onclick={() => void mediaAction('activate')}><Check class="size-4" />Show</Button
|
||||||
|
><Button
|
||||||
|
size="sm"
|
||||||
|
variant="secondary"
|
||||||
|
disabled={!selectedMedia.length}
|
||||||
|
onclick={() => void mediaAction('deactivate')}>Hide</Button
|
||||||
|
><Button size="sm" variant="danger" disabled={!selectedMedia.length} onclick={() => void mediaAction('delete')}
|
||||||
|
><Trash2 class="size-4" />Delete</Button
|
||||||
|
>
|
||||||
|
</div>
|
||||||
|
{#if loading}<p class="py-8 text-center text-sm text-muted-fg">
|
||||||
|
Loading media…
|
||||||
|
</p>{:else if media.length === 0}<EmptyState
|
||||||
|
title="No catalog media found"
|
||||||
|
message="MediaAnalyzer outputs will appear once the catalog synchronization has data."
|
||||||
|
/>{:else}<div class="overflow-x-auto">
|
||||||
|
<table class="w-full min-w-[720px] text-left">
|
||||||
|
<thead
|
||||||
|
><tr class="border-b border-border text-xs uppercase tracking-wider text-muted-fg"
|
||||||
|
><th class="w-10 py-3"></th><th class="py-3">Media</th><th class="py-3">Source</th><th class="py-3"
|
||||||
|
>Owner</th
|
||||||
|
><th class="py-3">Visibility</th></tr
|
||||||
|
></thead
|
||||||
|
><tbody class="divide-y divide-border"
|
||||||
|
>{#each media as item (item.id)}<tr class="hover:bg-surface-hover/50"
|
||||||
|
><td class="py-3"
|
||||||
|
><input
|
||||||
|
type="checkbox"
|
||||||
|
checked={selectedMedia.includes(String(item.id))}
|
||||||
|
onchange={() => toggle(selectedMedia, String(item.id), 'media')}
|
||||||
|
class="size-4 accent-primary"
|
||||||
|
/></td
|
||||||
|
><td class="py-3"
|
||||||
|
><p class="max-w-md truncate text-sm font-medium text-fg">
|
||||||
|
{item.title || item.mediaKey || `Media ${item.id}`}
|
||||||
|
</p>
|
||||||
|
<p class="mt-1 max-w-md truncate text-xs text-muted-fg">{item.mediaKey || 'No media key'}</p></td
|
||||||
|
><td class="py-3 text-xs text-muted-fg">{item.source || '—'}</td><td
|
||||||
|
class="py-3 text-xs text-muted-fg">{item.generatorUsername || '—'}</td
|
||||||
|
><td class="py-3"
|
||||||
|
><Badge tone={item.active === false ? 'danger' : 'success'}
|
||||||
|
>{item.active === false ? 'Hidden' : 'Visible'}</Badge
|
||||||
|
></td
|
||||||
|
></tr
|
||||||
|
>{/each}</tbody
|
||||||
|
>
|
||||||
|
</table>
|
||||||
|
</div>{/if}</Card
|
||||||
|
>
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
@@ -0,0 +1,184 @@
|
|||||||
|
<script lang="ts">
|
||||||
|
import { Database, FileClock, FolderOpen, HardDrive, Server, ShieldAlert } from '@lucide/svelte'
|
||||||
|
import { onMount } from 'svelte'
|
||||||
|
import { get } from '$lib/api'
|
||||||
|
import SectionTitle from '$lib/components/SectionTitle.svelte'
|
||||||
|
import Card from '$lib/components/ui/card.svelte'
|
||||||
|
import Badge from '$lib/components/ui/badge.svelte'
|
||||||
|
import Metric from '$lib/components/ui/metric.svelte'
|
||||||
|
import EmptyState from '$lib/components/EmptyState.svelte'
|
||||||
|
|
||||||
|
type Json = Record<string, unknown>
|
||||||
|
type FileRow = { rel?: string; name?: string; path?: string; mtime?: number; size?: number; type?: string }
|
||||||
|
|
||||||
|
let { panel = 'overview' }: { panel?: string } = $props()
|
||||||
|
let stats = $state<Json>({})
|
||||||
|
let mounts = $state<Json>({})
|
||||||
|
let bandwidth = $state<Json>({})
|
||||||
|
let files = $state<FileRow[]>([])
|
||||||
|
let loading = $state(true)
|
||||||
|
let error = $state('')
|
||||||
|
let lastUpdated = $state('')
|
||||||
|
|
||||||
|
const value = (source: Json, ...keys: string[]) => {
|
||||||
|
for (const key of keys) if (source[key] !== undefined && source[key] !== null) return String(source[key])
|
||||||
|
return '0'
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatBytes(input: unknown) {
|
||||||
|
const bytes = Number(input)
|
||||||
|
if (!Number.isFinite(bytes) || bytes <= 0) return '0 B'
|
||||||
|
const units = ['B', 'KB', 'MB', 'GB', 'TB']
|
||||||
|
const index = Math.min(units.length - 1, Math.floor(Math.log(bytes) / Math.log(1024)))
|
||||||
|
return `${(bytes / 1024 ** index).toFixed(index === 0 ? 0 : 1)} ${units[index]}`
|
||||||
|
}
|
||||||
|
|
||||||
|
// Each of these is independent data from a different (sometimes filesystem-touching, e.g.
|
||||||
|
// /api/stats walking every configured mount) backend call - fetched in parallel via
|
||||||
|
// allSettled (not sequential awaits, and not Promise.all) so a slow or failed one (an
|
||||||
|
// unreachable network mount, say) can neither hold up the others - /api/mounts is a pure
|
||||||
|
// settings read and should never wait behind /api/stats's filesystem walk - nor blank them
|
||||||
|
// out. Whatever succeeds still updates lastUpdated and its own section; only what actually
|
||||||
|
// failed reports an error.
|
||||||
|
async function load() {
|
||||||
|
loading = true
|
||||||
|
const failures: string[] = []
|
||||||
|
const [statsResult, mountsResult, filesResult] = await Promise.allSettled([
|
||||||
|
get<Json>('/api/stats'),
|
||||||
|
get<Json>('/api/mounts'),
|
||||||
|
get<Json>('/api/files/recent?limit=24'),
|
||||||
|
])
|
||||||
|
|
||||||
|
if (statsResult.status === 'fulfilled') {
|
||||||
|
stats = (statsResult.value.stats as Json) || {}
|
||||||
|
bandwidth = (statsResult.value.bandwidth as Json) || {}
|
||||||
|
} else {
|
||||||
|
failures.push(statsResult.reason instanceof Error ? statsResult.reason.message : 'stats unavailable')
|
||||||
|
}
|
||||||
|
|
||||||
|
if (mountsResult.status === 'fulfilled') {
|
||||||
|
mounts = (mountsResult.value.mappings as Json) || mountsResult.value
|
||||||
|
} else {
|
||||||
|
failures.push(mountsResult.reason instanceof Error ? mountsResult.reason.message : 'mounts unavailable')
|
||||||
|
}
|
||||||
|
|
||||||
|
if (filesResult.status === 'fulfilled') {
|
||||||
|
const rows = filesResult.value.files || filesResult.value.items || filesResult.value.rows
|
||||||
|
files = Array.isArray(rows) ? (rows as FileRow[]) : []
|
||||||
|
} else {
|
||||||
|
files = []
|
||||||
|
}
|
||||||
|
|
||||||
|
error = failures.join(' / ')
|
||||||
|
lastUpdated = new Date().toLocaleTimeString()
|
||||||
|
loading = false
|
||||||
|
}
|
||||||
|
|
||||||
|
onMount(() => {
|
||||||
|
void load()
|
||||||
|
const timer = window.setInterval(() => void load(), 15_000)
|
||||||
|
return () => window.clearInterval(timer)
|
||||||
|
})
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<div class="space-y-4">
|
||||||
|
{#if error}<div
|
||||||
|
class="flex items-center gap-2 rounded-md border border-warning/30 bg-warning/10 px-4 py-3 text-sm text-warning"
|
||||||
|
>
|
||||||
|
<ShieldAlert class="size-4" />{error}
|
||||||
|
</div>{/if}
|
||||||
|
<div class="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
|
||||||
|
<Metric
|
||||||
|
label="Requests"
|
||||||
|
value={value(stats, 'requests', 'totalRequests')}
|
||||||
|
detail="Tracked requests"
|
||||||
|
tone="primary"
|
||||||
|
/><Metric
|
||||||
|
label="Active mounts"
|
||||||
|
value={value(mounts, 'count', 'total', 'active')}
|
||||||
|
detail="Configured sources"
|
||||||
|
/><Metric
|
||||||
|
label="Bytes out"
|
||||||
|
value={formatBytes(bandwidth.bytesOut || bandwidth.egress)}
|
||||||
|
detail="Current tracker window"
|
||||||
|
tone="success"
|
||||||
|
/><Metric label="Updated" value={lastUpdated || '--'} detail={loading ? 'Refreshing' : 'Live snapshot'} />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{#if panel === 'files'}
|
||||||
|
<Card class="space-y-5"
|
||||||
|
><SectionTitle
|
||||||
|
title="Recent files"
|
||||||
|
description="The file feed is available when the browser has the required servant access."
|
||||||
|
/>{#if files.length === 0}<EmptyState
|
||||||
|
title="No recent file activity"
|
||||||
|
message="Recent files are protected by the internal service policy or no files have arrived yet."
|
||||||
|
/>{:else}<div class="divide-y divide-border">
|
||||||
|
{#each files as file, index (String(file.rel || file.path || index))}<div
|
||||||
|
class="flex items-center gap-3 py-3"
|
||||||
|
>
|
||||||
|
<div class="rounded-md border border-border bg-bg p-2"><FileClock class="size-4 text-primary" /></div>
|
||||||
|
<div class="min-w-0 flex-1">
|
||||||
|
<p class="truncate text-sm font-medium text-fg">{file.name || file.rel || file.path || 'Media file'}</p>
|
||||||
|
<p class="mt-1 truncate text-xs text-muted-fg">
|
||||||
|
{file.type || 'media'}{file.mtime ? ` - ${new Date(Number(file.mtime)).toLocaleString()}` : ''}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<span class="shrink-0 text-xs text-muted-fg">{formatBytes(file.size)}</span>
|
||||||
|
</div>{/each}
|
||||||
|
</div>{/if}</Card
|
||||||
|
>
|
||||||
|
{:else}
|
||||||
|
<div class="grid gap-4 lg:grid-cols-[minmax(0,1.25fr)_minmax(280px,.75fr)]">
|
||||||
|
<Card class="space-y-5"
|
||||||
|
><SectionTitle
|
||||||
|
title="Mount health"
|
||||||
|
description="Mount mappings are read from MediaConfig and used by the delivery layer."
|
||||||
|
/>{#if Object.keys(mounts).length === 0}<EmptyState
|
||||||
|
title="No mount mappings"
|
||||||
|
message="Connect MediaConfig and reload the mount configuration to see storage sources."
|
||||||
|
/>{:else}<div class="space-y-3">
|
||||||
|
{#each Object.entries(mounts) as [name, mapping] (name)}<div
|
||||||
|
class="flex items-center justify-between gap-3 rounded-md border border-border bg-bg p-3"
|
||||||
|
>
|
||||||
|
<div class="flex min-w-0 items-center gap-3">
|
||||||
|
<HardDrive class="size-4 shrink-0 text-primary" />
|
||||||
|
<div class="min-w-0">
|
||||||
|
<p class="truncate text-sm font-medium text-fg">{name}</p>
|
||||||
|
<p class="truncate text-xs text-muted-fg">
|
||||||
|
{typeof mapping === 'string' ? mapping : JSON.stringify(mapping)}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<Badge tone="success">Mapped</Badge>
|
||||||
|
</div>{/each}
|
||||||
|
</div>{/if}</Card
|
||||||
|
><Card class="space-y-5"
|
||||||
|
><SectionTitle title="Delivery signals" description="Useful at a glance when troubleshooting clients." />
|
||||||
|
<div class="space-y-3">
|
||||||
|
<div class="flex items-center gap-3 rounded-md border border-border bg-bg p-3">
|
||||||
|
<Server class="size-4 text-success" />
|
||||||
|
<div>
|
||||||
|
<p class="text-sm font-medium text-fg">Service online</p>
|
||||||
|
<p class="text-xs text-muted-fg">Health probes and file delivery share this process.</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="flex items-center gap-3 rounded-md border border-border bg-bg p-3">
|
||||||
|
<Database class="size-4 text-primary" />
|
||||||
|
<div>
|
||||||
|
<p class="text-sm font-medium text-fg">Database tracked</p>
|
||||||
|
<p class="text-xs text-muted-fg">Last refresh: {lastUpdated || '--'}</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="flex items-center gap-3 rounded-md border border-border bg-bg p-3">
|
||||||
|
<FolderOpen class="size-4 text-warning" />
|
||||||
|
<div>
|
||||||
|
<p class="text-sm font-medium text-fg">Recent entries</p>
|
||||||
|
<p class="text-xs text-muted-fg">{files.length || 'No'} visible in this session</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div></Card
|
||||||
|
>
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
@@ -0,0 +1,270 @@
|
|||||||
|
<script lang="ts">
|
||||||
|
import { page } from '$app/state'
|
||||||
|
import { ArrowLeft, ChevronLeft, ChevronRight, Image, Search, Tags as TagsIcon } from '@lucide/svelte'
|
||||||
|
import { onMount } from 'svelte'
|
||||||
|
import { get } from '$lib/api'
|
||||||
|
import EmptyState from '$lib/components/EmptyState.svelte'
|
||||||
|
import Badge from '$lib/components/ui/badge.svelte'
|
||||||
|
import Button from '$lib/components/ui/button.svelte'
|
||||||
|
import Card from '$lib/components/ui/card.svelte'
|
||||||
|
|
||||||
|
interface TagSummary {
|
||||||
|
tag: string
|
||||||
|
count: number
|
||||||
|
}
|
||||||
|
|
||||||
|
interface TagMedia {
|
||||||
|
mediaKey?: string
|
||||||
|
url?: string
|
||||||
|
thumbnail?: string
|
||||||
|
name?: string
|
||||||
|
filename?: string
|
||||||
|
mediaType?: string
|
||||||
|
relativePath?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
let tags = $state<TagSummary[]>([])
|
||||||
|
let tagQuery = $state('')
|
||||||
|
let loading = $state(true)
|
||||||
|
let error = $state('')
|
||||||
|
let tagMedia = $state<TagMedia[]>([])
|
||||||
|
let tagMediaLoading = $state(false)
|
||||||
|
let tagMediaError = $state('')
|
||||||
|
let tagPage = $state(1)
|
||||||
|
let tagTotalPages = $state(1)
|
||||||
|
let tagTotal = $state(0)
|
||||||
|
let tagListPage = $state(1)
|
||||||
|
let lastRequestedTag = ''
|
||||||
|
let mediaRequest = 0
|
||||||
|
|
||||||
|
const tagListPageSize = 24
|
||||||
|
const selectedTag = $derived(page.url.searchParams.get('tag')?.trim().toLowerCase() || '')
|
||||||
|
const visibleTags = $derived(tags.filter(({ tag }) => tag.toLowerCase().includes(tagQuery.trim().toLowerCase())))
|
||||||
|
const tagListTotalPages = $derived(Math.max(1, Math.ceil(visibleTags.length / tagListPageSize)))
|
||||||
|
const currentTagListPage = $derived(Math.min(Math.max(tagListPage, 1), tagListTotalPages))
|
||||||
|
const paginatedTags = $derived(
|
||||||
|
visibleTags.slice((currentTagListPage - 1) * tagListPageSize, currentTagListPage * tagListPageSize),
|
||||||
|
)
|
||||||
|
|
||||||
|
async function loadTags() {
|
||||||
|
loading = true
|
||||||
|
error = ''
|
||||||
|
try {
|
||||||
|
const response = await get<{ tags?: Array<TagSummary | string> }>('/api/tags/suggestions?limit=100000')
|
||||||
|
tags = (response.tags || [])
|
||||||
|
.map((entry) =>
|
||||||
|
typeof entry === 'string'
|
||||||
|
? { tag: entry, count: 0 }
|
||||||
|
: { tag: String(entry.tag || ''), count: Number(entry.count || 0) },
|
||||||
|
)
|
||||||
|
.filter(({ tag }) => tag.length > 0)
|
||||||
|
} catch (reason) {
|
||||||
|
error = reason instanceof Error ? reason.message : 'Unable to load tags.'
|
||||||
|
} finally {
|
||||||
|
loading = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function loadTagMedia(tag: string, nextPage: number) {
|
||||||
|
const request = ++mediaRequest
|
||||||
|
tagMediaLoading = true
|
||||||
|
tagMediaError = ''
|
||||||
|
try {
|
||||||
|
const response = await get<{
|
||||||
|
data?: TagMedia[]
|
||||||
|
pagination?: { page?: number; total?: number; totalPages?: number }
|
||||||
|
}>(`/api/tags/${encodeURIComponent(tag)}/media?page=${nextPage}&limit=24`)
|
||||||
|
if (request !== mediaRequest) return
|
||||||
|
tagMedia = response.data || []
|
||||||
|
tagPage = response.pagination?.page || nextPage
|
||||||
|
tagTotal = response.pagination?.total || tagMedia.length
|
||||||
|
tagTotalPages = Math.max(1, response.pagination?.totalPages || 1)
|
||||||
|
} catch (reason) {
|
||||||
|
if (request !== mediaRequest) return
|
||||||
|
tagMedia = []
|
||||||
|
tagMediaError = reason instanceof Error ? reason.message : 'Unable to load media for this tag.'
|
||||||
|
} finally {
|
||||||
|
if (request === mediaRequest) tagMediaLoading = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
$effect(() => {
|
||||||
|
const tag = selectedTag
|
||||||
|
if (tag === lastRequestedTag) return
|
||||||
|
lastRequestedTag = tag
|
||||||
|
tagPage = 1
|
||||||
|
tagMedia = []
|
||||||
|
tagTotal = 0
|
||||||
|
tagTotalPages = 1
|
||||||
|
if (tag) void loadTagMedia(tag, 1)
|
||||||
|
else {
|
||||||
|
mediaRequest += 1
|
||||||
|
tagMediaLoading = false
|
||||||
|
tagMediaError = ''
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
onMount(() => {
|
||||||
|
void loadTags()
|
||||||
|
})
|
||||||
|
|
||||||
|
function isImage(media: TagMedia) {
|
||||||
|
return media.mediaType === 'static' || media.mediaType === 'image'
|
||||||
|
}
|
||||||
|
|
||||||
|
function feedHref(media: TagMedia) {
|
||||||
|
const target = media.mediaKey || media.url || media.relativePath || ''
|
||||||
|
return `/feed?video=${encodeURIComponent(target)}`
|
||||||
|
}
|
||||||
|
|
||||||
|
function goToTagPage(nextPage: number) {
|
||||||
|
if (!selectedTag || nextPage < 1 || nextPage > tagTotalPages || tagMediaLoading) return
|
||||||
|
void loadTagMedia(selectedTag, nextPage)
|
||||||
|
}
|
||||||
|
|
||||||
|
function updateTagQuery(event: Event) {
|
||||||
|
tagQuery = (event.currentTarget as HTMLInputElement).value
|
||||||
|
tagListPage = 1
|
||||||
|
}
|
||||||
|
|
||||||
|
function goToTagListPage(nextPage: number) {
|
||||||
|
if (nextPage < 1 || nextPage > tagListTotalPages) return
|
||||||
|
tagListPage = nextPage
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
{#if selectedTag}
|
||||||
|
<div class="mb-5 flex justify-end">
|
||||||
|
<Button variant="secondary" size="sm" onclick={() => (window.location.href = '/tags')}>
|
||||||
|
<ArrowLeft />All tags
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="space-y-5">
|
||||||
|
{#if tagMediaError}
|
||||||
|
<div class="rounded-md border border-danger/30 bg-danger/10 px-4 py-3 text-sm text-danger">{tagMediaError}</div>
|
||||||
|
{:else if tagMediaLoading}
|
||||||
|
<div class="grid gap-4 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4">
|
||||||
|
{#each Array(8) as _, index (index)}<div
|
||||||
|
class="media-shimmer h-64 rounded-lg border border-border"
|
||||||
|
></div>{/each}
|
||||||
|
</div>
|
||||||
|
{:else if tagMedia.length === 0}
|
||||||
|
<EmptyState title="No media found" message={`No media is currently associated with “${selectedTag}”.`} />
|
||||||
|
{:else}
|
||||||
|
<div class="grid gap-4 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4">
|
||||||
|
{#each tagMedia as media (media.mediaKey || media.url || media.filename)}
|
||||||
|
<a
|
||||||
|
href={feedHref(media)}
|
||||||
|
class="group overflow-hidden rounded-lg border border-border bg-surface text-left shadow-sm transition hover:-translate-y-0.5 hover:border-primary/60 hover:shadow-md"
|
||||||
|
>
|
||||||
|
<div class="relative flex aspect-video items-center justify-center overflow-hidden bg-black">
|
||||||
|
{#if media.thumbnail || isImage(media)}
|
||||||
|
<img
|
||||||
|
src={media.thumbnail || media.url || ''}
|
||||||
|
alt={media.name || media.filename || selectedTag}
|
||||||
|
loading="lazy"
|
||||||
|
class="h-full w-full object-contain transition duration-300 group-hover:scale-105"
|
||||||
|
/>
|
||||||
|
{:else}
|
||||||
|
<Image class="size-10 text-muted-fg" />
|
||||||
|
{/if}
|
||||||
|
{#if media.mediaType}<Badge tone="neutral" class="absolute left-2 top-2">{media.mediaType}</Badge>{/if}
|
||||||
|
</div>
|
||||||
|
<div class="p-3">
|
||||||
|
<p class="truncate text-sm font-medium text-fg">{media.name || media.filename || 'Untitled media'}</p>
|
||||||
|
{#if media.filename}<p class="mt-1 truncate text-xs text-muted-fg">{media.filename}</p>{/if}
|
||||||
|
</div>
|
||||||
|
</a>
|
||||||
|
{/each}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="flex items-center justify-between gap-3 text-xs text-muted-fg">
|
||||||
|
<span>{tagTotal.toLocaleString()} items · Page {tagPage} of {tagTotalPages}</span>
|
||||||
|
<div class="flex gap-2">
|
||||||
|
<Button
|
||||||
|
variant="secondary"
|
||||||
|
size="sm"
|
||||||
|
disabled={tagPage <= 1 || tagMediaLoading}
|
||||||
|
onclick={() => goToTagPage(tagPage - 1)}
|
||||||
|
>
|
||||||
|
<ChevronLeft />Previous
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
variant="secondary"
|
||||||
|
size="sm"
|
||||||
|
disabled={tagPage >= tagTotalPages || tagMediaLoading}
|
||||||
|
onclick={() => goToTagPage(tagPage + 1)}
|
||||||
|
>
|
||||||
|
Next<ChevronRight />
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
|
{:else}
|
||||||
|
<div class="space-y-4">
|
||||||
|
<Card class="flex items-center gap-3">
|
||||||
|
<Search class="size-4 shrink-0 text-muted-fg" />
|
||||||
|
<input
|
||||||
|
value={tagQuery}
|
||||||
|
oninput={updateTagQuery}
|
||||||
|
class="h-9 min-w-0 flex-1 rounded-md border border-border bg-bg px-3 text-sm outline-none focus-visible:ring-2 focus-visible:ring-ring"
|
||||||
|
placeholder="Filter tags"
|
||||||
|
aria-label="Filter tags"
|
||||||
|
/>
|
||||||
|
<span class="shrink-0 text-xs text-muted-fg">{visibleTags.length.toLocaleString()} tags</span>
|
||||||
|
</Card>
|
||||||
|
|
||||||
|
{#if error}
|
||||||
|
<div class="rounded-md border border-danger/30 bg-danger/10 px-4 py-3 text-sm text-danger">{error}</div>
|
||||||
|
{:else if loading}
|
||||||
|
<div class="grid gap-4 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4">
|
||||||
|
{#each Array(8) as _, index (index)}<div
|
||||||
|
class="media-shimmer h-28 rounded-lg border border-border"
|
||||||
|
></div>{/each}
|
||||||
|
</div>
|
||||||
|
{:else if visibleTags.length === 0}
|
||||||
|
<EmptyState
|
||||||
|
title="No tags found"
|
||||||
|
message={tagQuery ? 'Try a different tag filter.' : 'Tags will appear after media analysis has run.'}
|
||||||
|
/>
|
||||||
|
{:else}
|
||||||
|
<div class="grid gap-4 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4">
|
||||||
|
{#each paginatedTags as entry (entry.tag)}
|
||||||
|
<a
|
||||||
|
href={`/tags?tag=${encodeURIComponent(entry.tag)}`}
|
||||||
|
class="flex min-h-28 flex-col justify-between rounded-lg border border-border bg-surface p-4 shadow-sm transition hover:-translate-y-0.5 hover:border-primary/60 hover:shadow-md"
|
||||||
|
>
|
||||||
|
<div class="flex items-center gap-3">
|
||||||
|
<TagsIcon class="size-5 shrink-0 text-primary" />
|
||||||
|
<span class="truncate text-sm font-medium text-fg">{entry.tag}</span>
|
||||||
|
</div>
|
||||||
|
<span class="mt-4 text-xs text-muted-fg">{entry.count.toLocaleString()} media items</span>
|
||||||
|
</a>
|
||||||
|
{/each}
|
||||||
|
</div>
|
||||||
|
<div class="flex items-center justify-between gap-3 text-xs text-muted-fg">
|
||||||
|
<span>{visibleTags.length.toLocaleString()} tags · Page {currentTagListPage} of {tagListTotalPages}</span>
|
||||||
|
<div class="flex gap-2">
|
||||||
|
<Button
|
||||||
|
variant="secondary"
|
||||||
|
size="sm"
|
||||||
|
disabled={currentTagListPage <= 1}
|
||||||
|
onclick={() => goToTagListPage(currentTagListPage - 1)}
|
||||||
|
>
|
||||||
|
<ChevronLeft />Previous
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
variant="secondary"
|
||||||
|
size="sm"
|
||||||
|
disabled={currentTagListPage >= tagListTotalPages}
|
||||||
|
onclick={() => goToTagListPage(currentTagListPage + 1)}
|
||||||
|
>
|
||||||
|
Next<ChevronRight />
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
@@ -0,0 +1,472 @@
|
|||||||
|
<script lang="ts">
|
||||||
|
import { Activity, ArrowRight, CheckCircle2, CloudDownload, Film, Upload, WandSparkles, X } from '@lucide/svelte'
|
||||||
|
import { onMount } from 'svelte'
|
||||||
|
import { notify } from '@gabriel20xx/web-ui'
|
||||||
|
import { get, post } from '$lib/api'
|
||||||
|
import SectionTitle from '$lib/components/SectionTitle.svelte'
|
||||||
|
import Card from '$lib/components/ui/card.svelte'
|
||||||
|
import Button from '$lib/components/ui/button.svelte'
|
||||||
|
import Badge from '$lib/components/ui/badge.svelte'
|
||||||
|
import Metric from '$lib/components/ui/metric.svelte'
|
||||||
|
import EmptyState from '$lib/components/EmptyState.svelte'
|
||||||
|
|
||||||
|
type Json = Record<string, unknown>
|
||||||
|
|
||||||
|
interface Job {
|
||||||
|
id?: string
|
||||||
|
tool?: string
|
||||||
|
status?: string
|
||||||
|
createdAt?: string
|
||||||
|
startedAt?: string
|
||||||
|
finishedAt?: string
|
||||||
|
error?: string
|
||||||
|
}
|
||||||
|
interface Schedule {
|
||||||
|
id?: string
|
||||||
|
name?: string
|
||||||
|
tool?: string
|
||||||
|
intervalMinutes?: number
|
||||||
|
enabled?: boolean
|
||||||
|
nextRunAt?: string
|
||||||
|
lastStatus?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
interface ConverterFormat {
|
||||||
|
id: string
|
||||||
|
label: string
|
||||||
|
extension?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
let { panel = 'generator' }: { panel?: string } = $props()
|
||||||
|
let jobs = $state<Job[]>([])
|
||||||
|
let schedules = $state<Schedule[]>([])
|
||||||
|
let queue: Job[] = $state([])
|
||||||
|
let loading = $state(true)
|
||||||
|
let error = $state('')
|
||||||
|
let starting = $state(false)
|
||||||
|
let prompt = $state('')
|
||||||
|
let sourceUrl = $state('')
|
||||||
|
let sourcePath = $state('')
|
||||||
|
let sourceFile = $state<File | null>(null)
|
||||||
|
let sourceFileInput = $state<HTMLInputElement | null>(null)
|
||||||
|
let sourceFileDragging = $state(false)
|
||||||
|
let uploadingSource = $state(false)
|
||||||
|
let workflowNames = $state<string[]>([])
|
||||||
|
let workflowName = $state('')
|
||||||
|
let workflowGraph = $state<Json>({})
|
||||||
|
let converterFormats = $state<ConverterFormat[]>([])
|
||||||
|
let targetFormat = $state('mp4')
|
||||||
|
let encodingProfile = $state('balanced')
|
||||||
|
|
||||||
|
const workflowTitle = $derived(
|
||||||
|
panel === 'schedules'
|
||||||
|
? 'Automation schedules'
|
||||||
|
: panel === 'library'
|
||||||
|
? 'Workflow library'
|
||||||
|
: panel[0]?.toUpperCase() + panel.slice(1),
|
||||||
|
)
|
||||||
|
|
||||||
|
function asRecord(value: unknown): Json {
|
||||||
|
return value && typeof value === 'object' && !Array.isArray(value) ? (value as Json) : {}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function loadJobs() {
|
||||||
|
try {
|
||||||
|
const toolQuery = ['generator', 'downloader', 'converter'].includes(panel)
|
||||||
|
? `?tool=${encodeURIComponent(panel)}`
|
||||||
|
: ''
|
||||||
|
const [jobResponse, scheduleResponse, queueResponse] = await Promise.all([
|
||||||
|
get<{ jobs?: Job[] }>(`/api/jobs${toolQuery}`).catch(() => ({ jobs: [] })),
|
||||||
|
get<{ schedules?: Schedule[] }>('/api/schedules').catch(() => ({ schedules: [] })),
|
||||||
|
get<{ queue?: Job[] }>(`/api/queue${toolQuery}`).catch(() => ({ queue: [] })),
|
||||||
|
])
|
||||||
|
jobs = Array.isArray(jobResponse.jobs) ? jobResponse.jobs : []
|
||||||
|
schedules = Array.isArray(scheduleResponse.schedules) ? scheduleResponse.schedules : []
|
||||||
|
queue = Array.isArray(queueResponse.queue) ? queueResponse.queue : []
|
||||||
|
} catch (reason) {
|
||||||
|
error = reason instanceof Error ? reason.message : 'Unable to load workflow state.'
|
||||||
|
} finally {
|
||||||
|
loading = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function loadGeneratorOptions() {
|
||||||
|
try {
|
||||||
|
const response = await get<{ builtIn?: string[]; mine?: string[]; data?: string[] }>('/api/workflows/list')
|
||||||
|
const names = [...(response.builtIn || []), ...(response.mine || []), ...(response.data || [])].filter(
|
||||||
|
(name, index, values) => typeof name === 'string' && name.trim() && values.indexOf(name) === index,
|
||||||
|
)
|
||||||
|
workflowNames = names
|
||||||
|
if (!workflowName || !names.includes(workflowName)) workflowName = names[0] || ''
|
||||||
|
if (workflowName) await loadWorkflowGraph(workflowName)
|
||||||
|
} catch (reason) {
|
||||||
|
error = reason instanceof Error ? reason.message : 'Unable to load generator workflows.'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function loadWorkflowGraph(name: string) {
|
||||||
|
if (!name) {
|
||||||
|
workflowGraph = {}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const response = await get<{ graph?: Json }>(`/api/generator/workflows/meta?name=${encodeURIComponent(name)}`)
|
||||||
|
workflowGraph = asRecord(response.graph)
|
||||||
|
} catch (reason) {
|
||||||
|
workflowGraph = {}
|
||||||
|
error = reason instanceof Error ? reason.message : 'Unable to load the selected generator workflow.'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function loadConverterOptions() {
|
||||||
|
try {
|
||||||
|
const response = await get<{ formats?: ConverterFormat[] }>('/api/converter/formats')
|
||||||
|
converterFormats = Array.isArray(response.formats) ? response.formats : []
|
||||||
|
if (converterFormats.length > 0 && !converterFormats.some((format) => format.id === targetFormat)) {
|
||||||
|
targetFormat = converterFormats[0].id
|
||||||
|
}
|
||||||
|
} catch (reason) {
|
||||||
|
error = reason instanceof Error ? reason.message : 'Unable to load converter formats.'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatFileSize(size: number) {
|
||||||
|
if (size < 1024) return size + ' B'
|
||||||
|
if (size < 1024 * 1024) return (size / 1024).toFixed(1) + ' KB'
|
||||||
|
if (size < 1024 * 1024 * 1024) return (size / (1024 * 1024)).toFixed(1) + ' MB'
|
||||||
|
return (size / (1024 * 1024 * 1024)).toFixed(1) + ' GB'
|
||||||
|
}
|
||||||
|
|
||||||
|
async function uploadSourceFile(file: File) {
|
||||||
|
sourceFile = file
|
||||||
|
sourcePath = ''
|
||||||
|
uploadingSource = true
|
||||||
|
try {
|
||||||
|
const form = new FormData()
|
||||||
|
form.append('file', file)
|
||||||
|
const response = await post<{
|
||||||
|
filename?: string
|
||||||
|
file?: { path?: string; filename?: string }
|
||||||
|
}>('/api/upload', form)
|
||||||
|
sourcePath = response.file?.path || response.filename || ''
|
||||||
|
if (!sourcePath) throw new Error('Upload completed without a usable file path.')
|
||||||
|
notify.success(file.name + ' uploaded and ready to convert.')
|
||||||
|
} catch (reason) {
|
||||||
|
notify.error(reason instanceof Error ? reason.message : 'Unable to upload the converter input.')
|
||||||
|
} finally {
|
||||||
|
uploadingSource = false
|
||||||
|
sourceFileDragging = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function handleSourceFileChange(event: Event) {
|
||||||
|
const input = event.currentTarget as HTMLInputElement
|
||||||
|
const file = input.files?.[0]
|
||||||
|
input.value = ''
|
||||||
|
if (file) void uploadSourceFile(file)
|
||||||
|
}
|
||||||
|
|
||||||
|
function handleSourceFileDragOver(event: DragEvent) {
|
||||||
|
event.preventDefault()
|
||||||
|
sourceFileDragging = true
|
||||||
|
}
|
||||||
|
|
||||||
|
function handleSourceFileDragLeave(event: DragEvent) {
|
||||||
|
const dropZone = event.currentTarget as HTMLElement
|
||||||
|
const nextTarget = event.relatedTarget as Node | null
|
||||||
|
if (!nextTarget || !dropZone.contains(nextTarget)) sourceFileDragging = false
|
||||||
|
}
|
||||||
|
|
||||||
|
function handleSourceFileDrop(event: DragEvent) {
|
||||||
|
event.preventDefault()
|
||||||
|
sourceFileDragging = false
|
||||||
|
const file = event.dataTransfer?.files?.[0]
|
||||||
|
if (file) void uploadSourceFile(file)
|
||||||
|
}
|
||||||
|
|
||||||
|
function clearSourceFile() {
|
||||||
|
sourceFile = null
|
||||||
|
sourcePath = ''
|
||||||
|
sourceFileInput?.focus()
|
||||||
|
}
|
||||||
|
|
||||||
|
async function startWorkflow() {
|
||||||
|
starting = true
|
||||||
|
try {
|
||||||
|
if (panel === 'generator') {
|
||||||
|
if (!workflowName || Object.keys(workflowGraph).length === 0) {
|
||||||
|
throw new Error('Select a valid generator workflow before starting.')
|
||||||
|
}
|
||||||
|
await post('/api/jobs/generator/start', {
|
||||||
|
workflow: workflowGraph,
|
||||||
|
workflowName,
|
||||||
|
...(prompt.trim() ? { promptText: prompt.trim() } : {}),
|
||||||
|
})
|
||||||
|
notify.success('Generator workflow queued.')
|
||||||
|
} else if (panel === 'downloader') {
|
||||||
|
if (!sourceUrl.trim()) throw new Error('Enter a source URL before starting a download.')
|
||||||
|
await post('/api/downloader/single', { url: sourceUrl.trim() })
|
||||||
|
notify.success('Downloader workflow queued.')
|
||||||
|
} else {
|
||||||
|
if (uploadingSource) throw new Error('Wait for the input upload to finish before starting a conversion.')
|
||||||
|
if (!sourcePath.trim()) throw new Error('Upload an input file before starting a conversion.')
|
||||||
|
await post('/api/converter/start', {
|
||||||
|
input: sourcePath.trim(),
|
||||||
|
targetFormat,
|
||||||
|
encoding: encodingProfile,
|
||||||
|
})
|
||||||
|
notify.success('Converter workflow queued.')
|
||||||
|
}
|
||||||
|
prompt = ''
|
||||||
|
sourceUrl = ''
|
||||||
|
sourcePath = ''
|
||||||
|
sourceFile = null
|
||||||
|
await loadJobs()
|
||||||
|
} catch (reason) {
|
||||||
|
notify.error(reason instanceof Error ? reason.message : 'Unable to start workflow.')
|
||||||
|
} finally {
|
||||||
|
starting = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function runSchedule(id: string) {
|
||||||
|
try {
|
||||||
|
await post(`/api/schedules/${encodeURIComponent(id)}/run`)
|
||||||
|
notify.success('Schedule queued.')
|
||||||
|
await loadJobs()
|
||||||
|
} catch (reason) {
|
||||||
|
notify.error(reason instanceof Error ? reason.message : 'Unable to run schedule.')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
onMount(() => {
|
||||||
|
const timer = window.setInterval(() => void loadJobs(), 10_000)
|
||||||
|
return () => window.clearInterval(timer)
|
||||||
|
})
|
||||||
|
|
||||||
|
$effect(() => {
|
||||||
|
const currentPanel = panel
|
||||||
|
void loadJobs()
|
||||||
|
if (currentPanel === 'generator') void loadGeneratorOptions()
|
||||||
|
if (currentPanel === 'converter') void loadConverterOptions()
|
||||||
|
})
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<div class="space-y-4">
|
||||||
|
<div class="grid gap-4 sm:grid-cols-3">
|
||||||
|
<Metric
|
||||||
|
label="Active queue"
|
||||||
|
value={queue.length}
|
||||||
|
detail="Waiting or running"
|
||||||
|
tone={queue.length ? 'warning' : 'default'}
|
||||||
|
/><Metric label="Recent jobs" value={jobs.length} detail="Retained workflow history" /><Metric
|
||||||
|
label="Schedules"
|
||||||
|
value={schedules.length}
|
||||||
|
detail="Recurring automations"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{#if error}<div class="rounded-md border border-danger/30 bg-danger/10 px-4 py-3 text-sm text-danger">
|
||||||
|
{error}
|
||||||
|
</div>{/if}
|
||||||
|
|
||||||
|
{#if panel === 'schedules'}
|
||||||
|
<Card class="space-y-5"
|
||||||
|
><SectionTitle
|
||||||
|
title="Schedules"
|
||||||
|
description="Keep recurring downloader and converter jobs visible and controllable."
|
||||||
|
/>
|
||||||
|
{#if schedules.length === 0}<EmptyState
|
||||||
|
title="No schedules configured"
|
||||||
|
message="Create schedules from the service API or use the builder in the next iteration."
|
||||||
|
/>{:else}<div class="divide-y divide-border">
|
||||||
|
{#each schedules as schedule (schedule.id)}<div
|
||||||
|
class="flex flex-col gap-3 py-3 sm:flex-row sm:items-center sm:justify-between"
|
||||||
|
>
|
||||||
|
<div>
|
||||||
|
<div class="flex items-center gap-2">
|
||||||
|
<p class="text-sm font-medium text-fg">{schedule.name || schedule.tool || 'Workflow schedule'}</p>
|
||||||
|
<Badge tone={schedule.enabled === false ? 'neutral' : 'success'}
|
||||||
|
>{schedule.enabled === false ? 'Paused' : 'Enabled'}</Badge
|
||||||
|
>
|
||||||
|
</div>
|
||||||
|
<p class="mt-1 text-xs text-muted-fg">
|
||||||
|
{schedule.tool || 'tool'} · every {schedule.intervalMinutes || '—'} minutes · {schedule.lastStatus ||
|
||||||
|
'never run'}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
{#if schedule.id}<Button
|
||||||
|
variant="secondary"
|
||||||
|
size="sm"
|
||||||
|
onclick={() => void runSchedule(String(schedule.id))}>Run now <ArrowRight class="size-4" /></Button
|
||||||
|
>{/if}
|
||||||
|
</div>{/each}
|
||||||
|
</div>{/if}
|
||||||
|
</Card>
|
||||||
|
{:else if panel === 'library'}
|
||||||
|
<Card class="space-y-5"
|
||||||
|
><SectionTitle
|
||||||
|
title="Generated media"
|
||||||
|
description="Browse the output produced by generator and converter workflows."
|
||||||
|
/><EmptyState
|
||||||
|
title="Library view"
|
||||||
|
message="The unified library API remains available at /library/unified; use it to inspect generated outputs once a workflow has completed."
|
||||||
|
/></Card
|
||||||
|
>
|
||||||
|
{:else}
|
||||||
|
<div class="grid gap-4 xl:grid-cols-[minmax(0,1fr)_360px]">
|
||||||
|
<Card class="space-y-5"
|
||||||
|
><div class="flex items-start gap-3">
|
||||||
|
<div class="flex size-10 items-center justify-center rounded-lg bg-primary/15 text-primary">
|
||||||
|
{#if panel === 'downloader'}<CloudDownload class="size-5" />{:else if panel === 'converter'}<Film
|
||||||
|
class="size-5"
|
||||||
|
/>{:else}<WandSparkles class="size-5" />{/if}
|
||||||
|
</div>
|
||||||
|
<SectionTitle
|
||||||
|
title={`${workflowTitle} workspace`}
|
||||||
|
description={panel === 'generator'
|
||||||
|
? 'Choose a ComfyUI workflow and optionally provide a text prompt.'
|
||||||
|
: panel === 'downloader'
|
||||||
|
? 'Queue a download from a public media URL.'
|
||||||
|
: 'Choose an input file, output format, and encoding profile.'}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
{#if panel === 'generator'}
|
||||||
|
<label class="block text-xs font-medium text-muted-fg"
|
||||||
|
>Workflow<select
|
||||||
|
bind:value={workflowName}
|
||||||
|
onchange={(event) => void loadWorkflowGraph((event.currentTarget as HTMLSelectElement).value)}
|
||||||
|
class="mt-1 h-10 w-full rounded-md border border-border bg-bg px-3 text-sm text-fg outline-none focus-visible:ring-2 focus-visible:ring-ring"
|
||||||
|
>
|
||||||
|
{#if workflowNames.length === 0}
|
||||||
|
<option value="">No workflows available</option>
|
||||||
|
{:else}
|
||||||
|
{#each workflowNames as name (name)}<option value={name}>{name}</option>{/each}
|
||||||
|
{/if}
|
||||||
|
</select></label
|
||||||
|
><label class="block text-xs font-medium text-muted-fg"
|
||||||
|
>Prompt (optional)<textarea
|
||||||
|
bind:value={prompt}
|
||||||
|
rows="5"
|
||||||
|
placeholder="Text prompt to apply to the selected workflow"
|
||||||
|
class="mt-1 w-full resize-y rounded-md border border-border bg-bg px-3 py-2 text-sm text-fg outline-none focus-visible:ring-2 focus-visible:ring-ring"
|
||||||
|
></textarea></label
|
||||||
|
>
|
||||||
|
{:else if panel === 'downloader'}
|
||||||
|
<label class="block text-xs font-medium text-muted-fg"
|
||||||
|
>Source URL<input
|
||||||
|
bind:value={sourceUrl}
|
||||||
|
type="url"
|
||||||
|
placeholder="https://example.com/media"
|
||||||
|
class="mt-1 h-10 w-full rounded-md border border-border bg-bg px-3 py-2 text-sm text-fg outline-none focus-visible:ring-2 focus-visible:ring-ring"
|
||||||
|
/></label
|
||||||
|
>
|
||||||
|
{:else}
|
||||||
|
<div class="grid gap-4 sm:grid-cols-2">
|
||||||
|
<div class="space-y-2">
|
||||||
|
<span class="block text-xs font-medium text-muted-fg">Input file</span>
|
||||||
|
<label
|
||||||
|
for="converter-source-file"
|
||||||
|
class={sourceFileDragging
|
||||||
|
? 'group flex min-h-36 cursor-pointer flex-col items-center justify-center rounded-md border border-dashed border-primary bg-primary/10 px-4 py-6 text-center transition-colors'
|
||||||
|
: 'group flex min-h-36 cursor-pointer flex-col items-center justify-center rounded-md border border-dashed border-border bg-bg px-4 py-6 text-center transition-colors hover:border-primary/60 hover:bg-surface-hover'}
|
||||||
|
ondragover={handleSourceFileDragOver}
|
||||||
|
ondragleave={handleSourceFileDragLeave}
|
||||||
|
ondrop={handleSourceFileDrop}
|
||||||
|
>
|
||||||
|
<input
|
||||||
|
id="converter-source-file"
|
||||||
|
bind:this={sourceFileInput}
|
||||||
|
type="file"
|
||||||
|
accept="audio/*,video/*"
|
||||||
|
class="sr-only"
|
||||||
|
onchange={handleSourceFileChange}
|
||||||
|
disabled={uploadingSource}
|
||||||
|
/>
|
||||||
|
{#if uploadingSource}
|
||||||
|
<Activity class="mb-2 size-6 animate-spin text-primary" />
|
||||||
|
<span class="text-sm font-medium text-fg">Uploading {sourceFile?.name || 'file'}…</span>
|
||||||
|
<span class="mt-1 text-xs text-muted-fg">Keep this page open while the upload finishes.</span>
|
||||||
|
{:else if sourceFile && sourcePath}
|
||||||
|
<CheckCircle2 class="mb-2 size-6 text-success" />
|
||||||
|
<span class="max-w-full truncate text-sm font-medium text-fg">{sourceFile.name}</span>
|
||||||
|
<span class="mt-1 text-xs text-muted-fg">{formatFileSize(sourceFile.size)} · Ready to convert</span>
|
||||||
|
<span class="mt-2 text-xs text-primary">Drop another file or click to replace</span>
|
||||||
|
{:else if sourceFile}
|
||||||
|
<Upload class="mb-2 size-6 text-danger" />
|
||||||
|
<span class="max-w-full truncate text-sm font-medium text-fg">{sourceFile.name}</span>
|
||||||
|
<span class="mt-1 text-xs text-danger">Upload failed. Drop another file or click to retry.</span>
|
||||||
|
{:else}
|
||||||
|
<Upload class="mb-2 size-6 text-primary" />
|
||||||
|
<span class="text-sm font-medium text-fg">Drop a media file here</span>
|
||||||
|
<span class="mt-1 text-xs text-muted-fg">or click to browse · audio and video files</span>
|
||||||
|
{/if}
|
||||||
|
</label>
|
||||||
|
{#if sourceFile && !uploadingSource}
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
class="inline-flex items-center gap-1 text-xs text-muted-fg hover:text-fg"
|
||||||
|
onclick={clearSourceFile}
|
||||||
|
>
|
||||||
|
<X class="size-3.5" /> Clear selected file
|
||||||
|
</button>
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
|
<label class="block text-xs font-medium text-muted-fg"
|
||||||
|
>Target format<select
|
||||||
|
bind:value={targetFormat}
|
||||||
|
class="mt-1 h-10 w-full rounded-md border border-border bg-bg px-3 text-sm text-fg outline-none focus-visible:ring-2 focus-visible:ring-ring"
|
||||||
|
>
|
||||||
|
{#if converterFormats.length === 0}
|
||||||
|
<option value="mp4">MP4</option>
|
||||||
|
{:else}
|
||||||
|
{#each converterFormats as format (format.id)}<option value={format.id}>{format.label}</option>{/each}
|
||||||
|
{/if}
|
||||||
|
</select></label
|
||||||
|
>
|
||||||
|
</div>
|
||||||
|
<label class="block text-xs font-medium text-muted-fg"
|
||||||
|
>Encoding profile<select
|
||||||
|
bind:value={encodingProfile}
|
||||||
|
class="mt-1 h-10 w-full rounded-md border border-border bg-bg px-3 py-2 text-sm text-fg outline-none focus-visible:ring-2 focus-visible:ring-ring"
|
||||||
|
>
|
||||||
|
<option value="fast">Fast</option>
|
||||||
|
<option value="balanced">Balanced</option>
|
||||||
|
<option value="quality">High quality</option>
|
||||||
|
</select></label
|
||||||
|
>
|
||||||
|
{/if}
|
||||||
|
<div class="flex items-center justify-between gap-3 border-t border-border pt-4">
|
||||||
|
<p class="text-xs text-muted-fg">Jobs keep running in the service queue after you leave this page.</p>
|
||||||
|
<Button disabled={starting || uploadingSource} onclick={() => void startWorkflow()}
|
||||||
|
><Activity class="size-4" />{starting ? 'Queueing…' : `Start ${panel}`}</Button
|
||||||
|
>
|
||||||
|
</div>
|
||||||
|
</Card>
|
||||||
|
<Card class="space-y-4"
|
||||||
|
><SectionTitle title="Queue activity" description="Recent jobs update automatically." />{#if loading}<p
|
||||||
|
class="text-sm text-muted-fg"
|
||||||
|
>
|
||||||
|
Loading queue…
|
||||||
|
</p>{:else if jobs.length === 0}<EmptyState
|
||||||
|
title="Queue is quiet"
|
||||||
|
message="Start a workflow to see progress here."
|
||||||
|
/>{:else}<div class="space-y-2">
|
||||||
|
{#each jobs.slice(0, 8) as job (job.id)}<div class="rounded-md border border-border bg-bg p-3">
|
||||||
|
<div class="flex items-center justify-between gap-2">
|
||||||
|
<p class="truncate text-sm font-medium text-fg">{job.tool || 'workflow'}</p>
|
||||||
|
<Badge
|
||||||
|
tone={job.status === 'completed' || job.status === 'complete'
|
||||||
|
? 'success'
|
||||||
|
: job.status === 'error'
|
||||||
|
? 'danger'
|
||||||
|
: 'primary'}>{job.status || 'queued'}</Badge
|
||||||
|
>
|
||||||
|
</div>
|
||||||
|
<p class="mt-1 truncate text-xs text-muted-fg">{job.id || 'job id unavailable'}</p>
|
||||||
|
</div>{/each}
|
||||||
|
</div>{/if}</Card
|
||||||
|
>
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,631 @@
|
|||||||
|
<script lang="ts">
|
||||||
|
import { pushState, replaceState } from '$app/navigation'
|
||||||
|
import { page as appPage } from '$app/state'
|
||||||
|
import { ChevronDown, ChevronUp, Film, Music2, Play, Search, SlidersHorizontal, X } from '@lucide/svelte'
|
||||||
|
import { onMount } from 'svelte'
|
||||||
|
import { SvelteURLSearchParams } from 'svelte/reactivity'
|
||||||
|
import { get } from '$lib/api'
|
||||||
|
import EmptyState from '$lib/components/EmptyState.svelte'
|
||||||
|
import Button from '$lib/components/ui/button.svelte'
|
||||||
|
import Card from '$lib/components/ui/card.svelte'
|
||||||
|
import Badge from '$lib/components/ui/badge.svelte'
|
||||||
|
|
||||||
|
interface MediaItem {
|
||||||
|
id: string
|
||||||
|
numericId?: number
|
||||||
|
url?: string
|
||||||
|
thumbnail?: string
|
||||||
|
filename: string
|
||||||
|
title: string | null
|
||||||
|
relPath?: string
|
||||||
|
mediaType: 'video' | 'audio' | 'image' | string
|
||||||
|
hasFunscript?: boolean
|
||||||
|
isVr?: boolean
|
||||||
|
width?: number | null
|
||||||
|
height?: number | null
|
||||||
|
durationMs?: number | null
|
||||||
|
sizeBytes?: string | null
|
||||||
|
}
|
||||||
|
|
||||||
|
let { panel = 'library' }: { panel?: string } = $props()
|
||||||
|
let items = $state<MediaItem[]>([])
|
||||||
|
let loading = $state(true)
|
||||||
|
let error = $state('')
|
||||||
|
let query = $state('')
|
||||||
|
let submittedQuery = $state('')
|
||||||
|
let selected = $state<MediaItem | null>(null)
|
||||||
|
let currentPage = $state(1)
|
||||||
|
let pageUrlSyncReady = $state(false)
|
||||||
|
let total = $state(0)
|
||||||
|
const pageSize = 24
|
||||||
|
const maxLengthSeconds = 3600
|
||||||
|
const maxSpeed = 1000
|
||||||
|
|
||||||
|
const resolutionOptions = [
|
||||||
|
{ value: '', label: 'Any resolution' },
|
||||||
|
{ value: '480', label: '480p or higher' },
|
||||||
|
{ value: '720', label: '720p or higher' },
|
||||||
|
{ value: '1080', label: '1080p or higher' },
|
||||||
|
{ value: '1440', label: '1440p or higher' },
|
||||||
|
{ value: '2160', label: '2160p or higher' },
|
||||||
|
{ value: '4320', label: '4320p or higher' },
|
||||||
|
]
|
||||||
|
|
||||||
|
let resolutionMin = $state('')
|
||||||
|
let vrFilter = $state('all')
|
||||||
|
let funscriptFilter = $state('all')
|
||||||
|
let lengthMin = $state(0)
|
||||||
|
let lengthMax = $state(maxLengthSeconds)
|
||||||
|
let speedMin = $state(0)
|
||||||
|
let speedMax = $state(maxSpeed)
|
||||||
|
let filtersOpen = $state(false)
|
||||||
|
|
||||||
|
function formatBytes(value: string | null | undefined) {
|
||||||
|
const bytes = Number(value)
|
||||||
|
if (!Number.isFinite(bytes) || bytes <= 0) return '—'
|
||||||
|
const units = ['B', 'KB', 'MB', 'GB', 'TB']
|
||||||
|
const index = Math.min(units.length - 1, Math.floor(Math.log(bytes) / Math.log(1024)))
|
||||||
|
return `${(bytes / 1024 ** index).toFixed(index ? 1 : 0)} ${units[index]}`
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatDuration(value: number | null | undefined) {
|
||||||
|
if (!value || value <= 0) return '—'
|
||||||
|
const seconds = Math.floor(value / 1000)
|
||||||
|
const minutes = Math.floor(seconds / 60)
|
||||||
|
const remainder = seconds % 60
|
||||||
|
return minutes ? `${minutes}m ${String(remainder).padStart(2, '0')}s` : `${remainder}s`
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatLengthRange(minimum: number, maximum: number) {
|
||||||
|
if (minimum <= 0 && maximum >= maxLengthSeconds) return 'Any length'
|
||||||
|
if (minimum <= 0) return `Up to ${formatDuration(maximum * 1000)}`
|
||||||
|
if (maximum >= maxLengthSeconds) return `${formatDuration(minimum * 1000)} or longer`
|
||||||
|
return `${formatDuration(minimum * 1000)} – ${formatDuration(maximum * 1000)}`
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatSpeedRange(minimum: number, maximum: number) {
|
||||||
|
if (minimum <= 0 && maximum >= maxSpeed) return 'Any speed'
|
||||||
|
if (minimum <= 0) return `Up to ${maximum}%/s`
|
||||||
|
if (maximum >= maxSpeed) return `${minimum}%/s or faster`
|
||||||
|
return `${minimum}–${maximum}%/s`
|
||||||
|
}
|
||||||
|
|
||||||
|
function updateLengthMinimum(event: Event) {
|
||||||
|
const value = Number((event.currentTarget as HTMLInputElement).value)
|
||||||
|
lengthMin = Math.min(Math.max(value, 0), lengthMax)
|
||||||
|
}
|
||||||
|
|
||||||
|
function updateLengthMaximum(event: Event) {
|
||||||
|
const value = Number((event.currentTarget as HTMLInputElement).value)
|
||||||
|
lengthMax = Math.max(Math.min(value, maxLengthSeconds), lengthMin)
|
||||||
|
}
|
||||||
|
|
||||||
|
function updateSpeedMinimum(event: Event) {
|
||||||
|
const value = Number((event.currentTarget as HTMLInputElement).value)
|
||||||
|
speedMin = Math.min(Math.max(value, 0), speedMax)
|
||||||
|
}
|
||||||
|
|
||||||
|
function updateSpeedMaximum(event: Event) {
|
||||||
|
const value = Number((event.currentTarget as HTMLInputElement).value)
|
||||||
|
speedMax = Math.max(Math.min(value, maxSpeed), speedMin)
|
||||||
|
}
|
||||||
|
|
||||||
|
function rangePercent(value: number, maximum: number) {
|
||||||
|
return `${Math.min(100, Math.max(0, (value / maximum) * 100))}%`
|
||||||
|
}
|
||||||
|
|
||||||
|
function activeFilterCount() {
|
||||||
|
return [
|
||||||
|
resolutionMin !== '',
|
||||||
|
vrFilter !== 'all',
|
||||||
|
funscriptFilter !== 'all',
|
||||||
|
lengthMin > 0 || lengthMax < maxLengthSeconds,
|
||||||
|
speedMin > 0 || speedMax < maxSpeed,
|
||||||
|
].filter(Boolean).length
|
||||||
|
}
|
||||||
|
|
||||||
|
function thumbnail(item: MediaItem) {
|
||||||
|
return item.thumbnail || `/api/media/thumb?mediaKey=${encodeURIComponent(item.id)}`
|
||||||
|
}
|
||||||
|
|
||||||
|
function stream(item: MediaItem) {
|
||||||
|
return item.url || `/api/media/stream?mediaKey=${encodeURIComponent(item.id)}`
|
||||||
|
}
|
||||||
|
|
||||||
|
function openMedia(item: MediaItem) {
|
||||||
|
if (item.mediaType === 'video') {
|
||||||
|
window.location.assign(`/video/${encodeURIComponent(String(item.numericId ?? item.id))}`)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
selected = item
|
||||||
|
}
|
||||||
|
|
||||||
|
function pageFromUrl() {
|
||||||
|
const value = Number.parseInt(appPage.url.searchParams.get('page') || '1', 10)
|
||||||
|
return Number.isFinite(value) && value > 0 ? value : 1
|
||||||
|
}
|
||||||
|
|
||||||
|
function updatePageUrl(nextPage: number, historyMode: 'push' | 'replace' = 'push') {
|
||||||
|
const searchParams = new SvelteURLSearchParams(appPage.url.searchParams)
|
||||||
|
searchParams.set('page', String(nextPage))
|
||||||
|
const query = searchParams.toString()
|
||||||
|
const url = `${appPage.url.pathname}${query ? `?${query}` : ''}${appPage.url.hash}`
|
||||||
|
if (historyMode === 'push') void pushState(url, {})
|
||||||
|
else void replaceState(url, {})
|
||||||
|
}
|
||||||
|
|
||||||
|
function goToPage(nextPage: number) {
|
||||||
|
const target = Math.max(1, nextPage)
|
||||||
|
if (target === currentPage) return
|
||||||
|
currentPage = target
|
||||||
|
updatePageUrl(target)
|
||||||
|
void loadMedia()
|
||||||
|
}
|
||||||
|
|
||||||
|
async function loadMedia() {
|
||||||
|
loading = true
|
||||||
|
error = ''
|
||||||
|
try {
|
||||||
|
const params: Record<string, string> = {
|
||||||
|
page: String(currentPage),
|
||||||
|
pageSize: String(pageSize),
|
||||||
|
sortBy: 'modified',
|
||||||
|
sortDir: 'desc',
|
||||||
|
}
|
||||||
|
if (submittedQuery) params.q = submittedQuery
|
||||||
|
if (resolutionMin) params.minHeight = resolutionMin
|
||||||
|
if (vrFilter === 'vr') params.isVr = '1'
|
||||||
|
if (vrFilter === 'nonvr') params.isVr = '0'
|
||||||
|
if (funscriptFilter === 'with') params.hasFunscript = '1'
|
||||||
|
if (funscriptFilter === 'without') params.hasFunscript = '0'
|
||||||
|
if (lengthMin > 0) params.minDurationSec = String(lengthMin)
|
||||||
|
if (lengthMax < maxLengthSeconds) params.maxDurationSec = String(lengthMax)
|
||||||
|
if (speedMin > 0) params.minSpeed = String(speedMin)
|
||||||
|
if (speedMax < maxSpeed) params.maxSpeed = String(speedMax)
|
||||||
|
|
||||||
|
const queryString = Object.entries(params)
|
||||||
|
.map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(value)}`)
|
||||||
|
.join('&')
|
||||||
|
const response = await get<{ items?: MediaItem[]; total?: number }>(`/api/media?${queryString}`)
|
||||||
|
items = Array.isArray(response.items) ? response.items : []
|
||||||
|
total = Number(response.total || 0)
|
||||||
|
} catch (reason) {
|
||||||
|
error = reason instanceof Error ? reason.message : 'Unable to load the media library.'
|
||||||
|
} finally {
|
||||||
|
loading = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function submitSearch() {
|
||||||
|
currentPage = 1
|
||||||
|
updatePageUrl(1, 'replace')
|
||||||
|
submittedQuery = query.trim()
|
||||||
|
void loadMedia()
|
||||||
|
}
|
||||||
|
|
||||||
|
function applyFilters() {
|
||||||
|
currentPage = 1
|
||||||
|
updatePageUrl(1, 'replace')
|
||||||
|
void loadMedia()
|
||||||
|
}
|
||||||
|
|
||||||
|
function clearFilters() {
|
||||||
|
resolutionMin = ''
|
||||||
|
vrFilter = 'all'
|
||||||
|
funscriptFilter = 'all'
|
||||||
|
lengthMin = 0
|
||||||
|
lengthMax = maxLengthSeconds
|
||||||
|
speedMin = 0
|
||||||
|
speedMax = maxSpeed
|
||||||
|
applyFilters()
|
||||||
|
}
|
||||||
|
|
||||||
|
onMount(() => {
|
||||||
|
if (panel !== 'library') return
|
||||||
|
currentPage = pageFromUrl()
|
||||||
|
updatePageUrl(currentPage, 'replace')
|
||||||
|
pageUrlSyncReady = true
|
||||||
|
void loadMedia()
|
||||||
|
})
|
||||||
|
|
||||||
|
$effect(() => {
|
||||||
|
if (panel !== 'library') return
|
||||||
|
const urlPage = pageFromUrl()
|
||||||
|
if (pageUrlSyncReady && urlPage !== currentPage) {
|
||||||
|
currentPage = urlPage
|
||||||
|
void loadMedia()
|
||||||
|
}
|
||||||
|
})
|
||||||
|
</script>
|
||||||
|
|
||||||
|
{#if panel === 'playlists'}
|
||||||
|
<div>
|
||||||
|
<EmptyState
|
||||||
|
title="Playlists are ready for your favorites"
|
||||||
|
message="Create and manage playlists from the player. The shared media service remains available while this workspace grows with your collection."
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
{:else}
|
||||||
|
<div class="space-y-4">
|
||||||
|
<Card class="flex flex-col gap-3 sm:flex-row sm:items-center">
|
||||||
|
<form
|
||||||
|
class="flex min-w-0 flex-1 gap-2"
|
||||||
|
onsubmit={(event) => {
|
||||||
|
event.preventDefault()
|
||||||
|
submitSearch()
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<div class="relative min-w-0 flex-1">
|
||||||
|
<Search class="pointer-events-none absolute left-3 top-1/2 size-4 -translate-y-1/2 text-muted-fg" /><input
|
||||||
|
bind:value={query}
|
||||||
|
placeholder="Search title or filename"
|
||||||
|
class="h-10 w-full rounded-md border border-border bg-bg pl-9 pr-3 text-sm text-fg outline-none focus-visible:ring-2 focus-visible:ring-ring"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<Button type="submit">Search</Button>
|
||||||
|
</form>
|
||||||
|
<div class="flex items-center gap-2 text-xs text-muted-fg">
|
||||||
|
<span>{total.toLocaleString()} items</span><span class="rounded-full bg-surface-hover px-2 py-1"
|
||||||
|
>Page {currentPage}</span
|
||||||
|
>
|
||||||
|
</div>
|
||||||
|
</Card>
|
||||||
|
|
||||||
|
{#if panel === 'library'}
|
||||||
|
<Card class="space-y-4">
|
||||||
|
<div class="flex flex-wrap items-center justify-between gap-3">
|
||||||
|
<div class="flex min-w-0 items-start gap-3">
|
||||||
|
<SlidersHorizontal class="mt-0.5 size-4 shrink-0 text-primary" />
|
||||||
|
<div class="min-w-0">
|
||||||
|
<div class="flex flex-wrap items-center gap-2">
|
||||||
|
<p class="text-sm font-medium text-fg">Filters</p>
|
||||||
|
{#if activeFilterCount() > 0}<Badge tone="primary">{activeFilterCount()} active</Badge>{/if}
|
||||||
|
</div>
|
||||||
|
<p class="mt-1 text-xs text-muted-fg">
|
||||||
|
{activeFilterCount() > 0
|
||||||
|
? 'Filters are narrowing the library results.'
|
||||||
|
: 'Narrow the library by resolution, VR, funscript, speed, or length.'}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="flex items-center gap-2">
|
||||||
|
{#if filtersOpen}<Button variant="ghost" size="sm" onclick={clearFilters}>Clear filters</Button>{/if}
|
||||||
|
<Button
|
||||||
|
variant="secondary"
|
||||||
|
size="sm"
|
||||||
|
aria-expanded={filtersOpen}
|
||||||
|
aria-controls="library-filters"
|
||||||
|
onclick={() => (filtersOpen = !filtersOpen)}
|
||||||
|
>
|
||||||
|
{#if filtersOpen}<ChevronUp class="size-4" />Hide filters{:else}<ChevronDown class="size-4" />Show filters{/if}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{#if filtersOpen}
|
||||||
|
<div id="library-filters" class="grid gap-4 border-t border-border pt-4 sm:grid-cols-2 lg:grid-cols-3">
|
||||||
|
<label class="grid gap-1.5 text-xs font-medium text-muted-fg">
|
||||||
|
Resolution
|
||||||
|
<select
|
||||||
|
bind:value={resolutionMin}
|
||||||
|
onchange={applyFilters}
|
||||||
|
class="h-9 rounded-md border border-border bg-bg px-3 text-sm font-normal text-fg outline-none focus-visible:ring-2 focus-visible:ring-ring"
|
||||||
|
>
|
||||||
|
{#each resolutionOptions as option (option.value)}
|
||||||
|
<option value={option.value}>{option.label}</option>
|
||||||
|
{/each}
|
||||||
|
</select>
|
||||||
|
</label>
|
||||||
|
|
||||||
|
<label class="grid gap-1.5 text-xs font-medium text-muted-fg">
|
||||||
|
VR
|
||||||
|
<select
|
||||||
|
bind:value={vrFilter}
|
||||||
|
onchange={applyFilters}
|
||||||
|
class="h-9 rounded-md border border-border bg-bg px-3 text-sm font-normal text-fg outline-none focus-visible:ring-2 focus-visible:ring-ring"
|
||||||
|
>
|
||||||
|
<option value="all">VR and non-VR</option>
|
||||||
|
<option value="vr">VR only</option>
|
||||||
|
<option value="nonvr">Non-VR only</option>
|
||||||
|
</select>
|
||||||
|
</label>
|
||||||
|
|
||||||
|
<label class="grid gap-1.5 text-xs font-medium text-muted-fg">
|
||||||
|
Funscript
|
||||||
|
<select
|
||||||
|
bind:value={funscriptFilter}
|
||||||
|
onchange={applyFilters}
|
||||||
|
class="h-9 rounded-md border border-border bg-bg px-3 text-sm font-normal text-fg outline-none focus-visible:ring-2 focus-visible:ring-ring"
|
||||||
|
>
|
||||||
|
<option value="all">With and without funscript</option>
|
||||||
|
<option value="with">With funscript</option>
|
||||||
|
<option value="without">Without funscript</option>
|
||||||
|
</select>
|
||||||
|
</label>
|
||||||
|
|
||||||
|
<fieldset class="rounded-md border border-border bg-bg p-3 sm:col-span-2">
|
||||||
|
<div class="flex items-center justify-between gap-3">
|
||||||
|
<legend class="text-xs font-medium text-muted-fg">Length</legend>
|
||||||
|
<span class="text-xs text-fg">{formatLengthRange(lengthMin, lengthMax)}</span>
|
||||||
|
</div>
|
||||||
|
<div class="mt-3 dual-range">
|
||||||
|
<div class="dual-range__track"></div>
|
||||||
|
<div
|
||||||
|
class="dual-range__fill"
|
||||||
|
style={`left: ${rangePercent(lengthMin, maxLengthSeconds)}; width: ${rangePercent(lengthMax - lengthMin, maxLengthSeconds)}`}
|
||||||
|
></div>
|
||||||
|
<input
|
||||||
|
class="dual-range__input"
|
||||||
|
type="range"
|
||||||
|
min="0"
|
||||||
|
max={maxLengthSeconds}
|
||||||
|
step="30"
|
||||||
|
value={lengthMin}
|
||||||
|
aria-label="Minimum length"
|
||||||
|
style="z-index: 2"
|
||||||
|
oninput={updateLengthMinimum}
|
||||||
|
onchange={applyFilters}
|
||||||
|
/>
|
||||||
|
<input
|
||||||
|
class="dual-range__input"
|
||||||
|
type="range"
|
||||||
|
min="0"
|
||||||
|
max={maxLengthSeconds}
|
||||||
|
step="30"
|
||||||
|
value={lengthMax}
|
||||||
|
aria-label="Maximum length"
|
||||||
|
style="z-index: 3"
|
||||||
|
oninput={updateLengthMaximum}
|
||||||
|
onchange={applyFilters}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div class="mt-1 flex justify-between text-[11px] text-muted-fg">
|
||||||
|
<span>0s</span><span>{formatDuration(maxLengthSeconds * 1000)}+</span>
|
||||||
|
</div>
|
||||||
|
</fieldset>
|
||||||
|
|
||||||
|
<fieldset class="rounded-md border border-border bg-bg p-3 sm:col-span-2">
|
||||||
|
<div class="flex items-center justify-between gap-3">
|
||||||
|
<legend class="text-xs font-medium text-muted-fg">Speed</legend>
|
||||||
|
<span class="text-xs text-fg">{formatSpeedRange(speedMin, speedMax)}</span>
|
||||||
|
</div>
|
||||||
|
<div class="mt-3 dual-range">
|
||||||
|
<div class="dual-range__track"></div>
|
||||||
|
<div
|
||||||
|
class="dual-range__fill"
|
||||||
|
style={`left: ${rangePercent(speedMin, maxSpeed)}; width: ${rangePercent(speedMax - speedMin, maxSpeed)}`}
|
||||||
|
></div>
|
||||||
|
<input
|
||||||
|
class="dual-range__input"
|
||||||
|
type="range"
|
||||||
|
min="0"
|
||||||
|
max={maxSpeed}
|
||||||
|
step="5"
|
||||||
|
value={speedMin}
|
||||||
|
aria-label="Minimum speed"
|
||||||
|
style="z-index: 2"
|
||||||
|
oninput={updateSpeedMinimum}
|
||||||
|
onchange={applyFilters}
|
||||||
|
/>
|
||||||
|
<input
|
||||||
|
class="dual-range__input"
|
||||||
|
type="range"
|
||||||
|
min="0"
|
||||||
|
max={maxSpeed}
|
||||||
|
step="5"
|
||||||
|
value={speedMax}
|
||||||
|
aria-label="Maximum speed"
|
||||||
|
style="z-index: 3"
|
||||||
|
oninput={updateSpeedMaximum}
|
||||||
|
onchange={applyFilters}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div class="mt-1 flex justify-between text-[11px] text-muted-fg">
|
||||||
|
<span>0%/s</span><span>{maxSpeed}%/s+</span>
|
||||||
|
</div>
|
||||||
|
</fieldset>
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
|
</Card>
|
||||||
|
{/if}
|
||||||
|
|
||||||
|
{#if error}<div class="rounded-md border border-danger/30 bg-danger/10 px-4 py-3 text-sm text-danger">
|
||||||
|
{error}
|
||||||
|
</div>{/if}
|
||||||
|
{#if loading}
|
||||||
|
<div class="grid gap-4 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4">
|
||||||
|
{#each Array(8) as _, index (index)}<div
|
||||||
|
class="media-shimmer h-64 rounded-lg border border-border"
|
||||||
|
></div>{/each}
|
||||||
|
</div>
|
||||||
|
{:else if items.length === 0}
|
||||||
|
<EmptyState
|
||||||
|
title="No media found"
|
||||||
|
message={submittedQuery
|
||||||
|
? 'Try a different search phrase.'
|
||||||
|
: 'Media will appear here after the collection has been indexed.'}
|
||||||
|
/>
|
||||||
|
{:else}
|
||||||
|
<div class="grid gap-4 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4">
|
||||||
|
{#each items as item (item.id)}
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
class="group overflow-hidden rounded-lg border border-border bg-surface text-left shadow-sm transition hover:-translate-y-0.5 hover:border-primary/60 hover:shadow-md"
|
||||||
|
onclick={() => openMedia(item)}
|
||||||
|
>
|
||||||
|
<div class="relative aspect-video overflow-hidden bg-bg">
|
||||||
|
{#if item.mediaType === 'image'}<img
|
||||||
|
src={thumbnail(item)}
|
||||||
|
alt={item.title || item.filename}
|
||||||
|
loading="lazy"
|
||||||
|
class="h-full w-full object-cover transition duration-300 group-hover:scale-105"
|
||||||
|
/>{:else}<div class="flex h-full items-center justify-center text-muted-fg">
|
||||||
|
{#if item.mediaType === 'audio'}<Music2 class="size-10" />{:else}<Film class="size-10" />{/if}
|
||||||
|
</div>{/if}
|
||||||
|
<span class="absolute left-2 top-2"><Badge tone="neutral">{item.mediaType}</Badge></span>
|
||||||
|
{#if item.isVr}<span class="absolute right-2 top-2"><Badge tone="primary">VR</Badge></span>{/if}
|
||||||
|
<span class="absolute bottom-2 right-2 rounded bg-black/70 px-1.5 py-0.5 text-[11px] text-white"
|
||||||
|
>{formatDuration(item.durationMs)}</span
|
||||||
|
>
|
||||||
|
</div>
|
||||||
|
<div class="p-3">
|
||||||
|
<p class="truncate text-sm font-medium text-fg">{item.title || item.filename}</p>
|
||||||
|
<div class="mt-2 flex items-center justify-between gap-2 text-xs text-muted-fg">
|
||||||
|
<span class="truncate">{item.filename}</span><span class="shrink-0">{formatBytes(item.sizeBytes)}</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</button>
|
||||||
|
{/each}
|
||||||
|
</div>
|
||||||
|
<div class="flex items-center justify-between">
|
||||||
|
<p class="text-xs text-muted-fg">Showing {items.length} of {total.toLocaleString()}</p>
|
||||||
|
<div class="flex gap-2">
|
||||||
|
<Button
|
||||||
|
variant="secondary"
|
||||||
|
size="sm"
|
||||||
|
disabled={currentPage <= 1 || loading}
|
||||||
|
onclick={() => goToPage(currentPage - 1)}>Previous</Button
|
||||||
|
><Button
|
||||||
|
variant="secondary"
|
||||||
|
size="sm"
|
||||||
|
disabled={currentPage * pageSize >= total || loading}
|
||||||
|
onclick={() => goToPage(currentPage + 1)}>Next</Button
|
||||||
|
>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
|
|
||||||
|
{#if selected}
|
||||||
|
<div
|
||||||
|
class="fixed inset-0 z-50 flex items-center justify-center bg-black/80 p-4"
|
||||||
|
role="presentation"
|
||||||
|
onclick={(event) => event.target === event.currentTarget && (selected = null)}
|
||||||
|
>
|
||||||
|
<div
|
||||||
|
class="relative flex max-h-[calc(100dvh-2rem)] w-full max-w-5xl flex-col overflow-hidden rounded-xl border border-border bg-bg shadow-2xl"
|
||||||
|
role="dialog"
|
||||||
|
aria-modal="true"
|
||||||
|
aria-label={selected.title || selected.filename}
|
||||||
|
tabindex="-1"
|
||||||
|
>
|
||||||
|
<Button
|
||||||
|
variant="ghost"
|
||||||
|
size="icon"
|
||||||
|
class="absolute right-3 top-3 z-10 bg-black/40 text-white hover:bg-black/60"
|
||||||
|
aria-label="Close player"
|
||||||
|
onclick={() => (selected = null)}><X class="size-5" /></Button
|
||||||
|
>
|
||||||
|
<div class="flex min-h-0 flex-1 items-center justify-center bg-black p-2 sm:p-6">
|
||||||
|
{#if selected.mediaType === 'image'}<img
|
||||||
|
src={thumbnail(selected)}
|
||||||
|
alt={selected.title || selected.filename}
|
||||||
|
class="max-h-[70dvh] max-w-full object-contain"
|
||||||
|
/>{:else if selected.mediaType === 'audio'}<div
|
||||||
|
class="flex w-full max-w-xl flex-col items-center gap-6 p-8 text-white"
|
||||||
|
>
|
||||||
|
<Music2 class="size-16 text-primary" /><audio src={stream(selected)} controls autoplay class="w-full"
|
||||||
|
></audio>
|
||||||
|
</div>{:else}<video
|
||||||
|
src={stream(selected)}
|
||||||
|
controls
|
||||||
|
autoplay
|
||||||
|
playsinline
|
||||||
|
class="max-h-[70dvh] max-w-full object-contain"
|
||||||
|
><track kind="captions" srclang="en" label="Captions" src="data:text/vtt,WEBVTT" /></video
|
||||||
|
>{/if}
|
||||||
|
</div>
|
||||||
|
<div class="flex items-center justify-between gap-3 border-t border-border px-4 py-3">
|
||||||
|
<div class="min-w-0">
|
||||||
|
<p class="truncate text-sm font-medium text-fg">{selected.title || selected.filename}</p>
|
||||||
|
<p class="mt-1 truncate text-xs text-muted-fg">{selected.filename}</p>
|
||||||
|
</div>
|
||||||
|
<Button variant="secondary" size="sm" onclick={() => (selected = null)}><Play class="size-4" />Close</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
|
|
||||||
|
<style>
|
||||||
|
.dual-range {
|
||||||
|
position: relative;
|
||||||
|
height: 1.5rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.dual-range__track,
|
||||||
|
.dual-range__fill {
|
||||||
|
position: absolute;
|
||||||
|
top: 50%;
|
||||||
|
height: 0.375rem;
|
||||||
|
border-radius: 9999px;
|
||||||
|
pointer-events: none;
|
||||||
|
transform: translateY(-50%);
|
||||||
|
}
|
||||||
|
|
||||||
|
.dual-range__track {
|
||||||
|
left: 0;
|
||||||
|
right: 0;
|
||||||
|
background: var(--color-border);
|
||||||
|
}
|
||||||
|
|
||||||
|
.dual-range__fill {
|
||||||
|
background: var(--color-primary);
|
||||||
|
}
|
||||||
|
|
||||||
|
.dual-range__input {
|
||||||
|
position: absolute;
|
||||||
|
top: 0;
|
||||||
|
left: 0;
|
||||||
|
width: 100%;
|
||||||
|
height: 1.5rem;
|
||||||
|
margin: 0;
|
||||||
|
appearance: none;
|
||||||
|
background: transparent;
|
||||||
|
pointer-events: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.dual-range__input::-webkit-slider-runnable-track {
|
||||||
|
height: 0.375rem;
|
||||||
|
background: transparent;
|
||||||
|
}
|
||||||
|
|
||||||
|
.dual-range__input::-moz-range-track {
|
||||||
|
height: 0.375rem;
|
||||||
|
background: transparent;
|
||||||
|
}
|
||||||
|
|
||||||
|
.dual-range__input::-webkit-slider-thumb {
|
||||||
|
width: 1rem;
|
||||||
|
height: 1rem;
|
||||||
|
margin-top: -0.3125rem;
|
||||||
|
appearance: none;
|
||||||
|
border: 2px solid var(--color-surface);
|
||||||
|
border-radius: 9999px;
|
||||||
|
background: var(--color-primary);
|
||||||
|
box-shadow: 0 0 0 1px var(--color-primary);
|
||||||
|
cursor: pointer;
|
||||||
|
pointer-events: auto;
|
||||||
|
}
|
||||||
|
|
||||||
|
.dual-range__input::-moz-range-thumb {
|
||||||
|
width: 1rem;
|
||||||
|
height: 1rem;
|
||||||
|
border: 2px solid var(--color-surface);
|
||||||
|
border-radius: 9999px;
|
||||||
|
background: var(--color-primary);
|
||||||
|
box-shadow: 0 0 0 1px var(--color-primary);
|
||||||
|
cursor: pointer;
|
||||||
|
pointer-events: auto;
|
||||||
|
}
|
||||||
|
|
||||||
|
.dual-range__input:focus-visible {
|
||||||
|
outline: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.dual-range__input:focus-visible::-webkit-slider-thumb,
|
||||||
|
.dual-range__input:focus-visible::-moz-range-thumb {
|
||||||
|
outline: 2px solid var(--color-ring);
|
||||||
|
outline-offset: 2px;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
@@ -0,0 +1,76 @@
|
|||||||
|
<script lang="ts">
|
||||||
|
import { onMount } from 'svelte'
|
||||||
|
import { get } from '$lib/api'
|
||||||
|
|
||||||
|
type TechStackEntry = { label: string; value: string }
|
||||||
|
type TechStack = {
|
||||||
|
appVersion?: string
|
||||||
|
stack?: TechStackEntry[]
|
||||||
|
}
|
||||||
|
|
||||||
|
const frontendTechStack = __FRONTEND_TECH_STACK__
|
||||||
|
let techStack = $state<TechStack | null>(null)
|
||||||
|
let loading = $state(true)
|
||||||
|
let error = $state<string | null>(null)
|
||||||
|
|
||||||
|
onMount(() => {
|
||||||
|
let cancelled = false
|
||||||
|
|
||||||
|
async function loadTechStack() {
|
||||||
|
try {
|
||||||
|
const data = await get<TechStack>('/api/tech-stack')
|
||||||
|
if (!cancelled) techStack = data
|
||||||
|
} catch (cause) {
|
||||||
|
if (!cancelled) error = cause instanceof Error ? cause.message : 'Unable to load tech stack.'
|
||||||
|
} finally {
|
||||||
|
if (!cancelled) loading = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void loadTechStack()
|
||||||
|
return () => {
|
||||||
|
cancelled = true
|
||||||
|
}
|
||||||
|
})
|
||||||
|
</script>
|
||||||
|
|
||||||
|
{#snippet infoRow(label: string, value: string)}
|
||||||
|
<div class="flex items-center justify-between gap-2 py-1 text-sm">
|
||||||
|
<span class="text-muted-fg">{label}</span>
|
||||||
|
<span class="text-right font-mono text-xs text-fg">{value}</span>
|
||||||
|
</div>
|
||||||
|
{/snippet}
|
||||||
|
|
||||||
|
<div class="rounded-lg border border-border bg-surface p-4">
|
||||||
|
<h2 class="text-sm font-medium text-fg">Tech stack</h2>
|
||||||
|
|
||||||
|
{#if loading}
|
||||||
|
<p class="mt-3 text-sm text-muted-fg">Loading tech stack…</p>
|
||||||
|
{:else if error}
|
||||||
|
<p class="mt-3 text-sm text-danger">{error}</p>
|
||||||
|
{/if}
|
||||||
|
|
||||||
|
<div class="mt-4 grid gap-6 sm:grid-cols-2">
|
||||||
|
<div>
|
||||||
|
<h3 class="mb-1 text-xs font-medium uppercase tracking-wide text-muted-fg">Backend</h3>
|
||||||
|
{#if techStack}
|
||||||
|
{#if techStack.appVersion}{@render infoRow('Version', techStack.appVersion)}{/if}
|
||||||
|
{#each techStack.stack || [] as entry (entry.label)}
|
||||||
|
{@render infoRow(entry.label, entry.value)}
|
||||||
|
{/each}
|
||||||
|
{:else if !loading}
|
||||||
|
<p class="py-1 text-sm text-muted-fg">Backend metadata unavailable.</p>
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<h3 class="mb-1 text-xs font-medium uppercase tracking-wide text-muted-fg">Frontend</h3>
|
||||||
|
{#if frontendTechStack.length}
|
||||||
|
{#each frontendTechStack as entry (entry.name)}
|
||||||
|
{@render infoRow(entry.name, entry.version)}
|
||||||
|
{/each}
|
||||||
|
{:else}
|
||||||
|
<p class="py-1 text-sm text-muted-fg">Build metadata unavailable.</p>
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
@@ -0,0 +1,63 @@
|
|||||||
|
import { browser } from '$app/environment'
|
||||||
|
|
||||||
|
export const languages = [
|
||||||
|
{ id: 'ar', label: 'العربية' },
|
||||||
|
{ id: 'ca', label: 'Català' },
|
||||||
|
{ id: 'de', label: 'Deutsch' },
|
||||||
|
{ id: 'en', label: 'English' },
|
||||||
|
{ id: 'es', label: 'Español' },
|
||||||
|
{ id: 'fr', label: 'Français' },
|
||||||
|
{ id: 'hi', label: 'हिन्दी' },
|
||||||
|
{ id: 'it', label: 'Italiano' },
|
||||||
|
{ id: 'ja', label: '日本語' },
|
||||||
|
{ id: 'nl', label: 'Nederlands' },
|
||||||
|
{ id: 'pt', label: 'Português' },
|
||||||
|
{ id: 'ru', label: 'Русский' },
|
||||||
|
{ id: 'tr', label: 'Türkçe' },
|
||||||
|
{ id: 'uk', label: 'Українська' },
|
||||||
|
{ id: 'zh', label: '中文' },
|
||||||
|
] as const
|
||||||
|
|
||||||
|
export type LanguageId = (typeof languages)[number]['id']
|
||||||
|
|
||||||
|
const defaultLanguage: LanguageId = 'en'
|
||||||
|
const storageKey = 'media-collection-language'
|
||||||
|
const supportedIds = new Set<string>(languages.map((language) => language.id))
|
||||||
|
const rtlLanguages = new Set<LanguageId>(['ar'])
|
||||||
|
|
||||||
|
function isLanguage(value: string | null | undefined): value is LanguageId {
|
||||||
|
return Boolean(value && supportedIds.has(value))
|
||||||
|
}
|
||||||
|
|
||||||
|
function getInitialLanguage(): LanguageId {
|
||||||
|
if (!browser) return defaultLanguage
|
||||||
|
|
||||||
|
const stored = localStorage.getItem(storageKey)
|
||||||
|
if (isLanguage(stored)) return stored
|
||||||
|
|
||||||
|
const automatic = navigator.language?.split('-')[0]
|
||||||
|
return isLanguage(automatic) ? automatic : defaultLanguage
|
||||||
|
}
|
||||||
|
|
||||||
|
function applyLanguage(language: LanguageId) {
|
||||||
|
document.documentElement.lang = language
|
||||||
|
document.documentElement.dir = rtlLanguages.has(language) ? 'rtl' : 'ltr'
|
||||||
|
}
|
||||||
|
|
||||||
|
let selectedLanguage = $state<LanguageId>(getInitialLanguage())
|
||||||
|
|
||||||
|
export function currentLanguage(): LanguageId {
|
||||||
|
return selectedLanguage
|
||||||
|
}
|
||||||
|
|
||||||
|
export function setLanguage(language: string) {
|
||||||
|
if (!isLanguage(language)) return
|
||||||
|
|
||||||
|
selectedLanguage = language
|
||||||
|
if (browser) {
|
||||||
|
localStorage.setItem(storageKey, language)
|
||||||
|
applyLanguage(language)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (browser) applyLanguage(currentLanguage())
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
export type StatusLevel = 'checking' | 'healthy' | 'degraded' | 'offline'
|
||||||
|
|
||||||
|
export interface StatusProbe {
|
||||||
|
path: string
|
||||||
|
ok: boolean
|
||||||
|
httpStatus: number | null
|
||||||
|
service: string | null
|
||||||
|
error: string | null
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface StatusSnapshot {
|
||||||
|
level: StatusLevel
|
||||||
|
health: StatusProbe | null
|
||||||
|
readiness: StatusProbe | null
|
||||||
|
checkedAt: string | null
|
||||||
|
loading: boolean
|
||||||
|
}
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
import type { Snippet } from 'svelte'
|
||||||
|
|
||||||
|
// AppShell renders the page title above the routed page content, so a workspace feature that
|
||||||
|
// wants a button inside the title container (e.g. a Save action) has to hand it up through this
|
||||||
|
// shared reactive slot rather than rendering it inline in its own markup.
|
||||||
|
export const pageActions = $state<{ snippet: Snippet | null }>({ snippet: null })
|
||||||
@@ -0,0 +1,84 @@
|
|||||||
|
import { browser } from '$app/environment'
|
||||||
|
|
||||||
|
export type ThemeMode = 'light' | 'dark' | 'system'
|
||||||
|
type ResolvedTheme = Exclude<ThemeMode, 'system'>
|
||||||
|
|
||||||
|
const storageKey = 'media-collection-theme'
|
||||||
|
|
||||||
|
function normalizeMode(value: string | null | undefined): ThemeMode {
|
||||||
|
return value === 'light' || value === 'dark' || value === 'system' ? value : 'system'
|
||||||
|
}
|
||||||
|
|
||||||
|
function prefersDarkMediaQuery(): MediaQueryList | undefined {
|
||||||
|
return browser && typeof window.matchMedia === 'function'
|
||||||
|
? window.matchMedia('(prefers-color-scheme: dark)')
|
||||||
|
: undefined
|
||||||
|
}
|
||||||
|
|
||||||
|
function getStoredMode(): ThemeMode {
|
||||||
|
if (!browser) return 'system'
|
||||||
|
|
||||||
|
try {
|
||||||
|
return normalizeMode(localStorage.getItem(storageKey))
|
||||||
|
} catch {
|
||||||
|
return 'system'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let mode = $state<ThemeMode>(getStoredMode())
|
||||||
|
let systemPrefersDark = $state(prefersDarkMediaQuery()?.matches ?? false)
|
||||||
|
|
||||||
|
function resolveTheme(next: ThemeMode): ResolvedTheme {
|
||||||
|
return next === 'system' ? (systemPrefersDark ? 'dark' : 'light') : next
|
||||||
|
}
|
||||||
|
|
||||||
|
function applyTheme(next: ThemeMode) {
|
||||||
|
if (browser) document.documentElement.setAttribute('data-theme', resolveTheme(next))
|
||||||
|
}
|
||||||
|
|
||||||
|
function setMode(next: ThemeMode) {
|
||||||
|
mode = normalizeMode(next)
|
||||||
|
if (!browser) return
|
||||||
|
|
||||||
|
applyTheme(mode)
|
||||||
|
try {
|
||||||
|
localStorage.setItem(storageKey, mode)
|
||||||
|
} catch {
|
||||||
|
// Ignore storage failures; the current page can still use the selected theme.
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Keep the DOM theme in sync with both the selected mode and the system preference.
|
||||||
|
$effect.root(() => {
|
||||||
|
$effect(() => {
|
||||||
|
if (browser) applyTheme(mode)
|
||||||
|
})
|
||||||
|
|
||||||
|
if (!browser) return
|
||||||
|
|
||||||
|
const mediaQuery = prefersDarkMediaQuery()
|
||||||
|
if (mediaQuery) {
|
||||||
|
const onChange = () => {
|
||||||
|
systemPrefersDark = mediaQuery.matches
|
||||||
|
}
|
||||||
|
|
||||||
|
if (typeof mediaQuery.addEventListener === 'function') {
|
||||||
|
mediaQuery.addEventListener('change', onChange)
|
||||||
|
} else if (typeof mediaQuery.addListener === 'function') {
|
||||||
|
mediaQuery.addListener(onChange)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
export const themeState = {
|
||||||
|
get mode() {
|
||||||
|
return mode
|
||||||
|
},
|
||||||
|
setMode,
|
||||||
|
get isDark() {
|
||||||
|
return resolveTheme(mode) === 'dark'
|
||||||
|
},
|
||||||
|
toggle() {
|
||||||
|
setMode(mode === 'light' ? 'dark' : mode === 'dark' ? 'system' : 'light')
|
||||||
|
},
|
||||||
|
}
|
||||||
@@ -0,0 +1,74 @@
|
|||||||
|
export type AppId = 'viewer' | 'tools' | 'analyzer' | 'config' | 'moderator' | 'kiosk' | 'servant' | 'desktop'
|
||||||
|
|
||||||
|
export type ProjectIconName =
|
||||||
|
'image' | 'monitor-play' | 'play' | 'scan-search' | 'server' | 'settings-2' | 'shield-check' | 'wand-sparkles'
|
||||||
|
|
||||||
|
export type IconName =
|
||||||
|
| 'activity'
|
||||||
|
| 'archive'
|
||||||
|
| 'audio-lines'
|
||||||
|
| 'bar-chart-3'
|
||||||
|
| 'bot'
|
||||||
|
| 'box'
|
||||||
|
| 'circle-help'
|
||||||
|
| 'cloud-download'
|
||||||
|
| 'database'
|
||||||
|
| 'file-cog'
|
||||||
|
| 'folder-open'
|
||||||
|
| 'gallery-horizontal-end'
|
||||||
|
| 'hard-drive'
|
||||||
|
| 'image'
|
||||||
|
| 'layout-dashboard'
|
||||||
|
| 'list-video'
|
||||||
|
| 'logs'
|
||||||
|
| 'monitor-play'
|
||||||
|
| 'play'
|
||||||
|
| 'refresh-cw'
|
||||||
|
| 'scroll-text'
|
||||||
|
| 'search'
|
||||||
|
| 'server'
|
||||||
|
| 'settings-2'
|
||||||
|
| 'shield-check'
|
||||||
|
| 'sliders-horizontal'
|
||||||
|
| 'sparkles'
|
||||||
|
| 'tags'
|
||||||
|
| 'users'
|
||||||
|
| 'wand-sparkles'
|
||||||
|
|
||||||
|
export interface NavItem {
|
||||||
|
label: string
|
||||||
|
panel: string
|
||||||
|
path: string
|
||||||
|
icon: IconName
|
||||||
|
description?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface AppConfig {
|
||||||
|
id: AppId
|
||||||
|
name: string
|
||||||
|
icon: ProjectIconName
|
||||||
|
eyebrow: string
|
||||||
|
description: string
|
||||||
|
nav: NavItem[]
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface AuthUser {
|
||||||
|
id?: string | number
|
||||||
|
email?: string
|
||||||
|
username?: string
|
||||||
|
role?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface AuthState {
|
||||||
|
user: AuthUser | null
|
||||||
|
authRequired: boolean
|
||||||
|
setupRequired: boolean
|
||||||
|
loading: boolean
|
||||||
|
error: string | null
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ApiError {
|
||||||
|
error?: string
|
||||||
|
message?: string
|
||||||
|
detail?: string
|
||||||
|
}
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
import { clsx, type ClassValue } from 'clsx'
|
||||||
|
import { twMerge } from 'tailwind-merge'
|
||||||
|
|
||||||
|
export function cn(...inputs: ClassValue[]) {
|
||||||
|
return twMerge(clsx(inputs))
|
||||||
|
}
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
<script lang="ts">
|
||||||
|
import '../app.css'
|
||||||
|
import '@gabriel20xx/web-ui/styles.css'
|
||||||
|
import AppShell from '$lib/components/AppShell.svelte'
|
||||||
|
import { getAppConfig } from '$lib/app-config'
|
||||||
|
import type { Snippet } from 'svelte'
|
||||||
|
|
||||||
|
let { children }: { children: Snippet } = $props()
|
||||||
|
const app = getAppConfig(__MEDIA_APP__)
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<svelte:head><title>{app.name}</title><meta name="description" content={app.description} /></svelte:head>
|
||||||
|
|
||||||
|
<AppShell {app}>
|
||||||
|
{@render children()}
|
||||||
|
</AppShell>
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
<script lang="ts">
|
||||||
|
import WorkspacePage from '$lib/components/WorkspacePage.svelte'
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<WorkspacePage />
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
<script lang="ts">
|
||||||
|
import WorkspacePage from '$lib/components/WorkspacePage.svelte'
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<WorkspacePage />
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="#5b8cff" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" role="img" aria-labelledby="favicon-title">
|
||||||
|
<title id="favicon-title">MediaViewer</title>
|
||||||
|
<path d="M5 5a2 2 0 0 1 3.008-1.728l11.997 6.998a2 2 0 0 1 .003 3.458l-12 7A2 2 0 0 1 5 19z" />
|
||||||
|
</svg>
|
||||||
|
After Width: | Height: | Size: 373 B |
@@ -0,0 +1,10 @@
|
|||||||
|
import adapter from '@sveltejs/adapter-static'
|
||||||
|
|
||||||
|
/** @type {import('@sveltejs/kit').Config} */
|
||||||
|
const config = {
|
||||||
|
kit: {
|
||||||
|
adapter: adapter({ fallback: 'index.html' }),
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
export default config
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
{
|
||||||
|
"extends": "./.svelte-kit/tsconfig.json",
|
||||||
|
"compilerOptions": {
|
||||||
|
"allowJs": true,
|
||||||
|
"checkJs": true,
|
||||||
|
"esModuleInterop": true,
|
||||||
|
"forceConsistentCasingInFileNames": true,
|
||||||
|
"resolveJsonModule": true,
|
||||||
|
"skipLibCheck": true,
|
||||||
|
"sourceMap": true,
|
||||||
|
"strict": true,
|
||||||
|
"moduleResolution": "bundler"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,58 @@
|
|||||||
|
import fs from 'node:fs'
|
||||||
|
import { writeFile } from 'node:fs/promises'
|
||||||
|
import path from 'node:path'
|
||||||
|
import tailwindcss from '@tailwindcss/vite'
|
||||||
|
import { sveltekit } from '@sveltejs/kit/vite'
|
||||||
|
import { defineConfig, type ResolvedConfig } from 'vite'
|
||||||
|
import { renderProjectFavicon } from './scripts/project-favicon.mjs'
|
||||||
|
|
||||||
|
const packages = [
|
||||||
|
['Svelte', 'svelte'],
|
||||||
|
['SvelteKit', '@sveltejs/kit'],
|
||||||
|
['TanStack Query', '@tanstack/svelte-query'],
|
||||||
|
['Tailwind CSS', 'tailwindcss'],
|
||||||
|
['bits-ui', 'bits-ui'],
|
||||||
|
['Vite', 'vite'],
|
||||||
|
]
|
||||||
|
|
||||||
|
const frontendTechStack = packages.flatMap(([label, pkg]) => {
|
||||||
|
try {
|
||||||
|
const file = path.resolve(import.meta.dirname, 'node_modules', pkg, 'package.json')
|
||||||
|
const version = JSON.parse(fs.readFileSync(file, 'utf8')).version
|
||||||
|
return version ? [{ name: label, version }] : []
|
||||||
|
} catch {
|
||||||
|
return []
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
function projectFavicon() {
|
||||||
|
const appId = process.env.VITE_MEDIA_APP || 'viewer'
|
||||||
|
let outputDir = ''
|
||||||
|
|
||||||
|
return {
|
||||||
|
name: 'media-collection-project-favicon',
|
||||||
|
configResolved(config: ResolvedConfig) {
|
||||||
|
outputDir = path.resolve(config.root, config.build.outDir)
|
||||||
|
},
|
||||||
|
async writeBundle() {
|
||||||
|
await writeFile(path.join(outputDir, 'favicon.svg'), renderProjectFavicon(appId), 'utf8')
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export default defineConfig({
|
||||||
|
plugins: [tailwindcss(), sveltekit(), projectFavicon()],
|
||||||
|
define: {
|
||||||
|
__MEDIA_APP__: JSON.stringify(process.env.VITE_MEDIA_APP || 'viewer'),
|
||||||
|
__FRONTEND_TECH_STACK__: JSON.stringify(frontendTechStack),
|
||||||
|
},
|
||||||
|
server: {
|
||||||
|
port: 5173,
|
||||||
|
proxy: {
|
||||||
|
'/api': 'http://localhost:3000',
|
||||||
|
'/auth': 'http://localhost:3000',
|
||||||
|
'/health': 'http://localhost:3000',
|
||||||
|
'/ws': { target: 'ws://localhost:3000', ws: true },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
})
|
||||||
Generated
+406
-112
File diff suppressed because it is too large.
Load diff
+15
-2
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@gabriel20xx/shared-code",
|
"name": "@gabriel20xx/shared-code",
|
||||||
"version": "0.1.0",
|
"version": "0.1.1",
|
||||||
"description": "Shared UI and backend packages for Gabriel20xx projects.",
|
"description": "Shared UI and backend packages for Gabriel20xx projects.",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"repository": {
|
"repository": {
|
||||||
@@ -45,7 +45,20 @@
|
|||||||
"prepare": "npm run build && node scripts/build-root-styles.mjs",
|
"prepare": "npm run build && node scripts/build-root-styles.mjs",
|
||||||
"changeset": "changeset",
|
"changeset": "changeset",
|
||||||
"version-packages": "changeset version",
|
"version-packages": "changeset version",
|
||||||
"release": "npm run build && npm run test:node-backend && changeset publish"
|
"release": "npm run build && npm run test:node-backend && changeset publish",
|
||||||
|
"media:audit:html-js": "node scripts/media/audit-html-js.mjs",
|
||||||
|
"media:audit:layout": "node scripts/media/audit-inline-layout.mjs",
|
||||||
|
"media:audit:layout:strict": "node scripts/media/audit-inline-layout.mjs --strict",
|
||||||
|
"media:clean:test-artifacts": "node scripts/media/clean-test-artifacts.mjs",
|
||||||
|
"media:enforce:css-design-system": "node scripts/media/enforce-design-system-css.mjs",
|
||||||
|
"media:enforce:js-mapping": "node scripts/media/enforce-js-mapping.mjs",
|
||||||
|
"media:enforce:no-skipped-tests": "node scripts/media/enforce-no-skipped-tests.mjs",
|
||||||
|
"media:lint:all": "node scripts/media/lint-all.mjs",
|
||||||
|
"media:lint:all:json": "node scripts/media/lint-all-json.mjs",
|
||||||
|
"media:test:list-skipped": "node scripts/media/list-skipped-tests.mjs",
|
||||||
|
"media:test:timings": "node scripts/media/report-test-timings.mjs",
|
||||||
|
"media:vitest:inspect-exports": "node scripts/media/inspect-vitest-exports.mjs",
|
||||||
|
"media:deps:upgrade": "node scripts/media/upgrade-deps.mjs"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"pg": "^8.17.2"
|
"pg": "^8.17.2"
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@gabriel20xx/design-tokens",
|
"name": "@gabriel20xx/design-tokens",
|
||||||
"version": "0.1.0",
|
"version": "0.1.1",
|
||||||
"description": "Shared visual tokens for Gabriel20xx web projects.",
|
"description": "Shared visual tokens for Gabriel20xx web projects.",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"files": [
|
"files": [
|
||||||
|
|||||||
@@ -0,0 +1,18 @@
|
|||||||
|
# `com.gabriel20xx.shared:java-backend`
|
||||||
|
|
||||||
|
Shared account-management, TOTP, admin reset-code, and AuthGuard client primitives for Java services:
|
||||||
|
|
||||||
|
- `Roles` - shared account-management roles (`superadmin`/`admin`/`user`) and permission checks;
|
||||||
|
- `Totp` - RFC 6238 TOTP secret generation, provisioning URIs, and verification;
|
||||||
|
- `ResetManager` - a short-lived, one-time admin reset-code primitive printed to the server console;
|
||||||
|
- `AuthClient` - a client for a centralized AuthGuard instance's `GET /api/session/validate`, for services that want one shared identity instead of their own local user table. Mirrors `shared/backend/authclient` (Go) and `shared/packages/node-backend/src/authclient.js` (Node) - keep the three in sync if any of them changes shape. Additive: no project is wired up to use it just because this class exists.
|
||||||
|
|
||||||
|
## How this package is actually consumed
|
||||||
|
|
||||||
|
Unlike its `node-backend`/`python-backend` siblings, this package is not published and installed as a dependency. Its real, already-identified consumer - [MegaBasterd](../../../../Forks/MegaBasterd) - instead adds this package's `src/main/java` as an extra source directory of its *own* Maven build, via the `build-helper-maven-plugin` "add-shared-java-auth" execution in `MegaBasterd/pom.xml`, and compiles these `.java` files straight into its own jar. That pom pins `<maven.compiler.source>`/`<target>` to `1.8`, which is why every class in this package targets Java 8 and none of them (including `AuthClient`) take on a dependency beyond the JDK - both would break that real build.
|
||||||
|
|
||||||
|
This package's own `pom.xml` exists only so it can be built and tested in isolation during development; it plays no part in how MegaBasterd (or any future consumer that adopts the same source-inclusion approach) actually builds.
|
||||||
|
|
||||||
|
## Testing
|
||||||
|
|
||||||
|
Run `mvn test` from this package.
|
||||||
@@ -0,0 +1,49 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||||
|
<modelVersion>4.0.0</modelVersion>
|
||||||
|
<groupId>com.gabriel20xx.shared</groupId>
|
||||||
|
<artifactId>java-backend</artifactId>
|
||||||
|
<version>0.1.0</version>
|
||||||
|
<packaging>jar</packaging>
|
||||||
|
<name>java-backend</name>
|
||||||
|
<description>Shared account-management, TOTP, admin reset-code, and AuthGuard client primitives for Java services.</description>
|
||||||
|
|
||||||
|
<!--
|
||||||
|
This pom.xml exists only so this package can be built and tested on
|
||||||
|
its own (mirroring @gabriel20xx/node-backend's package.json and
|
||||||
|
python-backend's pyproject.toml). It is not how the real,
|
||||||
|
already-identified consumer of this package - MegaBasterd - uses it:
|
||||||
|
MegaBasterd/pom.xml instead adds src/main/java as an extra source
|
||||||
|
directory of its own build via build-helper-maven-plugin, compiling
|
||||||
|
this source straight into its jar with no dependency on this
|
||||||
|
artifact. That is also why maven.compiler.source/target below is
|
||||||
|
pinned to 1.8 - it must match MegaBasterd/pom.xml's
|
||||||
|
<maven.compiler.source>/<target>, since both poms compile the exact
|
||||||
|
same .java files.
|
||||||
|
-->
|
||||||
|
<properties>
|
||||||
|
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||||
|
<maven.compiler.source>1.8</maven.compiler.source>
|
||||||
|
<maven.compiler.target>1.8</maven.compiler.target>
|
||||||
|
<junit.version>5.10.2</junit.version>
|
||||||
|
</properties>
|
||||||
|
|
||||||
|
<dependencies>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.junit.jupiter</groupId>
|
||||||
|
<artifactId>junit-jupiter</artifactId>
|
||||||
|
<version>${junit.version}</version>
|
||||||
|
<scope>test</scope>
|
||||||
|
</dependency>
|
||||||
|
</dependencies>
|
||||||
|
|
||||||
|
<build>
|
||||||
|
<plugins>
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
|
<artifactId>maven-surefire-plugin</artifactId>
|
||||||
|
<version>3.2.5</version>
|
||||||
|
</plugin>
|
||||||
|
</plugins>
|
||||||
|
</build>
|
||||||
|
</project>
|
||||||
Loaded 100 of 184 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user