Compare commits
34
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
bda5229183 | ||
|
|
b95b8e98cd | ||
|
|
b87bf6f77e | ||
|
|
46a0429d5e | ||
|
|
815164843b | ||
|
|
66ed1e2c9b | ||
|
|
2275974cde | ||
|
|
d4543a9843 | ||
|
|
106b6f311f | ||
|
|
d3f40cfea3 | ||
|
|
a843d4de9b | ||
|
|
d2f02d8054 | ||
|
|
8a3c616b5f | ||
|
|
e1b001a431 | ||
|
|
e9d7b12c66 | ||
|
|
b46fbea4c9 | ||
|
|
df1eba74e8 | ||
|
|
b41163965e | ||
|
|
aabbff8127 | ||
|
|
7cdf712829 | ||
|
|
327fa53d7b | ||
|
|
80c6bf3b7d | ||
|
|
b682bdd5b0 | ||
|
|
d109ad6ff1 | ||
|
|
f45fce7d69 | ||
|
|
a11a88456c | ||
|
|
c9c950de1b | ||
|
|
9c9697dc6e | ||
|
|
a869f0b042 | ||
|
|
cc4126d23c | ||
|
|
4fdb7a4407 | ||
|
|
7d10d5b601 | ||
|
|
2c2ec81d51 | ||
|
|
4acd616555 |
@@ -14,3 +14,6 @@ dist
|
|||||||
.mypy_cache
|
.mypy_cache
|
||||||
**/__pycache__
|
**/__pycache__
|
||||||
**/*.pyc
|
**/*.pyc
|
||||||
|
|
||||||
|
# macOS metadata at any depth
|
||||||
|
**/.DS_Store
|
||||||
|
|||||||
+3
-1
@@ -2,7 +2,9 @@ TZ=Asia/Shanghai
|
|||||||
# Default local access. For NAS LAN access set this to the NAS LAN IP (recommended)
|
# Default local access. For NAS LAN access set this to the NAS LAN IP (recommended)
|
||||||
# or explicitly 0.0.0.0. No router, reverse proxy or firewall rules are modified.
|
# or explicitly 0.0.0.0. No router, reverse proxy or firewall rules are modified.
|
||||||
WEB_BIND=127.0.0.1
|
WEB_BIND=127.0.0.1
|
||||||
WEB_PORT=18787
|
WEB_PORT=6005
|
||||||
|
# Display name of the NAS/server storing the local gallery.
|
||||||
|
FRAME_FLOW_STORAGE_NAME=NAS
|
||||||
KOKONNA_MOCK=true
|
KOKONNA_MOCK=true
|
||||||
KOKONNA_WRITE_ENABLED=false
|
KOKONNA_WRITE_ENABLED=false
|
||||||
KOKONNA_API_KEY=
|
KOKONNA_API_KEY=
|
||||||
|
|||||||
@@ -1,16 +1,14 @@
|
|||||||
name: Verify Frame Flow
|
name: Verify Frame Flow
|
||||||
on:
|
on:
|
||||||
push:
|
push:
|
||||||
|
# Branch verification gates releases; tags do not duplicate the same build.
|
||||||
|
branches: ["**"]
|
||||||
pull_request:
|
pull_request:
|
||||||
workflow_dispatch:
|
workflow_dispatch:
|
||||||
inputs:
|
|
||||||
deploy_action:
|
|
||||||
description: Production action (deploy requires explicit enabled Variable)
|
|
||||||
type: choice
|
|
||||||
options: [plan, bootstrap, deploy, rollback]
|
|
||||||
default: plan
|
|
||||||
jobs:
|
jobs:
|
||||||
verify:
|
verify:
|
||||||
|
# The NAS Docker runner must never execute code from external forks.
|
||||||
|
if: github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
env:
|
env:
|
||||||
DOCKER_PIP_INDEX_URL: ${{ vars.DOCKER_PIP_INDEX_URL }}
|
DOCKER_PIP_INDEX_URL: ${{ vars.DOCKER_PIP_INDEX_URL }}
|
||||||
@@ -20,8 +18,8 @@ jobs:
|
|||||||
DEBIAN_MIRROR: ${{ vars.DEBIAN_MIRROR }}
|
DEBIAN_MIRROR: ${{ vars.DEBIAN_MIRROR }}
|
||||||
DEBIAN_SECURITY_MIRROR: ${{ vars.DEBIAN_SECURITY_MIRROR }}
|
DEBIAN_SECURITY_MIRROR: ${{ vars.DEBIAN_SECURITY_MIRROR }}
|
||||||
steps:
|
steps:
|
||||||
- uses: https://tea.pigway.com/way/frame-flow-ci-actions/checkout@bada0aa1b7e0d23fe9da66ce2ec9b193c211ea46 # v4
|
- uses: https://github.com/actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
|
||||||
- uses: https://tea.pigway.com/way/frame-flow-ci-actions/setup-python@bada0aa1b7e0d23fe9da66ce2ec9b193c211ea46 # v5
|
- uses: https://github.com/actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5
|
||||||
with:
|
with:
|
||||||
python-version: '3.14'
|
python-version: '3.14'
|
||||||
- name: Install CI dependencies with index diagnostics and fallback
|
- name: Install CI dependencies with index diagnostics and fallback
|
||||||
@@ -43,53 +41,5 @@ jobs:
|
|||||||
python scripts/ci-compose-verify.py --cleanup
|
python scripts/ci-compose-verify.py --cleanup
|
||||||
fi
|
fi
|
||||||
|
|
||||||
deploy:
|
# Production moved to Ubuntu Server. Release manually with scripts/server-release.py;
|
||||||
needs: verify
|
# the shared NAS runner performs isolated verification only.
|
||||||
if: success() && github.ref == 'refs/heads/main' && (github.event_name == 'push' || github.event_name == 'workflow_dispatch')
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
concurrency:
|
|
||||||
group: frame-flow-production
|
|
||||||
cancel-in-progress: false
|
|
||||||
env:
|
|
||||||
CD_ACTION: ${{ github.event.inputs.deploy_action }}
|
|
||||||
PROD_DEPLOY_ENABLED: ${{ vars.PROD_DEPLOY_ENABLED }}
|
|
||||||
PROD_PROJECT: ${{ vars.PROD_PROJECT }}
|
|
||||||
PROD_CONTAINER: ${{ vars.PROD_CONTAINER }}
|
|
||||||
PROD_IMAGE_REPO: ${{ vars.PROD_IMAGE_REPO }}
|
|
||||||
PROD_DATA_DIR: ${{ vars.PROD_DATA_DIR }}
|
|
||||||
PROD_CONFIG_DIR: ${{ vars.PROD_CONFIG_DIR }}
|
|
||||||
PROD_PHOTOS_DIR: ${{ vars.PROD_PHOTOS_DIR }}
|
|
||||||
SYNOLOGY_PHOTOS_URL: ${{ vars.SYNOLOGY_PHOTOS_URL }}
|
|
||||||
SYNOLOGY_PHOTOS_CERT_SHA256: ${{ vars.SYNOLOGY_PHOTOS_CERT_SHA256 }}
|
|
||||||
PROD_WEB_BIND: ${{ vars.PROD_WEB_BIND }}
|
|
||||||
PROD_WEB_PORT: ${{ vars.PROD_WEB_PORT }}
|
|
||||||
PROD_STATE_VOLUME: ${{ vars.PROD_STATE_VOLUME }}
|
|
||||||
PROD_MOCK: ${{ vars.PROD_MOCK }}
|
|
||||||
PROD_WRITE_ENABLED: ${{ vars.PROD_WRITE_ENABLED }}
|
|
||||||
DOCKER_PIP_INDEX_URL: ${{ vars.DOCKER_PIP_INDEX_URL }}
|
|
||||||
DOCKER_PIP_FALLBACK_INDEX_URL: ${{ vars.DOCKER_PIP_FALLBACK_INDEX_URL }}
|
|
||||||
CI_PIP_INDEX_URL: ${{ vars.CI_PIP_INDEX_URL }}
|
|
||||||
CI_PIP_FALLBACK_INDEX_URL: ${{ vars.CI_PIP_FALLBACK_INDEX_URL }}
|
|
||||||
DEBIAN_MIRROR: ${{ vars.DEBIAN_MIRROR }}
|
|
||||||
DEBIAN_SECURITY_MIRROR: ${{ vars.DEBIAN_SECURITY_MIRROR }}
|
|
||||||
steps:
|
|
||||||
- uses: https://tea.pigway.com/way/frame-flow-ci-actions/checkout@bada0aa1b7e0d23fe9da66ce2ec9b193c211ea46 # v4
|
|
||||||
- uses: https://tea.pigway.com/way/frame-flow-ci-actions/setup-python@bada0aa1b7e0d23fe9da66ce2ec9b193c211ea46 # v5
|
|
||||||
with:
|
|
||||||
python-version: '3.14'
|
|
||||||
- name: Install deploy tooling
|
|
||||||
run: python scripts/ci-install.py
|
|
||||||
- name: Plan or deploy production (default is plan)
|
|
||||||
env:
|
|
||||||
PRODUCTION_ENV: ${{ secrets.PRODUCTION_ENV }}
|
|
||||||
run: |
|
|
||||||
. ./deploy/build-cn.env
|
|
||||||
python scripts/production-deploy.py
|
|
||||||
- name: Recover interrupted production deployment
|
|
||||||
if: always()
|
|
||||||
env:
|
|
||||||
CD_ACTION: recover
|
|
||||||
run: |
|
|
||||||
if [ -n "${FRAME_FLOW_DEPLOY_OWNER:-}" ]; then
|
|
||||||
python scripts/production-deploy.py
|
|
||||||
fi
|
|
||||||
|
|||||||
@@ -20,3 +20,7 @@ build-cache/debs/*
|
|||||||
!build-cache/debs/.gitkeep
|
!build-cache/debs/.gitkeep
|
||||||
build-cache/wheels/*
|
build-cache/wheels/*
|
||||||
!build-cache/wheels/.gitkeep
|
!build-cache/wheels/.gitkeep
|
||||||
|
|
||||||
|
# Private browser captures and platform metadata
|
||||||
|
docs/screenshots/
|
||||||
|
.DS_Store
|
||||||
|
|||||||
+14
-1
@@ -1,5 +1,5 @@
|
|||||||
ARG PYTHON_BASE=python:3.14.5-slim-bookworm@sha256:ec58d916f9e24a6035cab2bdf07f6206c4cc092a16613c60597534711332d9d6
|
ARG PYTHON_BASE=python:3.14.5-slim-bookworm@sha256:ec58d916f9e24a6035cab2bdf07f6206c4cc092a16613c60597534711332d9d6
|
||||||
FROM ${PYTHON_BASE}
|
FROM ${PYTHON_BASE} AS prepared
|
||||||
ARG DEBIAN_MIRROR=deb.debian.org
|
ARG DEBIAN_MIRROR=deb.debian.org
|
||||||
ARG DEBIAN_SECURITY_MIRROR=deb.debian.org
|
ARG DEBIAN_SECURITY_MIRROR=deb.debian.org
|
||||||
ARG TARGETARCH
|
ARG TARGETARCH
|
||||||
@@ -37,6 +37,19 @@ RUN --mount=type=cache,id=frameflow-pip-py314-${TARGETARCH},target=/root/.cache/
|
|||||||
else python /build-tools/install.py --locked; fi
|
else python /build-tools/install.py --locked; fi
|
||||||
COPY pigway_frame_flow ./pigway_frame_flow
|
COPY pigway_frame_flow ./pigway_frame_flow
|
||||||
COPY vendor ./vendor
|
COPY vendor ./vendor
|
||||||
|
# Publish only the cleaned filesystem, without retaining build-stage layers.
|
||||||
|
RUN rm -rf /usr/local/lib/python*/site-packages/pip \
|
||||||
|
/usr/local/lib/python*/site-packages/pip-*.dist-info \
|
||||||
|
/usr/local/lib/python*/ensurepip \
|
||||||
|
&& rm -f /usr/local/bin/pip /usr/local/bin/pip[0-9]* \
|
||||||
|
&& find / -name .DS_Store -type f -delete
|
||||||
|
|
||||||
|
FROM scratch
|
||||||
|
COPY --from=prepared / /
|
||||||
|
ENV PATH=/usr/local/bin:/usr/local/sbin:/usr/sbin:/usr/bin:/sbin:/bin LANG=C.UTF-8
|
||||||
|
ENV PYTHONDONTWRITEBYTECODE=1 PYTHONUNBUFFERED=1 TZ=Asia/Shanghai \
|
||||||
|
DATA_DIR=/data CONFIG_DIR=/config
|
||||||
|
WORKDIR /app
|
||||||
ARG BUILD_COMMIT=development
|
ARG BUILD_COMMIT=development
|
||||||
ARG BUILD_TIME=unknown
|
ARG BUILD_TIME=unknown
|
||||||
ENV BUILD_COMMIT=$BUILD_COMMIT BUILD_TIME=$BUILD_TIME
|
ENV BUILD_COMMIT=$BUILD_COMMIT BUILD_TIME=$BUILD_TIME
|
||||||
|
|||||||
@@ -1,359 +1,95 @@
|
|||||||
# Pigway Frame Flow
|
# Pigway Frame Flow
|
||||||
|
|
||||||
Pigway Frame Flow is a lightweight self-hosted platform for programmable smart-frame automation.
|
[简体中文](README.zh-CN.md) | English
|
||||||
|
|
||||||
独立运行的智能画框服务:中英文 Web UI、深浅色模式、设备驱动抽象、KoKonna 全部已公开接口、图片处理、模板、SQLite 调度与播放列表、临时覆盖恢复和 REST API。
|
Pigway Frame Flow is a lightweight, self-hosted platform for programmable smart-frame automation. It runs independently on a NAS or server, with its own Web UI, image library, rendering, scheduler and REST API. KoKonna is a supported device integration; external applications do not need its credentials or SDK.
|
||||||
|
|
||||||
KoKonna is a supported device integration and is not affiliated with this project unless otherwise stated.
|
### Installation
|
||||||
|
|
||||||
## Quick Start / 快速开始
|
Deploy with Docker Compose. The current default configuration and verified platform are AMD64:
|
||||||
|
|
||||||
```sh
|
```bash
|
||||||
python3 -m venv .venv
|
|
||||||
.venv/bin/python -m pip install -r requirements.lock
|
|
||||||
.venv/bin/python scripts/run_local.py
|
|
||||||
```
|
|
||||||
|
|
||||||
Open http://127.0.0.1:18787. The local demo creates a private `.env` with a random
|
|
||||||
FRAME_FLOW_TOKEN. Read that token locally in an editor and enter it on the login
|
|
||||||
screen. Do not paste a KoKonna API Key into Web UI. Demo always forces mock mode
|
|
||||||
and disables real writes. It leaves data persistent in ./data and ./config.
|
|
||||||
|
|
||||||
网页使用账号密码登录。通过 `python scripts/create-account.py --username YOUR_NAME` 创建账号,再启动服务;密码不会写入代码或明文配置。勾选记住登录可保持 30 天,设置页面可修改密码或退出。
|
|
||||||
|
|
||||||
## Architecture / 架构
|
|
||||||
|
|
||||||
```
|
|
||||||
providers → templates / renderers → generated image
|
|
||||||
↓
|
|
||||||
Web UI / external REST → DisplayService → FrameDeviceDriver → KokonnaDriver
|
|
||||||
Scheduler / Playlist ─────────────┘
|
|
||||||
SQLite: operations / history / jobs / overrides / assets
|
|
||||||
```
|
|
||||||
|
|
||||||
Package: pigway_frame_flow. Device composition is in core/registry.py;
|
|
||||||
vendor-specific code is in drivers/kokonna. One process, one worker, no Redis,
|
|
||||||
message broker, OpenClaw, Home Assistant or external application dependency.
|
|
||||||
|
|
||||||
## Configuration / 配置
|
|
||||||
|
|
||||||
Copy `.env.example` to `.env`, set a strong FRAME_FLOW_TOKEN, chmod 600 .env.
|
|
||||||
- KOKONNA_MOCK=true: independent persistent demo, no cloud calls.
|
|
||||||
- KOKONNA_WRITE_ENABLED=false: live write protection, mandatory before verification.
|
|
||||||
- KOKONNA_API_KEY: device key, never stored in DB or returned to Web UI.
|
|
||||||
- *_FILE: optional Docker Secret equivalent.
|
|
||||||
- WEB_BIND/WEB_PORT: Compose host bind and port. Internal app binds container network.
|
|
||||||
- CORS_ALLOWED_ORIGINS: exact comma-separated origins; default empty.
|
|
||||||
- IMAGE_URL_ALLOWED_HOSTS: exact public HTTPS hosts; default disabled. Redirects denied.
|
|
||||||
- TZ=Asia/Shanghai; DATA_DIR=/data; CONFIG_DIR=/config.
|
|
||||||
|
|
||||||
For multiple devices copy deploy/devices.yml.example into config/devices.yml,
|
|
||||||
reference a separate environment key per device. Jobs bind a device_id. Layout
|
|
||||||
currently targets 1200 × 1600; incompatible geometry is refused before writes.
|
|
||||||
|
|
||||||
## Docker
|
|
||||||
|
|
||||||
```sh
|
|
||||||
cp .env.example .env
|
cp .env.example .env
|
||||||
# Configure a token; keep API key empty, mock true, writes false.
|
# Set a strong FRAME_FLOW_TOKEN; keep mock=true and writes=false initially.
|
||||||
|
chmod 600 .env
|
||||||
mkdir -p data/images data/generated data/cache config
|
mkdir -p data/images data/generated data/cache config
|
||||||
sudo chown -R 10333:10333 data config
|
sudo chown -R 10333:10333 data config
|
||||||
./scripts/build-verify.sh
|
./scripts/build-verify.sh
|
||||||
|
# Create the browser administrator account; enter its password interactively.
|
||||||
|
docker compose run --rm --no-deps -e PYTHONPATH=/app \
|
||||||
|
-v "$PWD/scripts:/bootstrap:ro" --entrypoint python pigway-frame-flow \
|
||||||
|
/bootstrap/create-account.py --username admin --config-dir /config
|
||||||
docker compose up -d
|
docker compose up -d
|
||||||
python3 scripts/smoke-test.py
|
|
||||||
```
|
```
|
||||||
|
|
||||||
Image pigway-frame-flow:latest, service/container pigway-frame-flow, AMD64,
|
Open `http://127.0.0.1:6005` and sign in with the account you created. The browser uses an HttpOnly session cookie; it does not require an API token. Remembered sessions last 30 days. Change the password or sign out in Settings. `FRAME_FLOW_TOKEN` authenticates external API clients and is separate from the KoKonna API key.
|
||||||
Python 3.14.5, pinned runtime dependencies, CJK fonts, non-root UID/GID 10333,
|
|
||||||
read-only root filesystem, writable /data and /config, no capabilities, no host
|
|
||||||
network, no Docker socket. Restart unless-stopped. JSON-file logs capped 10m × 3.
|
|
||||||
Healthcheck uses service /health, not cloud availability. No second log database.
|
|
||||||
|
|
||||||
## Synology NAS
|
The published interface defaults to loopback. For LAN access, explicitly set `WEB_BIND` to your NAS LAN address and choose an available `WEB_PORT`. See [Synology deployment](docs/NAS.md), [build mirrors and caching](docs/BUILDING.md), and [Gitea deployment/rollback](docs/deployment/GITEA_CD.md). No firewall, router or reverse-proxy settings are changed automatically.
|
||||||
|
|
||||||
Target `/volume2/docker/pigway-frame-flow/`. See [NAS deployment](docs/NAS.md).
|
For a local mock demo, use Python 3.14:
|
||||||
Set WEB_BIND to the NAS LAN IP to restrict the published interface, or explicitly
|
|
||||||
0.0.0.0 when desired. Port 18787 must be free. No router/firewall/reverse proxy
|
|
||||||
rules are modified. Source and persistent volumes stay in this project directory.
|
|
||||||
No artificial logs directory is required. Compose creates its own bridge network.
|
|
||||||
|
|
||||||
## KoKonna Setup / 真实设备
|
```bash
|
||||||
|
python3.14 -m venv .venv
|
||||||
|
.venv/bin/python -m pip install -r requirements.lock
|
||||||
|
.venv/bin/python scripts/create-account.py --username admin
|
||||||
|
.venv/bin/python scripts/run_local.py
|
||||||
|
```
|
||||||
|
|
||||||
First deploy Mock and verify persistence. Then set KOKONNA_MOCK=false and fill
|
The demo forces mock mode and disables device writes. Data and configuration remain in `data/` and `config/` across restarts.
|
||||||
KOKONNA_API_KEY through private environment/secret. Keep writes false. /ready checks
|
|
||||||
configuration/DB/worker/token without a cloud call. Query device and images metadata;
|
|
||||||
compare model, geometry, timezone, heartbeat, battery, imageId, coverId, sync.
|
|
||||||
If different, stop and report. **Do not enable writes or perform the single test
|
|
||||||
until the owner explicitly authorizes it.** Test design: [REAL_DEVICE_TEST.md](docs/REAL_DEVICE_TEST.md).
|
|
||||||
|
|
||||||
## Security
|
Synology Photos API sources work without `/photos` or NFS mounts, with shared/current-account personal spaces, people filters and bounded on-demand XL preview caching. Original downloads are not supported by this verified implementation. See [Photos API and Ubuntu migration candidate](docs/SYNOLOGY_PHOTOS_API.md).
|
||||||
|
|
||||||
Protected /api/v1 capabilities accept an administrator account session, or external
|
### Features and boundaries
|
||||||
Frame Flow Bearer auth with scope checks.
|
|
||||||
SQLite stores token hashes. Device keys live only in env/secret and runtime memory.
|
|
||||||
Browser login uses SQLite accounts with salted scrypt password hashes and revocable,
|
|
||||||
HttpOnly/SameSite=Strict cookies (30 days when remembered, 12 hours otherwise).
|
|
||||||
Mutations require a session CSRF header. Logout and password changes revoke sessions.
|
|
||||||
Passwords and browser sessions are never stored in localStorage. Bootstrap hashes
|
|
||||||
in private `config/accounts.json` seed new accounts only; restarting does not undo
|
|
||||||
a password change. Five failed logins per source IP cause a five-minute lockout.
|
|
||||||
The browser needs no API Token. Bearer authentication remains compatible for
|
|
||||||
external clients; the KoKonna key is never used for account login.
|
|
||||||
The LAN deployment uses HTTP; use an explicitly configured HTTPS endpoint if
|
|
||||||
transport encryption is needed. No reverse proxy or firewall is changed automatically.
|
|
||||||
|
|
||||||
## API
|
- Chinese and English Web UI, light/dark themes, account login, device dashboard and image previews.
|
||||||
|
- Local staging and KoKonna cloud gallery, uploads, image switching, stars, source/task filters and batch actions.
|
||||||
|
- Aspect-ratio-preserving contain/cover/smart conversion, color/grayscale profiles and orientation selection for photo sources.
|
||||||
|
- Seven templates: Daily Dashboard, Weather, Calendar, Quote, Photo + Text, Daily Poetry and System Alert.
|
||||||
|
- Layout Studio for collages/posters with 1–12 images; optional OpenAI-compatible layout planning and source-driven automatic collages.
|
||||||
|
- Device-bound schedules, ordered/random playlists, temporary priority overrides, restore and persistent operation history.
|
||||||
|
- Read-only NAS folders, Synology Photos person filtering, WebDAV and optional cloud-drive connectors. Each source has its own folder and filter settings. People filtering uses one shared Synology Photos sign-in; WebDAV and cloud-drive credentials belong to their respective sources.
|
||||||
|
- Optional weather, calendar, monitoring, AI, MQTT and webhook integrations. Provider configuration is required; an unconnected provider is not a working connection.
|
||||||
|
|
||||||
OpenAPI 3.x at /openapi.json; Swagger at /docs; stable /api/v1. Display/render/upload
|
Templates **render images**, including text-only templates. Choose a template, edit its data, generate a preview, then display it. Preview generation and saving template settings do not update the frame. Photo + Text and Daily Dashboard can include a selected local photo; other templates do not automatically choose one. Scheduled template jobs render afresh on each run. See [photo sources](docs/PHOTO_SOURCES.md), [automatic collages](docs/AUTOMATIC_COLLAGE.md) and [integration setup/limits](docs/EXTENSIONS.md).
|
||||||
return 202 + operation_id. Poll /api/v1/operations/{id}; completion requires matching
|
|
||||||
image ID and cloud synced flag. Idempotency-Key retained seven days. X-Request-ID
|
|
||||||
traces history. UNKNOWN writes block later mutations; read-only reconciliation
|
|
||||||
and explicit admin acknowledgement release the block, never replay a write.
|
|
||||||
The older /api/display route is retained and deprecated (same v1 payload).
|
|
||||||
See [external integration contract](docs/integrations/TICKTAR.md).
|
|
||||||
|
|
||||||
## Scheduler / Playback
|
Real weather uses the configured provider/location and is refreshed when rendered; it does not update an already displayed image by itself. Official KoKonna widgets are separate from Frame Flow templates and require optional vendor-account authorization. API-key access remains independent.
|
||||||
|
|
||||||
Cron (5 fields), daily, weekdays, weekends, date and temporary tasks; Shanghai time.
|
### Device integration and API
|
||||||
Use source {"type":"restore"} for explicit restore jobs. Unique job/slot and persistent
|
|
||||||
idempotency prevent duplicate dispatch. Overdue tasks >5 minutes are skipped rather
|
|
||||||
than unexpectedly overwriting artwork after downtime. State persists across restart.
|
|
||||||
Overrides use priority then recency; lower priorities wait without uploading.
|
|
||||||
If another app changes the frame, expired overrides do not overwrite its artwork.
|
|
||||||
Frame Flow playlists support ordered/random cloud image IDs and >=5-minute intervals;
|
|
||||||
only one enabled playlist per device. They pause for overrides/unknown writes.
|
|
||||||
Native cloud slideshow mode/interval are readable; membership/editing are unavailable
|
|
||||||
in the official API. Avoid having native and Frame Flow playback compete.
|
|
||||||
|
|
||||||
## Templates / 图片
|
```text
|
||||||
|
Providers → Templates / Renderers → Generated image
|
||||||
|
Web UI / Scheduler / REST API → DisplayService → FrameDeviceDriver → KoKonna
|
||||||
|
↓
|
||||||
|
SQLite: jobs, operations, history, overrides, assets
|
||||||
|
```
|
||||||
|
|
||||||
Seven JSON layout templates: daily-dashboard, weather, calendar, quote, photo-text,
|
Configure the device key privately through `.env` or a secret file. Start with `KOKONNA_MOCK=true` and `KOKONNA_WRITE_ENABLED=false`; after mock verification, connect read-only before explicitly enabling writes. Multi-device definitions use `config/devices.yml` and device-specific key references. Vendor code stays in `drivers/kokonna`; other applications use the same service API as the Web UI.
|
||||||
daily-poetry and system-alert, with color and grayscale profiles. Every template
|
|
||||||
renders an image, including templates that contain only text.
|
|
||||||
|
|
||||||
使用流程:选择模板 → 编辑数据 → 生成预览 → 显示到画框。生成预览只创建本地图片;
|
The public API is `/api/v1`, with OpenAPI at `/openapi.json` and Swagger UI at `/docs`. Display/render/upload operations return HTTP 202 and an operation ID; poll `/api/v1/operations/{id}` for the outcome. `Idempotency-Key` prevents duplicate dispatch, and `X-Request-ID` links requests to history. An uncertain write blocks subsequent mutations until read-only reconciliation or explicit administrator acknowledgement; it is never automatically replayed.
|
||||||
保存默认数据只保存配置,两者都不会更新设备。自动化模板任务每次运行重新生成图片。
|
|
||||||
|
|
||||||
- **照片与文字 / Photo + Text**:标题、中央照片区域、下方正文;与照片数据源任务的底部水印布局不同。
|
Ticktar integration is optional. Frame Flow has no runtime dependency on Ticktar and never accesses its database. See the [external integration contract](docs/integrations/TICKTAR.md).
|
||||||
- **家庭早报 / Daily Dashboard**:日期、天气、事项、一句话与所选照片区域。
|
|
||||||
- **天气 / Weather**:当前天气与三天预报;天气 JSON 留空时使用配置的 Provider。
|
|
||||||
- **日历、每日诗词、一句话、系统告警**:将相应信息排版为图片,不自动选择图库照片。
|
|
||||||
|
|
||||||
Photos use a local asset ID (`photo_id`); without a selected photo, a placeholder
|
### Storage and security
|
||||||
is rendered. Configure Open-Meteo and location coordinates in **Settings → Weather
|
|
||||||
source** for real weather. Forecasts are fetched on demand and cached for ten minutes;
|
|
||||||
unavailable/stale data is labeled explicitly. Weather remains static on the frame
|
|
||||||
until the next render and display, so use an Automation job for regular updates.
|
|
||||||
Official KoKonna widgets are a separate integration, not these local templates.
|
|
||||||
No unreliable lunar date is fabricated.
|
|
||||||
Contain preserves composition with margins; cover crops centrally; smart is an
|
|
||||||
edge-saliency heuristic. Always inspect preview; face-aware guarantees are not claimed.
|
|
||||||
Cloud uploads activate immediately, so gallery-only means **local staging**.
|
|
||||||
|
|
||||||
## Development / Testing
|
Docker persists `/data/frameflow.db`, images/generated/cache under `/data`, and private configuration/session files under `/config`. It runs as UID/GID 10333 with a read-only root filesystem, its own bridge network, `unless-stopped` restart policy and bounded stdout/stderr logs. No privileged mode, host network or Docker socket is required.
|
||||||
|
|
||||||
```sh
|
Passwords are hashed; browser mutations require CSRF protection. API keys and provider credentials stay server-side and must never enter Git or logs. CORS is disabled unless origins are explicitly configured. `/health` checks the service; `/ready` checks local dependencies without making cloud availability a restart trigger. See [public repository privacy](docs/PUBLICATION.md), [LICENSE](LICENSE) and [NOTICE](NOTICE.md).
|
||||||
|
|
||||||
|
KoKonna is a supported integration. This project is not affiliated with or endorsed by KoKonna.
|
||||||
|
|
||||||
|
### Development and known limitations
|
||||||
|
|
||||||
|
```bash
|
||||||
.venv/bin/python -m pip install -e '.[test]'
|
.venv/bin/python -m pip install -e '.[test]'
|
||||||
.venv/bin/python -m pytest -q
|
|
||||||
.venv/bin/python -m ruff check pigway_frame_flow tests scripts
|
.venv/bin/python -m ruff check pigway_frame_flow tests scripts
|
||||||
.venv/bin/python -m ruff format --check pigway_frame_flow tests scripts
|
.venv/bin/python -m ruff format --check pigway_frame_flow tests scripts
|
||||||
.venv/bin/python -m mypy pigway_frame_flow
|
.venv/bin/python -m mypy pigway_frame_flow
|
||||||
|
.venv/bin/python -m pytest -q
|
||||||
.venv/bin/python -m pip_audit -r requirements.lock --no-deps --disable-pip
|
.venv/bin/python -m pip_audit -r requirements.lock --no-deps --disable-pip
|
||||||
```
|
```
|
||||||
|
|
||||||
Tests mock every cloud request; no real-device writes. scripts/ui-smoke.cjs runs an
|
Tests mock cloud/device calls. CI also verifies an isolated Docker build, readiness, smoke tests, restart and cleanup. External fork PRs do not execute on the production-capable NAS runner.
|
||||||
isolated headless browser and checks settings.mock before acting. CI builds AMD64,
|
|
||||||
validates Compose, starts a container, checks health/ready and restarts for persistence.
|
|
||||||
|
|
||||||
## Known Limitations / 已知边界
|
Cloud synchronization does not prove the physical pixels refreshed. KoKonna cloud uploads activate immediately, so upload-only uses local staging. Native slideshow membership editing is unavailable; avoid running native and Frame Flow playback simultaneously. Smart cropping is a saliency heuristic, not guaranteed face detection. The service uses one worker and is not designed for multiple replicas. Browser OAuth, AI daily-art scheduling, additional calendar recurrence features and more device drivers remain roadmap items.
|
||||||
|
|
||||||
Cloud acknowledgements do not prove physical display pixels. Model fields may be
|
Related projects: [PIGWay Raspberry Pi Agent](https://tea.pigway.com/way/pigway-raspberry-pi-agent) · [PIGWay Device Console](https://tea.pigway.com/way/pigway-device-console) · [PIGWay Yahboom Cooling HAT](https://tea.pigway.com/way/pigway-yahboom-cooling-hat)
|
||||||
omitted and are explicitly marked configured. No native slideshow membership API,
|
|
||||||
no cloud upload-only API, no automatic retries after uncertain writes. Opt-in local retention protects manual uploads, stars and active references; its quota is a cleanup target, not a hard disk limit. Rendering assets are local, limited
|
|
||||||
to 25M pixels/20 MiB. This release uses a single worker and is not multi-replica.
|
|
||||||
Gallery reads have no pagination because upstream documents none. Web UI hides
|
|
||||||
secrets and lazy-loads thumbnails; generating a first thumbnail fetches one original.
|
|
||||||
Scoped client provisioning and bounded signed webhook delivery are available in Connections. Docker build/NAS
|
|
||||||
status is recorded honestly in docs/ACCEPTANCE.md.
|
|
||||||
|
|
||||||
## Roadmap
|
|
||||||
|
|
||||||
Browser OAuth login, AI daily-art scheduling, custom ICS timezones/EXRULE and additional hardware-specific adapters remain pending. MQTT, bounded recurrence, token refresh, transition events and single-image AI generation are optional capabilities. See [optional capabilities and exact limits](docs/EXTENSIONS.md).
|
|
||||||
|
|
||||||
## Layout Studio and optional integrations
|
|
||||||
|
|
||||||
Bilingual Layout Studio imports 1–12 images, edits bounded regions and renders a collage or poster. Optional OpenAI-compatible AI plans receive text and dimensions only. Connections configures provider credentials, calendars/state, retention, client scopes and webhooks. Photo Sources includes NAS, WebDAV, Google Drive, AliPan and Baidu readers. Authorization is separate from implementation; unconnected providers return explicit errors. See [setup and limitations](docs/EXTENSIONS.md).
|
|
||||||
|
|
||||||
## Template editing
|
|
||||||
|
|
||||||
Templates provide bilingual form fields, event lists, local photo selection, advanced
|
|
||||||
JSON, color/grayscale previews, persistent defaults and reset to built-in defaults.
|
|
||||||
Changing content invalidates the previous preview. Weather uses the labeled Mock
|
|
||||||
provider until a real provider is configured. Live display controls stay disabled
|
|
||||||
until real writes are separately approved.
|
|
||||||
|
|
||||||
Browser smoke tests use a disposable Mock account via FRAME_FLOW_TEST_USERNAME
|
|
||||||
and FRAME_FLOW_TEST_PASSWORD; never run the mutation smoke suite against live devices.
|
|
||||||
|
|
||||||
## Current content and completed page workflows
|
|
||||||
|
|
||||||
Dashboard displays the actual current image and recorded content source. Frame Flow
|
|
||||||
stores immutable template/data/profile snapshots when it renders an asset and maps
|
|
||||||
successful upload results to the device/image ID. The current-content endpoint
|
|
||||||
matches the live device image ID; vendor images with no recorded source remain
|
|
||||||
explicitly unknown. Switching externally never makes the previous template appear
|
|
||||||
as the current one. Restore also restores the matching content provenance.
|
|
||||||
|
|
||||||
Templates can load the current recorded template or continue editing a generated
|
|
||||||
local image. They support direct photo import and protected image downloads.
|
|
||||||
Gallery provides search, sorting, dimensions and downloads. Display confirmation
|
|
||||||
supports duration, priority and restoration. History includes operation details.
|
|
||||||
Automation offers content pickers, template profiles, previews and manual execution;
|
|
||||||
playlists offer gallery image checkboxes. Real writes remain blocked by the server
|
|
||||||
regardless of the UI controls.
|
|
||||||
|
|
||||||
Settings persists weather coordinates/provider and image URL host allowlists in
|
|
||||||
SQLite. Open-Meteo provides current model weather and a three-day forecast, cached
|
|
||||||
for ten minutes on demand. Network failures show unavailable/stale data and use a
|
|
||||||
two-minute backoff, without replacing it with fictitious live data. Default remains
|
|
||||||
Mock until configured in Settings. Open-Meteo attribution is included in the UI and
|
|
||||||
weather/dashboard renders. Image URL import is HTTPS-only with explicit hostnames,
|
|
||||||
public-address validation and pinned DNS; redirects and private addresses are blocked.
|
|
||||||
|
|
||||||
Additional v1 endpoints: `/devices/{id}/current-content`, `/assets/{id}/source`,
|
|
||||||
`/providers/weather`, `/settings/weather`, `/settings/image-url`, `/jobs/{id}`,
|
|
||||||
`/jobs/{id}/preview`, `/jobs/{id}/run` (all under `/api/v1`). Existing contracts remain
|
|
||||||
compatible; new endpoints are included in generated OpenAPI and contract tests.
|
|
||||||
|
|
||||||
## Daily Poetry / 每日诗词
|
|
||||||
|
|
||||||
The daily-poetry template includes 20 public-domain classical Chinese poems, selected deterministically by Shanghai date, or manually. Create a daily job from its editor; new poetry jobs are paused by default until you enable them. Custom title, author and verses are editable. This is an independent Frame Flow content provider, not the KoKonna mini-program subscription. Official public API does not expose mini-program subscription/template settings.
|
|
||||||
|
|
||||||
每日诗词支持按上海日期选诗、手选 20 首古典诗词、自定义文本以及每日任务。模板显示操作使用统一上传/显示服务;真实写入须开启 KOKONNA_WRITE_ENABLED,结果未知不会自动重试。官方小程序原有每日诗词订阅不能通过当前公开 API 查询或修改。
|
|
||||||
|
|
||||||
|
|
||||||
### 官方账号连接 / Official account connection
|
|
||||||
|
|
||||||
在 Templates → 官方小组件中,由管理员输入 KoKonna 官方账号和密码,查询账号下
|
|
||||||
的设备后手动关联当前 Frame Flow 设备。此流程不绑定或解绑云端设备,也不改变
|
|
||||||
图片或订阅。现有 API Key 接入继续负责设备、图库和显示能力。
|
|
||||||
|
|
||||||
密码不保存;会话与关联信息保存在 `/config/official-{device_id}.secret`,权限 0600。
|
|
||||||
容器重启可恢复连接。会话过期需要重新登录;断开连接会清除本地会话,不撤销
|
|
||||||
官方服务器上的其他登录。局域网访问沿用现有部署方式。
|
|
||||||
|
|
||||||
Official account connection is admin-only and separate from API Key access.
|
|
||||||
Login, device discovery, local association and disconnect are available through
|
|
||||||
`/api/v1/devices/{device_id}/official/connection`. Passwords are never persisted;
|
|
||||||
server-side sessions are stored as restricted secret files. No official widget
|
|
||||||
mutation or other extra RPC write is enabled by connecting.
|
|
||||||
|
|
||||||
### Photo sources / 照片数据源
|
|
||||||
|
|
||||||
Gallery supports read-only NAS folders and HTTPS WebDAV sources, random photo
|
|
||||||
preview, and device-bound scheduled random photos. Source definitions are persisted
|
|
||||||
in SQLite. See [setup and limits](docs/PHOTO_SOURCES.md).
|
|
||||||
NAS 本地目录需要显式只读挂载;网盘先支持通用 WebDAV,也可使用同步到 NAS 的目录。
|
|
||||||
|
|
||||||
### Build networking and cache
|
|
||||||
|
|
||||||
The Dockerfile retains the pinned Python base, locked Python dependencies,
|
|
||||||
`fonts-noto-cjk`, Debian repository signature checks, and offline artifact
|
|
||||||
SHA256 verification. Both production and CI use `scripts/build-verify.sh`,
|
|
||||||
which enables BuildKit and retains `docker compose build --pull`.
|
|
||||||
|
|
||||||
APT mirror hosts are configurable through `DEBIAN_MIRROR` and
|
|
||||||
`DEBIAN_SECURITY_MIRROR` (hosts only, without scheme or path). Defaults are
|
|
||||||
`deb.debian.org`; HTTPS is used for both Debian and security repositories.
|
|
||||||
For mainland-China NAS builds, use the shared profile:
|
|
||||||
|
|
||||||
```sh
|
|
||||||
. ./deploy/build-cn.env
|
|
||||||
./scripts/build-verify.sh
|
|
||||||
```
|
|
||||||
|
|
||||||
CI loads this same profile, using Tsinghua TUNA for both repositories unless
|
|
||||||
Gitea repository variables `DEBIAN_MIRROR` / `DEBIAN_SECURITY_MIRROR` override
|
|
||||||
it. Production may also set the two hosts directly in `.env` when calling the
|
|
||||||
build script without the profile. An alternate mainland mirror is
|
|
||||||
`mirrors.ustc.edu.cn`; availability and throughput depend on the Runner network.
|
|
||||||
No fallback disables signature verification or removes packages.
|
|
||||||
|
|
||||||
Layer order stays: pinned base → APT/font dependencies → `requirements.lock`
|
|
||||||
→ pip dependencies → application/vendor source → build metadata.
|
|
||||||
A source-only change therefore reuses the APT and pip layers, provided the
|
|
||||||
same builder, base digest, mirror arguments, and optional offline artifacts
|
|
||||||
are used. Changing the lockfile rebuilds pip and later layers, not APT.
|
|
||||||
Changing the mirror or APT instructions rebuilds APT and later layers.
|
|
||||||
|
|
||||||
Previously an APT layer miss redownloaded indexes/packages, and pip used
|
|
||||||
`--no-cache-dir`. Now locked BuildKit mounts retain APT indexes, downloaded
|
|
||||||
`.deb` files, and pip downloads/wheels outside the final image. Debian's
|
|
||||||
`docker-clean` hook is disabled so it cannot discard cached packages.
|
|
||||||
Re-executed APT steps still run `apt-get update` and validate repository
|
|
||||||
signatures; cached packages and pip artifacts can avoid repeat large downloads.
|
|
||||||
The initial build after this Dockerfile change will miss dependency layers;
|
|
||||||
subsequent builds benefit. No measured speedup is claimed before CI completes.
|
|
||||||
|
|
||||||
Caches belong to the Docker builder, not the ephemeral CI workspace. Keep the
|
|
||||||
NAS Runner's builder storage across jobs; removing the builder, pruning caches,
|
|
||||||
or using a fresh Docker daemon loses the benefit. Cache mounts are disposable:
|
|
||||||
an empty cache still builds correctly. `--pull` remains enabled; a pinned base
|
|
||||||
digest check alone does not invalidate dependency layers. To deliberately
|
|
||||||
refresh installed APT versions, use `docker compose build --pull --no-cache`.
|
|
||||||
|
|
||||||
### CI with a host Docker socket
|
|
||||||
|
|
||||||
Run `python scripts/ci-compose-verify.py` after loading the build mirror profile.
|
|
||||||
The script derives a temporary Compose document from production settings, with
|
|
||||||
an absolute client-side build context, a UUID project name, a unique CI image
|
|
||||||
tag, and project-scoped `data` / `config` named volumes. It removes production
|
|
||||||
bind mounts, the fixed container name, host ports, and the production `.env`
|
|
||||||
reference. A fresh test token, mock driver, and disabled device writes are
|
|
||||||
explicitly configured. Docker initializes empty named volumes from the image's
|
|
||||||
owned `/data` and `/config` directories; the service remains UID/GID 10333.
|
|
||||||
|
|
||||||
Build contexts are sent by the Docker client, so the job workspace can remain
|
|
||||||
inside the job container. Runtime storage is managed by the daemon; no matching
|
|
||||||
NAS host `/workspace` directory is needed. HTTP readiness and the unmodified
|
|
||||||
nine-endpoint smoke script run inside the service with `compose exec -T`.
|
|
||||||
Restart is followed by another readiness check and the same smoke test.
|
|
||||||
|
|
||||||
A `finally` block removes the test containers, network, volumes, and unique
|
|
||||||
image tag on success or failure. The workflow records the private temporary
|
|
||||||
Compose path in `GITHUB_ENV` and repeats cleanup in an `always()` step, covering
|
|
||||||
normal cancellation/interruption. Failed cleanup retains the manifest so the
|
|
||||||
fallback can retry. Abrupt host/daemon loss or a forcibly terminated entire job
|
|
||||||
can prevent both cleanup paths; no CI script can guarantee cleanup in that case.
|
|
||||||
No global prune or production resource removal is performed. Keep builder
|
|
||||||
caches: only the run-specific image tag is removed.
|
|
||||||
|
|
||||||
### CI Job pip indexes versus Docker build indexes
|
|
||||||
|
|
||||||
The Job bootstrap runs `python scripts/ci-install.py` before Ruff/mypy/tests.
|
|
||||||
It needs only the Python standard library, so it runs before PyYAML or tooling
|
|
||||||
is installed. `CI_PIP_INDEX_URL` and `CI_PIP_FALLBACK_INDEX_URL` are optional
|
|
||||||
Gitea repository variables. Defaults are the TUNA HTTPS PyPI simple endpoint
|
|
||||||
and official `https://pypi.org/simple`. Each is attempted separately; the
|
|
||||||
fallback repeats the unchanged editable `.[test]` installation, including
|
|
||||||
PEP 517 build isolation and `setuptools>=75`. No simultaneous extra index is
|
|
||||||
used, no build dependency is removed, and both failures fail CI.
|
|
||||||
|
|
||||||
Logs show inherited index/config/proxy hosts and the selected index host for
|
|
||||||
each attempt, with URL credentials and query strings removed. Bootstrap
|
|
||||||
disables inherited pip config files via `PIP_CONFIG_FILE=/dev/null`, explicitly
|
|
||||||
sets the selected index, and clears no-index/extra-index/find-links, insecure
|
|
||||||
trusted-host, and no-build-isolation environment settings. Constraints, TLS
|
|
||||||
certificate environment settings, and proxy settings remain in effect.
|
|
||||||
|
|
||||||
These `CI_PIP_*` settings apply only to the Job's pip install. They are not
|
|
||||||
passed into Docker build arguments or persisted into the production image.
|
|
||||||
The Dockerfile keeps its own cached/offline dependency installation and logs
|
|
||||||
the Docker pip index host for online installs. Debian mirror variables affect
|
|
||||||
APT only and are loaded later in the Docker verification step.
|
|
||||||
|
|
||||||
If dependency installation fails, the always() cleanup step still executes.
|
|
||||||
It skips the Python/PyYAML cleanup script when no CI Compose manifest exists,
|
|
||||||
as no Docker verification resources have been created at that point.
|
|
||||||
|
|
||||||
Production CD: [safe trial, configuration, and rollback](docs/deployment/GITEA_CD.md).
|
|
||||||
|
|||||||
@@ -0,0 +1,95 @@
|
|||||||
|
# Pigway Frame Flow
|
||||||
|
|
||||||
|
简体中文 | [English](README.md)
|
||||||
|
|
||||||
|
轻量、自托管的智能画框自动化平台,可独立运行在 NAS 或服务器上,提供自己的 Web 界面、图库、图片渲染、调度器和 REST API。KoKonna 是支持的设备集成之一;外部应用无需持有它的凭据或引入其 SDK。
|
||||||
|
|
||||||
|
### 安装
|
||||||
|
|
||||||
|
使用 Docker Compose 部署。当前默认配置与已验证平台为 AMD64:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cp .env.example .env
|
||||||
|
# 设置强 FRAME_FLOW_TOKEN;首次保持 mock=true、writes=false。
|
||||||
|
chmod 600 .env
|
||||||
|
mkdir -p data/images data/generated data/cache config
|
||||||
|
sudo chown -R 10333:10333 data config
|
||||||
|
./scripts/build-verify.sh
|
||||||
|
# 创建网页管理员账号,密码通过交互输入。
|
||||||
|
docker compose run --rm --no-deps -e PYTHONPATH=/app \
|
||||||
|
-v "$PWD/scripts:/bootstrap:ro" --entrypoint python pigway-frame-flow \
|
||||||
|
/bootstrap/create-account.py --username admin --config-dir /config
|
||||||
|
docker compose up -d
|
||||||
|
```
|
||||||
|
|
||||||
|
打开 `http://127.0.0.1:6005`,使用刚创建的账号登录。网页使用 HttpOnly 会话 Cookie,无需输入 API Token;勾选记住登录后会话有效期为 30 天,可在设置中修改密码或退出。`FRAME_FLOW_TOKEN` 用于外部 API 客户端鉴权,与 KoKonna API Key 分开。
|
||||||
|
|
||||||
|
默认端口只绑定本机回环地址。需要局域网访问时,显式将 `WEB_BIND` 设置为 NAS 的局域网地址,并通过 `WEB_PORT` 选择空闲端口。参见[群晖部署](docs/NAS.md)、[构建镜像源与缓存](docs/BUILDING.md)和 [Gitea 部署与回滚](docs/deployment/GITEA_CD.md)。不会自动修改防火墙、路由器或反向代理。
|
||||||
|
|
||||||
|
使用 Python 3.14 运行本地 Mock 演示:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
python3.14 -m venv .venv
|
||||||
|
.venv/bin/python -m pip install -r requirements.lock
|
||||||
|
.venv/bin/python scripts/create-account.py --username admin
|
||||||
|
.venv/bin/python scripts/run_local.py
|
||||||
|
```
|
||||||
|
|
||||||
|
演示强制使用 Mock,并关闭设备写入。数据与配置保存在 `data/`、`config/`,重启后保留。
|
||||||
|
|
||||||
|
Synology Photos 可使用独立的 API 来源,无需 `/photos` 或 NFS 挂载;支持共享 / 当前账号个人空间、人物筛选和按需 XL 预览缓存。原图下载不在本次已验证支持范围内。见 [API 来源与 Ubuntu 候选迁移说明](docs/SYNOLOGY_PHOTOS_API.md)。
|
||||||
|
|
||||||
|
### 功能与边界
|
||||||
|
|
||||||
|
- 中英文 Web 界面、深浅色主题、账号登录、设备面板与图片预览。
|
||||||
|
- NAS 本地图库和 KoKonna 云端图库;星标、来源/任务筛选及批量操作位于本地图库,上传到云端并显示需单独操作。
|
||||||
|
- 保持比例的 contain/cover/smart 图片转换,彩色/灰度模式与照片数据源的横竖方向选择。
|
||||||
|
- 七种模板:家庭早报、天气、日历、一句话、照片与文字、每日诗词、系统告警。
|
||||||
|
- 拼图工作室支持 1–12 张图片的拼图与海报;可选 OpenAI 兼容接口排版,以及从数据源自动选图拼接。
|
||||||
|
- 绑定设备的定时任务、顺序/随机播放列表、带优先级的临时覆盖、恢复与持久化操作历史。
|
||||||
|
- 只读 NAS 文件夹、Synology Photos 人物筛选、WebDAV 和可选网盘连接器;每个数据源独立配置、独立授权。
|
||||||
|
- 可选天气、日历、监控、AI、MQTT 与 Webhook 集成。需要配置对应 Provider;尚未授权的数据源不会被当作已连接。
|
||||||
|
|
||||||
|
模板会**生成图片**,纯文字模板也是如此。使用顺序是:选择模板 → 编辑内容 → 生成预览 → 显示到画框。生成预览和保存模板设置都不会更新画框。“照片与文字”和“家庭早报”可以包含指定的本地照片,其他模板不会自动选图;定时模板任务每次运行会重新渲染。参见[照片数据源](docs/PHOTO_SOURCES.md)、[自动拼图](docs/AUTOMATIC_COLLAGE.md)和[集成配置及限制](docs/EXTENSIONS.md)。
|
||||||
|
|
||||||
|
天气使用配置的服务和地点,在渲染时更新,不会自行刷新已显示的图片。KoKonna 官方小组件与 Frame Flow 模板是两项独立能力;使用官方小组件需要额外授权厂商账号,API Key 接入仍可单独使用。
|
||||||
|
|
||||||
|
### 设备集成与 API
|
||||||
|
|
||||||
|
```text
|
||||||
|
Provider → 模板 / Renderer → 生成图片
|
||||||
|
Web UI / Scheduler / REST API → DisplayService → FrameDeviceDriver → KoKonna
|
||||||
|
↓
|
||||||
|
SQLite:任务、操作、历史、覆盖状态、图片
|
||||||
|
```
|
||||||
|
|
||||||
|
设备 Key 通过私有 `.env` 或 Secret 文件配置。首次保持 `KOKONNA_MOCK=true`、`KOKONNA_WRITE_ENABLED=false`,Mock 验证后先只读连接,再明确开启写入。多设备使用 `config/devices.yml` 配置,每台设备引用自己的 Key。厂商代码位于 `drivers/kokonna`;Web 界面与外部程序使用相同业务服务。
|
||||||
|
|
||||||
|
正式 API 为 `/api/v1`,OpenAPI 位于 `/openapi.json`,Swagger 位于 `/docs`。显示、渲染、上传返回 HTTP 202 和操作 ID,通过 `/api/v1/operations/{id}` 查询结果。`Idempotency-Key` 防止重复派发,`X-Request-ID` 串联请求与历史。写入结果不确定时会阻止后续修改,必须只读核对或由管理员明确确认,不会自动重放写请求。
|
||||||
|
|
||||||
|
Ticktar 集成为可选项,Frame Flow 不依赖 Ticktar 启动,也不访问其数据库。参见[外部集成契约](docs/integrations/TICKTAR.md)。
|
||||||
|
|
||||||
|
### 存储与安全
|
||||||
|
|
||||||
|
Docker 持久化 `/data/frameflow.db`、`/data` 下的图片/生成文件/缓存,以及 `/config` 下的私有配置和会话文件。容器以 UID/GID 10333 运行,根文件系统只读,使用独立桥接网络、`unless-stopped` 重启策略和有大小限制的标准输出日志;不需要 privileged、host network 或 Docker socket。
|
||||||
|
|
||||||
|
账号密码保存为哈希,网页修改操作有 CSRF 校验。API Key 和 Provider 凭据仅留在服务端,不得提交 Git 或写入日志。CORS 默认不开启,需明确配置来源。`/health` 检查服务自身,`/ready` 检查本地依赖,不以云端可用性触发重启。参见[公开仓库隐私](docs/PUBLICATION.md)、[LICENSE](LICENSE) 和 [NOTICE](NOTICE.md)。
|
||||||
|
|
||||||
|
KoKonna 是支持的设备集成。本项目与 KoKonna 无隶属关系,也不代表其官方认可。
|
||||||
|
|
||||||
|
### 开发与已知限制
|
||||||
|
|
||||||
|
```bash
|
||||||
|
.venv/bin/python -m pip install -e '.[test]'
|
||||||
|
.venv/bin/python -m ruff check pigway_frame_flow tests scripts
|
||||||
|
.venv/bin/python -m ruff format --check pigway_frame_flow tests scripts
|
||||||
|
.venv/bin/python -m mypy pigway_frame_flow
|
||||||
|
.venv/bin/python -m pytest -q
|
||||||
|
.venv/bin/python -m pip_audit -r requirements.lock --no-deps --disable-pip
|
||||||
|
```
|
||||||
|
|
||||||
|
测试使用 Mock 云端/设备调用;CI 还验证隔离的 Docker 构建、就绪检查、smoke test、重启与清理。外部 Fork PR 不会在可访问生产环境的 NAS Runner 上执行。
|
||||||
|
|
||||||
|
云端同步不等于已确认物理屏幕刷新。KoKonna 云端上传会立即切换,因此“仅上传”使用本地暂存。官方接口不支持编辑原生轮播成员,应避免原生轮播与 Frame Flow 播放同时运行。smart 裁切采用显著性启发式,不保证识别人脸。当前服务使用单 Worker,不面向多副本部署。浏览器 OAuth、AI 每日艺术调度、更多日历重复规则及设备驱动仍属于后续计划。
|
||||||
|
|
||||||
|
相关项目:[PIGWay Raspberry Pi Agent](https://tea.pigway.com/way/pigway-raspberry-pi-agent) · [PIGWay Device Console](https://tea.pigway.com/way/pigway-device-console) · [PIGWay Yahboom Cooling HAT](https://tea.pigway.com/way/pigway-yahboom-cooling-hat)
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
# Reuse a reviewed image only when the locked Python dependencies are identical.
|
||||||
|
# For a fresh installation use the repository's main Dockerfile instead.
|
||||||
|
ARG BASE_IMAGE
|
||||||
|
FROM ${BASE_IMAGE} AS prepared
|
||||||
|
# Cleanup runs only in the disposable preparation stage.
|
||||||
|
USER 0
|
||||||
|
COPY requirements.lock /app/requirements.expected.lock
|
||||||
|
RUN python -c "from pathlib import Path; assert Path('/app/requirements.lock').read_bytes() == Path('/app/requirements.expected.lock').read_bytes(), 'Dependency lock changed; use the full Dockerfile'"
|
||||||
|
COPY pigway_frame_flow /app/pigway_frame_flow
|
||||||
|
COPY vendor /app/vendor
|
||||||
|
# Publish only the cleaned filesystem, without retaining build-stage layers.
|
||||||
|
RUN rm -rf /usr/local/lib/python*/site-packages/pip \
|
||||||
|
/usr/local/lib/python*/site-packages/pip-*.dist-info \
|
||||||
|
/usr/local/lib/python*/ensurepip \
|
||||||
|
&& rm -f /usr/local/bin/pip /usr/local/bin/pip[0-9]* \
|
||||||
|
&& find / -name .DS_Store -type f -delete
|
||||||
|
|
||||||
|
FROM scratch
|
||||||
|
COPY --from=prepared / /
|
||||||
|
ENV PATH=/usr/local/bin:/usr/local/sbin:/usr/sbin:/usr/bin:/sbin:/bin LANG=C.UTF-8
|
||||||
|
ENV PYTHONDONTWRITEBYTECODE=1 PYTHONUNBUFFERED=1 TZ=Asia/Shanghai \
|
||||||
|
DATA_DIR=/data CONFIG_DIR=/config
|
||||||
|
WORKDIR /app
|
||||||
|
USER 10333:10333
|
||||||
|
EXPOSE 18787
|
||||||
|
HEALTHCHECK --interval=30s --timeout=5s --start-period=20s --retries=3 \
|
||||||
|
CMD python -c "import urllib.request; urllib.request.urlopen('http://127.0.0.1:18787/health',timeout=3)"
|
||||||
|
CMD ["python", "-m", "uvicorn", "pigway_frame_flow.main:app", "--host", "0.0.0.0", "--port", "18787", "--workers", "1", "--no-access-log"]
|
||||||
|
ARG BUILD_COMMIT
|
||||||
|
ARG BUILD_TIME
|
||||||
|
ENV BUILD_COMMIT=$BUILD_COMMIT BUILD_TIME=$BUILD_TIME
|
||||||
|
LABEL org.opencontainers.image.title="Pigway Frame Flow" org.opencontainers.image.version="0.1.9" org.opencontainers.image.revision=$BUILD_COMMIT
|
||||||
@@ -0,0 +1,51 @@
|
|||||||
|
# Candidate only. Never start alongside a live-writing NAS instance.
|
||||||
|
name: pigway-frame-flow
|
||||||
|
services:
|
||||||
|
pigway-frame-flow:
|
||||||
|
image: ${FRAME_FLOW_IMAGE:?Set the verified immutable image reference}
|
||||||
|
container_name: pigway-frame-flow
|
||||||
|
platform: linux/amd64
|
||||||
|
restart: unless-stopped
|
||||||
|
init: true
|
||||||
|
user: "10333:10333"
|
||||||
|
ports:
|
||||||
|
- "${FRAME_FLOW_BIND:-192.0.2.10}:81:18787"
|
||||||
|
env_file: ${FRAME_FLOW_ENV_FILE:-/srv/pigway/apps/pigway-frame-flow/.env}
|
||||||
|
environment:
|
||||||
|
TZ: Asia/Shanghai
|
||||||
|
DATA_DIR: /data
|
||||||
|
CONFIG_DIR: /config
|
||||||
|
FRAME_FLOW_STORAGE_NAME: Ubuntu Server
|
||||||
|
SYNOLOGY_PHOTOS_CACHE_BYTES: ${SYNOLOGY_PHOTOS_CACHE_BYTES:-268435456}
|
||||||
|
# Migration starts read-only. Activation is a separate authorized action.
|
||||||
|
KOKONNA_WRITE_ENABLED: "false"
|
||||||
|
PYTHONDONTWRITEBYTECODE: "1"
|
||||||
|
TMPDIR: /data/tmp
|
||||||
|
volumes:
|
||||||
|
- type: bind
|
||||||
|
source: /srv/pigway/apps/pigway-frame-flow/data
|
||||||
|
target: /data
|
||||||
|
bind:
|
||||||
|
create_host_path: false
|
||||||
|
- type: bind
|
||||||
|
source: /srv/pigway/apps/pigway-frame-flow/config
|
||||||
|
target: /config
|
||||||
|
bind:
|
||||||
|
create_host_path: false
|
||||||
|
read_only: true
|
||||||
|
cap_drop: [ALL]
|
||||||
|
security_opt: [no-new-privileges:true]
|
||||||
|
pids_limit: 100
|
||||||
|
mem_limit: 768m
|
||||||
|
healthcheck:
|
||||||
|
test: [CMD, python, -c, "import urllib.request; urllib.request.urlopen('http://127.0.0.1:18787/ready',timeout=3)"]
|
||||||
|
interval: 30s
|
||||||
|
timeout: 5s
|
||||||
|
start_period: 20s
|
||||||
|
retries: 3
|
||||||
|
# Docker data-root and container logs must reside on the T7 too.
|
||||||
|
logging:
|
||||||
|
driver: json-file
|
||||||
|
options:
|
||||||
|
max-size: 10m
|
||||||
|
max-file: "3"
|
||||||
@@ -1,14 +1,6 @@
|
|||||||
# Opt-in read-only photo mount. Set NAS_PHOTOS_DIR to the actual NAS folder.
|
# Retired: filesystem photo mounts are forbidden. Use Photos API sources.
|
||||||
|
# This compatibility filename intentionally grants no additional host access.
|
||||||
services:
|
services:
|
||||||
pigway-frame-flow:
|
pigway-frame-flow:
|
||||||
environment:
|
environment:
|
||||||
PHOTO_ROOT: /photos
|
SYNOLOGY_PHOTOS_CACHE_BYTES: ${SYNOLOGY_PHOTOS_CACHE_BYTES:-268435456}
|
||||||
group_add:
|
|
||||||
- "${NAS_PHOTOS_GID:-10333}"
|
|
||||||
volumes:
|
|
||||||
- type: bind
|
|
||||||
source: ${NAS_PHOTOS_DIR:?Set NAS_PHOTOS_DIR to your existing photo directory}
|
|
||||||
target: /photos
|
|
||||||
read_only: true
|
|
||||||
bind:
|
|
||||||
create_host_path: false
|
|
||||||
|
|||||||
+2
-1
@@ -17,12 +17,13 @@ services:
|
|||||||
init: true
|
init: true
|
||||||
user: "10333:10333"
|
user: "10333:10333"
|
||||||
ports:
|
ports:
|
||||||
- "${WEB_BIND:-127.0.0.1}:${WEB_PORT:-18787}:18787"
|
- "${WEB_BIND:-127.0.0.1}:${WEB_PORT:-6005}:18787"
|
||||||
env_file: .env
|
env_file: .env
|
||||||
environment:
|
environment:
|
||||||
TZ: Asia/Shanghai
|
TZ: Asia/Shanghai
|
||||||
DATA_DIR: /data
|
DATA_DIR: /data
|
||||||
CONFIG_DIR: /config
|
CONFIG_DIR: /config
|
||||||
|
FRAME_FLOW_STORAGE_NAME: ${FRAME_FLOW_STORAGE_NAME:-NAS}
|
||||||
volumes:
|
volumes:
|
||||||
- ./data:/data
|
- ./data:/data
|
||||||
- ./config:/config
|
- ./config:/config
|
||||||
|
|||||||
@@ -0,0 +1,55 @@
|
|||||||
|
# Automatic collage
|
||||||
|
|
||||||
|
The navigation starts with Dashboard, followed by Gallery, Photo Sources, Upload,
|
||||||
|
Templates, Layout Studio, Automation, Playlists, History, Connections and Settings.
|
||||||
|
|
||||||
|
## Web workflow / 界面操作
|
||||||
|
|
||||||
|
在「拼图」选择照片来源与数量(1–12),填写可选标题或排版要求,点击
|
||||||
|
「随机选图并生成预览」。默认使用启用的数据源;没有数据源时使用本地上传照片。
|
||||||
|
AI 只接收图片尺寸、内部资产 ID 和排版文字,不发送照片。
|
||||||
|
AI 未配置或请求失败会明确报错,不会偷偷切换引擎;取消 AI 勾选可用自动网格。
|
||||||
|
预览不会上传或切换画框,确认效果后再点「显示到画框」。
|
||||||
|
|
||||||
|
Choose a source and count, then create a preview. Only dimensions, asset IDs and
|
||||||
|
layout instructions are sent to AI. AI configuration/errors are explicit; uncheck
|
||||||
|
AI for deterministic grid layout. Preview never changes the frame. Canvas
|
||||||
|
orientation follows the target device. Manual layout is under Advanced.
|
||||||
|
|
||||||
|
「创建自动化任务」保存来源和数量,而不是固定图片列表。任务初始暂停,
|
||||||
|
请在自动化中编辑执行时间后启用。每次运行重新随机选图,但不同运行之间可能重复;
|
||||||
|
单次不重复选同一照片。照片不足时失败,不重复图片凑数。
|
||||||
|
NAS 来源继续使用人物、方向与质量筛选;一次最多检查数量的五倍候选图片。
|
||||||
|
输入图缓存与生成图在 NAS;原始 NAS 照片不会被修改或删除。
|
||||||
|
定时拼图沿用云库每任务保留最近一张成功图的策略,下一张确认成功前不删除上一张。
|
||||||
|
|
||||||
|
Create automation stores the source/count, initially paused. Edit its schedule
|
||||||
|
and enable it. Each execution selects new candidates; repeats across executions
|
||||||
|
are possible. Too few usable photos fails before upload. Existing unknown-write,
|
||||||
|
restoration and cloud-retention safeguards apply.
|
||||||
|
|
||||||
|
## Public API
|
||||||
|
|
||||||
|
`POST /api/v1/render` accepts this additive content type, returning HTTP 202 and
|
||||||
|
an operation ID. `POST /api/v1/display` uses the same content inside its existing
|
||||||
|
request envelope. Scheduler `source` accepts the same object; job previews are
|
||||||
|
read-only.
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"type": "auto_collage",
|
||||||
|
"source_id": "nas-photos",
|
||||||
|
"count": 4,
|
||||||
|
"title": "Our moments",
|
||||||
|
"orientation": "auto",
|
||||||
|
"style": "grid",
|
||||||
|
"use_ai": true,
|
||||||
|
"prompt": "Feature one photo with smaller supporting photos",
|
||||||
|
"profile": "color"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
`source_id: null` chooses local uploaded assets (generated and cache images are
|
||||||
|
excluded). AI configuration is shared with existing Layout Studio. No new API key
|
||||||
|
or vendor dependency is introduced. The OpenAPI contract test records the new
|
||||||
|
content schema while keeping all existing schema fields unchanged.
|
||||||
@@ -0,0 +1,103 @@
|
|||||||
|
# Build networking, cache and CI
|
||||||
|
|
||||||
|
### Build networking and cache
|
||||||
|
|
||||||
|
The Dockerfile retains the pinned Python base, locked Python dependencies,
|
||||||
|
`fonts-noto-cjk`, Debian repository signature checks, and offline artifact
|
||||||
|
SHA256 verification. Production uses `scripts/build-verify.sh`; CI uses `scripts/ci-compose-verify.py`.
|
||||||
|
Both build the same Dockerfile with BuildKit and retain `docker compose build --pull`.
|
||||||
|
|
||||||
|
APT mirror hosts are configurable through `DEBIAN_MIRROR` and
|
||||||
|
`DEBIAN_SECURITY_MIRROR` (hosts only, without scheme or path). Defaults are
|
||||||
|
`deb.debian.org`; HTTPS is used for both Debian and security repositories.
|
||||||
|
For mainland-China NAS builds, use the shared profile:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
. ./deploy/build-cn.env
|
||||||
|
./scripts/build-verify.sh
|
||||||
|
```
|
||||||
|
|
||||||
|
CI loads this same profile, using Tsinghua TUNA for both repositories unless
|
||||||
|
Gitea repository variables `DEBIAN_MIRROR` / `DEBIAN_SECURITY_MIRROR` override
|
||||||
|
it. Production may also set the two hosts directly in `.env` when calling the
|
||||||
|
build script without the profile. An alternate mainland mirror is
|
||||||
|
`mirrors.ustc.edu.cn`; availability and throughput depend on the Runner network.
|
||||||
|
No fallback disables signature verification or removes packages.
|
||||||
|
|
||||||
|
Layer order stays: pinned base → APT/font dependencies → `requirements.lock`
|
||||||
|
→ pip dependencies → application/vendor source → build metadata.
|
||||||
|
A source-only change therefore reuses the APT and pip layers, provided the
|
||||||
|
same builder, base digest, mirror arguments, and optional offline artifacts
|
||||||
|
are used. Changing the lockfile rebuilds pip and later layers, not APT.
|
||||||
|
Changing the mirror or APT instructions rebuilds APT and later layers.
|
||||||
|
|
||||||
|
Previously an APT layer miss redownloaded indexes/packages, and pip used
|
||||||
|
`--no-cache-dir`. Now locked BuildKit mounts retain APT indexes, downloaded
|
||||||
|
`.deb` files, and pip downloads/wheels outside the final image. Debian's
|
||||||
|
`docker-clean` hook is disabled so it cannot discard cached packages.
|
||||||
|
Re-executed APT steps still run `apt-get update` and validate repository
|
||||||
|
signatures; cached packages and pip artifacts can avoid repeat large downloads.
|
||||||
|
The initial build after this Dockerfile change will miss dependency layers;
|
||||||
|
subsequent builds benefit. No measured speedup is claimed before CI completes.
|
||||||
|
|
||||||
|
Caches belong to the Docker builder, not the ephemeral CI workspace. Keep the
|
||||||
|
NAS Runner's builder storage across jobs; removing the builder, pruning caches,
|
||||||
|
or using a fresh Docker daemon loses the benefit. Cache mounts are disposable:
|
||||||
|
an empty cache still builds correctly. `--pull` remains enabled; a pinned base
|
||||||
|
digest check alone does not invalidate dependency layers. To deliberately
|
||||||
|
refresh installed APT versions, use `docker compose build --pull --no-cache`.
|
||||||
|
|
||||||
|
### CI with a host Docker socket
|
||||||
|
|
||||||
|
Run `python scripts/ci-compose-verify.py` after loading the build mirror profile.
|
||||||
|
The script derives a temporary Compose document from production settings, with
|
||||||
|
an absolute client-side build context, a UUID project name, a unique CI image
|
||||||
|
tag, and project-scoped `data` / `config` named volumes. It removes production
|
||||||
|
bind mounts, the fixed container name, host ports, and the production `.env`
|
||||||
|
reference. A fresh test token, mock driver, and disabled device writes are
|
||||||
|
explicitly configured. Docker initializes empty named volumes from the image's
|
||||||
|
owned `/data` and `/config` directories; the service remains UID/GID 10333.
|
||||||
|
|
||||||
|
Build contexts are sent by the Docker client, so the job workspace can remain
|
||||||
|
inside the job container. Runtime storage is managed by the daemon; no matching
|
||||||
|
NAS host `/workspace` directory is needed. HTTP readiness and the unmodified
|
||||||
|
nine-endpoint smoke script run inside the service with `compose exec -T`.
|
||||||
|
Restart is followed by another readiness check and the same smoke test.
|
||||||
|
|
||||||
|
A `finally` block removes the test containers, network, volumes, and unique
|
||||||
|
image tag on success or failure. The workflow records the private temporary
|
||||||
|
Compose path in `GITHUB_ENV` and repeats cleanup in an `always()` step, covering
|
||||||
|
normal cancellation/interruption. Failed cleanup retains the manifest so the
|
||||||
|
fallback can retry. Abrupt host/daemon loss or a forcibly terminated entire job
|
||||||
|
can prevent both cleanup paths; no CI script can guarantee cleanup in that case.
|
||||||
|
No global prune or production resource removal is performed. Keep builder
|
||||||
|
caches: only the run-specific image tag is removed.
|
||||||
|
|
||||||
|
### CI Job pip indexes versus Docker build indexes
|
||||||
|
|
||||||
|
The Job bootstrap runs `python scripts/ci-install.py` before Ruff/mypy/tests.
|
||||||
|
It needs only the Python standard library, so it runs before PyYAML or tooling
|
||||||
|
is installed. `CI_PIP_INDEX_URL` and `CI_PIP_FALLBACK_INDEX_URL` are optional
|
||||||
|
Gitea repository variables. Defaults are the TUNA HTTPS PyPI simple endpoint
|
||||||
|
and official `https://pypi.org/simple`. Each is attempted separately; the
|
||||||
|
fallback repeats the unchanged editable `.[test]` installation, including
|
||||||
|
PEP 517 build isolation and `setuptools>=75`. No simultaneous extra index is
|
||||||
|
used, no build dependency is removed, and both failures fail CI.
|
||||||
|
|
||||||
|
Logs show inherited index/config/proxy hosts and the selected index host for
|
||||||
|
each attempt, with URL credentials and query strings removed. Bootstrap
|
||||||
|
disables inherited pip config files via `PIP_CONFIG_FILE=/dev/null`, explicitly
|
||||||
|
sets the selected index, and clears no-index/extra-index/find-links, insecure
|
||||||
|
trusted-host, and no-build-isolation environment settings. Constraints, TLS
|
||||||
|
certificate environment settings, and proxy settings remain in effect.
|
||||||
|
|
||||||
|
These `CI_PIP_*` settings apply only to the Job's pip install. They are not
|
||||||
|
passed into Docker build arguments or persisted into the production image.
|
||||||
|
The Dockerfile keeps its own cached/offline dependency installation and logs
|
||||||
|
the Docker pip index host for online installs. Debian mirror variables affect
|
||||||
|
APT only and are loaded later in the Docker verification step.
|
||||||
|
|
||||||
|
If dependency installation fails, the always() cleanup step still executes.
|
||||||
|
It skips the Python/PyYAML cleanup script when no CI Compose manifest exists,
|
||||||
|
as no Docker verification resources have been created at that point.
|
||||||
|
|
||||||
@@ -0,0 +1,61 @@
|
|||||||
|
# KoKonna 错误、重试与阻塞处理
|
||||||
|
|
||||||
|
核对日期:2026-10-16。依据:[KoKonna OpenAPI 官方文档](https://kokonna.art/pages/openapi)、[Requests 异常定义](https://requests.readthedocs.io/en/latest/_modules/requests/exceptions/)。本页区分厂商契约与 Frame Flow 的本地策略;没有文档保证的行为不作为自动重发依据。
|
||||||
|
|
||||||
|
## 官方接口契约
|
||||||
|
|
||||||
|
- 设备 API Key 使用 Bearer 鉴权;单设备每分钟上限 20 次,请求超限返回 429。
|
||||||
|
- 上传成功返回新图片 ID 和计数,并立即激活新图;接口不提供幂等键或上传状态查询契约。
|
||||||
|
- 删除可能改变当前图片。切换与删除都不能视为天然可重放。
|
||||||
|
- 404 可表示方法不存在;图片下载时也可表示目标图片不存在。
|
||||||
|
- 500 既可能是通用服务故障,也可能明确表示设备密钥无效、图片不存在或图片 ID 参数错误。实现只匹配官方明确列出的签名,其他 500 不猜测是否产生副作用。
|
||||||
|
- 上传请求体上限 50 MB;本服务原图限制仍为 20 MiB,并保留像素上限和 base64 检查。
|
||||||
|
- 官方文档未承诺服务处理时长、超时后的取消、事务回滚或 Retry-After 返回;不能靠等待固定时间证明写入没有执行。
|
||||||
|
- Requests 将连接建立超时定义为可安全重试;读取超时不提供相同保证。一般连接异常也不能推定请求未发送。
|
||||||
|
|
||||||
|
## 已落实的本地策略
|
||||||
|
|
||||||
|
| 结果 | 处理 | 自动重试 | 设备阻塞 |
|
||||||
|
| --- | --- | --- | --- |
|
||||||
|
| 未配置密钥 | CONFIG_REQUIRED | 无 | 无 |
|
||||||
|
| 明确的设备密钥无效 | CONFIG_REQUIRED,保存固定错误分类 | 无 | 无 |
|
||||||
|
| 明确的图片不存在 | NOT_FOUND | 无 | 无 |
|
||||||
|
| 明确的图片 ID 参数错误 | INVALID_REQUEST | 无 | 无 |
|
||||||
|
| 明确的方法不存在 | UNSUPPORTED_CAPABILITY | 无 | 无 |
|
||||||
|
| 其他 HTTP 4xx 拒绝 | 保存状态码,结束失败 | 除 429 外无 | 无 |
|
||||||
|
| 本地请求预算耗尽 | 等待预算窗口 | 同一请求最多 3 次尝试 | 不创建 UNKNOWN |
|
||||||
|
| HTTP 429 | RATE_LIMITED,尊重服务端冷却时间 | 最多 3 次尝试 | 耗尽后失败,不创建 UNKNOWN |
|
||||||
|
| ConnectTimeout | 确定请求未发送 | 读写均最多 3 次尝试 | 耗尽后失败,不创建 UNKNOWN |
|
||||||
|
| 只读查询的临时网络错误、通用 5xx、无效 JSON | CLOUD_UNAVAILABLE | 最多 3 次尝试 | 不创建 UNKNOWN |
|
||||||
|
| TLS 异常 | 保存固定分类 | 无 | 写请求仍保守标为 UNKNOWN |
|
||||||
|
| 写请求读取超时、一般连接异常、通用 5xx | 无法确定写入结果 | 不重发,只读核对 | UNKNOWN,保留保护 |
|
||||||
|
| 写请求无效响应或无有效上传 ID | 无法确认成功 | 不重发,只读核对 | UNKNOWN,保留保护 |
|
||||||
|
|
||||||
|
“最多 3 次”包含首次请求,重试发生在同一传输请求内,不重新渲染、不重新执行整个操作。普通退避为 1、2 秒;每次实际请求都计入本地 18 次/分钟预算。429 优先使用 Retry-After 秒数或 HTTP 日期;缺失/无效时按 60 秒。单次等待不超过 60 秒,超过此值保留冷却并结束当前尝试,不提前请求。没有无限循环,也不在重启后重放不确定的写入。
|
||||||
|
|
||||||
|
操作错误的 details 保存 attempts、retryable、write_outcome,以及 transport_error / http_status / failure_kind 等固定分类。不会保存异常原文、完整下载 URL、带密钥的厂商消息或响应正文。是否重试由结果类别决定,不能仅依据 HTTP 500。
|
||||||
|
|
||||||
|
## 未知写入的核对与升级
|
||||||
|
|
||||||
|
上传前记录资产、哈希、字节数、名称、上传前图库和时间。响应丢失后只读查找并校验唯一候选;图片相同且设备已同步才能记为成功。已证明上传、但设备持续停留原图时,沿用两次稳定观察的失败关闭规则。
|
||||||
|
|
||||||
|
没有候选、候选不唯一、内容不符、设备未同步、查询失败或缺少历史证据,都有独立恢复原因。图库没有目标图片不等于厂商保证从未接受请求,因此不自动把它改为失败或重传。
|
||||||
|
|
||||||
|
`GET /api/v1/operations/{operation_id}` 的 `recovery` 返回:
|
||||||
|
|
||||||
|
- `state`:checking / manual_review / resolved。
|
||||||
|
- `reason`:gallery_match_missing、gallery_match_ambiguous、content_mismatch、waiting_device_sync、target_mismatch、read_unavailable、reconciliation_error、missing_upload_evidence 或 manual_reconciliation_required。
|
||||||
|
- `first_checked_at`、`last_checked_at`、`checks`、`requires_manual_review`。
|
||||||
|
|
||||||
|
只读核对每条操作至多每分钟一次。操作持续未知超过 sync_timeout + 300 秒(默认约 15 分钟)时,持久化一次 `operation.blocked` 事件和 `MANUAL_REVIEW_REQUIRED` 历史记录;服务重启、重复检查或原因改变均不会重复升级同一条未解决操作。既有检查继续运行,不自动取消设备保护。
|
||||||
|
|
||||||
|
管理员可在 Webhooks 中订阅 `operation.blocked`;未配置订阅不会自动向外发送通知。事件和 API 记录始终保留,但它们不能替代已配置的通知渠道。单个任务失败、单条未知操作的元数据异常均不应中断其他任务处理。
|
||||||
|
|
||||||
|
## 人工处理
|
||||||
|
|
||||||
|
1. 根据 operation_id 查看原始错误、恢复原因、当前设备和图库;不点击重新执行来猜测结果。
|
||||||
|
2. 调用现有 reconcile 接口并传 `acknowledge=false` 进行核对。
|
||||||
|
3. 无法证明成功、但管理员确认可以结束旧操作时,传 `acknowledge=true`:结束为失败,保留原始目标、上传意图和此前错误,记录观察到的图片与人工处理历史。该接口不会重发设备写入。
|
||||||
|
4. 有目标一致且同步完成的证据才记为成功。处理后恢复原计划,错过的任务不补发。
|
||||||
|
|
||||||
|
仍可能因厂商无法给出明确写入结果而需要人工处理;本策略解决错误误判、可安全重试的暂时失败和长期阻塞缺乏解释的问题,不承诺网络故障时所有设备任务都能自动成功。
|
||||||
+9
-3
@@ -1,7 +1,9 @@
|
|||||||
# Synology NAS deployment / 群晖部署
|
# Synology NAS deployment / 群晖部署
|
||||||
|
|
||||||
Target: DS923+, DSM 7.4.1 (verified on target; originally specified 7.3.1), AMD64, Container Manager.
|
Target: DS923+, DSM 7.4.1 (verified on target; originally specified 7.3.1), AMD64, Container Manager.
|
||||||
Directory: /volume2/docker/pigway-frame-flow. Port: 18787.
|
Directory: /volume2/docker/pigway-frame-flow. Default published port: 6005.
|
||||||
|
The container still listens on 18787; Compose maps host 6005 to container 18787.
|
||||||
|
Existing installations must update their own WEB_PORT and recreate the service to activate the change.
|
||||||
|
|
||||||
## 1. Package and upload / 打包上传
|
## 1. Package and upload / 打包上传
|
||||||
|
|
||||||
@@ -37,10 +39,14 @@ chmod 600 .env
|
|||||||
Edit `.env` on the NAS. Set FRAME_FLOW_TOKEN to a strong random token. API key
|
Edit `.env` on the NAS. Set FRAME_FLOW_TOKEN to a strong random token. API key
|
||||||
stays empty. KOKONNA_MOCK=true and KOKONNA_WRITE_ENABLED=false.
|
stays empty. KOKONNA_MOCK=true and KOKONNA_WRITE_ENABLED=false.
|
||||||
Set WEB_BIND to the actual NAS LAN address (recommended) or explicitly 0.0.0.0;
|
Set WEB_BIND to the actual NAS LAN address (recommended) or explicitly 0.0.0.0;
|
||||||
WEB_PORT=18787. The latter binds every NAS interface, so use the LAN IP when
|
WEB_PORT=6005. The latter binds every NAS interface, so use the LAN IP when
|
||||||
strict LAN-only binding is required. No firewall/router/proxy edits are performed.
|
strict LAN-only binding is required. No firewall/router/proxy edits are performed.
|
||||||
Copy deploy/devices.yml.example to config/devices.yml if multiple devices are desired.
|
Copy deploy/devices.yml.example to config/devices.yml if multiple devices are desired.
|
||||||
|
|
||||||
|
Set `FRAME_FLOW_STORAGE_NAME` to the NAS display name. The gallery tab shows
|
||||||
|
this name followed by “本地图库” (or “Local gallery”). For Actions deployment,
|
||||||
|
set the repository Variable of the same name. It is a display label, not a path.
|
||||||
|
|
||||||
## 3. Validate, build, start / 验证构建启动
|
## 3. Validate, build, start / 验证构建启动
|
||||||
|
|
||||||
Synology Docker is /usr/local/bin/docker. The SSH user may require sudo. Do not
|
Synology Docker is /usr/local/bin/docker. The SSH user may require sudo. Do not
|
||||||
@@ -61,7 +67,7 @@ sudo /usr/local/bin/docker image inspect pigway-frame-flow:latest \
|
|||||||
Do not print unfiltered `docker inspect`: its environment can contain keys/tokens.
|
Do not print unfiltered `docker inspect`: its environment can contain keys/tokens.
|
||||||
Likewise do not print `docker compose config` without --quiet on a live installation.
|
Likewise do not print `docker compose config` without --quiet on a live installation.
|
||||||
Run the read-only smoke checker from a machine with Python and set FRAME_FLOW_URL
|
Run the read-only smoke checker from a machine with Python and set FRAME_FLOW_URL
|
||||||
to http://NAS_LAN_IP:18787; FRAME_FLOW_TOKEN stays in private env/file.
|
to http://NAS_LAN_IP:6005; FRAME_FLOW_TOKEN stays in private env/file.
|
||||||
|
|
||||||
Health: GET /health → 200. Readiness: GET /ready → 200 when SQLite, driver config,
|
Health: GET /health → 200. Readiness: GET /ready → 200 when SQLite, driver config,
|
||||||
auth and Scheduler are ready. Missing credentials in live mode → 503. The cloud
|
auth and Scheduler are ready. Missing credentials in live mode → 503. The cloud
|
||||||
|
|||||||
@@ -4,6 +4,10 @@ Photo sources are independent read-only providers. They never call a frame drive
|
|||||||
SQLite persists source definitions and Scheduler jobs; passwords are not stored there.
|
SQLite persists source definitions and Scheduler jobs; passwords are not stored there.
|
||||||
The shared DisplayService handles fitting, upload, idempotency, overrides and restore.
|
The shared DisplayService handles fitting, upload, idempotency, overrides and restore.
|
||||||
|
|
||||||
|
## Synology Photos API (no mount)
|
||||||
|
|
||||||
|
Use the explicit `synology-photos` source type for Ubuntu without `/photos`. Existing local sources are not silently converted. Shared and current-account personal spaces use the shared Photos login, with ID-based any/all people filters and bounded XL preview caching. See [verified capabilities, migration and recovery](SYNOLOGY_PHOTOS_API.md). Original API downloads remain unsupported.
|
||||||
|
|
||||||
## NAS local folder
|
## NAS local folder
|
||||||
|
|
||||||
Add the actual existing photo directory to `.env`:
|
Add the actual existing photo directory to `.env`:
|
||||||
@@ -30,7 +34,7 @@ change NAS permissions. Unreadable roots return an explicit HTTP 403 rather than
|
|||||||
an empty catalog.
|
an empty catalog.
|
||||||
Missing host folders fail explicitly rather than being created automatically.
|
Missing host folders fail explicitly rather than being created automatically.
|
||||||
|
|
||||||
Open **Gallery → Photo sources → Add source**, choose **NAS local folder**,
|
Open **Photo sources → Add source**, choose **NAS local folder**,
|
||||||
enter a relative folder (`.` for root or `family` for a subfolder).
|
enter a relative folder (`.` for root or `family` for a subfolder).
|
||||||
Supported formats: JPEG, PNG, WebP. Optional recursion excludes hidden directories,
|
Supported formats: JPEG, PNG, WebP. Optional recursion excludes hidden directories,
|
||||||
Synology `@eaDir` thumbnail trees, and symlinks. Original files remain unchanged.
|
Synology `@eaDir` thumbnail trees, and symlinks. Original files remain unchanged.
|
||||||
@@ -134,7 +138,7 @@ caption still comes from the original curated directory.
|
|||||||
|
|
||||||
1. 将共享图库(如 `/volume1/photo`)挂载为 `/photos`,保持只读。
|
1. 将共享图库(如 `/volume1/photo`)挂载为 `/photos`,保持只读。
|
||||||
2. 在 `.env` 配置 `SYNOLOGY_PHOTOS_URL=https://NAS_IP:9115` 和 `SYNOLOGY_PHOTOS_CERT_SHA256`(服务实际 TLS 证书的 SHA-256 指纹,从可信 NAS 配置核实)。重建容器后生效。指纹变化时必须重新核实;每次连接在发送登录信息前校验同一个 TLS socket 的证书。
|
2. 在 `.env` 配置 `SYNOLOGY_PHOTOS_URL=https://NAS_IP:9115` 和 `SYNOLOGY_PHOTOS_CERT_SHA256`(服务实际 TLS 证书的 SHA-256 指纹,从可信 NAS 配置核实)。重建容器后生效。指纹变化时必须重新核实;每次连接在发送登录信息前校验同一个 TLS socket 的证书。
|
||||||
3. 照片数据源 → 编辑数据源 → 连接 / 选择人物。管理员输入 NAS 用户名、密码;只保存 session 到 `/config/synology-photos-session.json`(0600),不保存密码。会话过期后需要重新连接;断开连接删除本地 session。页面没有 password/token 回显。
|
3. 照片数据源 → 顶部共享连接 → 连接 Synology Photos。输入有权限的 NAS 用户名、密码;只保存 session 到 `/config/synology-photos-session.json`(0600),不保存密码。会话过期后需要重新连接;断开连接删除本地 session。页面没有 password/token 回显。登录由所有人物筛选数据源共享;随后进入各数据源编辑器选择人物。
|
||||||
4. 选择人物,启用筛选,选择“任意”或“同时包含所有”。默认只列出已命名人物,可搜索 ID、展开未命名分组。至少选择一个人物。
|
4. 选择人物,启用筛选,选择“任意”或“同时包含所有”。默认只列出已命名人物,可搜索 ID、展开未命名分组。至少选择一个人物。
|
||||||
5. 与当前本地目录、日期文件夹规则取交集,再随机选图。原文件夹标题、日期、地点仍保留。不匹配返回空图库;预览 / 定时任务失败,不回退到全图库。
|
5. 与当前本地目录、日期文件夹规则取交集,再随机选图。原文件夹标题、日期、地点仍保留。不匹配返回空图库;预览 / 定时任务失败,不回退到全图库。
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,44 @@
|
|||||||
|
# Photo sources and shared connections
|
||||||
|
|
||||||
|
Each photo source has a unique ID and independently persisted directory/URL,
|
||||||
|
orientation, caption, quality, duplicate and person-selection settings. Jobs refer
|
||||||
|
to the source ID. Updating one source does not change another source.
|
||||||
|
|
||||||
|
Local sources read folders under the configured NAS mount. Ordinary file reads
|
||||||
|
and local Synology thumbnails do not require a Photos login. Person filtering
|
||||||
|
uses the shared Synology Photos session, intersected with that source's folder
|
||||||
|
catalog. Shared/personal space and person IDs are saved separately per source.
|
||||||
|
|
||||||
|
The current service supports one NAS Photos endpoint and one active account.
|
||||||
|
Signing in with another account or disconnecting affects every people-filtered
|
||||||
|
source. Personal-space person IDs may differ between accounts: recheck each
|
||||||
|
source after an account switch. Multiple independent NAS/account connections
|
||||||
|
are not supported. Do not interpret multiple folder sources as multiple logins.
|
||||||
|
|
||||||
|
WebDAV credentials and native drive credentials belong to their respective
|
||||||
|
sources and do not use the shared NAS Photos login. Explicitly reusing a WebDAV
|
||||||
|
credential variable shares that credential, but does not share filter settings.
|
||||||
|
|
||||||
|
The UI labels the top card **Shared connection**, displays source IDs and paths
|
||||||
|
on each source card, and explains each source's connection dependency. Shared
|
||||||
|
session disconnect is available only in the shared connection card and asks for
|
||||||
|
confirmation of its impact on all people-filtered sources.
|
||||||
|
|
||||||
|
|
||||||
|
## Gallery destination labels / 图库目的地标签
|
||||||
|
|
||||||
|
图库标签描述可保存图片的具体目的地,照片来源连接不自动成为图库目的地。
|
||||||
|
当前为 `KoKonna 云端图库` 与 `<FRAME_FLOW_STORAGE_NAME> 本地图库`;
|
||||||
|
NAS 名称通过部署配置设置,空值回退为 NAS,不使用容器 ID 代替 NAS 名称。
|
||||||
|
英文使用同一实例名称与 cloud gallery / Local gallery。
|
||||||
|
|
||||||
|
`GET /api/v1/settings` 的 `gallery_destinations` 提供目的地 ID、适配器、
|
||||||
|
实例/服务商名称、存储类型、连接状态和保存能力。只有连接有效、明确支持上传且
|
||||||
|
前端存在对应适配器的目的地才进入标签栏。能力默认关闭;全局写入保护仍单独生效,
|
||||||
|
目的地的保存能力不等于当前用户获准写入。
|
||||||
|
|
||||||
|
后续网盘接入须先实现其读取/保存适配器、校验授权及能力,再注册目的地。
|
||||||
|
命名规则为“服务商/实例名称 + 云端图库”,例如已实现保存能力后才可展示
|
||||||
|
“百度网盘·家庭 云端图库”。多个账号/实例必须能从名称区分。
|
||||||
|
目前 Google Drive、阿里云盘、百度网盘和 WebDAV 仅作为只读照片来源,
|
||||||
|
不出现在可保存目的地标签栏,不显示尚未实现的上传入口。
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
# Public repository and deployment privacy
|
||||||
|
|
||||||
|
Runtime keys, passwords, sessions, private photos, databases and local `.env` files
|
||||||
|
must remain outside Git. Examples use documentation-only addresses and identities.
|
||||||
|
Personal deployment reports and screenshots are excluded from public history.
|
||||||
|
|
||||||
|
The NAS Docker runner accepts trusted repository events only. External fork PRs
|
||||||
|
are not executed on this runner; maintainers must review them before copying changes
|
||||||
|
to a trusted branch. All lint, type, test, audit and isolated Docker checks remain.
|
||||||
|
|
||||||
|
Private deployment configuration is stored in Gitea Actions Secrets:
|
||||||
|
`PROD_DATA_DIR`, `PROD_CONFIG_DIR`, `PROD_PHOTOS_DIR`, `PROD_WEB_BIND`,
|
||||||
|
`SYNOLOGY_PHOTOS_URL`, `SYNOLOGY_PHOTOS_CERT_SHA256`, and `PRODUCTION_ENV`.
|
||||||
|
Project/image names, ports, enable flags and mirror settings remain Variables.
|
||||||
|
Never print complete Docker inspect environment or secret values.
|
||||||
|
|
||||||
|
Publishing requires scanning all refs, removing private historic files, pruning
|
||||||
|
unreachable remote Git objects and archiving/removing historical Actions logs.
|
||||||
|
A private original mirror is retained outside the repository. Existing clones must
|
||||||
|
reclone after the privacy history rewrite; do not merge the original history back.
|
||||||
@@ -25,3 +25,23 @@
|
|||||||
The API cannot set coverId. Restoration guarantees a requested image switch when
|
The API cannot set coverId. Restoration guarantees a requested image switch when
|
||||||
confirmed, not arbitrary cover metadata restoration. Physical screen refresh has
|
confirmed, not arbitrary cover metadata restoration. Physical screen refresh has
|
||||||
no documented pixel telemetry; visual owner observation supplements cloud synced.
|
no documented pixel telemetry; visual owner observation supplements cloud synced.
|
||||||
|
|
||||||
|
### Upload response reconciliation
|
||||||
|
|
||||||
|
Before an upload, the service persists its asset ID, exact SHA256/size, filename,
|
||||||
|
existing gallery IDs and timestamp. When the response is lost, read-only queries
|
||||||
|
look for one new image in the upload time window; only an exact downloaded-byte
|
||||||
|
match identifies it. Ambiguous, missing or altered content remains locked for
|
||||||
|
manual review. No upload or switch is replayed by reconciliation.
|
||||||
|
|
||||||
|
A proven upload completes the display only when the device reports that exact
|
||||||
|
image and `synced=true`. If a normal display remains on its previous synced
|
||||||
|
image beyond the sync timeout plus five minutes, two observations at least one
|
||||||
|
minute apart record `DISPLAY_NOT_CONFIRMED` and unblock future scheduled work.
|
||||||
|
Temporary overrides retain their restore behavior and are not automatically
|
||||||
|
closed as failed. Legacy operations without durable upload evidence require
|
||||||
|
manual acknowledgement; absence from the gallery alone never proves failure.
|
||||||
|
|
||||||
|
### 错误与有限重试
|
||||||
|
|
||||||
|
完整错误矩阵、重试边界、持久化恢复状态和人工处理见 [KoKonna 恢复策略](KOKONNA_RECOVERY.md)。自动重试只允许只读请求、连接建立超时或明确限流拒绝;读取超时等未知写入不会重发。
|
||||||
|
|||||||
+3
-2
@@ -1,6 +1,7 @@
|
|||||||
# KoKonna API research / 接口调查
|
# KoKonna API research / 接口调查
|
||||||
|
|
||||||
Checked 2026-10-01 against https://kokonna.art/pages/openapi.
|
Rechecked 2026-10-16 against https://kokonna.art/pages/openapi.
|
||||||
|
错误分类、重试和未知写入处理见 [KoKonna 恢复策略](KOKONNA_RECOVERY.md)。
|
||||||
Base: https://api.kokonna.art/openapi. No fallback to legacy galaxyguide.cn.
|
Base: https://api.kokonna.art/openapi. No fallback to legacy galaxyguide.cn.
|
||||||
|
|
||||||
| Official endpoint | Frame Flow capability |
|
| Official endpoint | Frame Flow capability |
|
||||||
@@ -29,7 +30,7 @@ headroom at 18. Device state has a 60-second cache, gallery is loaded on demand.
|
|||||||
Uploads automatically activate a new image; there is no upload-without-activation
|
Uploads automatically activate a new image; there is no upload-without-activation
|
||||||
flag. Gallery-only uploads are therefore local staging, not a fictitious cloud
|
flag. Gallery-only uploads are therefore local staging, not a fictitious cloud
|
||||||
operation. Maximum upstream request size is 50 MB; this service accepts 20 MiB
|
operation. Maximum upstream request size is 50 MB; this service accepts 20 MiB
|
||||||
image files with bounded decoded pixels. No non-idempotent cloud write is retried.
|
image files with bounded decoded pixels. Only proven-unsent connections or explicit rate-limit rejections may retry a write, within a three-attempt budget. Ambiguous writes are never replayed.
|
||||||
Cloud acknowledgement is not physical refresh confirmation; /device synced and
|
Cloud acknowledgement is not physical refresh confirmation; /device synced and
|
||||||
imageId drive the operation state. Unconfirmed or interrupted writes become UNKNOWN
|
imageId drive the operation state. Unconfirmed or interrupted writes become UNKNOWN
|
||||||
and block later device writes until read-only reconciliation/explicit acknowledgement.
|
and block later device writes until read-only reconciliation/explicit acknowledgement.
|
||||||
|
|||||||
@@ -0,0 +1,65 @@
|
|||||||
|
# Synology Photos API 来源与 Ubuntu 迁移候选
|
||||||
|
|
||||||
|
本功能从 NAS 的 Photos API 按需读取照片,不需要 NFS、SMB 或 `/photos` 文件挂载。NAS 原照片不复制整库到 Server。
|
||||||
|
|
||||||
|
## 已支持与边界
|
||||||
|
|
||||||
|
- 新来源类型 `synology-photos`,与 `local` 挂载目录明确分开。
|
||||||
|
- 共享空间 `SYNO.FotoTeam`、当前登录账号的个人空间 `SYNO.Foto`;不是任意 NAS 用户的个人空间。
|
||||||
|
- 人物列表分批读取,照片按 ID 做 any 并集 / all 交集;无匹配时明确为空,不回退全库。
|
||||||
|
- 支持目录相对路径、递归开关、日期文件夹 / 标题、方向及现有质量筛选。`.` 表示所选空间根目录;路径以 Photos 返回的目录名为准,不是 Ubuntu 绝对路径。
|
||||||
|
- 图片使用经过实测的 `Thumbnail.get` v2、`size=xl`。原始文件名不代表下载的是原图。对 NAS 当前原图下载接口的探测被拒绝,原图下载**未宣称支持**。
|
||||||
|
- 照片枚举 `Browse.Item.list` v7,人物 `Browse.Person.list` v3;每批 500 条,最多 100000 条,超过明确失败,界面目录上限仍由 `catalog_limit` 控制。不支持 NAS 未暴露或账号无权访问的相册。
|
||||||
|
- 旧 `local` 来源保留挂载读取方式,不自动变成 API 来源。新建 / 编辑来源时可明确选择 API 类型。
|
||||||
|
|
||||||
|
## 安全与缓存
|
||||||
|
|
||||||
|
保持 HTTPS SHA-256 证书指纹校验,在同一 TLS socket 验证证书后才发送 SID。仅调用固定 API 与只读方法,不使用通用 RPC 转发、不跟随重定向。密码不持久化,会话文件保持 0600。会话过期返回明确重连提示;不保存密码以自动重登,也不对 NAS 原会话发 logout。权限不足与会话失效分开处理。
|
||||||
|
|
||||||
|
缓存为 `/data/cache/synology-photos`,默认总图片字节上限 256 MiB,可用 `SYNOLOGY_PHOTOS_CACHE_BYTES` 调整(环境配置最小 1 MiB),单张不超过应用 20 MiB 限制。只下载选中的图片。文件锁合并跨线程、跨进程下载,预留容量后写 0600 临时文件,完成长度核对及 Pillow 验证 / 解码后原子提交;超时、中断及无效数据清理临时文件,下次持锁读取清理进程异常退出遗留的 `.part`。按最近使用淘汰。缓存身份包含端点、会话摘要、空间、照片 ID、索引版本及缩略图缓存键,避免账号 / 空间混用。
|
||||||
|
|
||||||
|
容量上限针对图片和下载临时文件的逻辑字节,不含 SQLite、锁文件与文件系统元数据;并发串行缓存锁会等待正在进行的单张下载。网络 socket 超时 30 秒,流读取检查 90 秒期限,已阻塞的单次 socket 读取最多再等待其超时。
|
||||||
|
|
||||||
|
## Ubuntu 候选配置
|
||||||
|
|
||||||
|
正式代码在 `/home/developer/Documents/Projects/pigway-frame-flow` 的 `codex/synology-photos-api` 分支开发,不能以迁移临时解包目录作为开发仓库。
|
||||||
|
|
||||||
|
候选文件:`deploy/compose.ubuntu-photos-api.yml`。外部 `192.0.2.10:81`,内部 `18787`,UID/GID `10333:10333`,数据和配置固定为:
|
||||||
|
|
||||||
|
- `/srv/pigway/apps/pigway-frame-flow/data:/data`
|
||||||
|
- `/srv/pigway/apps/pigway-frame-flow/config:/config`
|
||||||
|
|
||||||
|
无 `/photos` 绑定。`create_host_path: false` 防止在 T7 未挂载时悄悄创建目录;但仍需在启动前检查 `findmnt -T /srv/pigway` 的实际源设备。
|
||||||
|
|
||||||
|
`.env` 需从已确认的配置安全迁移,保留 Photos URL、证书 pin 与已有 Frame Flow / 相框鉴权;不要把密钥写入仓库。模板默认 `KOKONNA_WRITE_ENABLED=false`。创建 `data/tmp`,属主保持 10333:10333,`TMPDIR=/data/tmp`。Docker data-root 和 containerd root 也必须在 T7,不能仅检查 bind mount。
|
||||||
|
|
||||||
|
```sh
|
||||||
|
# 仅检查候选配置;不会启动应用。
|
||||||
|
FRAME_FLOW_IMAGE='<已验证的镜像标签>' docker compose -f deploy/compose.ubuntu-photos-api.yml config --quiet
|
||||||
|
```
|
||||||
|
|
||||||
|
完整构建使用根目录 Dockerfile。若使用 `deploy/Dockerfile.runtime-update`,必须指定已审核的基础镜像,构建步骤会检查依赖锁与基础镜像相同;不相同时必须完整构建。本次依赖未新增,已比对现有 0.1.8 基础镜像的锁文件。
|
||||||
|
|
||||||
|
## 旧来源转换与恢复
|
||||||
|
|
||||||
|
**停止目标实例、复制数据、转换真实配置及切换部署均需另行授权,本次没有执行。**
|
||||||
|
|
||||||
|
1. 确认 T7 挂载,备份 NAS 原有完整 `/data`、`/config`、旧镜像及 Compose。SQLite 必须停服务后复制,或使用 SQLite backup API;不要只复制有活动 WAL 的主文件。
|
||||||
|
2. 将备份恢复到上述 Server 目录,保持私密文件权限,创建 `data/tmp`。保留旧 NAS 备份直至切换验收。
|
||||||
|
3. 对每个需要摆脱挂载的来源显式 dry run:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
python scripts/migrate-photos-api.py --database /data/frameflow.db --source family
|
||||||
|
# 已获授权、目标服务已停止时才执行:
|
||||||
|
python scripts/migrate-photos-api.py --database /data/frameflow.db --source family --apply --service-stopped
|
||||||
|
```
|
||||||
|
|
||||||
|
工具保持来源 ID、任务引用、人物空间、any/all、目录、方向及筛选设置,只修改来源类型并关闭旧本地 `@eaDir` 预览开关;自动在同一数据目录生成 0600 SQLite 备份。转换不会验证该账号在 Photos 中是否可访问相同目录,必须再做真实只读预览。不要转换确实依赖挂载且 Photos 未收录的目录。
|
||||||
|
4. 已获得单独授权后才停旧实例、以只读候选配置启动 Server,并逐个来源验收。没有授权前不执行 `compose up` 或开启真实写入。
|
||||||
|
5. 回退时停止 Server,恢复已备份的数据库和配置(停服务时处理对应 WAL/SHM),恢复旧来源类型与 NAS 原部署,保证只有一个实例有写权限。原 NAS 照片不受缓存或来源转换影响。
|
||||||
|
|
||||||
|
## NFS 授权判断
|
||||||
|
|
||||||
|
API 来源的共享 / 个人空间取图已经可以完全不依赖 NFS,因此这条新取图链路不需要为 `192.0.2.10` 保留 DSM `photo` NFS 授权。但目前旧来源和待迁移配置没有全部切换验收,不能据此宣称迁移完成或旧本地来源已可脱离挂载。确认没有其他已批准用途后,可以单独授权删除该特定 NFS 规则;本次没有删除。
|
||||||
|
|
||||||
|
实际版本、镜像标识、通过 / 失败 / 未执行项见本任务验证记录。
|
||||||
@@ -0,0 +1,62 @@
|
|||||||
|
# UI 一致性与图片加载检查
|
||||||
|
|
||||||
|
页面使用既有真实元数据创建控件和图片区域,不使用页面骨架或虚构图片卡片。
|
||||||
|
搜索、排序、卡片操作与写入保护在图片请求前初始化;已知图库数据可先显示,
|
||||||
|
后台刷新元数据。首页图片独立加载,不阻塞后续页面内容。
|
||||||
|
|
||||||
|
图片共用局部加载函数:旋转指示器仅居中显示于所属图片容器,网络请求与解码完成后
|
||||||
|
立即显示图片,失败后显示中英文提示。没有固定等待或动画最短展示时长。
|
||||||
|
图库仅请求可见区域及附近图片。浏览器禁缓存不会清除服务端缩略图缓存,
|
||||||
|
快速图片可能在第一帧绘制前完成,动画不一定肉眼可见。
|
||||||
|
|
||||||
|
手动拼版先创建全部真实区域与坐标/拖动交互,再并行请求图片。
|
||||||
|
每张图片独立完成或失败,持久的区域容器保持加载前后几何位置与坐标索引稳定。
|
||||||
|
过期布局事件不修改新的规划。
|
||||||
|
|
||||||
|
移动端导航单行横向滚动,当前入口自动进入可见区域;低高度横屏侧栏可滚动。
|
||||||
|
页头在窄屏分行,并为底部安全区域留白。可见控件保留 44 像素触控高度,
|
||||||
|
当前导航使用 aria-current,扩展表单标签关联相应控件。
|
||||||
|
表格与手机导航允许容器内滚动,不应导致整页水平溢出。
|
||||||
|
|
||||||
|
## 自动检查
|
||||||
|
|
||||||
|
使用隔离 Mock 服务、临时数据与测试账号,禁止对生产执行可写的 Mock 脚本。
|
||||||
|
Photos 授权使用拦截测试响应;不需要真实 NAS 凭据。
|
||||||
|
|
||||||
|
```sh
|
||||||
|
FRAME_FLOW_URL=http://127.0.0.1:6005 \
|
||||||
|
FRAME_FLOW_ENV_FILE=/path/to/mock.env \
|
||||||
|
FRAME_FLOW_TEST_USERNAME=test-ui \
|
||||||
|
FRAME_FLOW_TEST_PASSWORD=test-only-password \
|
||||||
|
node scripts/ui-layout-audit.cjs
|
||||||
|
```
|
||||||
|
|
||||||
|
需要已安装的 Playwright;可通过 NODE_PATH 指定运行时。
|
||||||
|
FRAME_FLOW_VIEWPORTS 接受包含 width/height 的 JSON 数组;
|
||||||
|
FRAME_FLOW_SCREENSHOT_DIR 可选,用于保存仅含测试数据的截图。
|
||||||
|
|
||||||
|
| 脚本 | 检查范围 | 本次结果 |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| ui-layout-audit.cjs | 11 页面、本地/云端图库、6 类弹窗、展开手动拼版;溢出、控件间距、触控高度、弹窗边界 | 16 组尺寸/语言/主题组合,305 项通过 |
|
||||||
|
| ui-image-loading.cjs | 三种宽度、明暗主题;局部居中、成功解码、错误提示与无障碍状态 | 45 项通过 |
|
||||||
|
| ui-progressive-loading.cjs | 阻塞初始化/元数据/图片/任务筛选;首次无缓存时控件先就绪、输入保留、慢请求切换、列表失败、无骨架 | 18 项通过 |
|
||||||
|
| ui-studio-image-loading.cjs | 桌面/手机、明暗主题;并行请求、独立完成/失败、坐标与拖动、稳定区域 | 31 项通过 |
|
||||||
|
|
||||||
|
上述检查无页面脚本异常。生产静态文件与构建文件哈希比对、health/ready 检查通过;
|
||||||
|
生产浏览器交互验证使用拦截的账号、规划及素材响应,对真实服务仅 GET,
|
||||||
|
不代表真实账号密码登录、AI 生成、iOS/Android 实机或软键盘测试。
|
||||||
|
|
||||||
|
连接中心内容较长,后续可按用户任务分组;模板与排版导航图标仍有重复。
|
||||||
|
|
||||||
|
|
||||||
|
## 首次未缓存图库的初始化
|
||||||
|
|
||||||
|
目的地标签、搜索、排序、刷新和上传控件必须先于列表接口完成。
|
||||||
|
仅已有列表的缓存分支先渲染还不够;无缓存时也应创建真实控件与空的列表容器。
|
||||||
|
元数据返回前不推测图片数量,不显示真实空图库提示,不生成骨架卡片。
|
||||||
|
列表失败保留页面控件;慢云端请求期间切换 NAS,迟到响应不得覆盖新页面。
|
||||||
|
列表返回后保留之前输入的搜索词和排序。任务筛选在同一导航内复用请求,仍不阻塞图库。
|
||||||
|
|
||||||
|
启动使用 Settings API 中不调用厂商接口的 device_catalog;完整设备状态作为后台更新,
|
||||||
|
迟到响应在退出账号后不应用。ui-gallery-bootstrap.cjs 同时阻塞设备状态与图片列表,
|
||||||
|
验证真实控件仍先显示,列表返回后保留查询和排序,2 项通过。
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
# 界面表达审计(2026-10-16)
|
||||||
|
|
||||||
|
范围:11 个主页面、主要弹窗、中英文文案、README 和照片数据源说明;对照当前 API、清理与来源记录逻辑。不是厂商接口能力或线上服务状态的全面审计。
|
||||||
|
|
||||||
|
| 位置 | 原问题 | 修正 |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| 图库 | 排序使用“适配方式” | 独立“排序方式”标签 |
|
||||||
|
| 轮播 / 播放列表 | 播放顺序使用图片适配标签;间隔重复单位 | 使用“播放顺序”“切换间隔” |
|
||||||
|
| 总览 | 天气缺译,显示原始 weather | 补齐中英文 |
|
||||||
|
| 总览 | 图片 ID 标成图片;型号来源标成型号 | 独立标注 ID 与信息来源 |
|
||||||
|
| 同步状态 | “已同步”容易被视为实物刷新确认 | 标明云端确认 |
|
||||||
|
| 图片来源 | 无记录却断言非本系统生成 | 只描述未找到可用记录 |
|
||||||
|
| 模板编辑 | 非模板图片复用不准确的来源错误 | 明确无可编辑的模板来源 |
|
||||||
|
| 删除 | 本地当前图也提示画框切图 | 按本地、云端、当前云端副本区分确认文案 |
|
||||||
|
| 星标 / 多选 | 自动清理保护及隐藏勾选项范围不明确 | 加入服务端保留、手动删除、当前页选择范围说明 |
|
||||||
|
| 上传 | 固定尺寸提示可能与输出不一致 | 提示以生成预览为准 |
|
||||||
|
| 显示选项 | 不勾选恢复时仍显示时长,容易误解 | 说明时长与优先级的临时显示用途 |
|
||||||
|
| 数据源 | 未配置与无匹配照片共用空态 | 拆分两种空态 |
|
||||||
|
| 数据源 | 位置标签、凭据提示仅描述 WebDAV | 补充网盘目录 ID、百度路径、OAuth 凭据 |
|
||||||
|
| 人物筛选 | 仅描述共享空间,但实际可选个人空间 | 按所选空间说明访问权限 |
|
||||||
|
| AI / MQTT | AI 密钥称为设备密钥;连接状态缺译 | 独立 API 密钥标签,补齐连接状态 |
|
||||||
|
| 错误页 | 所有失败都归因设备云端 | 改成通用页面加载失败,保留具体原因 |
|
||||||
|
| 文档 | 照片数据源旧入口及账号独立性描述过时 | 对齐独立导航与共享 Photos 登录 |
|
||||||
|
|
||||||
|
验证:305 项布局检查覆盖 320、390、844 横屏、1440 宽度,中英文与明暗主题,11 页及主要弹窗;8 组星标 / 反选回归;新增文案检查覆盖静态翻译完整性、排序 / 播放 / 型号标签、本地删除和星标作用范围。测试使用隔离 Mock,无真实设备写入、照片删除、AI 调用或部署。
|
||||||
|
|
||||||
|
此前未提交的反选、总览图片放大及共享图片查看器改动保留。此报告不代表已提交或已部署。
|
||||||
+76
-37
@@ -9,8 +9,8 @@ host bind/port. SQLite/images/generated/cache live under `/data`; accounts,
|
|||||||
vendor sessions and configuration live under `/config`. Neither is disposable.
|
vendor sessions and configuration live under `/config`. Neither is disposable.
|
||||||
The optional photos mount is read-only and has supplementary group access.
|
The optional photos mount is read-only and has supplementary group access.
|
||||||
|
|
||||||
Historical repository receipts mention `/volume2/docker/pigway-frame-flow/data`,
|
Historical repository receipts mention `/volume1/docker/pigway-frame-flow/data`,
|
||||||
`/volume2/docker/pigway-frame-flow/config`, `/volume1/photo`, port 18787, and
|
`/volume1/docker/pigway-frame-flow/config`, `/volume1/photo`, port 18787, and
|
||||||
container/project `pigway-frame-flow`. These are **confirmation candidates**, not
|
container/project `pigway-frame-flow`. These are **confirmation candidates**, not
|
||||||
script defaults. The deploy action accepts only explicitly configured paths
|
script defaults. The deploy action accepts only explicitly configured paths
|
||||||
that match the existing running container on the Runner's Docker daemon.
|
that match the existing running container on the Runner's Docker daemon.
|
||||||
@@ -24,19 +24,20 @@ configured names and existing bind mounts, with `create_host_path: false`.
|
|||||||
|
|
||||||
## Gitea configuration
|
## Gitea configuration
|
||||||
|
|
||||||
Repository Settings → Actions → Variables (ordinary configuration):
|
Repository Settings → Actions configuration (private paths/addresses use Secrets):
|
||||||
|
|
||||||
| Variable | Value to explicitly confirm |
|
| Variable or Secret | Value to explicitly confirm |
|
||||||
| --- | --- |
|
| --- | --- |
|
||||||
| `PROD_DEPLOY_ENABLED` | Initially `false`; change to `true` only after plan acceptance |
|
| `PROD_DEPLOY_ENABLED` | Initially `false`; change to `true` only after plan acceptance |
|
||||||
| `PROD_PROJECT` | Existing Compose project label; candidate `pigway-frame-flow` |
|
| `PROD_PROJECT` | Existing Compose project label; candidate `pigway-frame-flow` |
|
||||||
| `PROD_CONTAINER` | Existing container name; candidate `pigway-frame-flow` |
|
| `PROD_CONTAINER` | Existing container name; candidate `pigway-frame-flow` |
|
||||||
| `PROD_IMAGE_REPO` | Fixed local image repository; suggested `pigway-frame-flow` |
|
| `PROD_IMAGE_REPO` | Fixed local image repository; suggested `pigway-frame-flow` |
|
||||||
| `PROD_DATA_DIR` | Existing absolute NAS host data path; no default |
|
| `PROD_DATA_DIR` (Secret) | Existing absolute NAS host data path; no default |
|
||||||
| `PROD_CONFIG_DIR` | Existing absolute NAS host config path; no default |
|
| `PROD_CONFIG_DIR` (Secret) | Existing absolute NAS host config path; no default |
|
||||||
| `PROD_PHOTOS_DIR` | Existing read-only photos source if present; otherwise empty |
|
| `PROD_PHOTOS_DIR` (Secret) | Existing read-only photos source if present; otherwise empty |
|
||||||
| `PROD_WEB_BIND` | Exact existing Docker HostIp (`0.0.0.0` or NAS LAN IP etc.) |
|
| `PROD_WEB_BIND` (Secret) | Exact existing Docker HostIp (`0.0.0.0` or NAS LAN IP etc.) |
|
||||||
| `PROD_WEB_PORT` | Exact existing mapped port |
|
| `PROD_WEB_PORT` | Exact existing mapped port |
|
||||||
|
| `FRAME_FLOW_STORAGE_NAME` | Optional NAS display name for the local gallery; defaults to NAS |
|
||||||
| `PROD_STATE_VOLUME` | Dedicated new deployment journal volume, e.g. `pigway-frame-flow-cd-state` |
|
| `PROD_STATE_VOLUME` | Dedicated new deployment journal volume, e.g. `pigway-frame-flow-cd-state` |
|
||||||
| `PROD_MOCK` | Explicit `true`/`false`, consistent with intended production mode |
|
| `PROD_MOCK` | Explicit `true`/`false`, consistent with intended production mode |
|
||||||
| `PROD_WRITE_ENABLED` | Explicit `true`/`false`; preserve owner's existing write policy |
|
| `PROD_WRITE_ENABLED` | Explicit `true`/`false`; preserve owner's existing write policy |
|
||||||
@@ -75,7 +76,7 @@ Never upload that journal or a full Docker inspect as a public CI artifact.
|
|||||||
docker inspect pigway-frame-flow --format '{{json .Mounts}}'
|
docker inspect pigway-frame-flow --format '{{json .Mounts}}'
|
||||||
docker inspect pigway-frame-flow --format '{{json .HostConfig.PortBindings}} {{.HostConfig.NetworkMode}}'
|
docker inspect pigway-frame-flow --format '{{json .HostConfig.PortBindings}} {{.HostConfig.NetworkMode}}'
|
||||||
```
|
```
|
||||||
Confirm the Variables against these actual values, including photos.
|
Confirm the Variables/Secrets against these actual values, including photos.
|
||||||
2. Configure the Secret privately. Keep `PROD_DEPLOY_ENABLED=false`.
|
2. Configure the Secret privately. Keep `PROD_DEPLOY_ENABLED=false`.
|
||||||
3. Manually run **Verify Frame Flow** on `main`, `deploy_action=plan`.
|
3. Manually run **Verify Frame Flow** on `main`, `deploy_action=plan`.
|
||||||
Verify must pass first. Plan checks resource identity, paths/port, required
|
Verify must pass first. Plan checks resource identity, paths/port, required
|
||||||
@@ -107,7 +108,7 @@ been performed during implementation; those are first-run acceptance steps.
|
|||||||
an immutable rollback tag so normal dangling-image cleanup cannot remove it.
|
an immutable rollback tag so normal dangling-image cleanup cannot remove it.
|
||||||
4. Refuse a stale checked-out `main` revision that no longer equals remote main.
|
4. Refuse a stale checked-out `main` revision that no longer equals remote main.
|
||||||
Build an immutable `release-<commit>-<owner>` tag locally, without a registry
|
Build an immutable `release-<commit>-<owner>` tag locally, without a registry
|
||||||
and without changing `latest` or CI image tags.
|
then point `latest` at the candidate; CI image tags are never changed.
|
||||||
5. Persist a `prepared` journal with old/new runtime configs. Create an additive
|
5. Persist a `prepared` journal with old/new runtime configs. Create an additive
|
||||||
SQLite online backup under `/data/deploy-backups/<owner>.db`. No data/config
|
SQLite online backup under `/data/deploy-backups/<owner>.db`. No data/config
|
||||||
directory or file is removed, replaced or recursively chowned.
|
directory or file is removed, replaced or recursively chowned.
|
||||||
@@ -174,17 +175,17 @@ The confirmed NAS residue is a `created`, never-started container with dead
|
|||||||
`/workspace/way/...` bind paths. It is not an adoption/rollback baseline.
|
`/workspace/way/...` bind paths. It is not an adoption/rollback baseline.
|
||||||
No migration from those paths is performed. Production Compose remains independently usable.
|
No migration from those paths is performed. Production Compose remains independently usable.
|
||||||
|
|
||||||
Set these repository Actions **Variables** (not Secrets):
|
Set the ordinary repository Actions Variables below; set paths and addresses as Secrets (see docs/PUBLICATION.md):
|
||||||
|
|
||||||
```text
|
```text
|
||||||
PROD_DEPLOY_ENABLED=true
|
PROD_DEPLOY_ENABLED=true
|
||||||
PROD_PROJECT=pigway-frame-flow
|
PROD_PROJECT=pigway-frame-flow
|
||||||
PROD_CONTAINER=pigway-frame-flow
|
PROD_CONTAINER=pigway-frame-flow
|
||||||
PROD_IMAGE_REPO=pigway-frame-flow
|
PROD_IMAGE_REPO=pigway-frame-flow
|
||||||
PROD_DATA_DIR=/volume2/docker/pigway-frame-flow/data
|
PROD_DATA_DIR=/volume1/docker/pigway-frame-flow/data
|
||||||
PROD_CONFIG_DIR=/volume2/docker/pigway-frame-flow/config
|
PROD_CONFIG_DIR=/volume1/docker/pigway-frame-flow/config
|
||||||
PROD_WEB_BIND=192.0.2.10
|
PROD_WEB_BIND=192.0.2.10
|
||||||
PROD_WEB_PORT=18787
|
PROD_WEB_PORT=6005
|
||||||
PROD_STATE_VOLUME=pigway-frame-flow-cd-state
|
PROD_STATE_VOLUME=pigway-frame-flow-cd-state
|
||||||
PROD_MOCK=true
|
PROD_MOCK=true
|
||||||
PROD_WRITE_ENABLED=false
|
PROD_WRITE_ENABLED=false
|
||||||
@@ -262,11 +263,11 @@ as an Actions artifact. First bootstrap has no prior healthy version to roll bac
|
|||||||
No NAS bootstrap is executed merely by committing this implementation.
|
No NAS bootstrap is executed merely by committing this implementation.
|
||||||
3. Require `BOOTSTRAP VERIFIED` in the deploy log. In Container Manager confirm
|
3. Require `BOOTSTRAP VERIFIED` in the deploy log. In Container Manager confirm
|
||||||
container `pigway-frame-flow` is running/healthy, user 10333, restart unless-stopped,
|
container `pigway-frame-flow` is running/healthy, user 10333, restart unless-stopped,
|
||||||
exact `/volume2/docker/pigway-frame-flow/{data,config}` mounts and
|
exact `/volume1/docker/pigway-frame-flow/{data,config}` mounts and
|
||||||
`192.0.2.10:18787` binding (not loopback).
|
`192.0.2.10:6005` binding (not loopback).
|
||||||
4. Open `http://192.0.2.10:18787/api/v1/version`; its `commit` must equal the full
|
4. Open `http://192.0.2.10:6005/api/v1/version`; its `commit` must equal the full
|
||||||
workflow checkout commit. Check `/ready` returns HTTP 200. The immutable image tag
|
workflow checkout commit. Check `/ready` returns HTTP 200. The immutable image tag
|
||||||
is `pigway-frame-flow:release-<commit>-<transaction>`; compare its image ID in
|
is `pigway-frame-flow:latest`; compare its image ID in
|
||||||
Container Manager with the running container.
|
Container Manager with the running container.
|
||||||
5. Keep `PROD_DEPLOY_ENABLED=true`. Subsequent main pushes Verify then deploy using
|
5. Keep `PROD_DEPLOY_ENABLED=true`. Subsequent main pushes Verify then deploy using
|
||||||
this same runtime and journal mechanism. The first update records bootstrap as
|
this same runtime and journal mechanism. The first update records bootstrap as
|
||||||
@@ -279,33 +280,56 @@ real host mounts and restart, remains the required live acceptance.
|
|||||||
|
|
||||||
## Actions download transport
|
## Actions download transport
|
||||||
|
|
||||||
Verify and deploy fetch commit-pinned Actions from the supporting repository
|
Verify and deploy reference official GitHub Actions directly, pinned to immutable
|
||||||
`https://tea.pigway.com/way/frame-flow-ci-actions`, subdirectories `checkout`
|
commits rather than moving tags:
|
||||||
and `setup-python`, at commit `bada0aa1b7e0d23fe9da66ce2ec9b193c211ea46`.
|
|
||||||
This avoids unstable NAS downloads from GitHub (EOF/timeouts in runs 27/28)
|
|
||||||
and slow external Gitea Action preparation (run 29, superseded).
|
|
||||||
|
|
||||||
The cache contains unmodified official upstream source, including MIT licenses:
|
| Action | Official upstream commit |
|
||||||
|
| --- | --- |
|
||||||
|
| actions/checkout v4 | 11d5960a326750d5838078e36cf38b85af677262 |
|
||||||
|
| actions/setup-python v5 | a26af69be951a213d495a4c3e4e4022e16d87065 |
|
||||||
|
|
||||||
| Action | Official upstream commit | Identical Git tree |
|
The workflow uses explicit `https://github.com/actions/...` URLs so Gitea's
|
||||||
| --- | --- | --- |
|
configured default Actions host cannot redirect downloads to the project owner's
|
||||||
| actions/checkout v4 | 11d5960a326750d5838078e36cf38b85af677262 | f8a7b72dc00648d050099727d25ca92a43ad1162 |
|
server. Forks download Actions through their own Runner/network; no public action
|
||||||
| actions/setup-python v5 | a26af69be951a213d495a4c3e4e4022e16d87065 | 568c6310706725a8b725497dbe6b3b909cbcf6cd |
|
mirror is served by this project. The former Tea auxiliary repository is private
|
||||||
|
and is no longer required by current workflows.
|
||||||
|
|
||||||
`UPSTREAM.json` records provenance. Upstream tag SHAs were checked using the official
|
Keep the Runner's action cache and Python toolcache persistent. For Gitea Runner
|
||||||
GitHub API; each cached subtree hash was compared to the upstream commit tree.
|
versions supporting `cache.offline_mode`, use a private Runner configuration:
|
||||||
No application secrets are stored in this public upstream-source cache; its own
|
|
||||||
Actions are disabled. Intentional action updates must repeat tree verification
|
|
||||||
and change the workflow pin. All validation steps remain unchanged.
|
|
||||||
|
|
||||||
Python toolcache misses may still require setup-python to download Python from
|
```yaml
|
||||||
its upstream release source. This removes Action source download dependence,
|
runner:
|
||||||
not every possible external download. No Runner or NAS network configuration is changed.
|
file: /data/.runner
|
||||||
|
cache:
|
||||||
|
offline_mode: true
|
||||||
|
```
|
||||||
|
|
||||||
|
In the Runner's own Compose service (not the application), set `HOME=/data` and
|
||||||
|
`CONFIG_FILE=/data/config.yaml`, with `/data` already persisted. Before recreating
|
||||||
|
an idle Runner, back up its configuration and copy the existing action cache from
|
||||||
|
`/root/.cache/act` to `/data/.cache/act`. Preserve registration, labels, image,
|
||||||
|
mounts and networks; do not interrupt active jobs or recreate other services.
|
||||||
|
Verify cached actions against the pinned upstream commit and tree before reuse.
|
||||||
|
This is administrator configuration, not a public workflow dependency.
|
||||||
|
|
||||||
|
Offline reuse avoids refreshing cached actions from GitHub on each job. Moving
|
||||||
|
tags/branches may remain at the cached version; this workflow deliberately pins
|
||||||
|
immutable SHAs. A new action URL or commit requires an initial download or verified
|
||||||
|
administrator prewarming; an old mirror subtree is not automatically equivalent
|
||||||
|
to an upstream Git repository. Do not prune Runner caches between jobs. Python
|
||||||
|
toolcache misses still download Python from its upstream release source. Network
|
||||||
|
failures remain failures, never reasons to skip validation or silently fall back
|
||||||
|
to the owner's Tea server.
|
||||||
|
|
||||||
|
Administrators needing a mainland-specific download route can configure their
|
||||||
|
own Runner/network cache privately. Such settings must not introduce public
|
||||||
|
workflow references to a personal mirror. This change does not modify NAS VPN,
|
||||||
|
proxy, firewall or other applications. All validation and deploy gates remain.
|
||||||
|
|
||||||
### Synology Photos dependencies
|
### Synology Photos dependencies
|
||||||
|
|
||||||
For a production photo source using Synology Photos person filtering, configure
|
For a production photo source using Synology Photos person filtering, configure
|
||||||
`SYNOLOGY_PHOTOS_URL` and `SYNOLOGY_PHOTOS_CERT_SHA256` as Gitea Variables. The
|
`SYNOLOGY_PHOTOS_URL` and `SYNOLOGY_PHOTOS_CERT_SHA256` as Gitea Secrets. The
|
||||||
certificate fingerprint must match the configured HTTPS endpoint. Keep the Photos
|
certificate fingerprint must match the configured HTTPS endpoint. Keep the Photos
|
||||||
session in the persistent `/config` directory; never put session credentials in
|
session in the persistent `/config` directory; never put session credentials in
|
||||||
Variables or repository files.
|
Variables or repository files.
|
||||||
@@ -340,3 +364,18 @@ the audit client's normal HTTP freshness rules. It is not a permanent offline
|
|||||||
snapshot or a cross-job cache. Raw network exceptions are omitted because proxy
|
snapshot or a cross-job cache. Raw network exceptions are omitted because proxy
|
||||||
URLs may contain credentials. Logs identify the advisory host and whether the
|
URLs may contain credentials. Logs identify the advisory host and whether the
|
||||||
complete audit succeeded.
|
complete audit succeeded.
|
||||||
|
|
||||||
|
### Production image retention
|
||||||
|
|
||||||
|
Production uses `pigway-frame-flow:latest`. Builds first create a unique release
|
||||||
|
image, then tag it as latest before activation. The old image is pinned during
|
||||||
|
an update so a failed deployment can restore it. Only after the new version
|
||||||
|
passes verification are old release/rollback images and duplicate tags removed.
|
||||||
|
After successful deployment, only the current production image remains; there
|
||||||
|
is no retained historical image for manual rollback. Rebuild a historical
|
||||||
|
revision before manually reverting a successful deployment.
|
||||||
|
|
||||||
|
Images referenced by other containers (including stopped containers), images
|
||||||
|
with unrelated tags, and CI resources remain protected. Cleanup never prunes
|
||||||
|
volumes, data, or shared build cache. Cleanup failure is a warning and does not
|
||||||
|
roll back a verified deployment. Failed deployments do not run cleanup.
|
||||||
|
|||||||
@@ -17,8 +17,11 @@ Authorization: Bearer FRAME_FLOW_TOKEN. The bootstrap token is provided through
|
|||||||
client_id, name, permissions, enabled, created_at, last_used_at. Permissions:
|
client_id, name, permissions, enabled, created_at, last_used_at. Permissions:
|
||||||
devices:read, images:read, images:delete, display:write, templates:read, render:write,
|
devices:read, images:read, images:delete, display:write, templates:read, render:write,
|
||||||
jobs:read, jobs:write, history:read, settings:write, admin.
|
jobs:read, jobs:write, history:read, settings:write, admin.
|
||||||
0.1.0 seeds one admin token; provisioning scoped client rows is supported by middleware
|
The deployment token seeds an administrator. Administrators can create separate
|
||||||
but multi-token management UI is not implemented. Use a trusted server-to-server
|
scoped clients through Connections or POST /api/v1/clients. The returned token is
|
||||||
|
shown once; GET /api/v1/clients never returns tokens. DELETE /api/v1/clients/{id}
|
||||||
|
revokes access. For Ticktar, grant devices:read, templates:read, render:write and
|
||||||
|
display:write; add images:read or jobs permissions only when needed. Use a trusted server-to-server
|
||||||
connection; CORS is opt-in by exact origins, never wildcard by default.
|
connection; CORS is opt-in by exact origins, never wildcard by default.
|
||||||
|
|
||||||
## Discovery and capabilities
|
## Discovery and capabilities
|
||||||
@@ -86,13 +89,19 @@ The authenticated client is authoritative; source.client is optional metadata.
|
|||||||
History stores client_id/request_id/operation_id/device_id/action/result/timestamp.
|
History stores client_id/request_id/operation_id/device_id/action/result/timestamp.
|
||||||
No internal endpoints, headers, stacks, paths or secrets are returned.
|
No internal endpoints, headers, stacks, paths or secrets are returned.
|
||||||
|
|
||||||
## Future webhook
|
## Webhooks
|
||||||
|
|
||||||
SQLite events and webhook_subscriptions reserve operation.completed/failed,
|
Administrators register callbacks through POST /api/v1/webhooks. Allowed public
|
||||||
display.changed, device.online/offline/low_battery events. 0.1.0 emits operation/display
|
HTTPS hosts must be configured explicitly. Durable callbacks cover
|
||||||
events only; no callback delivery, retry worker or registration API is implemented.
|
operation.completed, operation.failed, display.changed and observed
|
||||||
Future deliveries should use signed payloads and bounded retries.
|
device.online/device.offline/device.low_battery transitions. Device observation
|
||||||
OAuth, tenancy, RBAC management and generated SDKs are future work.
|
runs at most once per minute; failed cloud queries do not imply offline.
|
||||||
|
|
||||||
|
X-Frame-Flow-Signature: sha256=<hex> is HMAC-SHA256 over the exact request body.
|
||||||
|
Signing secrets are shown once and stored in mode-0600 files. Verify signatures
|
||||||
|
and deduplicate event IDs. Delivery retries at most three times; events before
|
||||||
|
registration are not replayed. Polling Operations remains available.
|
||||||
|
OAuth, tenancy and generated SDKs are future work.
|
||||||
|
|
||||||
## Compatibility
|
## Compatibility
|
||||||
|
|
||||||
|
|||||||
+4950
-139
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,31 @@
|
|||||||
|
# Pigway Frame Flow v0.1.5
|
||||||
|
|
||||||
|
## 简体中文
|
||||||
|
|
||||||
|
- 图片仅在真实图片区域内居中显示加载动画,无页面骨架、虚构图片卡片或人为展示延时;请求及解码完成后立即显示,失败时显示局部提示。
|
||||||
|
- 图库搜索、排序、卡片操作及写入保护先于图片请求初始化,复用真实列表元数据;本地任务筛选异步填充,不阻塞其他控件。
|
||||||
|
- 手动拼版改为并行加载,各图独立完成或失败;固定区域容器保留坐标和拖动交互,加载前后位置一致。
|
||||||
|
- 修复手机底栏文字裁切、窄屏页头拥挤和横屏导航可达性,支持底部安全区域,补齐表单标签和当前导航无障碍状态。
|
||||||
|
- 默认对外访问端口改为 **6005**。本地启动、Compose、测试地址及文档同步;容器内部仍监听 18787。
|
||||||
|
|
||||||
|
### 验证
|
||||||
|
|
||||||
|
本地 505 项 Python 测试、Ruff、格式检查、mypy、JavaScript 语法和差异检查通过。
|
||||||
|
浏览器回归:布局 305 项、图片加载 45 项、图库加载顺序 14 项、手动拼版 31 项通过。
|
||||||
|
先行 UI 部署的生产静态文件哈希、health/ready 和拦截测试数据下的浏览器交互已验证;
|
||||||
|
不代表真实 AI 生成、画框写入、手机实机或软键盘测试。
|
||||||
|
|
||||||
|
### 升级说明
|
||||||
|
|
||||||
|
已有安装须更新私有环境配置中的 `WEB_PORT=6005`,并重建服务后生效。
|
||||||
|
自动部署的 `PROD_WEB_PORT` 必须与现有实例的映射一致;仅修改该变量不能迁移端口。
|
||||||
|
NAS 附件是源码部署包,需自行构建 Docker 镜像,不含密钥、运行配置、数据库或私人照片。
|
||||||
|
|
||||||
|
## English
|
||||||
|
|
||||||
|
Image loading indicators stay inside real image regions, without page skeletons or artificial delays.
|
||||||
|
Gallery controls initialize before image requests. Manual collage images load independently in parallel,
|
||||||
|
with stable regions and working coordinate/drag controls. Mobile navigation, safe-area spacing and form
|
||||||
|
accessibility are improved. The default published port is now **6005**, mapped to container port 18787.
|
||||||
|
Existing installations must update their private port configuration and recreate the service.
|
||||||
|
NAS source package and SHA256 checksum are included; this is not a prebuilt Docker image.
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
# Pigway Frame Flow v0.1.6
|
||||||
|
|
||||||
|
## 简体中文
|
||||||
|
|
||||||
|
- 图库使用具体目的地标签:`KoKonna 云端图库` 与 `<NAS 名称> 本地图库`,NAS 名称通过 `FRAME_FLOW_STORAGE_NAME` 配置。
|
||||||
|
- Settings API 增加目的地元数据,标签仅展示连接已配置、明确支持保存且存在适配器的目的地;全局写入保护保持独立。
|
||||||
|
- 后续网盘须实现读取/保存适配器并完成连接后才能加入标签栏,显示具体服务商/实例名称。当前只读照片来源不会作为保存目的地展示。
|
||||||
|
- 长标签在手机上换行,避免整页横向溢出;中英文保持相同目的地身份。
|
||||||
|
- Compose 和自动部署透传 NAS 展示名称;分支 CI 完整验证后发布标签,避免相同提交的标签推送重复占用构建队列。
|
||||||
|
|
||||||
|
### 验证
|
||||||
|
|
||||||
|
本地 507 项 Python 测试、Ruff、格式检查、mypy、JavaScript 语法检查通过。
|
||||||
|
图库目的地标签与能力过滤 18 项浏览器检查通过;覆盖 320–1440 像素、中英文、明暗主题和长 NAS 名称。
|
||||||
|
本次不增加任何网盘写入功能,不改变画框写入策略。
|
||||||
|
|
||||||
|
### 升级
|
||||||
|
|
||||||
|
Compose 设置 `FRAME_FLOW_STORAGE_NAME`;Actions 设置同名仓库 Variable。
|
||||||
|
名称只描述实例,不作为路径或授权凭据。未设置时回退为 NAS。
|
||||||
|
默认访问端口仍为 6005,容器内部端口仍为 18787。
|
||||||
|
NAS 源码包与 SHA256 附件不含运行配置、密钥、数据库或私人照片,需自行构建镜像。
|
||||||
|
|
||||||
|
## English
|
||||||
|
|
||||||
|
Gallery tabs identify the concrete destination: KoKonna cloud gallery and the configured NAS name plus Local gallery.
|
||||||
|
Destination metadata includes connection and upload capabilities; only implemented writable adapters are shown.
|
||||||
|
Existing read-only cloud photo sources are not presented as save destinations. Long labels wrap on mobile.
|
||||||
|
Set FRAME_FLOW_STORAGE_NAME in Compose or the Actions repository Variables. No cloud-drive write support or device write policy is changed.
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
# Pigway Frame Flow v0.1.7
|
||||||
|
|
||||||
|
## 简体中文
|
||||||
|
|
||||||
|
修复首次打开图库时内容区空白、必须等待云端图片列表返回才出现控件的问题。
|
||||||
|
|
||||||
|
- 目的地标签、搜索、排序、刷新和上传按钮立即初始化,图片列表独立请求。
|
||||||
|
- 仅在工具栏提示正在读取列表;未知数量时不生成图片卡片,不提前显示“图库为空”。实际图片仍在自己的区域内独立加载。
|
||||||
|
- 启动使用轻量设备身份目录,完整设备状态在后台更新,避免厂商状态请求阻塞首屏。
|
||||||
|
- 慢请求期间可以切换到 NAS 图库;过期响应不会覆盖当前页面。
|
||||||
|
- 列表失败时保留控件并在工具栏显示错误,仍可刷新或切换目的地。
|
||||||
|
- 保留等待期间输入的搜索词和排序选择;本地任务筛选请求在同一次导航内复用。
|
||||||
|
|
||||||
|
### 验证
|
||||||
|
|
||||||
|
本地 508 项 Python 测试、Ruff、格式检查、mypy 和 JavaScript 语法检查通过。
|
||||||
|
新增首次未缓存列表的控件就绪、输入保留、慢云端切换和列表失败回归。
|
||||||
|
不增加图库列表的服务端缓存,不修改厂商请求重试、照片、生成内容或设备写入策略。
|
||||||
|
|
||||||
|
## English
|
||||||
|
|
||||||
|
Fix the blank gallery on its first uncached visit. Destination tabs and gallery controls initialize before metadata requests complete.
|
||||||
|
Slow or failed cloud listing does not prevent switching to NAS storage. Search and sort choices survive list arrival, and stale responses cannot replace the active destination.
|
||||||
|
Only a small toolbar status indicates metadata loading; real images keep independent loading indicators.
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
# Pigway Frame Flow v0.1.8
|
||||||
|
|
||||||
|
增加 NAS 本地图库反选、放大总览图片,并统一图片查看器与界面表达。
|
||||||
|
|
||||||
|
- 反选只切换当前页可见图片的勾选状态;隐藏勾选项的批量操作范围明确提示。
|
||||||
|
- 总览当前图片预览增大,点击或键盘打开与图库相同的查看器,读取原图并支持适应屏幕、原始尺寸和 Esc 关闭。
|
||||||
|
- 修正图库排序、播放顺序、型号信息来源、云端确认状态等标签,补齐天气与连接状态翻译。
|
||||||
|
- 区分本地与云端删除影响,解释星标保留规则,避免对未知来源作无依据判断。
|
||||||
|
- 修正数据源空态、路径与凭据说明;同步 README 和操作文档中的共享 Photos 登录机制与入口。
|
||||||
|
|
||||||
|
验证:305 项布局检查、8 组星标与反选检查、12 组总览查看器检查、45 项图片加载检查及新增中英文文案检查通过。全套后端与静态检查由本次发布流水线再次验证。检查不涉及真实照片删除、设备写入或收费 AI 调用。
|
||||||
|
|
||||||
|
Improve NAS gallery selection, dashboard image viewing and UI wording. Invert selection affects visible items on the current page. Dashboard previews open the same full-image viewer as the gallery. Storage destinations, deletion scope, server-side stars, cloud confirmation and shared Photos credentials are clarified in both languages.
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
# v0.1.9
|
||||||
|
|
||||||
|
照片来源通过 Synology Photos API 按账号权限读取,共享/个人空间、人物 any/all 筛选和有界 XL 预览缓存可用。生产拒绝文件系统照片来源及 /photos 挂载;本地上传、生成图片和 Server 本地图库继续保留。NAS 原图下载接口曾被拒绝,本版不宣称支持原图下载。
|
||||||
|
|
||||||
|
自动化新增 1~10080 分钟的真实间隔,跨整点与跨天不按 Cron 字段重置,既有 Cron 任务保持原样。显示时长明确为到期恢复期限。统一来源快捷创建任务编辑器,改善登录及来源表单响应式布局、设备显示名与历史记录中英文;诊断详情保留原始标识。
|
||||||
|
|
||||||
|
## 生产部署
|
||||||
|
|
||||||
|
生产已迁至 Ubuntu Server,由 systemd 管理 Docker;业务、Docker 数据和恢复资料位于 T7,并有 UUID 与挂载依赖保护。NAS 旧 Frame 专属资源已清理且独立复核 PASS。CI 保留隔离验证,移除 NAS 自动生产部署任务,不再向 NAS 发布。
|
||||||
|
|
||||||
|
正式发布使用 scripts/server-release.py:仅在既有 Ubuntu Server 环境运行,从已提交源码包构建,校验依赖锁、源码哈希、T7 UUID、容器安全约束和真实写入设置;备份 SQLite、配置及 Compose 后切换镜像,失败恢复旧 Compose,不自动回写旧数据库。它不执行上传、显示、删除或恢复图片等设备操作。成功后记录正式提交号、保存源码包及审计回执,删除本次暂存目录;白名单内的 Frame 旧迁移输入归档到本次 recovery,清除无恢复引用的临时镜像别名,共享 Console 资料不动。旧镜像及历史恢复资料保留供回滚,不执行全局 prune。
|
||||||
|
|
||||||
|
脚本要求由 git archive 生成的源码放在 /srv/pigway/migration-inbox 的独立子目录;目录内同时提供 RELEASE_COMMIT、RELEASE_HASHES.json 和原始 source.tar.gz。哈希清单涵盖源码与源码包,不含自身。执行 sudo python3 <暂存目录>/scripts/server-release.py;成功后读取 /srv/pigway/apps/pigway-frame-flow/release-verification.json 并独立检查线上接口。
|
||||||
|
|
||||||
|
## 验收范围
|
||||||
|
|
||||||
|
完整后端测试、静态检查与桌面/平板/手机的中英文浏览器回归纳入发布检查。线上历史补丁已核验,真实写入保持开启;本轮正式发布不重复真实设备写入测试。隔离浏览器验证与真实设备写入证据分别记录于 docs/verification/2026-10-17-final-audit.md。
|
||||||
|
|
||||||
|
局域网 HTTPS、独立加密备份及恢复演练仍是后续工作;T7 recovery 不属于独立备份。没有执行 USB 断连、服务器重启或压力测试。
|
||||||
@@ -0,0 +1,84 @@
|
|||||||
|
# KoKonna local-control investigation
|
||||||
|
|
||||||
|
Reviewed 2026-10-06. No frame writes, network changes, or firmware changes.
|
||||||
|
|
||||||
|
## Sources and limits
|
||||||
|
|
||||||
|
- Official FAQ: https://kokonna.art/pages/faq explicitly describes Bluetooth
|
||||||
|
upload and switching. This is a product-level claim, not verified B101 behavior.
|
||||||
|
- Public OpenAPI: https://kokonna.art/pages/openapi documents cloud HTTPS calls.
|
||||||
|
- Existing official Android nightly 1.6.5 APK from the prior download:
|
||||||
|
SHA256 `8f611bf74bbda70e7e7a5d087e4065dc6000849dcd2f12538d5ff5017c91e1c0`.
|
||||||
|
Static inspection of its packaged app-service.js; no vendor code is copied here.
|
||||||
|
- Searches found community API clients, but no verified B101 firmware source or
|
||||||
|
documented bring-your-own-server configuration. Absence from search is not
|
||||||
|
proof that firmware source or another configuration path does not exist.
|
||||||
|
|
||||||
|
## Observed client behavior
|
||||||
|
|
||||||
|
The account client uses `https://robot.galaxyguide.cn/api/rpc`. Its Bluetooth
|
||||||
|
upload flow calls `appFrame.uploadImage` with base64 and `synced: true`, receives
|
||||||
|
an image ID, downloads the resulting image from the vendor server, and sends
|
||||||
|
the bytes to the frame over BLE. Therefore this observed flow still exposes
|
||||||
|
the original image to the vendor cloud.
|
||||||
|
|
||||||
|
BLE service UUID: `4fafc201-1fb5-459e-8fcc-c5c9c331914b`.
|
||||||
|
Characteristic UUID: `beb5483e-36e1-4688-b7f5-ea07361b26a7`.
|
||||||
|
|
||||||
|
Observed JSON commands include `get_info`, `refresh_image`, and `set_image`.
|
||||||
|
Image transfer uses start metadata (ID, rotation, type, size, chunk count),
|
||||||
|
numbered binary chunks, sync acknowledgements/missing-chunk information, and
|
||||||
|
an end command. The client chooses `y4` for firmware starting with B103 and
|
||||||
|
`jpg` otherwise. That makes local JPEG transmission a plausible B101 research
|
||||||
|
path, not a proven implementation: cloud-independent IDs, processing, firmware
|
||||||
|
acceptance, pairing and completion semantics still require validation.
|
||||||
|
|
||||||
|
The observed `set_config` payload contains `slideType`, `slideMinute`, and
|
||||||
|
`nickname`; `set_wifi` contains SSID and password. No server-host setter was
|
||||||
|
found in these paths or common host-setting symbol searches.
|
||||||
|
|
||||||
|
## Host replacement assessment
|
||||||
|
|
||||||
|
Changing Frame Flow's API base URL changes where Frame Flow sends requests,
|
||||||
|
not where the frame connects. Replacing the frame's cloud server requires its
|
||||||
|
device-side protocol and a supported address-setting mechanism or firmware
|
||||||
|
change. DNS redirection alone may fail HTTPS certificate validation and still
|
||||||
|
requires a compatible server implementation. TLS/pinning and actual device
|
||||||
|
polling transport have not been established from this APK.
|
||||||
|
|
||||||
|
Next read-only step: inspect BLE `get_info` and installed firmware compatibility.
|
||||||
|
Any subsequent local image write needs a separate controlled test. No BLE driver
|
||||||
|
is enabled by this investigation.
|
||||||
|
|
||||||
|
## Wi-Fi-only follow-up
|
||||||
|
|
||||||
|
The user excluded Bluetooth and additional gateways. The target is NAS-to-frame
|
||||||
|
Wi-Fi control with the original hardware.
|
||||||
|
|
||||||
|
GitHub's public repository search for `kokonna` returned three repositories:
|
||||||
|
`patrickchen914/kokonna`, `nixihz/kokonna-skill`, and
|
||||||
|
`zhengweiran66-eng/kokonna-product.html`. These provide a Home Assistant cloud
|
||||||
|
integration, an OpenAPI CLI, and a product page, respectively; no verified B101
|
||||||
|
device firmware or Wi-Fi local-server implementation was identified.
|
||||||
|
|
||||||
|
Static APK checks found no hard-coded private IPv4 target, WebSocket URL,
|
||||||
|
custom image-URL setter, or common server-host setter symbols in app-service.js.
|
||||||
|
This does not exclude hidden firmware features or native-library code paths.
|
||||||
|
`app.getFirmwares` is called with `robotId`. Upgrade submission passes a firmware
|
||||||
|
name, locale and distributor ID through `app.setUpgradeFirmware`; the inspected
|
||||||
|
UI does not supply a user-selected firmware download URL. Neither method was
|
||||||
|
called during this investigation. Existing account RPC allowlists remain intact.
|
||||||
|
|
||||||
|
Candidate paths, none yet verified:
|
||||||
|
|
||||||
|
1. A device-local HTTP/TCP service: requires a confirmed frame LAN address and
|
||||||
|
bounded service inspection while the frame is awake.
|
||||||
|
2. A firmware-supported custom server or image URL: requires configuration or
|
||||||
|
firmware evidence, not simply replacing the application's API host.
|
||||||
|
3. A NAS implementation of the device's cloud protocol: requires the actual
|
||||||
|
polling/download protocol and address/TLS behavior. Passive observation at
|
||||||
|
the existing gateway may provide evidence; a normal NAS on a switched LAN
|
||||||
|
cannot assume it sees another device's outbound packets.
|
||||||
|
|
||||||
|
No DNS redirection, router interception, certificate replacement, firmware
|
||||||
|
upgrade, reset, or automatic display change was performed.
|
||||||
@@ -29,12 +29,15 @@ from pigway_frame_flow.models import (
|
|||||||
Accepted,
|
Accepted,
|
||||||
Asset,
|
Asset,
|
||||||
AssetBatch,
|
AssetBatch,
|
||||||
|
AutoCollageContent,
|
||||||
CurrentDisplay,
|
CurrentDisplay,
|
||||||
DeleteRequest,
|
DeleteRequest,
|
||||||
Device,
|
Device,
|
||||||
|
DeviceIdentity,
|
||||||
DisplayRequest,
|
DisplayRequest,
|
||||||
ErrorResponse,
|
ErrorResponse,
|
||||||
Fit,
|
Fit,
|
||||||
|
GalleryDestination,
|
||||||
GalleryImage,
|
GalleryImage,
|
||||||
Health,
|
Health,
|
||||||
History,
|
History,
|
||||||
@@ -123,7 +126,7 @@ def create_app(settings=None, start_worker=True):
|
|||||||
app = FastAPI(
|
app = FastAPI(
|
||||||
title="Pigway Frame Flow API",
|
title="Pigway Frame Flow API",
|
||||||
docs_url=None,
|
docs_url=None,
|
||||||
version="0.1.0",
|
version="0.1.9",
|
||||||
lifespan=lifespan,
|
lifespan=lifespan,
|
||||||
responses=error_responses,
|
responses=error_responses,
|
||||||
)
|
)
|
||||||
@@ -485,7 +488,7 @@ def create_app(settings=None, start_worker=True):
|
|||||||
dependencies=[Depends(require("render:write"))],
|
dependencies=[Depends(require("render:write"))],
|
||||||
)
|
)
|
||||||
def render(
|
def render(
|
||||||
payload: TemplateContent,
|
payload: TemplateContent | AutoCollageContent,
|
||||||
request: Request,
|
request: Request,
|
||||||
idempotency_key: str | None = Header(default=None),
|
idempotency_key: str | None = Header(default=None),
|
||||||
):
|
):
|
||||||
@@ -999,7 +1002,36 @@ def create_app(settings=None, start_worker=True):
|
|||||||
)
|
)
|
||||||
def settings_view():
|
def settings_view():
|
||||||
return SettingsView(
|
return SettingsView(
|
||||||
version="0.1.0",
|
storage_name=settings.storage_name,
|
||||||
|
# Page navigation needs device identity, not a fresh cloud status request.
|
||||||
|
device_catalog=[
|
||||||
|
DeviceIdentity(
|
||||||
|
id=id,
|
||||||
|
name=getattr(getattr(driver, "cached", None), "name", id),
|
||||||
|
)
|
||||||
|
for id, driver in registry.drivers.items()
|
||||||
|
],
|
||||||
|
gallery_destinations=[
|
||||||
|
GalleryDestination(
|
||||||
|
id="cloud",
|
||||||
|
adapter="kokonna",
|
||||||
|
name="KoKonna",
|
||||||
|
storage="cloud",
|
||||||
|
supports_upload=True,
|
||||||
|
connected=settings.mock
|
||||||
|
or bool(settings.api_key)
|
||||||
|
or any(registry.keys),
|
||||||
|
),
|
||||||
|
GalleryDestination(
|
||||||
|
id="local",
|
||||||
|
adapter="local-assets",
|
||||||
|
name=settings.storage_name,
|
||||||
|
storage="local",
|
||||||
|
connected=True,
|
||||||
|
supports_upload=True,
|
||||||
|
),
|
||||||
|
],
|
||||||
|
version="0.1.9",
|
||||||
mock=settings.mock,
|
mock=settings.mock,
|
||||||
write_enabled=settings.write_enabled,
|
write_enabled=settings.write_enabled,
|
||||||
api_key_configured=bool(settings.api_key)
|
api_key_configured=bool(settings.api_key)
|
||||||
@@ -1175,9 +1207,11 @@ def create_app(settings=None, start_worker=True):
|
|||||||
idempotency_key: str | None = Header(default=None),
|
idempotency_key: str | None = Header(default=None),
|
||||||
):
|
):
|
||||||
source = get_job(job_id)["source"]
|
source = get_job(job_id)["source"]
|
||||||
if source["type"] != "template":
|
if source["type"] not in ("template", "auto_collage"):
|
||||||
raise FlowError(
|
raise FlowError(
|
||||||
E.UNSUPPORTED_CAPABILITY, "Job preview requires a template source", 422
|
E.UNSUPPORTED_CAPABILITY,
|
||||||
|
"Job preview requires template or auto-collage content",
|
||||||
|
422,
|
||||||
)
|
)
|
||||||
return submit(
|
return submit(
|
||||||
request, "render", source, get_job(job_id)["device_id"], idempotency_key
|
request, "render", source, get_job(job_id)["device_id"], idempotency_key
|
||||||
|
|||||||
@@ -23,7 +23,7 @@ class CloudLibrary:
|
|||||||
job_id = (
|
job_id = (
|
||||||
job["job_id"]
|
job["job_id"]
|
||||||
if job
|
if job
|
||||||
and content.get("type") == "photo_source"
|
and content.get("type") in ("photo_source", "auto_collage")
|
||||||
and content.get("item_id") is None
|
and content.get("item_id") is None
|
||||||
else None
|
else None
|
||||||
)
|
)
|
||||||
@@ -101,7 +101,7 @@ class CloudLibrary:
|
|||||||
return True
|
return True
|
||||||
|
|
||||||
def sweep(self):
|
def sweep(self):
|
||||||
if time.monotonic() - self.checked < 60:
|
if self.checked and time.monotonic() - self.checked < 60:
|
||||||
return
|
return
|
||||||
self.checked = time.monotonic()
|
self.checked = time.monotonic()
|
||||||
with self.service.lock:
|
with self.service.lock:
|
||||||
|
|||||||
@@ -0,0 +1,73 @@
|
|||||||
|
"""Durable, read-only recovery progress for writes with uncertain outcomes."""
|
||||||
|
|
||||||
|
from datetime import UTC, datetime
|
||||||
|
from uuid import uuid4
|
||||||
|
|
||||||
|
from pigway_frame_flow.storage.database import encode, now_iso
|
||||||
|
|
||||||
|
|
||||||
|
class RecoveryMonitor:
|
||||||
|
def __init__(self, service):
|
||||||
|
self.service, self.db = service, service.db
|
||||||
|
|
||||||
|
def observe(self, op, reason):
|
||||||
|
timestamp = now_iso()
|
||||||
|
age = (
|
||||||
|
datetime.now(UTC) - datetime.fromisoformat(op["created_at"])
|
||||||
|
).total_seconds()
|
||||||
|
review = age >= self.service.settings.sync_timeout + 300
|
||||||
|
with self.db.transaction() as tx:
|
||||||
|
previous = tx.execute(
|
||||||
|
"SELECT * FROM operation_recovery WHERE operation_id=?", (op["id"],)
|
||||||
|
).fetchone()
|
||||||
|
# Once escalated, wall-clock corrections must not clear the alert.
|
||||||
|
review = review or bool(previous and previous["state"] == "manual_review")
|
||||||
|
state = "manual_review" if review else "checking"
|
||||||
|
tx.execute(
|
||||||
|
"INSERT INTO operation_recovery VALUES(?,?,?,?,?,1) ON CONFLICT(operation_id) DO UPDATE SET state=excluded.state,reason=excluded.reason,last_checked_at=excluded.last_checked_at,checks=operation_recovery.checks+1",
|
||||||
|
(op["id"], state, reason, timestamp, timestamp),
|
||||||
|
)
|
||||||
|
if review and (not previous or previous["state"] != "manual_review"):
|
||||||
|
tx.execute(
|
||||||
|
"INSERT INTO events VALUES(?,?,?,?)",
|
||||||
|
(
|
||||||
|
uuid4().hex,
|
||||||
|
"operation.blocked",
|
||||||
|
encode(
|
||||||
|
{
|
||||||
|
"operation_id": op["id"],
|
||||||
|
"device_id": op["device_id"],
|
||||||
|
"reason": reason,
|
||||||
|
"requires_manual_review": True,
|
||||||
|
}
|
||||||
|
),
|
||||||
|
timestamp,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
tx.execute(
|
||||||
|
"INSERT INTO history(client_id,request_id,operation_id,device_id,action,result,timestamp) VALUES(?,?,?,?,?,?,?)",
|
||||||
|
(
|
||||||
|
op["client_id"],
|
||||||
|
op["request_id"],
|
||||||
|
op["id"],
|
||||||
|
op["device_id"],
|
||||||
|
op["action"],
|
||||||
|
"MANUAL_REVIEW_REQUIRED",
|
||||||
|
timestamp,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
|
def resolve(self, operation_id):
|
||||||
|
self.db.execute(
|
||||||
|
"UPDATE operation_recovery SET state='resolved' WHERE operation_id=? AND state!='resolved'",
|
||||||
|
(operation_id,),
|
||||||
|
)
|
||||||
|
|
||||||
|
def info(self, operation_id):
|
||||||
|
row = self.db.one(
|
||||||
|
"SELECT state,reason,first_checked_at,last_checked_at,checks FROM operation_recovery WHERE operation_id=?",
|
||||||
|
(operation_id,),
|
||||||
|
)
|
||||||
|
if row:
|
||||||
|
row["requires_manual_review"] = row["state"] == "manual_review"
|
||||||
|
return row
|
||||||
@@ -90,7 +90,7 @@ class Retention:
|
|||||||
)
|
)
|
||||||
|
|
||||||
def sweep(self):
|
def sweep(self):
|
||||||
if time.monotonic() - self.checked < 3600:
|
if self.checked and time.monotonic() - self.checked < 3600:
|
||||||
return
|
return
|
||||||
self.checked = time.monotonic()
|
self.checked = time.monotonic()
|
||||||
with self.service.lock:
|
with self.service.lock:
|
||||||
|
|||||||
@@ -6,11 +6,14 @@ from datetime import UTC, datetime, timedelta
|
|||||||
from uuid import uuid4
|
from uuid import uuid4
|
||||||
|
|
||||||
from pigway_frame_flow.display.cloud_library import CloudLibrary
|
from pigway_frame_flow.display.cloud_library import CloudLibrary
|
||||||
|
from pigway_frame_flow.display.recovery import RecoveryMonitor
|
||||||
from pigway_frame_flow.display.retention import Retention
|
from pigway_frame_flow.display.retention import Retention
|
||||||
|
from pigway_frame_flow.display.upload_reconciliation import UploadReconciliation
|
||||||
from pigway_frame_flow.drivers.base import DriverRegistry
|
from pigway_frame_flow.drivers.base import DriverRegistry
|
||||||
from pigway_frame_flow.errors import ErrorCode as E
|
from pigway_frame_flow.errors import ErrorCode as E
|
||||||
from pigway_frame_flow.errors import FlowError
|
from pigway_frame_flow.errors import FlowError
|
||||||
from pigway_frame_flow.models import (
|
from pigway_frame_flow.models import (
|
||||||
|
AutoCollageContent,
|
||||||
DisplayRequest,
|
DisplayRequest,
|
||||||
FutureContent,
|
FutureContent,
|
||||||
ImageContent,
|
ImageContent,
|
||||||
@@ -48,7 +51,10 @@ class DisplayService:
|
|||||||
self.lock = threading.RLock()
|
self.lock = threading.RLock()
|
||||||
self.retention = Retention(self)
|
self.retention = Retention(self)
|
||||||
self.cloud_library = CloudLibrary(self)
|
self.cloud_library = CloudLibrary(self)
|
||||||
|
self.recovery = RecoveryMonitor(self)
|
||||||
|
self.upload_reconciliation = UploadReconciliation(self)
|
||||||
self.expiration_checked: dict[str, float] = {}
|
self.expiration_checked: dict[str, float] = {}
|
||||||
|
self.unknown_checked: dict[str, float] = {}
|
||||||
# A killed write cannot be replayed safely; pre-write work can resume.
|
# A killed write cannot be replayed safely; pre-write work can resume.
|
||||||
db.execute(
|
db.execute(
|
||||||
"UPDATE operations SET status='UNKNOWN', updated_at=? WHERE write_started=1 AND status IN ('UPLOADING','RENDERING')",
|
"UPDATE operations SET status='UNKNOWN', updated_at=? WHERE write_started=1 AND status IN ('UPLOADING','RENDERING')",
|
||||||
@@ -81,6 +87,11 @@ class DisplayService:
|
|||||||
) from None
|
) from None
|
||||||
for region in plan.regions:
|
for region in plan.regions:
|
||||||
self.assets.path(region.asset_id)
|
self.assets.path(region.asset_id)
|
||||||
|
if (
|
||||||
|
isinstance(request.content, AutoCollageContent)
|
||||||
|
and request.content.source_id
|
||||||
|
):
|
||||||
|
self.photo_sources.get(request.content.source_id)
|
||||||
if isinstance(request.content, PhotoSourceContent):
|
if isinstance(request.content, PhotoSourceContent):
|
||||||
self.photo_sources.get(request.content.source_id)
|
self.photo_sources.get(request.content.source_id)
|
||||||
if writing and not self.settings.mock and not self.settings.write_enabled:
|
if writing and not self.settings.mock and not self.settings.write_enabled:
|
||||||
@@ -156,14 +167,16 @@ class DisplayService:
|
|||||||
request_id=op["request_id"],
|
request_id=op["request_id"],
|
||||||
client_id=op["client_id"],
|
client_id=op["client_id"],
|
||||||
action=op["action"],
|
action=op["action"],
|
||||||
|
recovery=self.recovery.info(id),
|
||||||
)
|
)
|
||||||
|
|
||||||
def update(self, id, status, result=None, error=None):
|
def update(self, id, status, result=None, error=None):
|
||||||
if result:
|
if result:
|
||||||
row = self.db.one("SELECT result FROM operations WHERE id=?", (id,))
|
row = self.db.one("SELECT result FROM operations WHERE id=?", (id,))
|
||||||
previous = json.loads(row["result"]) if row and row["result"] else {}
|
previous = json.loads(row["result"]) if row and row["result"] else {}
|
||||||
if "photo_attempts" in previous:
|
for key in ("photo_attempts", "upload_intent"):
|
||||||
result = {**result, "photo_attempts": previous["photo_attempts"]}
|
if key in previous:
|
||||||
|
result = {**result, key: previous[key]}
|
||||||
self.db.execute(
|
self.db.execute(
|
||||||
"UPDATE operations SET status=?,updated_at=?,result=COALESCE(?,result),error=? WHERE id=?",
|
"UPDATE operations SET status=?,updated_at=?,result=COALESCE(?,result),error=? WHERE id=?",
|
||||||
(
|
(
|
||||||
@@ -174,6 +187,8 @@ class DisplayService:
|
|||||||
id,
|
id,
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
|
if status in ("COMPLETED", "FAILED"):
|
||||||
|
self.recovery.resolve(id)
|
||||||
|
|
||||||
def blocked(self, device_id):
|
def blocked(self, device_id):
|
||||||
return (
|
return (
|
||||||
@@ -191,6 +206,12 @@ class DisplayService:
|
|||||||
return self.db.one("SELECT * FROM device_state WHERE device_id=?", (id,))
|
return self.db.one("SELECT * FROM device_state WHERE device_id=?", (id,))
|
||||||
|
|
||||||
def content_asset(self, content, device_id=None, operation_id=None):
|
def content_asset(self, content, device_id=None, operation_id=None):
|
||||||
|
if isinstance(content, AutoCollageContent):
|
||||||
|
from pigway_frame_flow.extensions.auto_collage import prepare
|
||||||
|
|
||||||
|
return self.content_asset(
|
||||||
|
prepare(self, content, device_id), device_id, operation_id
|
||||||
|
)
|
||||||
if isinstance(content, ProviderContent):
|
if isinstance(content, ProviderContent):
|
||||||
values = {**content.data, **self.providers.get(content.provider_id)}
|
values = {**content.data, **self.providers.get(content.provider_id)}
|
||||||
return self.content_asset(
|
return self.content_asset(
|
||||||
@@ -426,7 +447,7 @@ class DisplayService:
|
|||||||
"code": exc.code,
|
"code": exc.code,
|
||||||
"message": exc.message,
|
"message": exc.message,
|
||||||
"request_id": op["request_id"],
|
"request_id": op["request_id"],
|
||||||
"details": {},
|
"details": exc.details,
|
||||||
}
|
}
|
||||||
self.update(
|
self.update(
|
||||||
op["id"], "UNKNOWN" if uncertain else "FAILED", error=error
|
op["id"], "UNKNOWN" if uncertain else "FAILED", error=error
|
||||||
@@ -614,6 +635,8 @@ class DisplayService:
|
|||||||
raise FlowError(
|
raise FlowError(
|
||||||
E.CONFLICT, "Temporary override requires an existing image", 409
|
E.CONFLICT, "Temporary override requires an existing image", 409
|
||||||
)
|
)
|
||||||
|
if asset:
|
||||||
|
self.upload_reconciliation.prepare(id, driver, asset, previous)
|
||||||
self._start_write(id)
|
self._start_write(id)
|
||||||
if asset:
|
if asset:
|
||||||
self.update(id, "UPLOADING")
|
self.update(id, "UPLOADING")
|
||||||
@@ -677,6 +700,63 @@ class DisplayService:
|
|||||||
)
|
)
|
||||||
|
|
||||||
def sync(self):
|
def sync(self):
|
||||||
|
with self.lock:
|
||||||
|
self._sync()
|
||||||
|
|
||||||
|
def _sync(self):
|
||||||
|
# Late acknowledgements only resolve a known display target. Never replay
|
||||||
|
# writes or infer success from gallery presence alone.
|
||||||
|
for op in self.db.all(
|
||||||
|
"SELECT * FROM operations WHERE status='UNKNOWN' AND action!='render-ai' AND write_started=1"
|
||||||
|
):
|
||||||
|
expected = json.loads(op["result"] or "{}").get("image_id")
|
||||||
|
intent = json.loads(op["result"] or "{}").get("upload_intent")
|
||||||
|
checked = time.monotonic()
|
||||||
|
if checked - self.unknown_checked.get(op["id"], float("-inf")) < 60:
|
||||||
|
continue
|
||||||
|
self.unknown_checked[op["id"]] = checked
|
||||||
|
if op["action"] != "display" or (not expected and not intent):
|
||||||
|
self.recovery.observe(
|
||||||
|
op,
|
||||||
|
"missing_upload_evidence"
|
||||||
|
if op["action"] == "display"
|
||||||
|
else "manual_reconciliation_required",
|
||||||
|
)
|
||||||
|
continue
|
||||||
|
try:
|
||||||
|
driver = self.registry.get(op["device_id"])
|
||||||
|
device = driver.device(refresh=True)
|
||||||
|
if intent:
|
||||||
|
expected = self.upload_reconciliation.check(op, driver, device)
|
||||||
|
if (
|
||||||
|
self.db.one(
|
||||||
|
"SELECT status FROM operations WHERE id=?", (op["id"],)
|
||||||
|
)["status"]
|
||||||
|
== "FAILED"
|
||||||
|
):
|
||||||
|
continue
|
||||||
|
if (
|
||||||
|
expected
|
||||||
|
and device.current_content.id == expected
|
||||||
|
and device.current_content.synced
|
||||||
|
):
|
||||||
|
self.update(op["id"], "COMPLETED")
|
||||||
|
self.cloud_library.confirm(op["id"])
|
||||||
|
self.db.history(op, "COMPLETED")
|
||||||
|
self.db.event("operation.completed", {"operation_id": op["id"]})
|
||||||
|
self.unknown_checked.pop(op["id"], None)
|
||||||
|
elif expected:
|
||||||
|
self.recovery.observe(
|
||||||
|
op,
|
||||||
|
"waiting_device_sync"
|
||||||
|
if device.current_content.id == expected
|
||||||
|
else "target_mismatch",
|
||||||
|
)
|
||||||
|
except FlowError:
|
||||||
|
self.recovery.observe(op, "read_unavailable")
|
||||||
|
except Exception:
|
||||||
|
# Bad vendor metadata for one operation must not stop the worker.
|
||||||
|
self.recovery.observe(op, "reconciliation_error")
|
||||||
for op in self.db.all("SELECT * FROM operations WHERE status='SYNCING'"):
|
for op in self.db.all("SELECT * FROM operations WHERE status='SYNCING'"):
|
||||||
try:
|
try:
|
||||||
device = self.registry.get(op["device_id"]).device()
|
device = self.registry.get(op["device_id"]).device()
|
||||||
@@ -809,9 +889,25 @@ class DisplayService:
|
|||||||
self.update(
|
self.update(
|
||||||
id,
|
id,
|
||||||
"COMPLETED" if confirmed else "FAILED",
|
"COMPLETED" if confirmed else "FAILED",
|
||||||
{"image_id": device.current_content.id},
|
op["result"],
|
||||||
|
error=None
|
||||||
|
if confirmed
|
||||||
|
else {
|
||||||
|
"code": E.DISPLAY_NOT_CONFIRMED
|
||||||
|
if op["action"] == "display"
|
||||||
|
else E.WRITE_RESULT_UNKNOWN,
|
||||||
|
"message": "Manually closed unconfirmed write; no write replayed",
|
||||||
|
"request_id": op["request_id"],
|
||||||
|
"details": {
|
||||||
|
"observed_image_id": device.current_content.id,
|
||||||
|
"previous_error": op["error"],
|
||||||
|
},
|
||||||
|
},
|
||||||
)
|
)
|
||||||
resolved = True
|
resolved = True
|
||||||
|
if confirmed and op["action"] == "display":
|
||||||
|
self.cloud_library.confirm(id)
|
||||||
|
self.db.event("operation.completed", {"operation_id": id})
|
||||||
self.db.history(
|
self.db.history(
|
||||||
dict(
|
dict(
|
||||||
id=id,
|
id=id,
|
||||||
|
|||||||
@@ -0,0 +1,164 @@
|
|||||||
|
"""Resolve missing upload responses using read-only, exact-content evidence."""
|
||||||
|
|
||||||
|
import hashlib
|
||||||
|
import json
|
||||||
|
from datetime import UTC, datetime, timedelta
|
||||||
|
|
||||||
|
from pigway_frame_flow.errors import ErrorCode
|
||||||
|
from pigway_frame_flow.storage.database import encode, now_iso
|
||||||
|
|
||||||
|
|
||||||
|
class UploadReconciliation:
|
||||||
|
def __init__(self, service):
|
||||||
|
self.service = service
|
||||||
|
|
||||||
|
def prepare(self, operation_id, driver, asset, previous):
|
||||||
|
path = self.service.assets.path(asset["asset_id"])
|
||||||
|
self.service.update(
|
||||||
|
operation_id,
|
||||||
|
"RENDERING",
|
||||||
|
{
|
||||||
|
"rendered_asset_id": asset["asset_id"],
|
||||||
|
"upload_intent": {
|
||||||
|
"name": asset["name"],
|
||||||
|
"sha256": hashlib.sha256(path.read_bytes()).hexdigest(),
|
||||||
|
"size": path.stat().st_size,
|
||||||
|
"before_ids": [image.image_id for image in driver.images()],
|
||||||
|
"previous_image_id": previous,
|
||||||
|
"started_at": now_iso(),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
def check(self, op, driver, device):
|
||||||
|
service = self.service
|
||||||
|
result = json.loads(op["result"] or "{}")
|
||||||
|
intent = result.get("upload_intent")
|
||||||
|
if not intent:
|
||||||
|
return None
|
||||||
|
expected = result.get("image_id")
|
||||||
|
if not expected:
|
||||||
|
start = datetime.fromisoformat(intent["started_at"])
|
||||||
|
candidates = []
|
||||||
|
for image in driver.images():
|
||||||
|
if (
|
||||||
|
image.image_id in intent["before_ids"]
|
||||||
|
or image.name != intent["name"]
|
||||||
|
):
|
||||||
|
continue
|
||||||
|
if image.size_bytes is not None and image.size_bytes != intent["size"]:
|
||||||
|
continue
|
||||||
|
if not image.created_at:
|
||||||
|
continue
|
||||||
|
try:
|
||||||
|
created = datetime.fromisoformat(image.created_at)
|
||||||
|
age = (created - start).total_seconds()
|
||||||
|
except (ValueError, TypeError):
|
||||||
|
continue
|
||||||
|
if 0 <= age <= service.settings.sync_timeout + 300:
|
||||||
|
candidates.append(image)
|
||||||
|
# Ambiguous matches never release a write lock.
|
||||||
|
if len(candidates) != 1:
|
||||||
|
service.recovery.observe(
|
||||||
|
op,
|
||||||
|
"gallery_match_missing"
|
||||||
|
if not candidates
|
||||||
|
else "gallery_match_ambiguous",
|
||||||
|
)
|
||||||
|
return None
|
||||||
|
expected = candidates[0].image_id
|
||||||
|
data = driver.download(expected)
|
||||||
|
if (
|
||||||
|
len(data) != intent["size"]
|
||||||
|
or hashlib.sha256(data).hexdigest() != intent["sha256"]
|
||||||
|
):
|
||||||
|
service.recovery.observe(op, "content_mismatch")
|
||||||
|
return None
|
||||||
|
result["image_id"] = expected
|
||||||
|
result["upload_confirmed"] = True
|
||||||
|
service.update(op["id"], "UNKNOWN", result, json.loads(op["error"] or "{}"))
|
||||||
|
service.assets.promote(result["rendered_asset_id"])
|
||||||
|
source = service.db.one(
|
||||||
|
"SELECT payload FROM asset_sources WHERE asset_id=?",
|
||||||
|
(result["rendered_asset_id"],),
|
||||||
|
)
|
||||||
|
service.db.execute(
|
||||||
|
"INSERT OR REPLACE INTO image_sources VALUES(?,?,?,?,?)",
|
||||||
|
(
|
||||||
|
op["device_id"],
|
||||||
|
expected,
|
||||||
|
result["rendered_asset_id"],
|
||||||
|
op["id"],
|
||||||
|
source["payload"] if source else encode({"type": "image"}),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
if not service.db.one(
|
||||||
|
"SELECT image_id FROM managed_cloud_uploads WHERE operation_id=?",
|
||||||
|
(op["id"],),
|
||||||
|
):
|
||||||
|
service.cloud_library.register(
|
||||||
|
op["device_id"], expected, result["rendered_asset_id"], op["id"]
|
||||||
|
)
|
||||||
|
if device.current_content.id == expected and device.current_content.synced:
|
||||||
|
options = json.loads(op["payload"]).get("options", {})
|
||||||
|
service.db.execute(
|
||||||
|
"UPDATE device_state SET managed_image_id=? WHERE device_id=?",
|
||||||
|
(expected, op["device_id"]),
|
||||||
|
)
|
||||||
|
if options.get("restore_previous"):
|
||||||
|
expires = datetime.fromisoformat(intent["started_at"]) + timedelta(
|
||||||
|
seconds=options["duration"]
|
||||||
|
)
|
||||||
|
service.db.execute(
|
||||||
|
"INSERT OR IGNORE INTO overrides VALUES(?,?,?,?,?,?)",
|
||||||
|
(
|
||||||
|
op["id"],
|
||||||
|
op["device_id"],
|
||||||
|
expected,
|
||||||
|
options["priority"],
|
||||||
|
expires.isoformat(),
|
||||||
|
intent["started_at"],
|
||||||
|
),
|
||||||
|
)
|
||||||
|
return expected
|
||||||
|
elapsed = (
|
||||||
|
datetime.now(UTC) - datetime.fromisoformat(intent["started_at"])
|
||||||
|
).total_seconds()
|
||||||
|
if (
|
||||||
|
result.get("upload_confirmed")
|
||||||
|
and not json.loads(op["payload"]).get("options", {}).get("restore_previous")
|
||||||
|
and elapsed > service.settings.sync_timeout + 300
|
||||||
|
and device.current_content.id == intent["previous_image_id"]
|
||||||
|
and device.current_content.synced
|
||||||
|
):
|
||||||
|
# Upload is proven; display is not. Two separated stable observations
|
||||||
|
# close the failed display, without replaying either vendor write.
|
||||||
|
observed = result.get("unchanged_observed_at")
|
||||||
|
if not observed:
|
||||||
|
result["unchanged_observed_at"] = now_iso()
|
||||||
|
service.update(
|
||||||
|
op["id"], "UNKNOWN", result, json.loads(op["error"] or "{}")
|
||||||
|
)
|
||||||
|
elif (
|
||||||
|
datetime.now(UTC) - datetime.fromisoformat(observed)
|
||||||
|
).total_seconds() >= 60:
|
||||||
|
service.update(
|
||||||
|
op["id"],
|
||||||
|
"FAILED",
|
||||||
|
result,
|
||||||
|
{
|
||||||
|
"code": ErrorCode.DISPLAY_NOT_CONFIRMED,
|
||||||
|
"message": "Upload confirmed; frame remained on previous image",
|
||||||
|
"request_id": op["request_id"],
|
||||||
|
"details": {},
|
||||||
|
},
|
||||||
|
)
|
||||||
|
service.db.history(op, "DISPLAY_NOT_CONFIRMED")
|
||||||
|
service.db.event(
|
||||||
|
"operation.failed",
|
||||||
|
{"operation_id": op["id"], "code": ErrorCode.DISPLAY_NOT_CONFIRMED},
|
||||||
|
)
|
||||||
|
elif result.get("unchanged_observed_at"):
|
||||||
|
result.pop("unchanged_observed_at")
|
||||||
|
service.update(op["id"], "UNKNOWN", result, json.loads(op["error"] or "{}"))
|
||||||
|
return expected
|
||||||
@@ -1,7 +1,7 @@
|
|||||||
"""Hardened adapter over the MIT-0 guooscar 1.2.0 device/upload methods.
|
"""Hardened adapter over the MIT-0 guooscar 1.2.0 device/upload methods.
|
||||||
|
|
||||||
No UI, scheduler, renderer, environment lookup, or constructor cloud calls.
|
No UI, scheduler, renderer, environment lookup, or constructor cloud calls.
|
||||||
Never retry a write; a timeout may have occurred after cloud acceptance.
|
Retry only read-only requests or writes proven unsent/rejected; never replay ambiguous writes.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
import threading
|
import threading
|
||||||
@@ -19,28 +19,85 @@ BASE_URL = "https://api.kokonna.art/openapi"
|
|||||||
|
|
||||||
|
|
||||||
class SafeTransport:
|
class SafeTransport:
|
||||||
|
MAX_ATTEMPTS = 3
|
||||||
|
MAX_RETRY_DELAY = 60
|
||||||
|
|
||||||
def __init__(self, key, session=None):
|
def __init__(self, key, session=None):
|
||||||
self.key = key
|
self.key = key
|
||||||
self.session = session or requests.Session()
|
self.session = session or requests.Session()
|
||||||
self.calls: deque[float] = deque()
|
self.calls: deque[float] = deque()
|
||||||
self.lock = threading.Lock()
|
self.lock = threading.Lock()
|
||||||
|
self.cooldown_until = 0.0
|
||||||
|
|
||||||
def request(self, endpoint, payload=None, write=False, binary=False):
|
def request(self, endpoint, payload=None, write=False, binary=False):
|
||||||
if not self.key:
|
for attempt in range(1, self.MAX_ATTEMPTS + 1):
|
||||||
raise FlowError(E.CONFIG_REQUIRED, "KoKonna configuration required", 503)
|
try:
|
||||||
|
return self._request_once(endpoint, payload, write, binary)
|
||||||
|
except FlowError as exc:
|
||||||
|
exc.details["attempts"] = attempt
|
||||||
|
delay = max(
|
||||||
|
2 ** (attempt - 1), exc.details.get("retry_after_seconds", 0)
|
||||||
|
)
|
||||||
|
if (
|
||||||
|
not exc.details.get("retryable")
|
||||||
|
or attempt == self.MAX_ATTEMPTS
|
||||||
|
or delay > self.MAX_RETRY_DELAY
|
||||||
|
):
|
||||||
|
if exc.details.get("retryable"):
|
||||||
|
exc.details["retry_exhausted"] = attempt == self.MAX_ATTEMPTS
|
||||||
|
exc.details["retry_deferred"] = delay > self.MAX_RETRY_DELAY
|
||||||
|
raise
|
||||||
|
time.sleep(delay)
|
||||||
|
raise AssertionError("Retry loop exhausted")
|
||||||
|
|
||||||
|
def _reserve(self):
|
||||||
with self.lock:
|
with self.lock:
|
||||||
current = time.monotonic()
|
current = time.monotonic()
|
||||||
while self.calls and current - self.calls[0] >= 60:
|
while self.calls and current - self.calls[0] >= 60:
|
||||||
self.calls.popleft()
|
self.calls.popleft()
|
||||||
# Reserve capacity beneath the official 20/minute ceiling.
|
delay = max(0.0, self.cooldown_until - current)
|
||||||
if len(self.calls) >= 18:
|
if len(self.calls) >= 18:
|
||||||
raise FlowError(E.RATE_LIMITED, "Device request budget exhausted", 429)
|
delay = max(delay, 60 - (current - self.calls[0]))
|
||||||
|
if delay:
|
||||||
|
raise FlowError(
|
||||||
|
E.RATE_LIMITED,
|
||||||
|
"Device request budget exhausted",
|
||||||
|
429,
|
||||||
|
details={
|
||||||
|
"retryable": True,
|
||||||
|
"retry_after_seconds": delay,
|
||||||
|
"write_outcome": "not_sent",
|
||||||
|
"failure_kind": "local_rate_limit",
|
||||||
|
},
|
||||||
|
)
|
||||||
self.calls.append(current)
|
self.calls.append(current)
|
||||||
url = BASE_URL + endpoint
|
|
||||||
|
@staticmethod
|
||||||
|
def _retry_after(value):
|
||||||
|
from datetime import UTC, datetime
|
||||||
|
from email.utils import parsedate_to_datetime
|
||||||
|
|
||||||
|
try:
|
||||||
|
seconds = float(value)
|
||||||
|
except (ValueError, TypeError):
|
||||||
|
try:
|
||||||
|
seconds = (
|
||||||
|
parsedate_to_datetime(value) - datetime.now(UTC)
|
||||||
|
).total_seconds()
|
||||||
|
except (ValueError, TypeError, OverflowError):
|
||||||
|
return 60.0
|
||||||
|
import math
|
||||||
|
|
||||||
|
return max(0.0, seconds) if math.isfinite(seconds) else 60.0
|
||||||
|
|
||||||
|
def _request_once(self, endpoint, payload, write, binary):
|
||||||
|
if not self.key:
|
||||||
|
raise FlowError(E.CONFIG_REQUIRED, "KoKonna configuration required", 503)
|
||||||
|
self._reserve()
|
||||||
try:
|
try:
|
||||||
response = self.session.request(
|
response = self.session.request(
|
||||||
"GET" if binary else "POST",
|
"GET" if binary else "POST",
|
||||||
url,
|
BASE_URL + endpoint,
|
||||||
headers={}
|
headers={}
|
||||||
if binary
|
if binary
|
||||||
else {
|
else {
|
||||||
@@ -51,49 +108,140 @@ class SafeTransport:
|
|||||||
timeout=(5, 120 if endpoint == "/upload" else 30),
|
timeout=(5, 120 if endpoint == "/upload" else 30),
|
||||||
allow_redirects=False,
|
allow_redirects=False,
|
||||||
)
|
)
|
||||||
except requests.RequestException:
|
except requests.RequestException as exc:
|
||||||
|
# Never retain exception text or a URL: binary URLs contain the key.
|
||||||
|
category = next(
|
||||||
|
(
|
||||||
|
label
|
||||||
|
for kind, label in (
|
||||||
|
(requests.ConnectTimeout, "connect_timeout"),
|
||||||
|
(requests.ReadTimeout, "read_timeout"),
|
||||||
|
(requests.exceptions.SSLError, "tls_error"),
|
||||||
|
(requests.ConnectionError, "connection_error"),
|
||||||
|
(requests.Timeout, "timeout"),
|
||||||
|
)
|
||||||
|
if isinstance(exc, kind)
|
||||||
|
),
|
||||||
|
"request_error",
|
||||||
|
)
|
||||||
|
not_sent = isinstance(exc, requests.ConnectTimeout)
|
||||||
|
uncertain = write and not not_sent
|
||||||
raise FlowError(
|
raise FlowError(
|
||||||
E.WRITE_RESULT_UNKNOWN if write else E.CLOUD_UNAVAILABLE,
|
E.WRITE_RESULT_UNKNOWN if uncertain else E.CLOUD_UNAVAILABLE,
|
||||||
"Cloud write outcome is unknown"
|
"Cloud write outcome is unknown"
|
||||||
if write
|
if uncertain
|
||||||
else "Device cloud is unavailable",
|
else "Device cloud is unavailable",
|
||||||
502,
|
502,
|
||||||
|
details={
|
||||||
|
"transport_error": category,
|
||||||
|
"retryable": (not write and category != "tls_error") or not_sent,
|
||||||
|
"write_outcome": "unknown"
|
||||||
|
if uncertain
|
||||||
|
else ("not_sent" if write else "read_only"),
|
||||||
|
},
|
||||||
) from None
|
) from None
|
||||||
if response.status_code != 200:
|
|
||||||
code = (
|
|
||||||
E.RATE_LIMITED
|
|
||||||
if response.status_code == 429
|
|
||||||
else (
|
|
||||||
E.WRITE_RESULT_UNKNOWN
|
|
||||||
if write and response.status_code >= 500
|
|
||||||
else E.CLOUD_UNAVAILABLE
|
|
||||||
)
|
|
||||||
)
|
|
||||||
raise FlowError(
|
|
||||||
code,
|
|
||||||
"Device cloud request failed",
|
|
||||||
429 if code == E.RATE_LIMITED else 502,
|
|
||||||
)
|
|
||||||
if binary:
|
|
||||||
if len(response.content) > 20 * 1024 * 1024:
|
|
||||||
raise FlowError(E.INVALID_REQUEST, "Cloud image exceeds size limit")
|
|
||||||
return response.content
|
|
||||||
try:
|
try:
|
||||||
value = response.json()
|
value = None
|
||||||
if not isinstance(value, dict):
|
if not binary or response.status_code != 200:
|
||||||
raise ValueError()
|
try:
|
||||||
# Cloud errors may echo credentials: never return raw messages.
|
value = response.json()
|
||||||
if value.get("success") is False or (
|
except ValueError:
|
||||||
"message" in value and "id" not in value
|
pass
|
||||||
|
message = value.get("message") if isinstance(value, dict) else None
|
||||||
|
status = response.status_code
|
||||||
|
# Only exact documented business failures establish rejection. Generic
|
||||||
|
# 5xx responses may arrive after a write; those remain UNKNOWN.
|
||||||
|
business = None
|
||||||
|
if status in (404, 500) and isinstance(message, str):
|
||||||
|
if message == "image not found":
|
||||||
|
business = (
|
||||||
|
E.NOT_FOUND,
|
||||||
|
"Cloud image not found",
|
||||||
|
404,
|
||||||
|
"image_not_found",
|
||||||
|
)
|
||||||
|
elif status == 500 and message == "imageId is empty":
|
||||||
|
business = (
|
||||||
|
E.INVALID_REQUEST,
|
||||||
|
"Cloud image ID is invalid",
|
||||||
|
400,
|
||||||
|
"invalid_image_id",
|
||||||
|
)
|
||||||
|
elif status == 500 and message.startswith("can not find robot "):
|
||||||
|
business = (
|
||||||
|
E.CONFIG_REQUIRED,
|
||||||
|
"Device key does not identify a frame",
|
||||||
|
503,
|
||||||
|
"device_key_invalid",
|
||||||
|
)
|
||||||
|
elif status == 404 and message.startswith("can not find method "):
|
||||||
|
business = (
|
||||||
|
E.UNSUPPORTED_CAPABILITY,
|
||||||
|
"Cloud method not found",
|
||||||
|
422,
|
||||||
|
"method_not_found",
|
||||||
|
)
|
||||||
|
if business:
|
||||||
|
code, safe_message, local_status, kind = business
|
||||||
|
raise FlowError(
|
||||||
|
code,
|
||||||
|
safe_message,
|
||||||
|
local_status,
|
||||||
|
details={
|
||||||
|
"http_status": status,
|
||||||
|
"failure_kind": kind,
|
||||||
|
"retryable": False,
|
||||||
|
"write_outcome": "rejected" if write else "read_only",
|
||||||
|
},
|
||||||
|
)
|
||||||
|
if status != 200:
|
||||||
|
limited = status == 429
|
||||||
|
rejected = 400 <= status < 500
|
||||||
|
uncertain = write and not rejected
|
||||||
|
details = {
|
||||||
|
"http_status": status,
|
||||||
|
"retryable": limited or (not write and status >= 500),
|
||||||
|
"write_outcome": "unknown"
|
||||||
|
if uncertain
|
||||||
|
else ("rejected" if write else "read_only"),
|
||||||
|
}
|
||||||
|
if limited:
|
||||||
|
delay = self._retry_after(response.headers.get("Retry-After"))
|
||||||
|
details["retry_after_seconds"] = delay
|
||||||
|
with self.lock:
|
||||||
|
self.cooldown_until = max(
|
||||||
|
self.cooldown_until, time.monotonic() + delay
|
||||||
|
)
|
||||||
|
raise FlowError(
|
||||||
|
E.RATE_LIMITED
|
||||||
|
if limited
|
||||||
|
else (E.WRITE_RESULT_UNKNOWN if uncertain else E.CLOUD_UNAVAILABLE),
|
||||||
|
"Device cloud request failed",
|
||||||
|
429 if limited else 502,
|
||||||
|
details=details,
|
||||||
|
)
|
||||||
|
if binary:
|
||||||
|
if len(response.content) > 20 * 1024 * 1024:
|
||||||
|
raise FlowError(E.INVALID_REQUEST, "Cloud image exceeds size limit")
|
||||||
|
return response.content
|
||||||
|
if (
|
||||||
|
not isinstance(value, dict)
|
||||||
|
or value.get("success") is False
|
||||||
|
or ("message" in value and "id" not in value)
|
||||||
):
|
):
|
||||||
raise ValueError()
|
raise FlowError(
|
||||||
|
E.WRITE_RESULT_UNKNOWN if write else E.CLOUD_UNAVAILABLE,
|
||||||
|
"Invalid device cloud response",
|
||||||
|
502,
|
||||||
|
details={
|
||||||
|
"failure_kind": "invalid_response",
|
||||||
|
"retryable": not write,
|
||||||
|
"write_outcome": "unknown" if write else "read_only",
|
||||||
|
},
|
||||||
|
)
|
||||||
return value
|
return value
|
||||||
except ValueError:
|
finally:
|
||||||
raise FlowError(
|
response.close()
|
||||||
E.WRITE_RESULT_UNKNOWN if write else E.CLOUD_UNAVAILABLE,
|
|
||||||
"Invalid device cloud response",
|
|
||||||
502,
|
|
||||||
) from None
|
|
||||||
|
|
||||||
|
|
||||||
class KokonnaClient:
|
class KokonnaClient:
|
||||||
@@ -118,7 +266,7 @@ class KokonnaClient:
|
|||||||
def upload(self, path, name):
|
def upload(self, path, name):
|
||||||
self.guard()
|
self.guard()
|
||||||
value = guooscar_protocol.upload(self.transport, path.read_bytes(), name)
|
value = guooscar_protocol.upload(self.transport, path.read_bytes(), name)
|
||||||
if not isinstance(value.get("id"), int) or value["id"] <= 0:
|
if type(value.get("id")) is not int or value["id"] <= 0:
|
||||||
raise FlowError(E.WRITE_RESULT_UNKNOWN, "Upload ID not confirmed", 502)
|
raise FlowError(E.WRITE_RESULT_UNKNOWN, "Upload ID not confirmed", 502)
|
||||||
return value["id"]
|
return value["id"]
|
||||||
|
|
||||||
|
|||||||
@@ -11,6 +11,7 @@ class ErrorCode(StrEnum):
|
|||||||
UNSUPPORTED_CAPABILITY = "UNSUPPORTED_CAPABILITY"
|
UNSUPPORTED_CAPABILITY = "UNSUPPORTED_CAPABILITY"
|
||||||
RENDER_FAILED = "RENDER_FAILED"
|
RENDER_FAILED = "RENDER_FAILED"
|
||||||
UPLOAD_FAILED = "UPLOAD_FAILED"
|
UPLOAD_FAILED = "UPLOAD_FAILED"
|
||||||
|
DISPLAY_NOT_CONFIRMED = "DISPLAY_NOT_CONFIRMED"
|
||||||
WRITE_RESULT_UNKNOWN = "WRITE_RESULT_UNKNOWN"
|
WRITE_RESULT_UNKNOWN = "WRITE_RESULT_UNKNOWN"
|
||||||
RATE_LIMITED = "RATE_LIMITED"
|
RATE_LIMITED = "RATE_LIMITED"
|
||||||
INTERNAL_ERROR = "INTERNAL_ERROR"
|
INTERNAL_ERROR = "INTERNAL_ERROR"
|
||||||
@@ -22,6 +23,7 @@ class ErrorCode(StrEnum):
|
|||||||
|
|
||||||
|
|
||||||
class FlowError(Exception):
|
class FlowError(Exception):
|
||||||
def __init__(self, code: ErrorCode, message: str, status: int = 400):
|
def __init__(self, code: ErrorCode, message: str, status: int = 400, details=None):
|
||||||
self.code, self.message, self.status = code, message, status
|
self.code, self.message, self.status = code, message, status
|
||||||
|
self.details = details or {}
|
||||||
super().__init__(message)
|
super().__init__(message)
|
||||||
|
|||||||
@@ -146,6 +146,7 @@ def install_ai_images(app, service):
|
|||||||
}
|
}
|
||||||
).encode(),
|
).encode(),
|
||||||
limit=service.settings.max_bytes,
|
limit=service.settings.max_bytes,
|
||||||
|
timeout=180,
|
||||||
)
|
)
|
||||||
result = json.loads(raw)["data"]
|
result = json.loads(raw)["data"]
|
||||||
if len(result) != 1:
|
if len(result) != 1:
|
||||||
|
|||||||
@@ -0,0 +1,80 @@
|
|||||||
|
"""Random selection and layout shared by preview, display and scheduled jobs."""
|
||||||
|
|
||||||
|
import random
|
||||||
|
from io import BytesIO
|
||||||
|
|
||||||
|
from PIL import Image, ImageOps
|
||||||
|
|
||||||
|
from pigway_frame_flow.errors import ErrorCode as E
|
||||||
|
from pigway_frame_flow.errors import FlowError
|
||||||
|
from pigway_frame_flow.extensions.layout import LayoutInput, LayoutStudio
|
||||||
|
from pigway_frame_flow.models import TemplateContent
|
||||||
|
|
||||||
|
|
||||||
|
def prepare(service, content, device_id=None):
|
||||||
|
rng = random.SystemRandom()
|
||||||
|
ids = []
|
||||||
|
hashes = set()
|
||||||
|
if content.source_id:
|
||||||
|
from pigway_frame_flow.extensions.quality import passes, photo_quality
|
||||||
|
|
||||||
|
source = service.photo_sources.get(content.source_id)
|
||||||
|
items = service.photo_sources.catalog(content.source_id)
|
||||||
|
candidates = rng.sample(items, min(len(items), content.count * 5))
|
||||||
|
for item in candidates:
|
||||||
|
try:
|
||||||
|
data, name, _ = service.photo_sources.read(
|
||||||
|
content.source_id, item["id"]
|
||||||
|
)
|
||||||
|
quality = photo_quality(data)
|
||||||
|
if not passes(quality, source) or quality["sha256"] in hashes:
|
||||||
|
continue
|
||||||
|
if source.avoid_duplicates and quality["fingerprint"] in hashes:
|
||||||
|
continue
|
||||||
|
hashes.update([quality["sha256"], quality["fingerprint"]])
|
||||||
|
with Image.open(BytesIO(data)) as image:
|
||||||
|
photo = ImageOps.exif_transpose(image).convert("RGB")
|
||||||
|
photo.thumbnail((2400, 2400))
|
||||||
|
output = BytesIO()
|
||||||
|
photo.save(output, "JPEG", quality=92)
|
||||||
|
asset = service.assets.put(output.getvalue(), name, "cache")
|
||||||
|
if asset["asset_id"] not in ids:
|
||||||
|
ids.append(asset["asset_id"])
|
||||||
|
except (OSError, ValueError):
|
||||||
|
continue
|
||||||
|
if len(ids) == content.count:
|
||||||
|
break
|
||||||
|
else:
|
||||||
|
rows = service.db.all(
|
||||||
|
"SELECT id AS asset_id FROM assets WHERE kind='images' ORDER BY created_at DESC LIMIT 10000"
|
||||||
|
)
|
||||||
|
ids = rng.sample(
|
||||||
|
[row["asset_id"] for row in rows], min(content.count, len(rows))
|
||||||
|
)
|
||||||
|
if len(ids) != content.count:
|
||||||
|
raise FlowError(
|
||||||
|
E.INVALID_REQUEST, "Not enough distinct photos for requested count", 422
|
||||||
|
)
|
||||||
|
values = content.model_dump(exclude={"type", "source_id", "count", "profile"})
|
||||||
|
if content.orientation == "auto":
|
||||||
|
from pigway_frame_flow.renderers.frame_geometry import frame_canvas
|
||||||
|
|
||||||
|
display = (
|
||||||
|
service.registry.get(device_id or service.settings.device_id)
|
||||||
|
.device()
|
||||||
|
.display
|
||||||
|
)
|
||||||
|
width, height = frame_canvas(display)
|
||||||
|
values["orientation"] = "landscape" if width > height else "portrait"
|
||||||
|
plan = LayoutStudio(service.renderer).plan(
|
||||||
|
LayoutInput(
|
||||||
|
asset_ids=ids,
|
||||||
|
**values,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
return TemplateContent(
|
||||||
|
type="template",
|
||||||
|
template="poster" if content.style == "poster" else "collage",
|
||||||
|
data={"layout": plan.model_dump()},
|
||||||
|
profile=content.profile,
|
||||||
|
)
|
||||||
@@ -86,7 +86,7 @@ class LocalRetention:
|
|||||||
}
|
}
|
||||||
|
|
||||||
def sweep(self, force=False, dry_run=False):
|
def sweep(self, force=False, dry_run=False):
|
||||||
if not force and time.monotonic() - self.last < 3600:
|
if not force and self.last and time.monotonic() - self.last < 3600:
|
||||||
return {}
|
return {}
|
||||||
if not dry_run:
|
if not dry_run:
|
||||||
self.last = time.monotonic()
|
self.last = time.monotonic()
|
||||||
|
|||||||
@@ -39,12 +39,13 @@ class Webhooks:
|
|||||||
db = self.service.db
|
db = self.service.db
|
||||||
for sub in db.all("SELECT * FROM webhook_subscriptions WHERE enabled=1"):
|
for sub in db.all("SELECT * FROM webhook_subscriptions WHERE enabled=1"):
|
||||||
types = json.loads(sub["event_types"])
|
types = json.loads(sub["event_types"])
|
||||||
|
if not types:
|
||||||
|
continue
|
||||||
|
placeholders = ",".join("?" for _ in types)
|
||||||
for event in db.all(
|
for event in db.all(
|
||||||
"SELECT * FROM events e WHERE created_at>=? AND NOT EXISTS (SELECT 1 FROM webhook_deliveries d WHERE d.event_id=e.id AND d.subscription_id=?) ORDER BY created_at LIMIT 500",
|
f"SELECT * FROM events e WHERE created_at>=? AND event_type IN ({placeholders}) AND NOT EXISTS (SELECT 1 FROM webhook_deliveries d WHERE d.event_id=e.id AND d.subscription_id=?) ORDER BY created_at LIMIT 500",
|
||||||
(sub["created_at"], sub["id"]),
|
(sub["created_at"], *types, sub["id"]),
|
||||||
):
|
):
|
||||||
if event["event_type"] not in types:
|
|
||||||
continue
|
|
||||||
db.execute(
|
db.execute(
|
||||||
"INSERT OR IGNORE INTO webhook_deliveries VALUES(?,?,'QUEUED',0,?,NULL)",
|
"INSERT OR IGNORE INTO webhook_deliveries VALUES(?,?,'QUEUED',0,?,NULL)",
|
||||||
(sub["id"], event["id"], now_iso()),
|
(sub["id"], event["id"], now_iso()),
|
||||||
@@ -137,6 +138,7 @@ def install_webhooks(app, service):
|
|||||||
allowed = {
|
allowed = {
|
||||||
"operation.completed",
|
"operation.completed",
|
||||||
"operation.failed",
|
"operation.failed",
|
||||||
|
"operation.blocked",
|
||||||
"display.changed",
|
"display.changed",
|
||||||
"device.online",
|
"device.online",
|
||||||
"device.offline",
|
"device.offline",
|
||||||
|
|||||||
@@ -68,6 +68,19 @@ class PhotoSourceContent(StrictModel):
|
|||||||
profile: Profile = Profile.color
|
profile: Profile = Profile.color
|
||||||
|
|
||||||
|
|
||||||
|
class AutoCollageContent(StrictModel):
|
||||||
|
type: Literal["auto_collage"]
|
||||||
|
source_id: str | None = Field(default=None, pattern=r"^[a-z0-9-]{1,60}$")
|
||||||
|
count: int = Field(default=4, ge=1, le=12)
|
||||||
|
title: str = Field(default="", max_length=100)
|
||||||
|
message: str = Field(default="", max_length=500)
|
||||||
|
orientation: Literal["auto", "portrait", "landscape"] = "auto"
|
||||||
|
style: Literal["grid", "hero", "poster"] = "grid"
|
||||||
|
use_ai: bool = True
|
||||||
|
prompt: str = Field(default="", max_length=1500)
|
||||||
|
profile: Profile = Profile.color
|
||||||
|
|
||||||
|
|
||||||
class ProviderContent(StrictModel):
|
class ProviderContent(StrictModel):
|
||||||
type: Literal["provider"]
|
type: Literal["provider"]
|
||||||
provider_id: str = Field(pattern=r"^[a-z0-9-]{1,60}$")
|
provider_id: str = Field(pattern=r"^[a-z0-9-]{1,60}$")
|
||||||
@@ -86,6 +99,7 @@ Content = Annotated[
|
|||||||
| URLContent
|
| URLContent
|
||||||
| TemplateContent
|
| TemplateContent
|
||||||
| PhotoSourceContent
|
| PhotoSourceContent
|
||||||
|
| AutoCollageContent
|
||||||
| ProviderContent
|
| ProviderContent
|
||||||
| FutureContent,
|
| FutureContent,
|
||||||
Field(discriminator="type"),
|
Field(discriminator="type"),
|
||||||
@@ -163,7 +177,17 @@ class OperationResult(BaseModel):
|
|||||||
deferred: bool = False
|
deferred: bool = False
|
||||||
|
|
||||||
|
|
||||||
|
class RecoveryState(BaseModel):
|
||||||
|
state: Literal["checking", "manual_review", "resolved"]
|
||||||
|
reason: str
|
||||||
|
first_checked_at: str
|
||||||
|
last_checked_at: str
|
||||||
|
checks: int
|
||||||
|
requires_manual_review: bool
|
||||||
|
|
||||||
|
|
||||||
class Operation(BaseModel):
|
class Operation(BaseModel):
|
||||||
|
recovery: RecoveryState | None = None
|
||||||
operation_id: str
|
operation_id: str
|
||||||
status: OperationStatus
|
status: OperationStatus
|
||||||
device_id: str
|
device_id: str
|
||||||
@@ -241,7 +265,10 @@ class GalleryImage(BaseModel):
|
|||||||
|
|
||||||
|
|
||||||
class Schedule(StrictModel):
|
class Schedule(StrictModel):
|
||||||
type: Literal["cron", "daily", "weekdays", "weekends", "date", "temporary"]
|
type: Literal[
|
||||||
|
"cron", "daily", "weekdays", "weekends", "date", "temporary", "interval"
|
||||||
|
]
|
||||||
|
interval_minutes: int | None = Field(default=None, ge=1, le=10080)
|
||||||
cron: str | None = None
|
cron: str | None = None
|
||||||
time: str | None = Field(default=None, pattern=r"^([01]\d|2[0-3]):[0-5]\d$")
|
time: str | None = Field(default=None, pattern=r"^([01]\d|2[0-3]):[0-5]\d$")
|
||||||
at: datetime | None = None
|
at: datetime | None = None
|
||||||
@@ -309,7 +336,24 @@ class History(BaseModel):
|
|||||||
timestamp: str
|
timestamp: str
|
||||||
|
|
||||||
|
|
||||||
|
class GalleryDestination(BaseModel):
|
||||||
|
id: str
|
||||||
|
adapter: str
|
||||||
|
name: str
|
||||||
|
storage: Literal["cloud", "local"]
|
||||||
|
connected: bool = False
|
||||||
|
supports_upload: bool = False
|
||||||
|
|
||||||
|
|
||||||
|
class DeviceIdentity(BaseModel):
|
||||||
|
id: str
|
||||||
|
name: str
|
||||||
|
|
||||||
|
|
||||||
class SettingsView(BaseModel):
|
class SettingsView(BaseModel):
|
||||||
|
storage_name: str = "NAS"
|
||||||
|
gallery_destinations: list[GalleryDestination] = Field(default_factory=list)
|
||||||
|
device_catalog: list[DeviceIdentity] = Field(default_factory=list)
|
||||||
version: str
|
version: str
|
||||||
mock: bool
|
mock: bool
|
||||||
write_enabled: bool
|
write_enabled: bool
|
||||||
@@ -322,7 +366,7 @@ class SettingsView(BaseModel):
|
|||||||
|
|
||||||
class Health(BaseModel):
|
class Health(BaseModel):
|
||||||
status: str
|
status: str
|
||||||
version: str = "0.1.0"
|
version: str = "0.1.9"
|
||||||
|
|
||||||
|
|
||||||
class Readiness(BaseModel):
|
class Readiness(BaseModel):
|
||||||
@@ -352,7 +396,7 @@ class RestoreRequest(StrictModel):
|
|||||||
|
|
||||||
class Version(BaseModel):
|
class Version(BaseModel):
|
||||||
product: str = "Pigway Frame Flow"
|
product: str = "Pigway Frame Flow"
|
||||||
version: str = "0.1.0"
|
version: str = "0.1.9"
|
||||||
api_version: str = "v1"
|
api_version: str = "v1"
|
||||||
commit: str = "development"
|
commit: str = "development"
|
||||||
build_time: str = "unknown"
|
build_time: str = "unknown"
|
||||||
|
|||||||
@@ -27,7 +27,9 @@ from pigway_frame_flow.storage.database import encode
|
|||||||
|
|
||||||
class PhotoSourceInput(StrictModel):
|
class PhotoSourceInput(StrictModel):
|
||||||
name: str = Field(min_length=1, max_length=120)
|
name: str = Field(min_length=1, max_length=120)
|
||||||
kind: Literal["local", "webdav", "google-drive", "alipan", "baidu"]
|
kind: Literal[
|
||||||
|
"local", "synology-photos", "webdav", "google-drive", "alipan", "baidu"
|
||||||
|
]
|
||||||
location: str = Field(min_length=1, max_length=2048)
|
location: str = Field(min_length=1, max_length=2048)
|
||||||
recursive: bool = True
|
recursive: bool = True
|
||||||
enabled: bool = True
|
enabled: bool = True
|
||||||
@@ -77,6 +79,7 @@ class PhotoSources:
|
|||||||
def __init__(self, db, settings, assets):
|
def __init__(self, db, settings, assets):
|
||||||
self.db, self.settings, self.assets = db, settings, assets
|
self.db, self.settings, self.assets = db, settings, assets
|
||||||
self.cache = {}
|
self.cache = {}
|
||||||
|
self.api_items = {}
|
||||||
self.synology = SynologyPhotos(settings)
|
self.synology = SynologyPhotos(settings)
|
||||||
# Register provider secrets before request IDs or errors can be reflected.
|
# Register provider secrets before request IDs or errors can be reflected.
|
||||||
for row in self.list():
|
for row in self.list():
|
||||||
@@ -106,22 +109,33 @@ class PhotoSources:
|
|||||||
raise FlowError(E.NOT_FOUND, "Photo source not found", 404)
|
raise FlowError(E.NOT_FOUND, "Photo source not found", 404)
|
||||||
return PhotoSourceInput.model_validate_json(row["payload"])
|
return PhotoSourceInput.model_validate_json(row["payload"])
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def require_api_source(source):
|
||||||
|
# Block persisted legacy sources as well as new requests, before any disk read.
|
||||||
|
if source.kind == "local":
|
||||||
|
raise FlowError(
|
||||||
|
E.FORBIDDEN,
|
||||||
|
"Filesystem photo sources are disabled; use the Synology Photos API",
|
||||||
|
403,
|
||||||
|
)
|
||||||
|
|
||||||
def save(self, source_id, source):
|
def save(self, source_id, source):
|
||||||
|
self.require_api_source(source)
|
||||||
if source.minimum_brightness > source.maximum_brightness:
|
if source.minimum_brightness > source.maximum_brightness:
|
||||||
raise FlowError(E.INVALID_REQUEST, "Brightness range is reversed")
|
raise FlowError(E.INVALID_REQUEST, "Brightness range is reversed")
|
||||||
if source.kind != "local" and (
|
if source.kind not in ("local", "synology-photos") and (
|
||||||
source.organized_only or source.folder_caption or source.synology_previews
|
source.organized_only or source.folder_caption or source.synology_previews
|
||||||
):
|
):
|
||||||
raise FlowError(
|
raise FlowError(
|
||||||
E.UNSUPPORTED_CAPABILITY,
|
E.UNSUPPORTED_CAPABILITY,
|
||||||
"Folder captions and Synology previews require a local photo source",
|
"Folder captions and Synology previews require a local photo source",
|
||||||
)
|
)
|
||||||
if source.orientation and source.kind != "local":
|
if source.orientation and source.kind not in ("local", "synology-photos"):
|
||||||
raise FlowError(
|
raise FlowError(
|
||||||
E.UNSUPPORTED_CAPABILITY,
|
E.UNSUPPORTED_CAPABILITY,
|
||||||
"Orientation filtering requires a local photo source",
|
"Orientation filtering requires a local photo source",
|
||||||
)
|
)
|
||||||
if source.people_filter and source.kind != "local":
|
if source.people_filter and source.kind not in ("local", "synology-photos"):
|
||||||
raise FlowError(
|
raise FlowError(
|
||||||
E.INVALID_REQUEST,
|
E.INVALID_REQUEST,
|
||||||
"Person filtering requires a local Synology photo source",
|
"Person filtering requires a local Synology photo source",
|
||||||
@@ -140,6 +154,21 @@ class PhotoSources:
|
|||||||
raise FlowError(
|
raise FlowError(
|
||||||
E.INVALID_REQUEST, "Local sources do not use credentials"
|
E.INVALID_REQUEST, "Local sources do not use credentials"
|
||||||
)
|
)
|
||||||
|
elif source.kind == "synology-photos":
|
||||||
|
location = source.location.strip("/")
|
||||||
|
if location == ".":
|
||||||
|
location = ""
|
||||||
|
if "\\" in location or any(p in (".", "..") for p in location.split("/")):
|
||||||
|
raise FlowError(
|
||||||
|
E.INVALID_REQUEST,
|
||||||
|
"Photos API folder must be a relative folder path or root",
|
||||||
|
)
|
||||||
|
if source.credential_env or source.synology_previews:
|
||||||
|
raise FlowError(
|
||||||
|
E.INVALID_REQUEST,
|
||||||
|
"Photos API sources use the shared Photos session and XL thumbnail download",
|
||||||
|
)
|
||||||
|
source = source.model_copy(update={"location": location or "."})
|
||||||
elif source.kind == "webdav":
|
elif source.kind == "webdav":
|
||||||
source = source.model_copy(
|
source = source.model_copy(
|
||||||
update={
|
update={
|
||||||
@@ -169,6 +198,7 @@ class PhotoSources:
|
|||||||
("photo_source:" + source_id, encode(source.model_dump())),
|
("photo_source:" + source_id, encode(source.model_dump())),
|
||||||
)
|
)
|
||||||
self.cache.pop(source_id, None)
|
self.cache.pop(source_id, None)
|
||||||
|
self.api_items.pop(source_id, None)
|
||||||
return dict(source.model_dump(), id=source_id)
|
return dict(source.model_dump(), id=source_id)
|
||||||
|
|
||||||
def delete(self, source_id):
|
def delete(self, source_id):
|
||||||
@@ -186,6 +216,7 @@ class PhotoSources:
|
|||||||
"DELETE FROM app_config WHERE key=?", ("photo_source:" + source_id,)
|
"DELETE FROM app_config WHERE key=?", ("photo_source:" + source_id,)
|
||||||
)
|
)
|
||||||
self.cache.pop(source_id, None)
|
self.cache.pop(source_id, None)
|
||||||
|
self.api_items.pop(source_id, None)
|
||||||
|
|
||||||
def local_directory(self, location):
|
def local_directory(self, location):
|
||||||
root = self.settings.photo_root.resolve()
|
root = self.settings.photo_root.resolve()
|
||||||
@@ -264,8 +295,12 @@ class PhotoSources:
|
|||||||
|
|
||||||
def catalog(self, source_id, refresh=False, *, target_size=(1200, 1600)):
|
def catalog(self, source_id, refresh=False, *, target_size=(1200, 1600)):
|
||||||
source = self.get(source_id)
|
source = self.get(source_id)
|
||||||
|
self.require_api_source(source)
|
||||||
if not source.enabled:
|
if not source.enabled:
|
||||||
raise FlowError(E.CONFLICT, "Photo source is disabled", 409)
|
raise FlowError(E.CONFLICT, "Photo source is disabled", 409)
|
||||||
|
session_identity = (
|
||||||
|
self.synology.sid() if source.kind == "synology-photos" else None
|
||||||
|
)
|
||||||
wanted = (
|
wanted = (
|
||||||
orientation(*target_size)
|
orientation(*target_size)
|
||||||
if source.orientation == "auto"
|
if source.orientation == "auto"
|
||||||
@@ -277,6 +312,7 @@ class PhotoSources:
|
|||||||
and not refresh
|
and not refresh
|
||||||
and time.monotonic() - cached[0] < 60
|
and time.monotonic() - cached[0] < 60
|
||||||
and cached[2] == wanted
|
and cached[2] == wanted
|
||||||
|
and cached[3] == session_identity
|
||||||
):
|
):
|
||||||
return cached[1]
|
return cached[1]
|
||||||
allowed = (
|
allowed = (
|
||||||
@@ -286,7 +322,7 @@ class PhotoSources:
|
|||||||
refresh=refresh,
|
refresh=refresh,
|
||||||
space=source.people_space,
|
space=source.people_space,
|
||||||
)
|
)
|
||||||
if source.people_filter
|
if source.people_filter and source.kind == "local"
|
||||||
else None
|
else None
|
||||||
)
|
)
|
||||||
items = []
|
items = []
|
||||||
@@ -406,6 +442,58 @@ class PhotoSources:
|
|||||||
break
|
break
|
||||||
if len(items) >= source.catalog_limit:
|
if len(items) >= source.catalog_limit:
|
||||||
break
|
break
|
||||||
|
elif source.kind == "synology-photos":
|
||||||
|
self.synology.sid()
|
||||||
|
rows = self.synology.items(
|
||||||
|
source.person_ids if source.people_filter else [],
|
||||||
|
source.person_match,
|
||||||
|
space=source.people_space,
|
||||||
|
limit=100000,
|
||||||
|
)
|
||||||
|
location = "" if source.location == "." else source.location.strip("/")
|
||||||
|
self.api_items[source_id] = {}
|
||||||
|
for row in rows:
|
||||||
|
folder = row.get("additional", {}).get("folder")
|
||||||
|
if isinstance(folder, dict):
|
||||||
|
folder = folder.get("name")
|
||||||
|
if not isinstance(folder, str) or not isinstance(
|
||||||
|
row.get("filename"), str
|
||||||
|
):
|
||||||
|
raise FlowError(
|
||||||
|
E.CLOUD_UNAVAILABLE,
|
||||||
|
"Photos API response lacks folder or filename",
|
||||||
|
502,
|
||||||
|
)
|
||||||
|
relative = folder.strip("/") + "/" + row["filename"]
|
||||||
|
if location and not relative.startswith(location + "/"):
|
||||||
|
continue
|
||||||
|
if not source.recursive and folder.strip("/") != location:
|
||||||
|
continue
|
||||||
|
caption = path_caption(relative)
|
||||||
|
if source.organized_only and caption is None:
|
||||||
|
continue
|
||||||
|
size = row.get("additional", {}).get("resolution", {})
|
||||||
|
width, height = size.get("width", 0), size.get("height", 0)
|
||||||
|
rotation = row.get("additional", {}).get("orientation", 1)
|
||||||
|
if rotation in (5, 6, 7, 8):
|
||||||
|
width, height = height, width
|
||||||
|
direction = orientation(width, height)
|
||||||
|
if wanted and (not width or not height or direction != wanted):
|
||||||
|
continue
|
||||||
|
items.append(
|
||||||
|
{
|
||||||
|
"id": str(row["id"]),
|
||||||
|
"name": row["filename"],
|
||||||
|
"provider_preview": True,
|
||||||
|
"caption": caption if source.folder_caption else None,
|
||||||
|
"width": width,
|
||||||
|
"height": height,
|
||||||
|
"orientation": direction,
|
||||||
|
}
|
||||||
|
)
|
||||||
|
self.api_items[source_id][str(row["id"])] = row
|
||||||
|
if len(items) >= source.catalog_limit:
|
||||||
|
break
|
||||||
elif source.kind in ("google-drive", "alipan", "baidu"):
|
elif source.kind in ("google-drive", "alipan", "baidu"):
|
||||||
from pigway_frame_flow.providers.cloud_drives import CloudDrives
|
from pigway_frame_flow.providers.cloud_drives import CloudDrives
|
||||||
|
|
||||||
@@ -468,7 +556,7 @@ class PhotoSources:
|
|||||||
"INSERT OR REPLACE INTO photo_dimensions(path,mtime,bytes,width,height) VALUES(?,?,?,?,?)",
|
"INSERT OR REPLACE INTO photo_dimensions(path,mtime,bytes,width,height) VALUES(?,?,?,?,?)",
|
||||||
size_updates,
|
size_updates,
|
||||||
)
|
)
|
||||||
self.cache[source_id] = (time.monotonic(), items, wanted)
|
self.cache[source_id] = (time.monotonic(), items, wanted, session_identity)
|
||||||
return items
|
return items
|
||||||
|
|
||||||
def read(self, source_id, item_id=None, *, target_size=(1200, 1600)):
|
def read(self, source_id, item_id=None, *, target_size=(1200, 1600)):
|
||||||
@@ -526,6 +614,10 @@ class PhotoSources:
|
|||||||
os.close(parent_fd)
|
os.close(parent_fd)
|
||||||
except OSError:
|
except OSError:
|
||||||
raise FlowError(E.NOT_FOUND, "Photo is unavailable", 404) from None
|
raise FlowError(E.NOT_FOUND, "Photo is unavailable", 404) from None
|
||||||
|
elif source.kind == "synology-photos":
|
||||||
|
data = self.synology.download(
|
||||||
|
self.api_items[source_id][item["id"]], space=source.people_space
|
||||||
|
)
|
||||||
elif source.kind in ("google-drive", "alipan", "baidu"):
|
elif source.kind in ("google-drive", "alipan", "baidu"):
|
||||||
from pigway_frame_flow.providers.cloud_drives import CloudDrives
|
from pigway_frame_flow.providers.cloud_drives import CloudDrives
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,84 @@
|
|||||||
|
"""Bounded, process-safe cache for individually requested Photos images."""
|
||||||
|
|
||||||
|
import fcntl
|
||||||
|
import hashlib
|
||||||
|
import os
|
||||||
|
import tempfile
|
||||||
|
import time
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
from PIL import Image
|
||||||
|
|
||||||
|
from pigway_frame_flow.errors import ErrorCode as E
|
||||||
|
from pigway_frame_flow.errors import FlowError
|
||||||
|
from pigway_frame_flow.renderers.images import MAX_IMAGE_PIXELS
|
||||||
|
|
||||||
|
|
||||||
|
class PhotosCache:
|
||||||
|
def __init__(self, settings):
|
||||||
|
self.root = settings.data_dir / "cache" / "synology-photos"
|
||||||
|
self.capacity = settings.photos_cache_bytes
|
||||||
|
self.max_bytes = min(settings.max_bytes, self.capacity)
|
||||||
|
self.hits = 0
|
||||||
|
self.downloads = 0
|
||||||
|
|
||||||
|
def _prune(self, reserve=0):
|
||||||
|
entries = []
|
||||||
|
for path in self.root.iterdir():
|
||||||
|
if path.name.endswith(".part"):
|
||||||
|
path.unlink(missing_ok=True)
|
||||||
|
elif path.suffix == ".image" and not path.is_symlink():
|
||||||
|
entries.append(path)
|
||||||
|
entries.sort(key=lambda p: p.stat().st_mtime_ns)
|
||||||
|
total = sum(p.stat().st_size for p in entries)
|
||||||
|
for path in entries:
|
||||||
|
if total + reserve <= self.capacity:
|
||||||
|
break
|
||||||
|
total -= path.stat().st_size
|
||||||
|
path.unlink()
|
||||||
|
|
||||||
|
def read(self, key, download):
|
||||||
|
self.root.mkdir(parents=True, exist_ok=True, mode=0o700)
|
||||||
|
identity = hashlib.sha256(key.encode()).hexdigest()
|
||||||
|
path = self.root / (identity + ".image")
|
||||||
|
# One lock bounds total disk use and coalesces same-item downloads across
|
||||||
|
# threads/processes. The lock file is constant, not one file per photo.
|
||||||
|
with (self.root / ".lock").open("a+b") as lock:
|
||||||
|
fcntl.flock(lock, fcntl.LOCK_EX)
|
||||||
|
self._prune()
|
||||||
|
if path.is_file() and not path.is_symlink():
|
||||||
|
data = path.read_bytes()
|
||||||
|
os.utime(path, None)
|
||||||
|
self.hits += 1
|
||||||
|
return data
|
||||||
|
self._prune(self.max_bytes)
|
||||||
|
fd, temporary = tempfile.mkstemp(suffix=".part", dir=self.root)
|
||||||
|
part = Path(temporary)
|
||||||
|
try:
|
||||||
|
with os.fdopen(fd, "wb") as handle:
|
||||||
|
download(handle, self.max_bytes, time.monotonic() + 90)
|
||||||
|
handle.flush()
|
||||||
|
os.fsync(handle.fileno())
|
||||||
|
if not 0 < part.stat().st_size <= self.max_bytes:
|
||||||
|
raise ValueError()
|
||||||
|
with Image.open(part) as image:
|
||||||
|
if image.format not in ("JPEG", "PNG", "WEBP"):
|
||||||
|
raise ValueError()
|
||||||
|
if image.width * image.height > MAX_IMAGE_PIXELS:
|
||||||
|
raise ValueError()
|
||||||
|
image.verify()
|
||||||
|
# Decode before committing; truncated/compressed-bomb payloads
|
||||||
|
# must never become a reusable cache hit.
|
||||||
|
with Image.open(part) as image:
|
||||||
|
image.load()
|
||||||
|
part.replace(path)
|
||||||
|
self.downloads += 1
|
||||||
|
return path.read_bytes()
|
||||||
|
except (OSError, ValueError, Image.DecompressionBombError):
|
||||||
|
raise FlowError(
|
||||||
|
E.CLOUD_UNAVAILABLE,
|
||||||
|
"Photos download is incomplete or not a supported image",
|
||||||
|
502,
|
||||||
|
) from None
|
||||||
|
finally:
|
||||||
|
part.unlink(missing_ok=True)
|
||||||
@@ -119,12 +119,23 @@ class SynologyPhotos:
|
|||||||
result = json.loads(raw)
|
result = json.loads(raw)
|
||||||
if not result.get("success"):
|
if not result.get("success"):
|
||||||
code = result.get("error", {}).get("code")
|
code = result.get("error", {}).get("code")
|
||||||
if api == "SYNO.API.Auth" or code in (105, 106, 107, 119):
|
if api == "SYNO.API.Auth" or code in (106, 107, 119):
|
||||||
if api != "SYNO.API.Auth":
|
if api != "SYNO.API.Auth":
|
||||||
self.disconnect()
|
self.disconnect()
|
||||||
raise FlowError(
|
raise FlowError(
|
||||||
E.CONFIG_REQUIRED, "Reconnect Synology Photos account", 409
|
E.CONFIG_REQUIRED, "Reconnect Synology Photos account", 409
|
||||||
)
|
)
|
||||||
|
if code in (102, 103, 104):
|
||||||
|
raise FlowError(
|
||||||
|
E.UNSUPPORTED_CAPABILITY,
|
||||||
|
"This NAS Photos API or method is unavailable",
|
||||||
|
)
|
||||||
|
if code == 105:
|
||||||
|
raise FlowError(
|
||||||
|
E.FORBIDDEN,
|
||||||
|
"Photos account cannot access the selected space",
|
||||||
|
403,
|
||||||
|
)
|
||||||
raise FlowError(
|
raise FlowError(
|
||||||
E.CLOUD_UNAVAILABLE, "Synology Photos query was rejected", 502
|
E.CLOUD_UNAVAILABLE, "Synology Photos query was rejected", 502
|
||||||
)
|
)
|
||||||
@@ -141,7 +152,7 @@ class SynologyPhotos:
|
|||||||
sid = json.loads(self.path.read_text())["sid"]
|
sid = json.loads(self.path.read_text())["sid"]
|
||||||
if not isinstance(sid, str) or not sid:
|
if not isinstance(sid, str) or not sid:
|
||||||
raise ValueError()
|
raise ValueError()
|
||||||
except (OSError, ValueError, KeyError):
|
except (OSError, ValueError, KeyError, TypeError):
|
||||||
raise FlowError(
|
raise FlowError(
|
||||||
E.CONFIG_REQUIRED, "Connect Synology Photos account first", 409
|
E.CONFIG_REQUIRED, "Connect Synology Photos account first", 409
|
||||||
) from None
|
) from None
|
||||||
@@ -269,3 +280,156 @@ class SynologyPhotos:
|
|||||||
)
|
)
|
||||||
self.cache[key] = (time.monotonic(), selected)
|
self.cache[key] = (time.monotonic(), selected)
|
||||||
return selected
|
return selected
|
||||||
|
|
||||||
|
def items(self, person_ids=(), mode="any", *, space="shared", limit=10000):
|
||||||
|
"""Intersect identities, not filenames, for any/all people selection."""
|
||||||
|
prefix = "SYNO.FotoTeam" if space == "shared" else "SYNO.Foto"
|
||||||
|
if mode not in ("any", "all") or space not in ("shared", "personal"):
|
||||||
|
raise FlowError(E.INVALID_REQUEST, "Invalid Photos selection")
|
||||||
|
with self.lock:
|
||||||
|
self.sid()
|
||||||
|
if person_ids:
|
||||||
|
known = {x["id"] for x in self.people(space)}
|
||||||
|
if not set(person_ids) <= known:
|
||||||
|
raise FlowError(
|
||||||
|
E.INVALID_REQUEST, "Selected person no longer exists"
|
||||||
|
)
|
||||||
|
groups = []
|
||||||
|
for person in person_ids or [None]:
|
||||||
|
rows = self.pages(
|
||||||
|
prefix + ".Browse.Item",
|
||||||
|
7,
|
||||||
|
additional=json.dumps(["folder", "thumbnail", "resolution"]),
|
||||||
|
**({"person_id": person} if person is not None else {}),
|
||||||
|
)
|
||||||
|
groups.append(
|
||||||
|
{str(r["id"]): r for r in rows if r.get("type") == "photo"}
|
||||||
|
)
|
||||||
|
selected = set(groups[0])
|
||||||
|
for group in groups[1:]:
|
||||||
|
selected = (
|
||||||
|
selected & group.keys()
|
||||||
|
if mode == "all"
|
||||||
|
else selected | group.keys()
|
||||||
|
)
|
||||||
|
merged = {key: row for group in groups for key, row in group.items()}
|
||||||
|
return [merged[key] for key in sorted(selected, key=int)][:limit]
|
||||||
|
|
||||||
|
def download(self, row, *, space="shared", rendition="thumbnail"):
|
||||||
|
from pigway_frame_flow.providers.photos_cache import PhotosCache
|
||||||
|
|
||||||
|
sid = self.sid()
|
||||||
|
url, pin = self.endpoint()
|
||||||
|
prefix = "SYNO.FotoTeam" if space == "shared" else "SYNO.Foto"
|
||||||
|
if rendition == "thumbnail":
|
||||||
|
thumb = row.get("additional", {}).get("thumbnail", {})
|
||||||
|
if not thumb.get("cache_key") or not thumb.get("unit_id"):
|
||||||
|
raise FlowError(
|
||||||
|
E.UNSUPPORTED_CAPABILITY, "Photos thumbnail is unavailable"
|
||||||
|
)
|
||||||
|
api, method = prefix + ".Thumbnail", "get"
|
||||||
|
params = dict(
|
||||||
|
id=thumb["unit_id"],
|
||||||
|
cache_key=thumb["cache_key"],
|
||||||
|
size="xl",
|
||||||
|
type="unit",
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
raise FlowError(
|
||||||
|
E.UNSUPPORTED_CAPABILITY,
|
||||||
|
"Only verified XL thumbnails are supported; original download is unavailable",
|
||||||
|
)
|
||||||
|
if not hasattr(self, "image_cache"):
|
||||||
|
self.image_cache = PhotosCache(self.settings)
|
||||||
|
# Session/endpoint scoping prevents a different account from reusing a
|
||||||
|
# previous account's cached photo. Cache keys never contain raw secrets.
|
||||||
|
identity = hashlib.sha256((sid + str(url.geturl()) + pin).encode()).hexdigest()
|
||||||
|
key = json.dumps(
|
||||||
|
[
|
||||||
|
identity,
|
||||||
|
space,
|
||||||
|
row["id"],
|
||||||
|
rendition,
|
||||||
|
row.get("indexed_time"),
|
||||||
|
row.get("filesize"),
|
||||||
|
row.get("additional", {}).get("thumbnail", {}).get("cache_key"),
|
||||||
|
]
|
||||||
|
)
|
||||||
|
return self.image_cache.read(
|
||||||
|
key,
|
||||||
|
lambda handle, cap, deadline: self._download(
|
||||||
|
api, method, params, sid, handle, cap, deadline
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
|
def _download(self, api, method, params, sid, handle, cap, deadline):
|
||||||
|
if (api, method) not in {
|
||||||
|
("SYNO.FotoTeam.Thumbnail", "get"),
|
||||||
|
("SYNO.Foto.Thumbnail", "get"),
|
||||||
|
}:
|
||||||
|
raise FlowError(E.FORBIDDEN, "Unsupported Photos download", 403)
|
||||||
|
url, pin = self.endpoint()
|
||||||
|
connection = http.client.HTTPSConnection(
|
||||||
|
url.hostname,
|
||||||
|
url.port or 443,
|
||||||
|
timeout=30,
|
||||||
|
context=ssl._create_unverified_context(),
|
||||||
|
)
|
||||||
|
try:
|
||||||
|
connection.connect()
|
||||||
|
certificate = connection.sock.getpeercert(binary_form=True)
|
||||||
|
if not certificate or hashlib.sha256(certificate).hexdigest() != pin:
|
||||||
|
raise FlowError(E.FORBIDDEN, "Synology Photos certificate changed", 403)
|
||||||
|
connection.request(
|
||||||
|
"POST",
|
||||||
|
"/webapi/entry.cgi",
|
||||||
|
urlencode(dict(api=api, method=method, version=2, _sid=sid, **params)),
|
||||||
|
{"Content-Type": "application/x-www-form-urlencoded"},
|
||||||
|
)
|
||||||
|
response = connection.getresponse()
|
||||||
|
if response.status != 200:
|
||||||
|
raise ValueError()
|
||||||
|
if "json" in (response.getheader("Content-Type") or "").lower():
|
||||||
|
result = json.loads(response.read(65537))
|
||||||
|
if result.get("error", {}).get("code") in (106, 107, 119):
|
||||||
|
self.disconnect()
|
||||||
|
raise FlowError(
|
||||||
|
E.CONFIG_REQUIRED, "Reconnect Synology Photos account", 409
|
||||||
|
)
|
||||||
|
if result.get("error", {}).get("code") == 105:
|
||||||
|
raise FlowError(
|
||||||
|
E.FORBIDDEN, "Photos account cannot download this photo", 403
|
||||||
|
)
|
||||||
|
raise FlowError(
|
||||||
|
E.CLOUD_UNAVAILABLE, "Photos download was rejected", 502
|
||||||
|
)
|
||||||
|
expected = response.getheader("Content-Length")
|
||||||
|
if expected and int(expected) > cap:
|
||||||
|
raise FlowError(
|
||||||
|
E.INVALID_REQUEST,
|
||||||
|
"Photos image exceeds download limit; select thumbnail",
|
||||||
|
)
|
||||||
|
total = 0
|
||||||
|
while True:
|
||||||
|
if time.monotonic() > deadline:
|
||||||
|
raise TimeoutError()
|
||||||
|
chunk = response.read(min(65536, cap - total + 1))
|
||||||
|
if not chunk:
|
||||||
|
break
|
||||||
|
total += len(chunk)
|
||||||
|
if total > cap:
|
||||||
|
raise FlowError(
|
||||||
|
E.INVALID_REQUEST,
|
||||||
|
"Photos image exceeds download limit; select thumbnail",
|
||||||
|
)
|
||||||
|
handle.write(chunk)
|
||||||
|
if expected and total != int(expected):
|
||||||
|
raise ValueError()
|
||||||
|
except (OSError, ValueError, http.client.HTTPException):
|
||||||
|
raise FlowError(
|
||||||
|
E.CLOUD_UNAVAILABLE,
|
||||||
|
"Photos download interrupted; retry explicitly",
|
||||||
|
502,
|
||||||
|
) from None
|
||||||
|
finally:
|
||||||
|
connection.close()
|
||||||
|
|||||||
@@ -97,7 +97,7 @@ class Assets:
|
|||||||
"task"
|
"task"
|
||||||
if job
|
if job
|
||||||
else "template"
|
else "template"
|
||||||
if content.get("type") == "template"
|
if content.get("type") in ("template", "auto_collage")
|
||||||
else "manual"
|
else "manual"
|
||||||
if operation["client_id"].startswith("user:")
|
if operation["client_id"].startswith("user:")
|
||||||
else "external"
|
else "external"
|
||||||
@@ -161,6 +161,7 @@ class Assets:
|
|||||||
body=None,
|
body=None,
|
||||||
limit=None,
|
limit=None,
|
||||||
accepted_status=(200,),
|
accepted_status=(200,),
|
||||||
|
timeout=10,
|
||||||
):
|
):
|
||||||
limit = limit or self.settings.max_bytes
|
limit = limit or self.settings.max_bytes
|
||||||
parsed = urlsplit(url)
|
parsed = urlsplit(url)
|
||||||
@@ -193,12 +194,12 @@ class Assets:
|
|||||||
|
|
||||||
class PinnedHTTPS(http.client.HTTPSConnection):
|
class PinnedHTTPS(http.client.HTTPSConnection):
|
||||||
def connect(self):
|
def connect(self):
|
||||||
sock = socket.create_connection((ip, 443), timeout=10)
|
sock = socket.create_connection((ip, 443), timeout=timeout)
|
||||||
self.sock = ssl.create_default_context().wrap_socket(
|
self.sock = ssl.create_default_context().wrap_socket(
|
||||||
sock, server_hostname=parsed.hostname
|
sock, server_hostname=parsed.hostname
|
||||||
)
|
)
|
||||||
|
|
||||||
connection = PinnedHTTPS(parsed.hostname, timeout=10)
|
connection = PinnedHTTPS(parsed.hostname, timeout=timeout)
|
||||||
try:
|
try:
|
||||||
connection.request(
|
connection.request(
|
||||||
method,
|
method,
|
||||||
|
|||||||
@@ -23,6 +23,10 @@ from pigway_frame_flow.storage.database import encode, now_iso
|
|||||||
|
|
||||||
def next_run(schedule, after=None):
|
def next_run(schedule, after=None):
|
||||||
after = after or datetime.now(UTC)
|
after = after or datetime.now(UTC)
|
||||||
|
if schedule.type == "interval":
|
||||||
|
if schedule.interval_minutes is None:
|
||||||
|
raise FlowError(E.INVALID_REQUEST, "Interval requires interval_minutes")
|
||||||
|
return (after + timedelta(minutes=schedule.interval_minutes)).isoformat()
|
||||||
if schedule.type in ("date", "temporary"):
|
if schedule.type in ("date", "temporary"):
|
||||||
if not schedule.at or schedule.at.tzinfo is None:
|
if not schedule.at or schedule.at.tzinfo is None:
|
||||||
raise FlowError(E.INVALID_REQUEST, "One-time date must include timezone")
|
raise FlowError(E.INVALID_REQUEST, "One-time date must include timezone")
|
||||||
@@ -147,61 +151,72 @@ class Scheduler:
|
|||||||
"SELECT * FROM jobs WHERE enabled=1 AND next_run<=?",
|
"SELECT * FROM jobs WHERE enabled=1 AND next_run<=?",
|
||||||
(current.isoformat(),),
|
(current.isoformat(),),
|
||||||
):
|
):
|
||||||
job = JobInput.model_validate_json(row["payload"])
|
try:
|
||||||
slot = row["next_run"]
|
job = JobInput.model_validate_json(row["payload"])
|
||||||
if self.db.one(
|
slot = row["next_run"]
|
||||||
"SELECT * FROM job_runs WHERE job_id=? AND scheduled_at=?",
|
if self.db.one(
|
||||||
(row["id"], slot),
|
"SELECT * FROM job_runs WHERE job_id=? AND scheduled_at=?",
|
||||||
):
|
(row["id"], slot),
|
||||||
continue
|
):
|
||||||
# Skip overdue tasks (>5 minutes): avoid an unexpected artwork
|
continue
|
||||||
# overwrite after downtime. One-time tasks are retired too.
|
# Skip overdue tasks (>5 minutes): avoid an unexpected artwork
|
||||||
late = (current - datetime.fromisoformat(slot)).total_seconds() > 300
|
# overwrite after downtime. One-time tasks are retired too.
|
||||||
operation_id = None
|
late = (
|
||||||
if not late:
|
current - datetime.fromisoformat(slot)
|
||||||
action = "restore" if job.source.type == "restore" else "display"
|
).total_seconds() > 300
|
||||||
payload = (
|
operation_id = None
|
||||||
{}
|
if not late:
|
||||||
if isinstance(job.source, RestoreContent)
|
action = (
|
||||||
else DisplayRequest(
|
"restore" if job.source.type == "restore" else "display"
|
||||||
device_id=job.device_id,
|
)
|
||||||
content=job.source,
|
payload = (
|
||||||
options=Options(
|
{}
|
||||||
duration=job.display_duration,
|
if isinstance(job.source, RestoreContent)
|
||||||
restore_previous=job.restore_previous,
|
else DisplayRequest(
|
||||||
priority=job.priority,
|
device_id=job.device_id,
|
||||||
cleanup_unstarred=job.cleanup_unstarred,
|
content=job.source,
|
||||||
|
options=Options(
|
||||||
|
duration=job.display_duration,
|
||||||
|
restore_previous=job.restore_previous,
|
||||||
|
priority=job.priority,
|
||||||
|
cleanup_unstarred=job.cleanup_unstarred,
|
||||||
|
),
|
||||||
|
).model_dump(mode="json")
|
||||||
|
)
|
||||||
|
operation_id = self.service.submit(
|
||||||
|
action,
|
||||||
|
payload,
|
||||||
|
job.device_id,
|
||||||
|
"scheduler",
|
||||||
|
"schedule-" + uuid4().hex,
|
||||||
|
"job-" + row["id"] + "-" + slot,
|
||||||
|
)
|
||||||
|
following = next_run(job.schedule, current)
|
||||||
|
enabled = bool(following)
|
||||||
|
updated = job.model_copy(update={"enabled": enabled}).model_dump(
|
||||||
|
mode="json"
|
||||||
|
)
|
||||||
|
with self.db.transaction() as tx:
|
||||||
|
tx.execute(
|
||||||
|
"INSERT OR IGNORE INTO job_runs VALUES(?,?,?)",
|
||||||
|
(row["id"], slot, operation_id),
|
||||||
|
)
|
||||||
|
tx.execute(
|
||||||
|
"UPDATE jobs SET payload=?,enabled=?,next_run=?,last_run=?,last_result=? WHERE id=?",
|
||||||
|
(
|
||||||
|
encode(updated),
|
||||||
|
int(enabled),
|
||||||
|
following,
|
||||||
|
now_iso(),
|
||||||
|
"SKIPPED_OVERDUE" if late else operation_id,
|
||||||
|
row["id"],
|
||||||
),
|
),
|
||||||
).model_dump(mode="json")
|
)
|
||||||
)
|
except Exception:
|
||||||
operation_id = self.service.submit(
|
# Keep this slot pending for retry or the existing overdue policy.
|
||||||
action,
|
# A single device must not prevent other jobs or queue consumption.
|
||||||
payload,
|
logging.getLogger("frame-flow").error(
|
||||||
job.device_id,
|
"Scheduled job failed; details suppressed"
|
||||||
"scheduler",
|
|
||||||
"schedule-" + uuid4().hex,
|
|
||||||
"job-" + row["id"] + "-" + slot,
|
|
||||||
)
|
|
||||||
following = next_run(job.schedule, current)
|
|
||||||
enabled = bool(following)
|
|
||||||
updated = job.model_copy(update={"enabled": enabled}).model_dump(
|
|
||||||
mode="json"
|
|
||||||
)
|
|
||||||
with self.db.transaction() as tx:
|
|
||||||
tx.execute(
|
|
||||||
"INSERT OR IGNORE INTO job_runs VALUES(?,?,?)",
|
|
||||||
(row["id"], slot, operation_id),
|
|
||||||
)
|
|
||||||
tx.execute(
|
|
||||||
"UPDATE jobs SET payload=?,enabled=?,next_run=?,last_run=?,last_result=? WHERE id=?",
|
|
||||||
(
|
|
||||||
encode(updated),
|
|
||||||
int(enabled),
|
|
||||||
following,
|
|
||||||
now_iso(),
|
|
||||||
"SKIPPED_OVERDUE" if late else operation_id,
|
|
||||||
row["id"],
|
|
||||||
),
|
|
||||||
)
|
)
|
||||||
for row in self.db.all(
|
for row in self.db.all(
|
||||||
"SELECT * FROM playlists WHERE next_run<=?", (current.isoformat(),)
|
"SELECT * FROM playlists WHERE next_run<=?", (current.isoformat(),)
|
||||||
@@ -269,6 +284,9 @@ class Scheduler:
|
|||||||
def run(self):
|
def run(self):
|
||||||
while not self.stop_event.is_set():
|
while not self.stop_event.is_set():
|
||||||
try:
|
try:
|
||||||
|
# Resolve late sync before submitting due jobs: a write lock
|
||||||
|
# otherwise makes tick fail before reconciliation can run.
|
||||||
|
self.service.sync()
|
||||||
self.tick()
|
self.tick()
|
||||||
self.service.expire()
|
self.service.expire()
|
||||||
self.service.cloud_library.sweep()
|
self.service.cloud_library.sweep()
|
||||||
|
|||||||
@@ -27,6 +27,11 @@ class Settings:
|
|||||||
default_factory=lambda: secret("FRAME_FLOW_TOKEN"), repr=False
|
default_factory=lambda: secret("FRAME_FLOW_TOKEN"), repr=False
|
||||||
)
|
)
|
||||||
additional_secrets: list[str] = field(default_factory=list, repr=False)
|
additional_secrets: list[str] = field(default_factory=list, repr=False)
|
||||||
|
storage_name: str = field(
|
||||||
|
default_factory=lambda: (
|
||||||
|
os.getenv("FRAME_FLOW_STORAGE_NAME", "NAS").strip() or "NAS"
|
||||||
|
)
|
||||||
|
)
|
||||||
device_id: str = "living-room"
|
device_id: str = "living-room"
|
||||||
timezone: str = "Asia/Shanghai"
|
timezone: str = "Asia/Shanghai"
|
||||||
cors_origins: list[str] = field(
|
cors_origins: list[str] = field(
|
||||||
@@ -51,6 +56,12 @@ class Settings:
|
|||||||
photo_root: Path = field(
|
photo_root: Path = field(
|
||||||
default_factory=lambda: Path(os.getenv("PHOTO_ROOT", "/photos"))
|
default_factory=lambda: Path(os.getenv("PHOTO_ROOT", "/photos"))
|
||||||
)
|
)
|
||||||
|
photos_cache_bytes: int = field(
|
||||||
|
default_factory=lambda: max(
|
||||||
|
1024 * 1024,
|
||||||
|
int(os.getenv("SYNOLOGY_PHOTOS_CACHE_BYTES", str(256 * 1024 * 1024))),
|
||||||
|
)
|
||||||
|
)
|
||||||
max_bytes: int = 20 * 1024 * 1024
|
max_bytes: int = 20 * 1024 * 1024
|
||||||
idempotency_hours: int = 168
|
idempotency_hours: int = 168
|
||||||
sync_timeout: int = 600
|
sync_timeout: int = 600
|
||||||
|
|||||||
@@ -31,6 +31,7 @@ class Database:
|
|||||||
CREATE TABLE IF NOT EXISTS image_sources (device_id TEXT, image_id INTEGER, asset_id TEXT, operation_id TEXT, payload TEXT NOT NULL, PRIMARY KEY(device_id,image_id));
|
CREATE TABLE IF NOT EXISTS image_sources (device_id TEXT, image_id INTEGER, asset_id TEXT, operation_id TEXT, payload TEXT NOT NULL, PRIMARY KEY(device_id,image_id));
|
||||||
CREATE TABLE IF NOT EXISTS app_config (key TEXT PRIMARY KEY, payload TEXT NOT NULL);
|
CREATE TABLE IF NOT EXISTS app_config (key TEXT PRIMARY KEY, payload TEXT NOT NULL);
|
||||||
CREATE TABLE IF NOT EXISTS playlists (id TEXT PRIMARY KEY, payload TEXT, position INTEGER, next_run TEXT);
|
CREATE TABLE IF NOT EXISTS playlists (id TEXT PRIMARY KEY, payload TEXT, position INTEGER, next_run TEXT);
|
||||||
|
CREATE TABLE IF NOT EXISTS operation_recovery (operation_id TEXT PRIMARY KEY, state TEXT NOT NULL, reason TEXT NOT NULL, first_checked_at TEXT NOT NULL, last_checked_at TEXT NOT NULL, checks INTEGER NOT NULL);
|
||||||
CREATE TABLE IF NOT EXISTS operations (
|
CREATE TABLE IF NOT EXISTS operations (
|
||||||
id TEXT PRIMARY KEY, status TEXT NOT NULL, action TEXT NOT NULL,
|
id TEXT PRIMARY KEY, status TEXT NOT NULL, action TEXT NOT NULL,
|
||||||
payload TEXT NOT NULL, device_id TEXT NOT NULL, client_id TEXT NOT NULL,
|
payload TEXT NOT NULL, device_id TEXT NOT NULL, client_id TEXT NOT NULL,
|
||||||
|
|||||||
@@ -1,17 +1,22 @@
|
|||||||
'use strict';
|
'use strict';
|
||||||
const $=s=>document.querySelector(s);
|
const $=s=>document.querySelector(s);
|
||||||
const state={lang:localStorage.getItem('ff-language')||'zh',theme:localStorage.getItem('ff-theme')||'system',page:location.hash.slice(1)||'dashboard',token:'',csrf:'',device:'living-room',settings:null,devices:[],templates:[],gallery:[],assets:[],blobs:[],tab:'cloud',preview:null,templatePreview:null,selectedTemplate:null,epoch:0};
|
const state={lang:localStorage.getItem('ff-language')||'zh',theme:localStorage.getItem('ff-theme')||'system',page:location.hash.slice(1)||'dashboard',token:'',csrf:'',device:'living-room',settings:null,devices:[],templates:[],gallery:[],assets:[],blobs:[],tab:'cloud',preview:null,templatePreview:null,selectedTemplate:null,epoch:0};
|
||||||
function forgetLogin(){localStorage.removeItem('ff-login');state.token='';state.csrf='';state.settings=null;state.devices=[];state.templates=[];}
|
function forgetLogin(){state.galleryQuery='';state.galleryOrder='newest';state.galleryJobsRequest=null;state.galleryCache?.clear();localStorage.removeItem('ff-login');state.token='';state.csrf='';state.settings=null;state.devices=[];state.templates=[];}
|
||||||
async function loadConnection(){state.settings=await api('/api/v1/settings');try{state.devices=await api('/api/v1/devices');}catch(error){state.devices=[];toast(error.message);}state.templates=await api('/api/v1/templates');state.device=state.devices[0]?.id||state.device;}
|
async function loadConnection(){
|
||||||
const icons={studio:'▦',connections:'↔',dashboard:'◫',gallery:'▧','photo-sources':'▣',upload:'↥',templates:'▦',automation:'◷',playlists:'▤',history:'↺',settings:'⚙'};
|
const [settings,templates]=await Promise.all([api('/api/v1/settings'),api('/api/v1/templates')]);
|
||||||
|
const devices=settings.device_catalog||await api('/api/v1/devices').catch(error=>{toast(error.message);return [];});
|
||||||
|
state.settings=settings;state.devices=devices;state.templates=templates;state.device=devices[0]?.id||settings.device_id||state.device;
|
||||||
|
if(settings.device_catalog&&state.page!=='dashboard')void api('/api/v1/devices').then(details=>{if(state.settings!==settings||!state.token)return;state.devices=details;shell();}).catch(error=>{if(state.settings===settings&&state.token)toast(error.message);});
|
||||||
|
}
|
||||||
|
const icons={dashboard:'◫',gallery:'▧','photo-sources':'▣',upload:'↥',templates:'▦',studio:'▦',automation:'◷',playlists:'▤',history:'↺',connections:'↔',settings:'⚙'};
|
||||||
const t=k=>window.MESSAGES[state.lang][k]||k;
|
const t=k=>window.MESSAGES[state.lang][k]||k;
|
||||||
const esc=v=>String(v??'—').replace(/[&<>"']/g,c=>({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c]));
|
const esc=v=>String(v??'—').replace(/[&<>"']/g,c=>({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c]));
|
||||||
const fmt=v=>v?new Date(v).toLocaleString(state.lang==='zh'?'zh-CN':'en-GB',{timeZone:'Asia/Shanghai'}):'—';
|
const fmt=v=>v?new Date(v).toLocaleString(state.lang==='zh'?'zh-CN':'en-GB',{timeZone:'Asia/Shanghai'}):'—';
|
||||||
const padTime=(hour,minute)=>`${String(hour).padStart(2,'0')}:${String(minute).padStart(2,'0')}`;
|
const padTime=(hour,minute)=>`${String(hour).padStart(2,'0')}:${String(minute).padStart(2,'0')}`;
|
||||||
function normaliseSchedule(schedule){const copy={...schedule};if(copy.type!=='cron')return copy;const match=/^(\d{1,2})\s+(\d{1,2})\s+\*\s+\*\s+(\*|1-5|6,0|0,6)$/.exec(copy.cron||'');if(!match)return copy;const type=match[3]==='*'?'daily':match[3]==='1-5'?'weekdays':'weekends';return {type,time:padTime(match[2],match[1])};}
|
function normaliseSchedule(schedule){const copy={...schedule};if(copy.type==='interval')return {type:copy.interval_minutes%60===0?'hours':'minutes',every:copy.interval_minutes%60===0?copy.interval_minutes/60:copy.interval_minutes};if(copy.type!=='cron')return copy;const match=/^(\d{1,2})\s+(\d{1,2})\s+\*\s+\*\s+(\*|1-5|6,0|0,6)$/.exec(copy.cron||'');if(!match)return copy;const type=match[3]==='*'?'daily':match[3]==='1-5'?'weekdays':'weekends';return {type,time:padTime(match[2],match[1])};}
|
||||||
function scheduleTypeLabel(type){if(type!=='cron')return t(type);return state.lang==='zh'?'高级规则(Cron)':'Advanced rule (Cron)';}
|
function scheduleTypeLabel(type){if(type==='hours')return state.lang==='zh'?'每隔若干小时':'Every N hours';if(type==='minutes')return state.lang==='zh'?'每隔若干分钟':'Every N minutes';if(type!=='cron')return t(type);return state.lang==='zh'?'高级规则(Cron)':'Advanced rule (Cron)';}
|
||||||
function scheduleSummary(schedule){const value=normaliseSchedule(schedule);if(['daily','weekdays','weekends'].includes(value.type))return `${scheduleTypeLabel(value.type)} · ${value.time}(${state.lang==='zh'?'上海时间':'Shanghai time'})`;if(value.type==='cron')return `${scheduleTypeLabel('cron')} · ${value.cron}`;return `${scheduleTypeLabel(value.type)} · ${fmt(value.at)}`;}
|
function scheduleSummary(schedule){const value=normaliseSchedule(schedule);if(['hours','minutes'].includes(value.type))return state.lang==='zh'?`每 ${value.every} ${value.type==='hours'?'小时':'分钟'}`:`Every ${value.every} ${value.type}`;if(['daily','weekdays','weekends'].includes(value.type))return `${scheduleTypeLabel(value.type)} · ${value.time}(${state.lang==='zh'?'上海时间':'Shanghai time'})`;if(value.type==='cron')return `${scheduleTypeLabel('cron')} · ${value.cron}`;return `${scheduleTypeLabel(value.type)} · ${fmt(value.at)}`;}
|
||||||
function scheduleHint(type){if(type==='cron')return state.lang==='zh'?'仅在需要特殊规则时使用;例如“每天 08:00”请选择“每天”。':'Use only for special rules; choose Daily for a regular time.';if(['date','temporary'].includes(type))return state.lang==='zh'?'选择一次性执行的日期和时间。':'Choose the date and time for this one-time task.';return state.lang==='zh'?'选择执行时间(上海时区)。':'Choose a time in Shanghai time.';}
|
function scheduleHint(type){if(['hours','minutes'].includes(type))return state.lang==='zh'?'从保存起等待一个间隔后首次执行,此后按间隔重复;不是图片显示时长。':'First runs one interval after saving, then repeats. This is separate from display duration.';if(type==='cron')return state.lang==='zh'?'仅在需要特殊规则时使用;例如“每天 08:00”请选择“每天”。':'Use only for special rules; choose Daily for a regular time.';if(['date','temporary'].includes(type))return state.lang==='zh'?'选择一次性执行的日期和时间。':'Choose the date and time for this one-time task.';return state.lang==='zh'?'选择执行时间(上海时区)。':'Choose a time in Shanghai time.';}
|
||||||
const buttons=(id,text,primary=false)=>`<button type="button" id="${id}" class="${primary?'primary':''}">${t(text)}</button>`;
|
const buttons=(id,text,primary=false)=>`<button type="button" id="${id}" class="${primary?'primary':''}">${t(text)}</button>`;
|
||||||
let toastTimer;
|
let toastTimer;
|
||||||
function toast(message){$('#toast').textContent=message;$('#toast').style.display='block';clearTimeout(toastTimer);toastTimer=setTimeout(()=>$('#toast').style.display='none',6000);}
|
function toast(message){$('#toast').textContent=message;$('#toast').style.display='block';clearTimeout(toastTimer);toastTimer=setTimeout(()=>$('#toast').style.display='none',6000);}
|
||||||
@@ -27,17 +32,53 @@ async function api(path,options={}){
|
|||||||
function bind(id,fn){const element=$('#'+id);if(element)element.onclick=async event=>{try{element.disabled=true;await fn(event);}catch(e){toast(e.message);}finally{element.disabled=false;}};}
|
function bind(id,fn){const element=$('#'+id);if(element)element.onclick=async event=>{try{element.disabled=true;await fn(event);}catch(e){toast(e.message);}finally{element.disabled=false;}};}
|
||||||
function busy(fn){return async event=>{try{await fn(event);}catch(e){toast(e.message);}};}
|
function busy(fn){return async event=>{try{await fn(event);}catch(e){toast(e.message);}};}
|
||||||
function applyTheme(){const dark=state.theme==='dark'||(state.theme==='system'&&matchMedia('(prefers-color-scheme:dark)').matches);document.documentElement.dataset.theme=dark?'dark':'light';}
|
function applyTheme(){const dark=state.theme==='dark'||(state.theme==='system'&&matchMedia('(prefers-color-scheme:dark)').matches);document.documentElement.dataset.theme=dark?'dark':'light';}
|
||||||
function shell(){document.documentElement.lang=state.lang==='zh'?'zh-CN':'en';$('#lang').textContent=state.lang==='zh'?'EN':'中文';$('#theme').title=t('theme');$('#nav').innerHTML=Object.entries(icons).map(([id,icon])=>`<button data-page="${id}" class="${id===state.page?'active':''}"><span class="nav-icon">${icon}</span><span>${t(id)}</span></button>`).join('');document.querySelectorAll('[data-page]').forEach(b=>b.onclick=()=>navigate(b.dataset.page));$('#page-title').textContent=t(state.page);$('#device').innerHTML=(state.devices.length?state.devices:[{id:state.device,name:state.device}]).map(d=>`<option value="${esc(d.id)}" ${d.id===state.device?'selected':''}>${esc(d.name)}</option>`).join('');}
|
function revealCurrentNavigation(){const active=$('#nav .active'),sidebar=$('.sidebar');if(active&&matchMedia('(max-width:720px)').matches)sidebar.scrollLeft=active.offsetLeft-(sidebar.clientWidth-active.offsetWidth)/2;}
|
||||||
function clearBlobs(){for(const url of state.blobs)URL.revokeObjectURL(url);state.blobs=[];}
|
window.addEventListener('resize',revealCurrentNavigation);
|
||||||
async function blobImage(img,path){try{const blob=await api(path,{binary:true});if(!img.isConnected)return;const url=URL.createObjectURL(blob);state.blobs.push(url);img.src=url;}catch{img.alt=t('apiError');}}
|
function deviceNameForId(id){return deviceDisplayName(state.devices.find(d=>d.id===id)||{id,name:id});}
|
||||||
function hydrateImages(){const observer=new IntersectionObserver(entries=>entries.forEach(entry=>{if(entry.isIntersecting){observer.unobserve(entry.target);blobImage(entry.target,entry.target.dataset.src);}}),{rootMargin:'100px'});document.querySelectorAll('img[data-src]').forEach(img=>observer.observe(img));}
|
function operationActionLabel(action){const labels={'render':['生成预览','Generate preview'],'render-ai':['AI 生成图片','Generate AI image'],'official-widget':['更新官方订阅','Update official widget'],'delete':['删除图片','Delete image'],'display':['显示图片','Display image'],'restore':['恢复图片','Restore image'],'local-upload':['保存到图库','Save to gallery'],'reconcile':['核对状态','Reconcile']};return labels[action]?.[state.lang==='zh'?0:1]||t('operation');}
|
||||||
function notice(){return state.settings?.mock?`<div class="notice">${t('mock')}</div>`:'';}
|
function operationClientLabel(client){return client==='admin'?tr('管理员','Administrator'):client==='scheduler'?tr('自动调度','Scheduler'):client;}
|
||||||
async function navigate(page=state.page){state.page=icons[page]?page:'dashboard';location.hash=state.page;shell();clearBlobs();state.epoch++;const epoch=state.epoch;
|
function operationErrorLabel(error){if(!error?.code)return '';const label=t(error.code);return label===error.code?t('error'):label;}
|
||||||
if(!state.token){login();return;}
|
function deviceDisplayName(device){const name=device.name||device.id;return device.id==='living-room'&&['living-room','Living room'].includes(name)?t('livingRoom'):name;}
|
||||||
$('#main').innerHTML='<div class="spinner"></div>';
|
function shell(){document.documentElement.lang=state.lang==='zh'?'zh-CN':'en';$('#lang').textContent=state.lang==='zh'?'EN':'中文';$('#theme').title=t('theme');$('#nav').innerHTML=Object.entries(icons).map(([id,icon])=>`<button data-page="${id}" class="${id===state.page?'active':''}" ${id===state.page?'aria-current="page"':''}><span class="nav-icon">${icon}</span><span>${t(id)}</span></button>`).join('');document.querySelectorAll('[data-page]').forEach(b=>b.onclick=()=>navigate(b.dataset.page));$('#page-title').textContent=t(state.page);$('#device').innerHTML=(state.devices.length?state.devices:[{id:state.device,name:state.device}]).map(d=>`<option value="${esc(d.id)}" ${d.id===state.device?'selected':''}>${esc(deviceDisplayName(d))}</option>`).join('');revealCurrentNavigation();}
|
||||||
try{await views[state.page](epoch);if(epoch!==state.epoch)return;const enhance={dashboard:enhanceDashboard,templates:enhanceTemplates,gallery:enhanceGallery,settings:enhanceSettings,upload:enhanceUpload,history:enhanceHistory,automation:enhanceAutomation}[state.page];if(enhance)await enhance();guardDeviceButtons();}catch(e){if(epoch!==state.epoch)return;if(!state.token){shell();login();toast(e.message);return;}$('#main').innerHTML=`<div class="card empty"><strong>${t('apiError')}</strong><p>${esc(e.message)}</p>${buttons('retry','refresh')}</div>`;bind('retry',()=>navigate());}
|
// A destination appears only when its connection and read/write adapter are available.
|
||||||
|
// Future cloud-drive destinations must implement their adapter before registration here.
|
||||||
|
const galleryDestinationAdapters=new Set(['kokonna','local-assets']);
|
||||||
|
function galleryDestinations(){
|
||||||
|
const configured=state.settings?.gallery_destinations;
|
||||||
|
const destinations=Array.isArray(configured)?configured:[{id:'cloud',adapter:'kokonna',name:'KoKonna',storage:'cloud',connected:true,supports_upload:true},{id:'local',adapter:'local-assets',name:state.settings?.storage_name||'NAS',storage:'local',connected:true,supports_upload:true}];
|
||||||
|
return destinations.filter(d=>d.connected&&d.supports_upload&&galleryDestinationAdapters.has(d.adapter));
|
||||||
}
|
}
|
||||||
function login(){ $('#main').innerHTML=`<div class="card" style="max-width:560px;margin:40px auto"><span class="badge">FRAME FLOW</span><h2 style="margin-top:20px">${t('connect')}</h2><p class="hint">${t('tokenHint')}</p><form id="login-form"><div class="field"><label for="username">${t('username')}</label><input id="username" required autocomplete="username"></div><div class="field"><label for="password">${t('password')}</label><input id="password" type="password" required autocomplete="current-password"></div><label class="check-row"><input id="remember-login" type="checkbox" checked>${t('rememberLogin')}</label><button class="primary" type="submit">${t('connect')}</button></form></div>`;$('#login-form').onsubmit=busy(async e=>{e.preventDefault();try{const account=await api('/api/v1/auth/login',{method:'POST',body:{username:$('#username').value.trim(),password:$('#password').value,remember:$('#remember-login').checked}});state.token=account.username;state.csrf=account.csrf_token;await loadConnection();await navigate();}catch(error){forgetLogin();shell();login();toast(error.message);}});}
|
function galleryDestinationName(destination){return `${destination.name} ${t(destination.storage==='local'?'local':'cloudGallery')}`;}
|
||||||
|
function imageLoading(img){
|
||||||
|
if(img.parentElement?.classList.contains('image-loading'))return img.parentElement;
|
||||||
|
const box=document.createElement('div');box.className='image-loading';
|
||||||
|
if(img.classList.contains('thumb'))box.classList.add('image-loading-thumb');
|
||||||
|
if(img.closest('.frame-demo, .image-viewer-viewport, .studio-region'))box.classList.add('image-loading-fill');
|
||||||
|
box.setAttribute('aria-busy','true');img.before(box);box.append(img);
|
||||||
|
const status=document.createElement('span');status.className='image-loading-status';status.setAttribute('role','status');status.setAttribute('aria-label',t('loading'));
|
||||||
|
const spinner=document.createElement('span');spinner.className='spinner';spinner.setAttribute('aria-hidden','true');status.append(spinner);box.append(status);return box;
|
||||||
|
}
|
||||||
|
async function blobImage(img,path){
|
||||||
|
const box=imageLoading(img);
|
||||||
|
try{
|
||||||
|
const blob=await api(path,{binary:true});if(!img.isConnected)return;
|
||||||
|
const url=URL.createObjectURL(blob);state.blobs.push(url);
|
||||||
|
// Keep the placeholder until the browser has decoded the image as well as fetched it.
|
||||||
|
img.src=url;await img.decode();if(!img.isConnected)return;box.replaceWith(img);
|
||||||
|
}catch{
|
||||||
|
box.setAttribute('aria-busy','false');box.classList.add('image-load-error');
|
||||||
|
const status=box.querySelector('.image-loading-status');status.removeAttribute('aria-label');status.textContent=t('imageLoadError');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
function hydrateImages(){const observer=new IntersectionObserver(entries=>entries.forEach(entry=>{if(entry.isIntersecting){observer.unobserve(entry.target);blobImage(entry.target,entry.target.dataset.src);}}),{rootMargin:'100px'});document.querySelectorAll('img[data-src]').forEach(img=>{imageLoading(img);observer.observe(img);});}
|
||||||
|
function notice(){return state.settings?.mock?`<div class="notice">${t('mock')}</div>`:'';}
|
||||||
|
async function navigate(page=state.page){document.body.classList.toggle('login-mode',!state.token);const previousPage=state.page;state.page=icons[page]?page:'dashboard';location.hash=state.page;shell();state.epoch++;const epoch=state.epoch;
|
||||||
|
if(!state.token){login();return;}
|
||||||
|
if(previousPage!==state.page)$('#main').replaceChildren();
|
||||||
|
const previousBlobs=state.blobs;state.blobs=[];
|
||||||
|
try{await views[state.page](epoch);for(const url of previousBlobs)URL.revokeObjectURL(url);if(epoch!==state.epoch)return;const enhance={dashboard:enhanceDashboard,templates:enhanceTemplates,settings:enhanceSettings,upload:enhanceUpload,history:enhanceHistory,automation:enhanceAutomation}[state.page];if(enhance)await enhance();guardDeviceButtons();}catch(e){if(epoch!==state.epoch)return;if(!state.token){shell();login();toast(e.message);return;}$('#main').innerHTML=`<div class="card empty"><strong>${t('apiError')}</strong><p>${esc(e.message)}</p>${buttons('retry','refresh')}</div>`;bind('retry',()=>navigate());}
|
||||||
|
}
|
||||||
|
function login(){document.body.classList.add('login-mode');$('#page-title').textContent=t('signIn');$('#main').innerHTML=`<section class="card login-card" aria-labelledby="login-title"><span class="badge">FRAME FLOW</span><h2 id="login-title">${t('connect')}</h2><p class="hint">${t('tokenHint')}</p><form id="login-form"><div class="field"><label for="username">${t('username')}</label><input id="username" required autocomplete="username"></div><div class="field"><label for="password">${t('password')}</label><input id="password" type="password" required autocomplete="current-password"></div><label class="check-row"><input id="remember-login" type="checkbox" checked><span>${t('rememberLogin')}</span></label><button class="primary" type="submit">${t('connect')}</button></form></section>`;$('#login-form').onsubmit=busy(async e=>{e.preventDefault();try{const account=await api('/api/v1/auth/login',{method:'POST',body:{username:$('#username').value.trim(),password:$('#password').value,remember:$('#remember-login').checked}});state.token=account.username;state.csrf=account.csrf_token;await loadConnection();await navigate();}catch(error){forgetLogin();shell();login();toast(error.message);}});}
|
||||||
// LAN HTTP is not a secure context; getRandomValues remains available there.
|
// LAN HTTP is not a secure context; getRandomValues remains available there.
|
||||||
function clientUUID(){if(typeof crypto.randomUUID==='function')return crypto.randomUUID();const bytes=crypto.getRandomValues(new Uint8Array(16));bytes[6]=(bytes[6]&15)|64;bytes[8]=(bytes[8]&63)|128;const hex=Array.from(bytes,b=>b.toString(16).padStart(2,'0')).join('');return `${hex.slice(0,8)}-${hex.slice(8,12)}-${hex.slice(12,16)}-${hex.slice(16,20)}-${hex.slice(20)}`;}
|
function clientUUID(){if(typeof crypto.randomUUID==='function')return crypto.randomUUID();const bytes=crypto.getRandomValues(new Uint8Array(16));bytes[6]=(bytes[6]&15)|64;bytes[8]=(bytes[8]&63)|128;const hex=Array.from(bytes,b=>b.toString(16).padStart(2,'0')).join('');return `${hex.slice(0,8)}-${hex.slice(8,12)}-${hex.slice(12,16)}-${hex.slice(16,20)}-${hex.slice(20)}`;}
|
||||||
async function accepted(path,payload){const key='web-'+clientUUID();const result=await api(path,{method:'POST',body:payload,headers:{'Idempotency-Key':key}});toast(t('accepted'));return result.operation_id;}
|
async function accepted(path,payload){const key='web-'+clientUUID();const result=await api(path,{method:'POST',body:payload,headers:{'Idempotency-Key':key}});toast(t('accepted'));return result.operation_id;}
|
||||||
@@ -59,6 +100,7 @@ function showModal(html){
|
|||||||
}
|
}
|
||||||
dialog.showModal();bind('modal-cancel',()=>dialog.close());
|
dialog.showModal();bind('modal-cancel',()=>dialog.close());
|
||||||
}
|
}
|
||||||
|
async function openImageViewer(path,name){showModal(`<h2>${esc(name)}</h2><img id="original-image" class="preview" alt="${esc(name)}"><div class="modal-actions">${buttons('modal-cancel','cancel')}</div>`);await blobImage($('#original-image'),path);}
|
||||||
async function confirmDialog(message,fn){showModal(`<h2>${t('confirm')}</h2><p>${esc(message)}</p><div class="modal-actions">${buttons('modal-cancel','cancel')}${buttons('modal-confirm','confirm',true)}</div>`);bind('modal-confirm',async()=>{await fn();$('#modal').close();});}
|
async function confirmDialog(message,fn){showModal(`<h2>${t('confirm')}</h2><p>${esc(message)}</p><div class="modal-actions">${buttons('modal-cancel','cancel')}${buttons('modal-confirm','confirm',true)}</div>`);bind('modal-confirm',async()=>{await fn();$('#modal').close();});}
|
||||||
function detail(label,value){return `<div><small>${t(label)}</small><strong>${esc(value)}</strong></div>`;}
|
function detail(label,value){return `<div><small>${t(label)}</small><strong>${esc(value)}</strong></div>`;}
|
||||||
function liveWriteAllowed(){return state.settings?.mock||state.settings?.write_enabled;}
|
function liveWriteAllowed(){return state.settings?.mock||state.settings?.write_enabled;}
|
||||||
@@ -80,20 +122,33 @@ const views={
|
|||||||
studio:()=>layoutStudioPage(),
|
studio:()=>layoutStudioPage(),
|
||||||
connections:()=>connectionsPage(),
|
connections:()=>connectionsPage(),
|
||||||
'photo-sources':async()=>{ $('#main').innerHTML='';await photoSourcesPanel(); },
|
'photo-sources':async()=>{ $('#main').innerHTML='';await photoSourcesPanel(); },
|
||||||
async dashboard(epoch){const d=await api('/api/v1/devices/'+state.device);if(epoch!==state.epoch)return;const s=d.slideshow;$('#main').innerHTML=notice()+`${d.power.battery_percent!==null&&d.power.battery_percent<20?`<div class="notice warning">${t('lowBattery')}</div>`:''}<section class="card hero"><div class="hero-info"><span class="badge ${d.status==='offline'?'bad':''}">● ${t(d.status).toUpperCase()}</span><h2>${esc(d.name)}</h2><p>${esc(d.model)} · ${esc(d.model_code)} · ${d.display.width} × ${d.display.height}</p><div class="actions">${buttons('go-upload','upload',true)}${buttons('restore','restore')}${buttons('refresh-device','refresh')}</div><p class="hint" style="margin-top:28px">${t('refreshInterval')}</p></div><div class="frame-demo"><div class="mini-art"><div class="sun"></div></div><span class="frame-label">${t('testLabel')}</span></div></section><div class="stats">${[['battery',d.power.battery_percent===null?'—':d.power.battery_percent+'%'],['current',d.current_content.id??'—'],['sync',t(d.current_content.synced?'synced':'syncing')],['firmware',d.firmware]].map(([l,v])=>`<div class="card stat"><div class="label">${t(l)}</div><div class="value">${esc(v)}</div></div>`).join('')}</div><div class="columns"><section class="card"><h3>${t('device')}</h3><div class="detail-grid">${detail('heartbeat',fmt(d.last_seen_at))}${detail('rotation',d.display.rotation+'°')}${detail('timezone',d.timezone)}${detail('coverId',d.current_content.cover_id??'—')}${detail('storage',d.storage_used_bytes===null?'—':(d.storage_used_bytes/1024/1024).toFixed(1)+' MiB')}${detail('model',t(d.model_verified?'modelVerified':'modelConfigured'))}</div></section><section class="card"><h3>${t('cloudRotation')}</h3><div class="detail-grid">${detail('mode',s.mode?t(s.mode):'—')}${detail('interval',s.interval_minutes==null?'—':s.interval_minutes+' '+t('minutes'))}</div><p class="hint">${t('rotationNotice')}</p><a href="#playlists" id="go-playlists">${t('playlists')} →</a></section></div>`;bind('go-upload',()=>navigate('upload'));bind('refresh-device',async()=>{await api('/api/v1/devices/'+state.device+'?refresh=true');await navigate();});$('#restore').disabled=!d.can_restore;bind('restore',()=>accepted('/api/v1/devices/'+state.device+'/restore',{}));$('#go-playlists').onclick=e=>{e.preventDefault();navigate('playlists');};},
|
async dashboard(epoch){const d=await api('/api/v1/devices/'+state.device);if(epoch!==state.epoch)return;state.devices=state.devices.map(x=>x.id===d.id?{...x,name:d.name}:x);shell();const s=d.slideshow;$('#main').innerHTML=notice()+`${d.power.battery_percent!==null&&d.power.battery_percent<20?`<div class="notice warning">${t('lowBattery')}</div>`:''}<section class="card hero"><div class="hero-info"><span class="badge ${d.status==='offline'?'bad':''}">● ${t(d.status).toUpperCase()}</span><h2>${esc(d.name)}</h2><p>${esc(d.model)} · ${esc(d.model_code)} · ${d.display.width} × ${d.display.height}</p><div class="actions">${buttons('go-upload','upload',true)}${buttons('restore','restore')}${buttons('refresh-device','refresh')}</div><p class="hint" style="margin-top:28px">${t('refreshInterval')}</p></div><div class="frame-demo"></div></section><div class="stats">${[['battery',d.power.battery_percent===null?'—':d.power.battery_percent+'%'],['currentImageId',d.current_content.id??'—'],['sync',t(d.current_content.synced?'synced':'syncing')],['firmware',d.firmware]].map(([l,v])=>`<div class="card stat"><div class="label">${t(l)}</div><div class="value">${esc(v)}</div></div>`).join('')}</div><div class="columns"><section class="card"><h3>${t('device')}</h3><div class="detail-grid">${detail('heartbeat',fmt(d.last_seen_at))}${detail('rotation',d.display.rotation+'°')}${detail('timezone',d.timezone)}${detail('coverId',d.current_content.cover_id??'—')}${detail('storage',d.storage_used_bytes===null?'—':(d.storage_used_bytes/1024/1024).toFixed(1)+' MiB')}${detail('modelSource',t(d.model_verified?'modelVerified':'modelConfigured'))}</div></section><section class="card"><h3>${t('cloudRotation')}</h3><div class="detail-grid">${detail('playbackMode',s.mode?t(s.mode):'—')}${detail('switchInterval',s.interval_minutes==null?'—':s.interval_minutes+' '+t('minutes'))}</div><p class="hint">${t('rotationNotice')}</p><a href="#playlists" id="go-playlists">${t('playlists')} →</a></section></div>`;bind('go-upload',()=>navigate('upload'));bind('refresh-device',async()=>{await api('/api/v1/devices/'+state.device+'?refresh=true');await navigate();});$('#restore').disabled=!d.can_restore;bind('restore',()=>accepted('/api/v1/devices/'+state.device+'/restore',{}));$('#go-playlists').onclick=e=>{e.preventDefault();navigate('playlists');};},
|
||||||
async gallery(epoch){let items=state.tab==='cloud'?await api('/api/v1/devices/'+state.device+'/images'):await api('/api/v1/assets?limit=200&offset='+(state.assetOffset||0)+'&origin='+encodeURIComponent(state.assetOrigin||'all')+(state.assetJob?'&job_id='+encodeURIComponent(state.assetJob):''));if(epoch!==state.epoch)return;state.gallery=items;$('#main').innerHTML=notice()+`<div class="section-heading"><div class="tabs"><button id="cloud-tab" class="${state.tab==='cloud'?'active':''}">${t('cloud')}</button><button id="local-tab" class="${state.tab==='local'?'active':''}">${t('local')}</button></div><div class="actions">${buttons('gallery-refresh','refresh')}${state.tab==='cloud'?buttons('show-name','displayByName'):''}${buttons('gallery-upload','upload',true)}</div></div>${state.tab==='local'?`<div class="notice">${t('uploadNotice')}</div>`:''}${items.length?`<div class="gallery">${items.map((x,i)=>`<article class="card image-card"><img class="thumb" alt="${esc(x.name)}" data-src="${esc(x.url+(state.tab==='cloud'?'?thumbnail=true':''))}"><h3 title="${esc(x.name)}">${esc(x.name)}</h3><small>${state.tab==='cloud'?'#'+x.image_id:'LOCAL'} · ${esc(fmt(x.created_at))}</small><div class="actions"><button class="primary" data-show="${i}" ${x.current?'disabled':''}>${t(x.current?'current':'display')}</button><button data-original="${i}">${t('original')}</button><button class="danger" data-delete="${i}">${t('delete')}</button></div></article>`).join('')}</div>`:`<div class="card empty"><strong>${t('noImages')}</strong>${t('emptyHint')}</div>`}`;bind('cloud-tab',()=>{state.tab='cloud';return navigate();});bind('local-tab',()=>{state.tab='local';return navigate();});bind('gallery-refresh',()=>navigate());bind('gallery-upload',()=>navigate('upload'));bind('show-name',()=>{showModal(`<h2>${t('displayByName')}</h2><div class="field"><label for="image-name">${t('name')}</label><input id="image-name" maxlength="120"></div><div class="modal-actions">${buttons('modal-cancel','cancel')}${buttons('show-name-confirm','display',true)}</div>`);bind('show-name-confirm',async()=>{const name=$('#image-name').value;$('#modal').close();displayDialog({type:'image',image_name:name});});});hydrateImages();document.querySelectorAll('[data-show]').forEach(b=>b.onclick=busy(()=>{const x=items[b.dataset.show];if(x.current)return;return displayDialog(state.tab==='cloud'?{type:'image',image_id:x.image_id}:{type:'image',asset_id:x.asset_id});}));document.querySelectorAll('[data-original]').forEach(b=>b.onclick=busy(async()=>{const x=items[b.dataset.original];showModal(`<h2>${esc(x.name)}</h2><img id="original-image" class="preview" alt="${esc(x.name)}"><div class="modal-actions">${buttons('modal-cancel','cancel')}</div>`);await blobImage($('#original-image'),x.url);}));document.querySelectorAll('[data-delete]').forEach(b=>b.onclick=()=>{const x=items[b.dataset.delete];confirmDialog(x.current?t('deleteCurrent'):t('deleteConfirm'),async()=>{if(state.tab==='local'){await api('/api/v1/assets/'+x.asset_id,{method:'DELETE'});}else{const result=await api(`/api/v1/devices/${state.device}/images/${x.image_id}?confirm_current=${x.current}`,{method:'DELETE',headers:{'Idempotency-Key':'web-'+clientUUID()}});await waitOperation(result.operation_id);}await navigate();});});},
|
async gallery(epoch){
|
||||||
|
const destinations=galleryDestinations();if(!destinations.some(d=>d.id===state.tab))state.tab=destinations[0]?.id||'local';
|
||||||
|
const key=JSON.stringify([state.device,state.tab,state.assetOffset||0,state.assetOrigin||'all',state.assetJob||'']);
|
||||||
|
const cache=state.galleryCache||(state.galleryCache=new Map());const cached=cache.get(key);
|
||||||
|
const render=(items,pending=false)=>{if(epoch!==state.epoch)return;state.gallery=items;$('#main').innerHTML=notice()+`<div class="section-heading"><div class="tabs gallery-tabs">${destinations.map(d=>`<button id="${esc(d.id)}-tab" data-gallery-destination="${esc(d.id)}" class="${state.tab===d.id?'active':''}">${esc(galleryDestinationName(d))}</button>`).join('')}</div><div class="actions">${buttons('gallery-refresh','refresh')}${state.tab==='cloud'?buttons('show-name','displayByName'):''}${buttons('gallery-upload','upload',true)}<span id="gallery-list-status" class="hint" role="status" ${pending?'':'hidden'}>${pending?t('galleryListLoading'):''}</span></div></div>${state.tab==='local'?`<div class="notice">${t('uploadNotice')}</div>`:''}${`<div class="gallery" aria-busy="${pending}">${items.map((x,i)=>`<article class="card image-card"><img class="thumb" alt="${esc(x.name)}" data-src="${esc(x.url+(state.tab==='cloud'?'?thumbnail=true':''))}"><h3 title="${esc(x.name)}">${esc(x.name)}</h3><small>${state.tab==='cloud'?'#'+x.image_id:t('local')} · ${esc(fmt(x.created_at))}</small><div class="actions"><button class="primary" data-show="${i}" ${x.current?'disabled':''}>${t(x.current?'current':'display')}</button><button data-original="${i}">${t('original')}</button><button class="danger" data-delete="${i}">${t('delete')}</button></div></article>`).join('')}</div>`}${!pending&&!items.length?`<div class="card empty"><strong>${t('noImages')}</strong>${t('emptyHint')}</div>`:''}`;bind('cloud-tab',()=>{state.tab='cloud';return navigate();});bind('local-tab',()=>{state.tab='local';return navigate();});bind('gallery-refresh',()=>navigate());bind('gallery-upload',()=>navigate('upload'));bind('show-name',()=>{showModal(`<h2>${t('displayByName')}</h2><div class="field"><label for="image-name">${t('name')}</label><input id="image-name" maxlength="120"></div><div class="modal-actions">${buttons('modal-cancel','cancel')}${buttons('show-name-confirm','display',true)}</div>`);bind('show-name-confirm',async()=>{const name=$('#image-name').value;$('#modal').close();displayDialog({type:'image',image_name:name});});});enhanceGallery();guardDeviceButtons();hydrateImages();document.querySelectorAll('[data-show]').forEach(b=>b.onclick=busy(()=>{const x=items[b.dataset.show];if(x.current)return;return displayDialog(state.tab==='cloud'?{type:'image',image_id:x.image_id}:{type:'image',asset_id:x.asset_id});}));document.querySelectorAll('[data-original]').forEach(b=>b.onclick=busy(async()=>{const x=items[b.dataset.original];await openImageViewer(x.url,x.name);}));document.querySelectorAll('[data-delete]').forEach(b=>b.onclick=()=>{const x=items[b.dataset.delete];confirmDialog(state.tab==='local'?t('localDeleteConfirm'):x.current?t('deleteCurrent'):t('cloudDeleteConfirm'),async()=>{if(state.tab==='local'){await api('/api/v1/assets/'+x.asset_id,{method:'DELETE'});}else{const result=await api(`/api/v1/devices/${state.device}/images/${x.image_id}?confirm_current=${x.current}`,{method:'DELETE',headers:{'Idempotency-Key':'web-'+clientUUID()}});await waitOperation(result.operation_id);}await navigate();});});};
|
||||||
|
render(cached||[],!cached);
|
||||||
|
try{
|
||||||
|
const items=state.tab==='cloud'?await api('/api/v1/devices/'+state.device+'/images'):await api('/api/v1/assets?limit=200&offset='+(state.assetOffset||0)+'&origin='+encodeURIComponent(state.assetOrigin||'all')+(state.assetJob?'&job_id='+encodeURIComponent(state.assetJob):''));
|
||||||
|
if(epoch!==state.epoch)return;cache.set(key,items);
|
||||||
|
if(!cached||JSON.stringify(cached)!==JSON.stringify(items))render(items);
|
||||||
|
}catch(error){
|
||||||
|
if(epoch!==state.epoch)return;if(!state.token)throw error;
|
||||||
|
const status=$('#gallery-list-status');status.hidden=false;status.setAttribute('role','alert');status.textContent=error.message;
|
||||||
|
$('.gallery')?.setAttribute('aria-busy','false');
|
||||||
|
}
|
||||||
|
},
|
||||||
async upload(){state.preview=null;$('#main').innerHTML=notice()+`<div class="notice">${t('uploadNotice')}</div><div class="columns"><section class="card"><h2>${t('upload')}</h2><div class="dropzone"><strong>${t('selectFile')}</strong><p class="hint">${t('uploadHint')}</p><input id="file" type="file" accept="image/jpeg,image/png,image/webp" aria-label="${t('selectFile')}"></div><div class="form-grid" style="margin-top:24px"><div class="field"><label for="fit">${t('mode')}</label><select id="fit">${['contain','cover','smart'].map(x=>`<option value="${x}">${t(x)}</option>`).join('')}</select></div><div class="field"><label for="profile">${t('profile')}</label><select id="profile">${['color','grayscale'].map(x=>`<option value="${x}">${t(x)}</option>`).join('')}</select></div></div>${buttons('make-preview','preview',true)}<p class="hint">${t('previewHint')}</p></section><section class="card"><h3>${t('preview')}</h3><div id="preview-box" class="empty">${t('previewHint')}</div><div class="actions" style="margin-top:18px"><button id="save-local" disabled>${t('staging')}</button><button id="display-upload" class="primary" disabled>${t('display')}</button></div></section></div>`;bind('make-preview',async()=>{const file=$('#file').files[0];if(!file)throw new Error(t('selectFile'));const form=new FormData();form.append('file',file);form.append('fit',$('#fit').value);form.append('profile',$('#profile').value);state.preview=await api('/api/v1/preview',{method:'POST',body:form});$('#preview-box').className='';$('#preview-box').innerHTML='<img id="upload-preview" class="preview" alt="Preview">';await blobImage($('#upload-preview'),state.preview.url);$('#save-local').disabled=false;$('#display-upload').disabled=!liveWriteAllowed();});for(const id of ['file','fit','profile'])$('#'+id).onchange=()=>{state.preview=null;$('#save-local').disabled=true;$('#display-upload').disabled=true;};bind('save-local',async()=>{const id=await accepted('/api/v1/devices/'+state.device+'/upload',{type:'image',asset_id:state.preview.asset_id});await waitOperation(id);state.tab='local';return navigate('gallery');});bind('display-upload',()=>displayDialog({type:'image',asset_id:state.preview.asset_id}));},
|
async upload(){state.preview=null;$('#main').innerHTML=notice()+`<div class="notice">${t('uploadNotice')}</div><div class="columns"><section class="card"><h2>${t('upload')}</h2><div class="dropzone"><strong>${t('selectFile')}</strong><p class="hint">${t('uploadHint')}</p><input id="file" type="file" accept="image/jpeg,image/png,image/webp" aria-label="${t('selectFile')}"></div><div class="form-grid" style="margin-top:24px"><div class="field"><label for="fit">${t('mode')}</label><select id="fit">${['contain','cover','smart'].map(x=>`<option value="${x}">${t(x)}</option>`).join('')}</select></div><div class="field"><label for="profile">${t('profile')}</label><select id="profile">${['color','grayscale'].map(x=>`<option value="${x}">${t(x)}</option>`).join('')}</select></div></div>${buttons('make-preview','preview',true)}<p class="hint">${t('previewHint')}</p></section><section class="card"><h3>${t('preview')}</h3><div id="preview-box" class="empty">${t('previewHint')}</div><div class="actions" style="margin-top:18px"><button id="save-local" disabled>${t('staging')}</button><button id="display-upload" class="primary" disabled>${t('display')}</button></div></section></div>`;bind('make-preview',async()=>{const file=$('#file').files[0];if(!file)throw new Error(t('selectFile'));const form=new FormData();form.append('file',file);form.append('fit',$('#fit').value);form.append('profile',$('#profile').value);state.preview=await api('/api/v1/preview',{method:'POST',body:form});$('#preview-box').className='';$('#preview-box').innerHTML='<img id="upload-preview" class="preview" alt="Preview">';await blobImage($('#upload-preview'),state.preview.url);$('#save-local').disabled=false;$('#display-upload').disabled=!liveWriteAllowed();});for(const id of ['file','fit','profile'])$('#'+id).onchange=()=>{state.preview=null;$('#save-local').disabled=true;$('#display-upload').disabled=true;};bind('save-local',async()=>{const id=await accepted('/api/v1/devices/'+state.device+'/upload',{type:'image',asset_id:state.preview.asset_id});await waitOperation(id);state.tab='local';return navigate('gallery');});bind('display-upload',()=>displayDialog({type:'image',asset_id:state.preview.asset_id}));},
|
||||||
async templates(){state.templates=await api('/api/v1/templates');const selected=state.templates.find(x=>x.id===state.selectedTemplate)||state.templates[0];state.selectedTemplate=selected.id;if(state.pendingTemplateData?.template===selected.id){selected.defaults=state.pendingTemplateData.data;state.initialProfile=state.pendingTemplateData.profile;state.pendingTemplateData=null;}state.templatePreview=null;$('#main').innerHTML=notice()+`<div class="notice">${t('templateHint')}<p>${t('templateSteps')}</p></div><div class="template-grid">${state.templates.map((x,i)=>`<div class="card template-card ${x.id===selected.id?'selected':''}" role="button" tabindex="0" data-template="${x.id}"><span>${{'daily-poetry':'詩','calendar':'▦','daily-dashboard':'☀','photo-text':'▣','quote':'❝','system-alert':'◒','weather':'☁'}[x.id]||'▦'}</span><div><h3>${esc(x.name.split(' / ')[state.lang==='zh'?1:0]||x.name)}</h3><small>1200 × 1600 · ${esc(x.id)}</small></div></div>`).join('')}</div><div class="columns"><section class="card"><h3>${t('templateData')}</h3><p class="hint">${t('templateGuideTitle')}</p><p class="hint">${t({'photo-text':'guidePhotoText','daily-dashboard':'guideDashboard',weather:'guideWeather',calendar:'guideCalendar',quote:'guideQuote','daily-poetry':'guidePoetry','system-alert':'guideAlert'}[selected.id]||'templateContentHelp')}</p>${['weather','daily-dashboard'].includes(selected.id)?`<p class="hint">${t('templateWeatherHelp')}</p>`:''}<textarea id="template-data" aria-label="${t('templateData')}">${esc(JSON.stringify(selected.defaults,null,2))}</textarea><div class="field" style="margin-top:16px"><label for="template-profile">${t('profile')}</label><select id="template-profile"><option value="color">${t('color')}</option><option value="grayscale">${t('grayscale')}</option></select><p class="hint">${t('helpProfile')}</p></div><p class="hint">${t('templateActionHelp')}</p><p class="hint">${t('templateAutomationHelp')}</p><div class="actions">${buttons('render-template','render',true)}${buttons('save-template','saveTemplate')}</div></section><section class="card"><h3>${t('preview')}</h3><div id="template-preview" class="empty">${t('templatePreviewHint')}</div><button id="display-template" class="primary" style="margin-top:18px" disabled>${t('display')}</button></section></div>`;document.querySelectorAll('[data-template]').forEach(b=>{b.onclick=()=>{state.selectedTemplate=b.dataset.template;navigate(['collage','poster'].includes(b.dataset.template)?'studio':undefined);};b.onkeydown=e=>{if(e.key==='Enter')b.click();};});bind('render-template',async()=>{const content={type:'template',template:selected.id,data:JSON.parse($('#template-data').value),profile:$('#template-profile').value};if([...document.querySelectorAll('#template-fields textarea'),$('#template-data')].some(x=>!x.checkValidity())){toast(t('INVALID_REQUEST'));return;}const id=await accepted('/api/v1/render',content);$('#template-preview').textContent=t('previewLoading');const op=await waitOperation(id);state.templatePreview=op.result.asset_id;$('#template-preview').className='';$('#template-preview').innerHTML='<img id="template-image" class="preview" alt="Template preview">';await blobImage($('#template-image'),op.result.url);$('#display-template').disabled=!liveWriteAllowed();});bind('save-template',async()=>{await api('/api/v1/templates/'+selected.id+'/config',{method:'PUT',body:{data:JSON.parse($('#template-data').value)}});toast(t('done'));});$('#template-data').oninput=()=>$('#display-template').disabled=true;$('#template-profile').onchange=()=>$('#display-template').disabled=true;bind('display-template',()=>displayDialog({type:'image',asset_id:state.templatePreview}));await templateEditor(selected);if(state.initialProfile){$('#template-profile').value=state.initialProfile;state.initialProfile=null;}},
|
async templates(){state.templates=await api('/api/v1/templates');const selected=state.templates.find(x=>x.id===state.selectedTemplate)||state.templates[0];state.selectedTemplate=selected.id;if(state.pendingTemplateData?.template===selected.id){selected.defaults=state.pendingTemplateData.data;state.initialProfile=state.pendingTemplateData.profile;state.pendingTemplateData=null;}state.templatePreview=null;$('#main').innerHTML=notice()+`<div class="notice">${t('templateHint')}<p>${t('templateSteps')}</p></div><div class="template-grid">${state.templates.map((x,i)=>`<div class="card template-card ${x.id===selected.id?'selected':''}" role="button" tabindex="0" data-template="${x.id}"><span>${{'daily-poetry':'詩','calendar':'▦','daily-dashboard':'☀','photo-text':'▣','quote':'❝','system-alert':'◒','weather':'☁'}[x.id]||'▦'}</span><div><h3>${esc(x.name.split(' / ')[state.lang==='zh'?1:0]||x.name)}</h3><small>1200 × 1600 · ${esc(x.id)}</small></div></div>`).join('')}</div><div class="columns"><section class="card"><h3>${t('templateData')}</h3><p class="hint">${t('templateGuideTitle')}</p><p class="hint">${t({'photo-text':'guidePhotoText','daily-dashboard':'guideDashboard',weather:'guideWeather',calendar:'guideCalendar',quote:'guideQuote','daily-poetry':'guidePoetry','system-alert':'guideAlert'}[selected.id]||'templateContentHelp')}</p>${['weather','daily-dashboard'].includes(selected.id)?`<p class="hint">${t('templateWeatherHelp')}</p>`:''}<textarea id="template-data" aria-label="${t('templateData')}">${esc(JSON.stringify(selected.defaults,null,2))}</textarea><div class="field" style="margin-top:16px"><label for="template-profile">${t('profile')}</label><select id="template-profile"><option value="color">${t('color')}</option><option value="grayscale">${t('grayscale')}</option></select><p class="hint">${t('helpProfile')}</p></div><p class="hint">${t('templateActionHelp')}</p><p class="hint">${t('templateAutomationHelp')}</p><div class="actions">${buttons('render-template','render',true)}${buttons('save-template','saveTemplate')}</div></section><section class="card"><h3>${t('preview')}</h3><div id="template-preview" class="empty">${t('templatePreviewHint')}</div><button id="display-template" class="primary" style="margin-top:18px" disabled>${t('display')}</button></section></div>`;document.querySelectorAll('[data-template]').forEach(b=>{b.onclick=()=>{state.selectedTemplate=b.dataset.template;navigate(['collage','poster'].includes(b.dataset.template)?'studio':undefined);};b.onkeydown=e=>{if(e.key==='Enter')b.click();};});bind('render-template',async()=>{const content={type:'template',template:selected.id,data:JSON.parse($('#template-data').value),profile:$('#template-profile').value};if([...document.querySelectorAll('#template-fields textarea'),$('#template-data')].some(x=>!x.checkValidity())){toast(t('INVALID_REQUEST'));return;}const id=await accepted('/api/v1/render',content);$('#template-preview').textContent=t('previewLoading');const op=await waitOperation(id);state.templatePreview=op.result.asset_id;$('#template-preview').className='';$('#template-preview').innerHTML='<img id="template-image" class="preview" alt="Template preview">';await blobImage($('#template-image'),op.result.url);$('#display-template').disabled=!liveWriteAllowed();});bind('save-template',async()=>{await api('/api/v1/templates/'+selected.id+'/config',{method:'PUT',body:{data:JSON.parse($('#template-data').value)}});toast(t('done'));});$('#template-data').oninput=()=>$('#display-template').disabled=true;$('#template-profile').onchange=()=>$('#display-template').disabled=true;bind('display-template',()=>displayDialog({type:'image',asset_id:state.templatePreview}));await templateEditor(selected);if(state.initialProfile){$('#template-profile').value=state.initialProfile;state.initialProfile=null;}},
|
||||||
async automation(epoch){const jobs=await api('/api/v1/jobs');if(epoch!==state.epoch)return;$('#main').innerHTML=notice()+`<div class="section-heading"><p class="hint">Asia/Shanghai · ${t('automation')}</p>${buttons('new-job','newJob',true)}</div><div class="card">${jobs.length?`<div class="table-wrap"><table><thead><tr>${['name','schedule','status','nextRun','lastRun','result','action'].map(x=>`<th>${t(x)}</th>`).join('')}</tr></thead><tbody>${jobs.map((j,i)=>`<tr><td><strong>${esc(j.name)}</strong><br><small>${esc(j.device_id)}</small></td><td>${t(j.schedule.type)}<br>${esc(j.schedule.time||j.schedule.cron||fmt(j.schedule.at))}</td><td><span class="badge">${t(j.enabled?'enabled':'disabled')}</span></td><td>${fmt(j.next_run)}</td><td>${fmt(j.last_run)}</td><td><code>${esc(j.last_result)}</code></td><td><div class="row-actions"><button data-job-edit="${i}">${t('edit')}</button><button data-job-toggle="${i}">${t(j.enabled?'disabled':'enabled')}</button><button class="danger" data-job-delete="${i}">${t('remove')}</button></div></td></tr>`).join('')}</tbody></table></div>`:`<div class="empty"><strong>${t('noTasks')}</strong></div>`}</div>`;bind('new-job',()=>jobEditor());document.querySelectorAll('[data-job-edit]').forEach(b=>b.onclick=()=>jobEditor(jobs[b.dataset.jobEdit]));document.querySelectorAll('[data-job-toggle]').forEach(b=>b.onclick=busy(async()=>{const j=jobs[b.dataset.jobToggle];await api('/api/v1/jobs/'+j.id,{method:'PUT',body:jobPayload(j,{enabled:!j.enabled})});await navigate();}));document.querySelectorAll('[data-job-delete]').forEach(b=>b.onclick=()=>confirmDialog(t('removeConfirm'),async()=>{await api('/api/v1/jobs/'+jobs[b.dataset.jobDelete].id,{method:'DELETE'});await navigate();}));},
|
|
||||||
async playlists(epoch){const playlists=await api('/api/v1/playlists');if(epoch!==state.epoch)return;$('#main').innerHTML=notice()+`<div class="notice">${t('playlistNotice')}</div><div class="section-heading"><h2>${t('playlists')}</h2>${buttons('new-playlist','newPlaylist',true)}</div><div class="gallery">${playlists.map((p,i)=>`<section class="card"><span class="badge">${t(p.enabled?'enabled':'disabled')}</span><h3 style="margin-top:16px">${esc(p.name)}</h3><p class="hint">${p.image_ids.length} ${t('count')} · ${p.interval_minutes} ${t('minutes')} · ${t(p.mode)}</p><p><code>${esc(p.image_ids.join(' → '))}</code></p><small>${t('lastScheduled')}: ${p.position>=0?esc(p.image_ids[p.position]):'—'}</small><div class="actions" style="margin-top:16px"><button data-pl-edit="${i}">${t('edit')}</button><button class="danger" data-pl-delete="${i}">${t('remove')}</button></div></section>`).join('')||`<div class="card empty"><strong>${t('noTasks')}</strong></div>`}</div>`;bind('new-playlist',()=>playlistEditor());document.querySelectorAll('[data-pl-edit]').forEach(b=>b.onclick=()=>playlistEditor(playlists[b.dataset.plEdit]));document.querySelectorAll('[data-pl-delete]').forEach(b=>b.onclick=()=>confirmDialog(t('removeConfirm'),async()=>{await api('/api/v1/playlists/'+playlists[b.dataset.plDelete].id,{method:'DELETE'});await navigate();}));},
|
async playlists(epoch){const playlists=await api('/api/v1/playlists');if(epoch!==state.epoch)return;$('#main').innerHTML=notice()+`<div class="notice">${t('playlistNotice')}</div><div class="section-heading"><h2>${t('playlists')}</h2>${buttons('new-playlist','newPlaylist',true)}</div><div class="gallery">${playlists.map((p,i)=>`<section class="card"><span class="badge">${t(p.enabled?'enabled':'disabled')}</span><h3 style="margin-top:16px">${esc(p.name)}</h3><p class="hint">${p.image_ids.length} ${t('count')} · ${p.interval_minutes} ${t('minutes')} · ${t(p.mode)}</p><p><code>${esc(p.image_ids.join(' → '))}</code></p><small>${t('lastScheduled')}: ${p.position>=0?esc(p.image_ids[p.position]):'—'}</small><div class="actions" style="margin-top:16px"><button data-pl-edit="${i}">${t('edit')}</button><button class="danger" data-pl-delete="${i}">${t('remove')}</button></div></section>`).join('')||`<div class="card empty"><strong>${t('noTasks')}</strong></div>`}</div>`;bind('new-playlist',()=>playlistEditor());document.querySelectorAll('[data-pl-edit]').forEach(b=>b.onclick=()=>playlistEditor(playlists[b.dataset.plEdit]));document.querySelectorAll('[data-pl-delete]').forEach(b=>b.onclick=()=>confirmDialog(t('removeConfirm'),async()=>{await api('/api/v1/playlists/'+playlists[b.dataset.plDelete].id,{method:'DELETE'});await navigate();}));},
|
||||||
async history(epoch){const ops=await api('/api/v1/operations');if(epoch!==state.epoch)return;$('#main').innerHTML=`<div class="section-heading"><h2>${t('history')}</h2>${buttons('history-refresh','refresh')}</div>${ops.some(x=>x.status==='UNKNOWN')?`<div class="notice warning">${t('unknown')}</div>`:''}<div class="card table-wrap">${ops.length?`<table><thead><tr>${['created','action','status','result','client','requestId'].map(x=>`<th>${t(x)}</th>`).join('')}</tr></thead><tbody>${ops.map((o,i)=>`<tr><td>${fmt(o.created_at)}</td><td>${esc(o.action)}<br><small>${esc(o.device_id)}</small></td><td><span class="badge ${['FAILED','UNKNOWN'].includes(o.status)?'bad':''}">${t(o.status)}</span>${o.status==='UNKNOWN'?`<div><button data-reconcile="${i}">${t('reconcile')}</button></div>`:''}</td><td>${esc(o.result?.image_id||o.result?.asset_id||o.error?.code||'—')}</td><td>${esc(o.client_id)}</td><td><code>${esc(o.request_id)}<br>${esc(o.operation_id)}</code></td></tr>`).join('')}</tbody></table>`:`<div class="empty">${t('noHistory')}</div>`}</div>`;bind('history-refresh',()=>navigate());document.querySelectorAll('[data-reconcile]').forEach(b=>b.onclick=busy(async()=>{const o=ops[b.dataset.reconcile];const r=await api('/api/v1/operations/'+o.operation_id+'/reconcile',{method:'POST',body:{acknowledge:false}});showModal(`<h2>${t('reconcile')}</h2><p>${t('current')}: ${esc(r.current_image_id)}</p><p>${t('result')}: ${esc(r.expected_image_id)}</p><p class="hint">${t('unknown')}</p><div class="modal-actions">${buttons('modal-cancel','cancel')}${r.resolved?'':buttons('acknowledge','acknowledge')}</div>`);bind('acknowledge',async()=>{await api('/api/v1/operations/'+o.operation_id+'/reconcile',{method:'POST',body:{acknowledge:true}});$('#modal').close();await navigate();});}));},
|
async history(epoch){const ops=await api('/api/v1/operations');if(epoch!==state.epoch)return;$('#main').innerHTML=`<div class="section-heading"><h2>${t('history')}</h2>${buttons('history-refresh','refresh')}</div>${ops.some(x=>x.status==='UNKNOWN')?`<div class="notice warning">${t('unknown')}</div>`:''}<div class="card table-wrap">${ops.length?`<table><thead><tr>${['created','action','status','result','client','requestId'].map(x=>`<th>${t(x)}</th>`).join('')}</tr></thead><tbody>${ops.map((o,i)=>`<tr><td>${fmt(o.created_at)}</td><td>${esc(operationActionLabel(o.action))}<br><small>${esc(deviceNameForId(o.device_id))}</small></td><td><span class="badge ${['FAILED','UNKNOWN'].includes(o.status)?'bad':''}">${t(o.status)}</span>${o.status==='UNKNOWN'?`<div><button data-reconcile="${i}">${t('reconcile')}</button></div>`:''}</td><td>${esc(o.result?.image_id||o.result?.asset_id||operationErrorLabel(o.error)||'—')}</td><td>${esc(operationClientLabel(o.client_id))}</td><td><code>${esc(o.request_id)}<br>${esc(o.operation_id)}</code></td></tr>`).join('')}</tbody></table>`:`<div class="empty">${t('noHistory')}</div>`}</div>`;bind('history-refresh',()=>navigate());document.querySelectorAll('[data-reconcile]').forEach(b=>b.onclick=busy(async()=>{const o=ops[b.dataset.reconcile];const r=await api('/api/v1/operations/'+o.operation_id+'/reconcile',{method:'POST',body:{acknowledge:false}});showModal(`<h2>${t('reconcile')}</h2><p>${t('current')}: ${esc(r.current_image_id)}</p><p>${t('result')}: ${esc(r.expected_image_id)}</p><p class="hint">${t('unknown')}</p><div class="modal-actions">${buttons('modal-cancel','cancel')}${r.resolved?'':buttons('acknowledge','acknowledge')}</div>`);bind('acknowledge',async()=>{await api('/api/v1/operations/'+o.operation_id+'/reconcile',{method:'POST',body:{acknowledge:true}});$('#modal').close();await navigate();});}));},
|
||||||
async settings(){state.settings=await api('/api/v1/settings');const s=state.settings;$('#main').innerHTML=notice()+`<div class="columns"><section class="card"><h3>${t('settings')}</h3><div class="field"><label for="theme-select">${t('theme')}</label><select id="theme-select">${['system','light','dark'].map(x=>`<option value="${x}" ${state.theme===x?'selected':''}>${t(x==='system'?'systemTheme':x)}</option>`).join('')}</select></div><div class="field"><label for="language-select">${t('language')}</label><select id="language-select"><option value="zh" ${state.lang==='zh'?'selected':''}>简体中文</option><option value="en" ${state.lang==='en'?'selected':''}>English</option></select></div><p class="hint">${t('tokenHint')}</p>${buttons('logout','logout')}</section><section class="card"><h3>${t('auth')}</h3><div class="detail-grid">${detail('version',s.version)}${detail('writeProtection',t(!s.write_enabled?'yes':'no'))}${detail('keyConfigured',t(s.api_key_configured?'yes':'no'))}${detail('timezone',s.timezone)}</div><p class="hint">${t('refreshInterval')}</p><a href="/docs" target="_blank" rel="noopener">${t('apiDocs')} →</a><p class="hint">GET /openapi.json · /api/v1</p></section></div>`;$('#theme-select').onchange=()=>{state.theme=$('#theme-select').value;localStorage.setItem('ff-theme',state.theme);applyTheme();};$('#language-select').onchange=()=>{state.lang=$('#language-select').value;localStorage.setItem('ff-language',state.lang);navigate();};bind('logout',async()=>{await api('/api/v1/auth/logout',{method:'POST'});forgetLogin();shell();login();});accountSettings();}
|
async settings(){state.settings=await api('/api/v1/settings');const s=state.settings;$('#main').innerHTML=notice()+`<div class="columns"><section class="card"><h3>${t('settings')}</h3><div class="field"><label for="theme-select">${t('theme')}</label><select id="theme-select">${['system','light','dark'].map(x=>`<option value="${x}" ${state.theme===x?'selected':''}>${t(x==='system'?'systemTheme':x)}</option>`).join('')}</select></div><div class="field"><label for="language-select">${t('language')}</label><select id="language-select"><option value="zh" ${state.lang==='zh'?'selected':''}>简体中文</option><option value="en" ${state.lang==='en'?'selected':''}>English</option></select></div><p class="hint">${t('tokenHint')}</p>${buttons('logout','logout')}</section><section class="card"><h3>${t('auth')}</h3><div class="detail-grid">${detail('version',s.version)}${detail('writeProtection',t(!s.write_enabled?'yes':'no'))}${detail('keyConfigured',t(s.api_key_configured?'yes':'no'))}${detail('timezone',s.timezone)}</div><p class="hint">${t('refreshInterval')}</p><a href="/docs" target="_blank" rel="noopener">${t('apiDocs')} →</a><p class="hint">GET /openapi.json · /api/v1</p></section></div>`;$('#theme-select').onchange=()=>{state.theme=$('#theme-select').value;localStorage.setItem('ff-theme',state.theme);applyTheme();};$('#language-select').onchange=()=>{state.lang=$('#language-select').value;localStorage.setItem('ff-language',state.lang);navigate();};bind('logout',async()=>{await api('/api/v1/auth/logout',{method:'POST'});forgetLogin();shell();login();});accountSettings();}
|
||||||
};
|
};
|
||||||
function jobPayload(j,changes={}){return {name:j.name,enabled:j.enabled,device_id:j.device_id,schedule:j.schedule,source:j.source,display_duration:j.display_duration,restore_previous:j.restore_previous,priority:j.priority,cleanup_unstarred:j.cleanup_unstarred||false,...changes};}
|
function jobPayload(j,changes={}){return {name:j.name,enabled:j.enabled,device_id:j.device_id,schedule:j.schedule,source:j.source,display_duration:j.display_duration,restore_previous:j.restore_previous,priority:j.priority,cleanup_unstarred:j.cleanup_unstarred||false,...changes};}
|
||||||
async function jobEditor(job){const j=job||{name:'',enabled:true,device_id:state.device,schedule:{type:'daily',time:'07:00'},source:{type:'template',template:'daily-dashboard',data:{}},display_duration:5400,restore_previous:true,priority:50};showModal(`<h2>${t(job?'edit':'newJob')}</h2><form id="job-form"><div class="field"><label for="job-name">${t('name')}</label><input id="job-name" required maxlength="120" value="${esc(j.name)}"></div><div class="form-grid"><div class="field"><label for="job-schedule">${t('schedule')}</label><select id="job-schedule">${['daily','weekdays','weekends','cron','date','temporary'].map(x=>`<option ${j.schedule.type===x?'selected':''} value="${x}">${t(x)}</option>`).join('')}</select></div><div class="field"><label id="schedule-label" for="schedule-value">${t('time')}</label><input id="schedule-value" required value="${esc(j.schedule.time||j.schedule.cron||(j.schedule.at?j.schedule.at.slice(0,16):'07:00'))}"></div></div><div class="field"><label for="job-source">${t('source')} (JSON)</label><textarea id="job-source">${esc(JSON.stringify(j.source,null,2))}</textarea></div><div class="form-grid"><div class="field"><label for="job-duration">${t('duration')}</label><input id="job-duration" type="number" min="0" max="604800" value="${j.display_duration}"></div><div class="field"><label for="job-priority">${t('priority')}</label><input id="job-priority" type="number" min="0" max="100" value="${j.priority}"></div></div><label class="check-row"><input type="checkbox" id="job-enabled" ${j.enabled?'checked':''}>${t('enabled')}</label><label class="check-row"><input type="checkbox" id="job-restore" ${j.restore_previous?'checked':''}>${t('restoreAfter')}</label><div class="modal-actions">${buttons('modal-cancel','cancel')}<button type="submit" class="primary">${t('save')}</button></div></form>`);const source=$('#job-source');const choose=document.createElement('div');choose.className='field';choose.innerHTML=`<label for="job-template">${t('template')}</label><select id="job-template"><option value="">${t('advanced')}</option>${state.templates.map(x=>`<option value="${esc(x.id)}" ${j.source.template===x.id?'selected':''}>${esc(x.name)}</option>`).join('')}</select>`;source.parentElement.before(choose);$('#job-template').onchange=()=>{const id=$('#job-template').value;if(id)source.value=JSON.stringify({type:'template',template:id,data:{}},null,2);};function update(){const type=$('#job-schedule').value;$('#schedule-label').textContent=t(type==='cron'?'cron':['date','temporary'].includes(type)?'at':'time');$('#schedule-value').type=type==='cron'?'text':['date','temporary'].includes(type)?'datetime-local':'time';}$('#job-schedule').onchange=()=>{update();$('#schedule-value').value='';};update();$('#job-form').onsubmit=busy(async e=>{e.preventDefault();const type=$('#job-schedule').value,value=$('#schedule-value').value;const schedule={type};if(type==='cron')schedule.cron=value;else if(['date','temporary'].includes(type))schedule.at=value+':00+08:00';else schedule.time=value;const payload=jobPayload(j,{name:$('#job-name').value,schedule,source:JSON.parse($('#job-source').value),display_duration:Number($('#job-duration').value),priority:Number($('#job-priority').value),restore_previous:$('#job-restore').checked,cleanup_unstarred:false,enabled:$('#job-enabled').checked});await api('/api/v1/jobs'+(job?'/'+job.id:''),{method:job?'PUT':'POST',body:payload});$('#modal').close();await navigate();});await jobSourceEditor(j);}
|
async function playlistEditor(p){p=p||{name:'',image_ids:[],interval_minutes:60,mode:'queue',enabled:false};showModal(`<h2>${t('playlists')}</h2><form id="playlist-form"><div class="field"><label for="playlist-name">${t('name')}</label><input id="playlist-name" required maxlength="120" value="${esc(p.name)}"></div><div class="field"><label for="playlist-images">${t('imageIds')}</label><input id="playlist-images" required value="${esc(p.image_ids.join(','))}" placeholder="1,2,3"></div><div class="form-grid"><div class="field"><label for="playlist-interval">${t('interval')}</label><input id="playlist-interval" type="number" min="5" max="10080" value="${p.interval_minutes}"></div><div class="field"><label for="playlist-mode">${t('playbackMode')}</label><select id="playlist-mode"><option value="queue" ${p.mode==='queue'?'selected':''}>${t('queue')}</option><option value="random" ${p.mode==='random'?'selected':''}>${t('random')}</option></select></div></div><label class="check-row"><input id="playlist-enabled" type="checkbox" ${p.enabled?'checked':''}>${t('enabled')}</label><div class="modal-actions">${buttons('modal-cancel','cancel')}<button type="submit" class="primary">${t('save')}</button></div></form>`);$('#playlist-form').onsubmit=busy(async e=>{e.preventDefault();await api('/api/v1/playlists'+(p.id?'/'+p.id:''),{method:p.id?'PUT':'POST',body:{name:$('#playlist-name').value,device_id:p.device_id||state.device,image_ids:$('#playlist-images').value.split(',').map(x=>Number(x.trim())),interval_minutes:Number($('#playlist-interval').value),mode:$('#playlist-mode').value,enabled:$('#playlist-enabled').checked}});$('#modal').close();await navigate();});await playlistImagePicker(p);}
|
||||||
async function playlistEditor(p){p=p||{name:'',image_ids:[],interval_minutes:60,mode:'queue',enabled:false};showModal(`<h2>${t('playlists')}</h2><form id="playlist-form"><div class="field"><label for="playlist-name">${t('name')}</label><input id="playlist-name" required maxlength="120" value="${esc(p.name)}"></div><div class="field"><label for="playlist-images">${t('imageIds')}</label><input id="playlist-images" required value="${esc(p.image_ids.join(','))}" placeholder="1,2,3"></div><div class="form-grid"><div class="field"><label for="playlist-interval">${t('interval')}</label><input id="playlist-interval" type="number" min="5" max="10080" value="${p.interval_minutes}"></div><div class="field"><label for="playlist-mode">${t('mode')}</label><select id="playlist-mode"><option value="queue" ${p.mode==='queue'?'selected':''}>${t('queue')}</option><option value="random" ${p.mode==='random'?'selected':''}>${t('random')}</option></select></div></div><label class="check-row"><input id="playlist-enabled" type="checkbox" ${p.enabled?'checked':''}>${t('enabled')}</label><div class="modal-actions">${buttons('modal-cancel','cancel')}<button type="submit" class="primary">${t('save')}</button></div></form>`);$('#playlist-form').onsubmit=busy(async e=>{e.preventDefault();await api('/api/v1/playlists'+(p.id?'/'+p.id:''),{method:p.id?'PUT':'POST',body:{name:$('#playlist-name').value,device_id:p.device_id||state.device,image_ids:$('#playlist-images').value.split(',').map(x=>Number(x.trim())),interval_minutes:Number($('#playlist-interval').value),mode:$('#playlist-mode').value,enabled:$('#playlist-enabled').checked}});$('#modal').close();await navigate();});await playlistImagePicker(p);}
|
|
||||||
$('#lang').onclick=()=>{state.lang=state.lang==='zh'?'en':'zh';localStorage.setItem('ff-language',state.lang);navigate();};$('#theme').onclick=()=>{state.theme=document.documentElement.dataset.theme==='dark'?'light':'dark';localStorage.setItem('ff-theme',state.theme);applyTheme();};$('#device').onchange=()=>{state.device=$('#device').value;navigate();};window.addEventListener('hashchange',()=>{const page=location.hash.slice(1);if(page!==state.page)navigate(page);});matchMedia('(prefers-color-scheme:dark)').addEventListener('change',applyTheme);
|
$('#lang').onclick=()=>{state.lang=state.lang==='zh'?'en':'zh';localStorage.setItem('ff-language',state.lang);navigate();};$('#theme').onclick=()=>{state.theme=document.documentElement.dataset.theme==='dark'?'light':'dark';localStorage.setItem('ff-theme',state.theme);applyTheme();};$('#device').onchange=()=>{state.device=$('#device').value;navigate();};window.addEventListener('hashchange',()=>{const page=location.hash.slice(1);if(page!==state.page)navigate(page);});matchMedia('(prefers-color-scheme:dark)').addEventListener('change',applyTheme);
|
||||||
applyTheme();localStorage.removeItem('ff-login');(async()=>{try{const account=await api('/api/v1/auth/me');state.token=account.username;state.csrf=account.csrf_token;await loadConnection();}catch{forgetLogin();}await navigate();})();api('/api/v1/version').then(v=>$('#footer').innerHTML=`<span>Pigway Frame Flow · ${t('footer')}</span><span>v${esc(v.version)} · ${esc(v.commit.slice(0,8))} · ${esc(v.build_time)}</span>`).catch(()=>{});
|
applyTheme();shell();localStorage.removeItem('ff-login');(async()=>{try{const account=await api('/api/v1/auth/me');state.token=account.username;state.csrf=account.csrf_token;await loadConnection();}catch{forgetLogin();}await navigate();})();api('/api/v1/version').then(v=>$('#footer').innerHTML=`<span>Pigway Frame Flow · ${t('footer')}</span><span>v${esc(v.version)} · ${esc(v.commit.slice(0,8))} · ${esc(v.build_time)}</span>`).catch(()=>{});
|
||||||
setInterval(()=>{if(state.token&&state.page==='dashboard'&&!$('#modal').open)navigate();},60000);
|
setInterval(()=>{if(state.token&&state.page==='dashboard'&&!$('#modal').open)navigate();},60000);
|
||||||
|
|
||||||
// Keep Cron available for exceptional schedules, but make ordinary schedules form-based.
|
// Keep Cron available for exceptional schedules, but make ordinary schedules form-based.
|
||||||
@@ -101,25 +156,25 @@ async function jobEditor(job){
|
|||||||
const base={name:'',enabled:true,device_id:state.device,schedule:{type:'daily',time:'07:00'},source:{type:'template',template:'daily-dashboard',data:{}},display_duration:5400,restore_previous:true,priority:50};
|
const base={name:'',enabled:true,device_id:state.device,schedule:{type:'daily',time:'07:00'},source:{type:'template',template:'daily-dashboard',data:{}},display_duration:5400,restore_previous:true,priority:50};
|
||||||
const original=job||base;
|
const original=job||base;
|
||||||
const j={...base,...original,schedule:normaliseSchedule(original.schedule||base.schedule)};
|
const j={...base,...original,schedule:normaliseSchedule(original.schedule||base.schedule)};
|
||||||
const scheduleValue=j.schedule.time||j.schedule.cron||(j.schedule.at?j.schedule.at.slice(0,16):'07:00');
|
const scheduleValue=j.schedule.every||j.schedule.time||j.schedule.cron||(j.schedule.at?j.schedule.at.slice(0,16):'07:00');
|
||||||
showModal(`<h2>${t(job?'edit':'newJob')}</h2><form id="job-form"><div class="field"><label for="job-name">${t('name')}</label><input id="job-name" required maxlength="120" value="${esc(j.name)}"></div><div class="form-grid"><div class="field"><label for="job-schedule">${t('schedule')}</label><select id="job-schedule">${['daily','weekdays','weekends','date','temporary','cron'].map(type=>`<option value="${type}" ${j.schedule.type===type?'selected':''}>${scheduleTypeLabel(type)}</option>`).join('')}</select></div><div class="field"><label id="schedule-label" for="schedule-value">${t('time')}</label><input id="schedule-value" required value="${esc(scheduleValue)}"></div></div><p class="hint" id="schedule-hint"></p><div class="field"><label for="job-source">${t('source')} (JSON)</label><textarea id="job-source">${esc(JSON.stringify(j.source,null,2))}</textarea></div><div class="form-grid"><div class="field"><label for="job-duration">${t('duration')}</label><input id="job-duration" type="number" min="0" max="604800" value="${j.display_duration}"></div><div class="field"><label for="job-priority">${t('priority')}</label><input id="job-priority" type="number" min="0" max="100" value="${j.priority}"></div></div><label class="check-row"><input type="checkbox" id="job-enabled" ${j.enabled?'checked':''}>${t('enabled')}</label><label class="check-row"><input type="checkbox" id="job-restore" ${j.restore_previous?'checked':''}>${t('restoreAfter')}</label><p class="hint">${t('cloudKeepLatest')}</p><div class="modal-actions">${buttons('modal-cancel','cancel')}<button type="submit" class="primary">${t('save')}</button></div></form>`);
|
showModal(`<h2>${t(job?.id?'edit':'newJob')}</h2><form id="job-form"><div class="field"><label for="job-name">${t('name')}</label><input id="job-name" required maxlength="120" value="${esc(j.name)}"></div><div class="form-grid"><div class="field"><label for="job-schedule">${t('schedule')}</label><select id="job-schedule">${['minutes','hours','daily','weekdays','weekends','date','temporary','cron'].map(type=>`<option value="${type}" ${j.schedule.type===type?'selected':''}>${scheduleTypeLabel(type)}</option>`).join('')}</select></div><div class="field"><label id="schedule-label" for="schedule-value">${t('time')}</label><input id="schedule-value" required value="${esc(scheduleValue)}"></div></div><p class="hint" id="schedule-hint"></p><div class="field"><label for="job-source">${t('source')} (JSON)</label><textarea id="job-source">${esc(JSON.stringify(j.source,null,2))}</textarea></div><div class="form-grid"><div class="field"><label for="job-duration">${t('duration')}</label><input id="job-duration" type="number" min="0" max="604800" value="${j.display_duration}"></div><div class="field"><label for="job-priority">${t('priority')}</label><input id="job-priority" type="number" min="0" max="100" value="${j.priority}"></div></div><label class="check-row"><input type="checkbox" id="job-enabled" ${j.enabled?'checked':''}>${t('enabled')}</label><label class="check-row"><input type="checkbox" id="job-restore" ${j.restore_previous?'checked':''}>${t('restoreAfter')}</label><p class="hint">${t('temporaryOptionsHint')}</p><p class="hint">${t('cloudKeepLatest')}</p><div class="modal-actions">${buttons('modal-cancel','cancel')}<button type="submit" class="primary">${t('save')}</button></div></form>`);
|
||||||
const source=$('#job-source');
|
const source=$('#job-source');
|
||||||
const choose=document.createElement('div');
|
const choose=document.createElement('div');
|
||||||
choose.className='field';
|
choose.className='field';
|
||||||
choose.innerHTML=`<label for="job-template">${t('template')}</label><select id="job-template"><option value="">${t('advanced')}</option>${state.templates.map(template=>`<option value="${esc(template.id)}" ${j.source.template===template.id?'selected':''}>${esc(template.name)}</option>`).join('')}</select>`;
|
choose.innerHTML=`<label for="job-template">${t('template')}</label><select id="job-template"><option value="">${t('advanced')}</option>${state.templates.map(template=>`<option value="${esc(template.id)}" ${j.source.template===template.id?'selected':''}>${esc(template.name)}</option>`).join('')}</select>`;
|
||||||
source.parentElement.before(choose);
|
source.parentElement.before(choose);
|
||||||
$('#job-template').onchange=()=>{const id=$('#job-template').value;if(id)source.value=JSON.stringify({type:'template',template:id,data:{}},null,2);};
|
$('#job-template').onchange=()=>{const id=$('#job-template').value;if(id)source.value=JSON.stringify({type:'template',template:id,data:{}},null,2);};
|
||||||
function updateScheduleField(){const type=$('#job-schedule').value;$('#schedule-label').textContent=type==='cron'?scheduleTypeLabel(type):t(['date','temporary'].includes(type)?'at':'time');$('#schedule-value').type=type==='cron'?'text':['date','temporary'].includes(type)?'datetime-local':'time';$('#schedule-hint').textContent=scheduleHint(type);}
|
function updateScheduleField(){const type=$('#job-schedule').value;const interval=['hours','minutes'].includes(type);$('#schedule-value').min=interval?'1':'';$('#schedule-value').max=type==='hours'?'168':type==='minutes'?'10080':'';$('#schedule-value').step=interval?'1':'';$('#schedule-label').textContent=interval?tr('间隔数值','Interval'):type==='cron'?scheduleTypeLabel(type):t(['date','temporary'].includes(type)?'at':'time');$('#schedule-value').type=interval?'number':type==='cron'?'text':['date','temporary'].includes(type)?'datetime-local':'time';$('#schedule-hint').textContent=scheduleHint(type);}
|
||||||
$('#job-schedule').onchange=()=>{updateScheduleField();$('#schedule-value').value='';};
|
$('#job-schedule').onchange=()=>{updateScheduleField();$('#schedule-value').value='';};
|
||||||
updateScheduleField();
|
updateScheduleField();
|
||||||
$('#job-form').onsubmit=busy(async event=>{event.preventDefault();const type=$('#job-schedule').value;const value=$('#schedule-value').value;const schedule={type};if(type==='cron')schedule.cron=value;else if(['date','temporary'].includes(type))schedule.at=value+':00+08:00';else schedule.time=value;const payload=jobPayload(j,{name:$('#job-name').value,schedule,source:JSON.parse(source.value),display_duration:Number($('#job-duration').value),priority:Number($('#job-priority').value),restore_previous:$('#job-restore').checked,cleanup_unstarred:false,enabled:$('#job-enabled').checked});await api('/api/v1/jobs'+(job?'/'+job.id:''),{method:job?'PUT':'POST',body:payload});$('#modal').close();await navigate();});
|
$('#job-form').onsubmit=busy(async event=>{event.preventDefault();const type=$('#job-schedule').value;const value=$('#schedule-value').value;const schedule=['hours','minutes'].includes(type)?{type:'interval',interval_minutes:Number(value)*(type==='hours'?60:1)}:{type};if(['hours','minutes'].includes(type)){}else if(type==='cron')schedule.cron=value;else if(['date','temporary'].includes(type))schedule.at=value+':00+08:00';else schedule.time=value;const payload=jobPayload(j,{name:$('#job-name').value,schedule,source:JSON.parse(source.value),display_duration:Number($('#job-duration').value),priority:Number($('#job-priority').value),restore_previous:$('#job-restore').checked,cleanup_unstarred:false,enabled:$('#job-enabled').checked});await api('/api/v1/jobs'+(job?.id?'/'+job.id:''),{method:job?.id?'PUT':'POST',body:payload});$('#modal').close();await navigate();});
|
||||||
await jobSourceEditor(j);
|
await jobSourceEditor(j);
|
||||||
}
|
}
|
||||||
|
|
||||||
views.automation=async epoch=>{
|
views.automation=async epoch=>{
|
||||||
const jobs=await api('/api/v1/jobs');
|
const jobs=await api('/api/v1/jobs');
|
||||||
if(epoch!==state.epoch)return;
|
if(epoch!==state.epoch)return;
|
||||||
$('#main').innerHTML=notice()+`<div class="section-heading"><p class="hint">Asia/Shanghai · ${t('automation')}</p>${buttons('new-job','newJob',true)}</div><div class="card">${jobs.length?`<div class="table-wrap"><table><thead><tr>${['name','schedule','status','nextRun','lastRun','result','action'].map(key=>`<th>${t(key)}</th>`).join('')}</tr></thead><tbody>${jobs.map((job,index)=>`<tr><td><strong>${esc(job.name)}</strong><br><small>${esc(job.device_id)}</small></td><td>${esc(scheduleSummary(job.schedule))}</td><td><span class="badge">${t(job.enabled?'enabled':'disabled')}</span></td><td>${fmt(job.next_run)}</td><td>${fmt(job.last_run)}</td><td><code>${esc(job.last_result)}</code></td><td><div class="row-actions"><button data-job-edit="${index}">${t('edit')}</button><button data-job-toggle="${index}">${t(job.enabled?'disabled':'enabled')}</button><button class="danger" data-job-delete="${index}">${t('remove')}</button></div></td></tr>`).join('')}</tbody></table></div>`:`<div class="empty"><strong>${t('noTasks')}</strong></div>`}</div>`;
|
$('#main').innerHTML=notice()+`<div class="section-heading"><p class="hint">${state.lang==='zh'?'上海时间':'Shanghai time'} · ${t('automation')}</p>${buttons('new-job','newJob',true)}</div><div class="card">${jobs.length?`<div class="table-wrap"><table><thead><tr>${['name','schedule','status','nextRun','lastRun','result','action'].map(key=>`<th>${t(key)}</th>`).join('')}</tr></thead><tbody>${jobs.map((job,index)=>`<tr><td><strong>${esc(job.name)}</strong><br><small>${esc(deviceDisplayName(state.devices.find(d=>d.id===job.device_id)||{id:job.device_id,name:job.device_id}))}</small></td><td>${esc(scheduleSummary(job.schedule))}</td><td><span class="badge">${t(job.enabled?'enabled':'disabled')}</span></td><td>${fmt(job.next_run)}</td><td>${fmt(job.last_run)}</td><td><code>${esc(job.last_result)}</code></td><td><div class="row-actions"><button data-job-edit="${index}">${t('edit')}</button><button data-job-toggle="${index}">${t(job.enabled?'disabled':'enabled')}</button><button class="danger" data-job-delete="${index}">${t('remove')}</button></div></td></tr>`).join('')}</tbody></table></div>`:`<div class="empty"><strong>${t('noTasks')}</strong></div>`}</div>`;
|
||||||
bind('new-job',()=>jobEditor());
|
bind('new-job',()=>jobEditor());
|
||||||
document.querySelectorAll('[data-job-edit]').forEach(button=>button.onclick=()=>jobEditor(jobs[button.dataset.jobEdit]));
|
document.querySelectorAll('[data-job-edit]').forEach(button=>button.onclick=()=>jobEditor(jobs[button.dataset.jobEdit]));
|
||||||
document.querySelectorAll('[data-job-toggle]').forEach(button=>button.onclick=busy(async()=>{const job=jobs[button.dataset.jobToggle];await api('/api/v1/jobs/'+job.id,{method:'PUT',body:jobPayload(job,{enabled:!job.enabled})});await navigate();}));
|
document.querySelectorAll('[data-job-toggle]').forEach(button=>button.onclick=busy(async()=>{const job=jobs[button.dataset.jobToggle];await api('/api/v1/jobs/'+job.id,{method:'PUT',body:jobPayload(job,{enabled:!job.enabled})});await navigate();}));
|
||||||
|
|||||||
@@ -2,23 +2,25 @@
|
|||||||
const tr=(zh,en)=>state.lang==='zh'?zh:en;
|
const tr=(zh,en)=>state.lang==='zh'?zh:en;
|
||||||
async function layoutStudioPage(){
|
async function layoutStudioPage(){
|
||||||
const assets=await api('/api/v1/assets?source=uploaded&limit=200');let selected=new Set(),plan=null;
|
const assets=await api('/api/v1/assets?source=uploaded&limit=200');let selected=new Set(),plan=null;
|
||||||
$('#main').innerHTML=`<div class="notice">${tr('一次选择 1–12 张图片,生成多图拼版或海报。AI 只接收文字与尺寸,不接收照片。预览不会上传到画框。','Choose 1–12 photos for a collage or poster. AI receives text and dimensions, never photos. Preview does not upload to the frame.')}</div><div class="columns"><section class="card"><h3>${tr('选择照片','Choose photos')}</h3><input id="studio-files" type="file" multiple accept="image/jpeg,image/png,image/webp"><p class="hint">${tr('可以一次上传多张,保留原始比例。或勾选已有本地照片。','Upload several photos at once, preserving aspect ratio, or select local photos.')}</p><div id="studio-assets" class="studio-assets">${assets.map(a=>`<label class="check-row"><input type="checkbox" value="${a.asset_id}">${esc(a.name)}</label>`).join('')}</div><div class="field"><label>${tr('标题','Title')}</label><input id="studio-title" maxlength="100"></div><div class="field"><label>${tr('底部文字','Footer text')}</label><textarea id="studio-message" maxlength="500"></textarea></div><div class="form-grid"><div class="field"><label>${tr('布局','Layout')}</label><select id="studio-style"><option value="grid">${tr('均匀拼版','Grid')}</option><option value="hero">${tr('一张主图+多张附图','Hero with supporting photos')}</option><option value="poster">${tr('海报','Poster')}</option></select></div><div class="field"><label>${tr('方向','Orientation')}</label><select id="studio-orientation"><option value="portrait">${tr('竖向','Portrait')}</option><option value="landscape">${tr('横向','Landscape')}</option></select></div></div><div class="field"><label>${t('profile')}</label><select id="studio-profile"><option value="color">${t('color')}</option><option value="grayscale">${t('grayscale')}</option></select></div><label class="check-row"><input id="studio-ai" type="checkbox">${tr('使用 AI 排版(先在连接中心配置)','Use AI layout (configure in Connections first)')}</label><div class="field"><label>${tr('AI 排版要求','AI layout instructions')}</label><textarea id="studio-prompt" maxlength="1500" placeholder="${tr('例如:第一张作为主图,其余大小错落','Example: feature the first photo with smaller supporting photos')}"></textarea></div><div class="actions"><button id="studio-plan" class="primary">${tr('规划布局','Plan layout')}</button><button id="studio-render" disabled>${t('render')}</button></div><p class="hint">${tr('规划后可拖动照片区域或修改坐标尺寸。区域不能重叠,超出范围的布局会被拒绝。','After planning, drag photo regions or edit coordinates and sizes. Overlapping or out-of-bounds layouts are rejected.')}</p><div id="studio-region-editor"></div></section><section class="card"><h3>${t('preview')}</h3><div id="studio-layout"></div><div id="studio-preview" class="empty">${tr('先规划布局,再生成最终图片','Plan the layout, then render the final image')}</div><div class="actions"><button id="studio-display" disabled>${t('display')}</button><button id="studio-download" disabled>${t('download')}</button></div></section></div>`;
|
$('#main').innerHTML=`<div class="notice">${tr('一次选择 1–12 张图片,生成多图拼版或海报。AI 只接收文字与尺寸,不接收照片。预览不会上传到画框。','Choose 1–12 photos for a collage or poster. AI receives text and dimensions, never photos. Preview does not upload to the frame.')}</div><div class="columns"><section class="card"><h3>${tr('选择照片','Choose photos')}</h3><input id="studio-files" type="file" multiple accept="image/jpeg,image/png,image/webp"><p class="hint">${tr('可以一次上传多张,保留原始比例。或勾选已有本地照片。','Upload several photos at once, preserving aspect ratio, or select local photos.')}</p><div id="studio-assets" class="studio-assets">${assets.map(a=>`<label class="check-row"><input type="checkbox" value="${a.asset_id}">${esc(a.name)}</label>`).join('')}</div><div class="field"><label for="studio-title">${tr('标题','Title')}</label><input id="studio-title" maxlength="100"></div><div class="field"><label for="studio-message">${tr('底部文字','Footer text')}</label><textarea id="studio-message" maxlength="500"></textarea></div><div class="form-grid"><div class="field"><label for="studio-style">${tr('布局','Layout')}</label><select id="studio-style"><option value="grid">${tr('均匀拼版','Grid')}</option><option value="hero">${tr('一张主图+多张附图','Hero with supporting photos')}</option><option value="poster">${tr('海报','Poster')}</option></select></div><div class="field"><label for="studio-orientation">${tr('方向','Orientation')}</label><select id="studio-orientation"><option value="portrait">${tr('竖向','Portrait')}</option><option value="landscape">${tr('横向','Landscape')}</option></select></div></div><div class="field"><label for="studio-profile">${t('profile')}</label><select id="studio-profile"><option value="color">${t('color')}</option><option value="grayscale">${t('grayscale')}</option></select></div><label class="check-row"><input id="studio-ai" type="checkbox">${tr('使用 AI 排版(先在连接中心配置)','Use AI layout (configure in Connections first)')}</label><div class="field"><label for="studio-prompt">${tr('AI 排版要求','AI layout instructions')}</label><textarea id="studio-prompt" maxlength="1500" placeholder="${tr('例如:第一张作为主图,其余大小错落','Example: feature the first photo with smaller supporting photos')}"></textarea></div><div class="actions"><button id="studio-plan" class="primary">${tr('规划布局','Plan layout')}</button><button id="studio-render" disabled>${t('render')}</button></div><p class="hint">${tr('规划后可拖动照片区域或修改坐标尺寸。区域不能重叠,超出范围的布局会被拒绝。','After planning, drag photo regions or edit coordinates and sizes. Overlapping or out-of-bounds layouts are rejected.')}</p><div id="studio-region-editor"></div></section><section class="card"><h3>${t('preview')}</h3><div id="studio-layout"></div><div id="studio-preview" class="empty">${tr('先规划布局,再生成最终图片','Plan the layout, then render the final image')}</div><div class="actions"><button id="studio-display" disabled>${t('display')}</button><button id="studio-download" disabled>${t('download')}</button></div></section></div>`;
|
||||||
|
await autoCollagePanel();
|
||||||
let rendered=null;
|
let rendered=null;
|
||||||
const invalidate=()=>{rendered=null;$('#studio-display').disabled=true;$('#studio-download').disabled=true;};
|
const invalidate=()=>{rendered=null;$('#studio-display').disabled=true;$('#studio-download').disabled=true;};
|
||||||
$('#studio-assets').onchange=()=>{selected=new Set([...document.querySelectorAll('#studio-assets input:checked')].map(x=>x.value));plan=null;$('#studio-render').disabled=true;invalidate();};
|
$('#studio-assets').onchange=()=>{selected=new Set([...document.querySelectorAll('#studio-assets input:checked')].map(x=>x.value));plan=null;$('#studio-render').disabled=true;invalidate();};
|
||||||
$('#studio-files').onchange=busy(async()=>{const files=[...$('#studio-files').files];if(!files.length)return;const body=new FormData();files.forEach(f=>body.append('files',f));const uploaded=await api('/api/v1/layout/images',{method:'POST',body});for(const a of uploaded){const label=document.createElement('label');label.className='check-row';label.innerHTML=`<input type="checkbox" checked value="${a.asset_id}">${esc(a.name)}`;$('#studio-assets').append(label);}$('#studio-assets').onchange();toast(t('done'));});
|
$('#studio-files').onchange=busy(async()=>{const files=[...$('#studio-files').files];if(!files.length)return;const body=new FormData();files.forEach(f=>body.append('files',f));const uploaded=await api('/api/v1/layout/images',{method:'POST',body});for(const a of uploaded){const label=document.createElement('label');label.className='check-row';label.innerHTML=`<input type="checkbox" checked value="${a.asset_id}">${esc(a.name)}`;$('#studio-assets').append(label);}$('#studio-assets').onchange();toast(t('done'));});
|
||||||
async function showPlan(){
|
function showPlan(){
|
||||||
const box=$('#studio-layout');box.innerHTML='';box.className='studio-canvas';box.style.aspectRatio=plan.width+'/'+plan.height;
|
const layout=plan;
|
||||||
$('#studio-region-editor').innerHTML=plan.regions.map((r,i)=>`<div class="field"><label>${tr('图片区域','Photo region')} ${i+1}</label><div class="region-fields">${['x','y','width','height'].map(k=>`<label>${k}<input data-region="${i}" data-key="${k}" type="number" value="${r[k]}" min="0"></label>`).join('')}</div></div>`).join('');
|
const box=$('#studio-layout');box.innerHTML='';box.className='studio-canvas';box.style.aspectRatio=layout.width+'/'+layout.height;
|
||||||
const update=(el,r)=>{el.style.left=(r.x/plan.width*100)+'%';el.style.top=(r.y/plan.height*100)+'%';el.style.width=(r.width/plan.width*100)+'%';el.style.height=(r.height/plan.height*100)+'%';};
|
$('#studio-region-editor').innerHTML=layout.regions.map((r,i)=>`<div class="field"><label>${tr('图片区域','Photo region')} ${i+1}</label><div class="region-fields">${['x','y','width','height'].map(k=>`<label>${k}<input data-region="${i}" data-key="${k}" type="number" value="${r[k]}" min="0"></label>`).join('')}</div></div>`).join('');
|
||||||
for(const [i,r] of plan.regions.entries()){
|
const update=(el,r)=>{el.style.left=(r.x/layout.width*100)+'%';el.style.top=(r.y/layout.height*100)+'%';el.style.width=(r.width/layout.width*100)+'%';el.style.height=(r.height/layout.height*100)+'%';};
|
||||||
const img=document.createElement('img');img.alt=tr('拖动图片区域','Drag photo region')+' '+(i+1);img.draggable=false;update(img,r);box.append(img);await blobImage(img,'/api/v1/assets/'+r.asset_id);
|
for(const [i,r] of layout.regions.entries()){
|
||||||
img.onpointerdown=e=>{e.preventDefault();img.setPointerCapture(e.pointerId);const start={x:e.clientX,y:e.clientY,rx:r.x,ry:r.y};img.onpointermove=ev=>{r.x=Math.max(0,Math.min(plan.width-r.width,Math.round(start.rx+(ev.clientX-start.x)*plan.width/box.clientWidth)));r.y=Math.max(150,Math.min(plan.height-120-r.height,Math.round(start.ry+(ev.clientY-start.y)*plan.height/box.clientHeight)));update(img,r);for(const el of document.querySelectorAll(`[data-region="${i}"]`))el.value=r[el.dataset.key];invalidate();};img.onpointerup=()=>{img.onpointermove=null;};};
|
const region=document.createElement('div');region.className='studio-region';region.dataset.regionIndex=String(i);update(region,r);box.append(region);const img=document.createElement('img');img.alt=tr('拖动图片区域','Drag photo region')+' '+(i+1);img.draggable=false;region.append(img);void blobImage(img,'/api/v1/assets/'+r.asset_id);
|
||||||
|
region.onpointerdown=e=>{if(plan!==layout)return;e.preventDefault();region.setPointerCapture(e.pointerId);const start={x:e.clientX,y:e.clientY,rx:r.x,ry:r.y};region.onpointermove=ev=>{if(plan!==layout)return;r.x=Math.max(0,Math.min(layout.width-r.width,Math.round(start.rx+(ev.clientX-start.x)*layout.width/box.clientWidth)));r.y=Math.max(150,Math.min(layout.height-120-r.height,Math.round(start.ry+(ev.clientY-start.y)*layout.height/box.clientHeight)));update(region,r);for(const el of document.querySelectorAll(`[data-region="${i}"]`))el.value=r[el.dataset.key];invalidate();};region.onpointerup=region.onpointercancel=()=>{region.onpointermove=null;};};
|
||||||
}
|
}
|
||||||
document.querySelectorAll('[data-region]').forEach(el=>el.oninput=()=>{const r=plan.regions[Number(el.dataset.region)];r[el.dataset.key]=Number(el.value);update(box.children[Number(el.dataset.region)],r);invalidate();});
|
document.querySelectorAll('[data-region]').forEach(el=>el.oninput=()=>{if(plan!==layout)return;const r=layout.regions[Number(el.dataset.region)];r[el.dataset.key]=Number(el.value);update(box.children[Number(el.dataset.region)],r);invalidate();});
|
||||||
}
|
}
|
||||||
for(const id of ['studio-title','studio-message','studio-style','studio-orientation','studio-ai','studio-prompt','studio-profile'])$('#'+id).oninput=()=>{plan=null;$('#studio-render').disabled=true;invalidate();};
|
for(const id of ['studio-title','studio-message','studio-style','studio-orientation','studio-ai','studio-prompt','studio-profile'])$('#'+id).oninput=()=>{plan=null;$('#studio-render').disabled=true;invalidate();};
|
||||||
bind('studio-plan',async()=>{plan=await api('/api/v1/layout/plan',{method:'POST',body:{asset_ids:[...selected],title:$('#studio-title').value,message:$('#studio-message').value,orientation:$('#studio-orientation').value,style:$('#studio-style').value,use_ai:$('#studio-ai').checked,prompt:$('#studio-prompt').value}});invalidate();await showPlan();$('#studio-render').disabled=false;});
|
bind('studio-plan',async()=>{plan=await api('/api/v1/layout/plan',{method:'POST',body:{asset_ids:[...selected],title:$('#studio-title').value,message:$('#studio-message').value,orientation:$('#studio-orientation').value,style:$('#studio-style').value,use_ai:$('#studio-ai').checked,prompt:$('#studio-prompt').value}});invalidate();showPlan();$('#studio-render').disabled=false;});
|
||||||
bind('studio-render',async()=>{if(!plan)return;const accepted=await api('/api/v1/render',{method:'POST',body:{type:'template',template:$('#studio-style').value==='poster'?'poster':'collage',data:{layout:plan},profile:$('#studio-profile').value}});const op=await waitOperation(accepted.operation_id);rendered=op.result;$('#studio-preview').className='';$('#studio-preview').innerHTML='<img class="preview" id="studio-result" alt="Preview">';await blobImage($('#studio-result'),rendered.url);$('#studio-display').disabled=!liveWriteAllowed();$('#studio-download').disabled=false;});
|
bind('studio-render',async()=>{if(!plan)return;const accepted=await api('/api/v1/render',{method:'POST',body:{type:'template',template:$('#studio-style').value==='poster'?'poster':'collage',data:{layout:plan},profile:$('#studio-profile').value}});const op=await waitOperation(accepted.operation_id);rendered=op.result;$('#studio-preview').className='';$('#studio-preview').innerHTML='<img class="preview" id="studio-result" alt="Preview">';await blobImage($('#studio-result'),rendered.url);$('#studio-display').disabled=!liveWriteAllowed();$('#studio-download').disabled=false;});
|
||||||
bind('studio-display',()=>displayDialog({type:'image',asset_id:rendered.asset_id}));bind('studio-download',()=>downloadImage(rendered.url,'frame-flow-layout.jpg'));
|
bind('studio-display',()=>displayDialog({type:'image',asset_id:rendered.asset_id}));bind('studio-download',()=>downloadImage(rendered.url,'frame-flow-layout.jpg'));
|
||||||
}
|
}
|
||||||
@@ -27,32 +29,44 @@ async function connectionsPage(){
|
|||||||
await aiSettingsPanel();await aiImagePanel();await storageSettingsPanel();await clientsPanel();await webhooksPanel();await externalProvidersPanel();await mqttPanel();
|
await aiSettingsPanel();await aiImagePanel();await storageSettingsPanel();await clientsPanel();await webhooksPanel();await externalProvidersPanel();await mqttPanel();
|
||||||
}
|
}
|
||||||
async function aiSettingsPanel(){
|
async function aiSettingsPanel(){
|
||||||
const config=await api('/api/v1/settings/ai-layout');const card=document.createElement('section');card.className='card';card.innerHTML=`<h3>${tr('AI 排版 · OpenAI 兼容','AI layout · OpenAI compatible')}</h3><p class="hint">${tr('只发送文字、尺寸和排版要求,不发送照片。填写完整 chat/completions 地址;使用服务商的模型名称。','Only text, dimensions and instructions are sent; never photos. Enter the full chat/completions URL and provider model name.')}</p><form id="ai-settings-form"><div class="field"><label>Endpoint</label><input id="ai-endpoint" type="url" value="${esc(config.endpoint)}" placeholder="https://…/v1/chat/completions"></div><div class="field"><label>Model</label><input id="ai-model" value="${esc(config.model)}"></div><div class="field"><label>${tr('API Key(留空保留已有密钥)','API key (blank keeps existing)')}</label><input id="ai-key" type="password" autocomplete="off"><p class="hint">${t('keyConfigured')}: ${t(config.key_configured?'yes':'no')}</p></div><button type="submit">${t('save')}</button></form>`;$('#main').append(card);$('#ai-settings-form').onsubmit=busy(async e=>{e.preventDefault();await api('/api/v1/settings/ai-layout',{method:'PUT',body:{endpoint:$('#ai-endpoint').value,model:$('#ai-model').value}});const key=$('#ai-key').value;$('#ai-key').value='';if(key)await api('/api/v1/settings/ai-layout/key',{method:'PUT',body:{key}});toast(t('done'));});
|
const config=await api('/api/v1/settings/ai-layout');const card=document.createElement('section');card.className='card';card.innerHTML=`<h3>${tr('AI 排版 · OpenAI 兼容','AI layout · OpenAI compatible')}</h3><p class="hint">${tr('只发送文字、尺寸和排版要求,不发送照片。填写完整 chat/completions 地址;使用服务商的模型名称。','Only text, dimensions and instructions are sent; never photos. Enter the full chat/completions URL and provider model name.')}</p><form id="ai-settings-form"><div class="field"><label for="ai-endpoint">Endpoint</label><input id="ai-endpoint" type="url" value="${esc(config.endpoint)}" placeholder="https://…/v1/chat/completions"></div><div class="field"><label for="ai-model">Model</label><input id="ai-model" value="${esc(config.model)}"></div><div class="field"><label for="ai-key">${tr('API Key(留空保留已有密钥)','API key (blank keeps existing)')}</label><input id="ai-key" type="password" autocomplete="off"><p class="hint">${t('apiKeyConfigured')}: ${t(config.key_configured?'yes':'no')}</p></div><button type="submit">${t('save')}</button></form>`;$('#main').append(card);$('#ai-settings-form').onsubmit=busy(async e=>{e.preventDefault();await api('/api/v1/settings/ai-layout',{method:'PUT',body:{endpoint:$('#ai-endpoint').value,model:$('#ai-model').value}});const key=$('#ai-key').value;$('#ai-key').value='';if(key)await api('/api/v1/settings/ai-layout/key',{method:'PUT',body:{key}});toast(t('done'));});
|
||||||
}
|
}
|
||||||
async function storageSettingsPanel(){
|
async function storageSettingsPanel(){
|
||||||
const data=await api('/api/v1/storage');const p=data.policy;const card=document.createElement('section');card.className='card';card.innerHTML=`<h3>${tr('本地图库保留策略','Local storage retention')}</h3><p>${data.asset_count} ${t('count')} · ${(data.total_bytes/1024/1024).toFixed(1)} MiB · ${tr('受保护','Protected')}: ${data.protected_count}</p><p class="hint">${tr('仅清理生成图和预览缓存;手动上传、星标、当前/恢复图片以及任务/模板引用会保留。不会删除 NAS 原照片或云端图片。先查看清理预估,再开启自动清理。','Only generated images and preview cache are cleaned. Manual uploads, stars, current/restore content and task/template references are retained. NAS originals and cloud images are untouched. Preview cleanup before enabling it.')}</p><form id="storage-policy"><label class="check-row"><input id="storage-enabled" type="checkbox" ${p.enabled?'checked':''}>${t('enabled')}</label><div class="form-grid"><div class="field"><label>${tr('生成图保留天数','Generated image retention days')}</label><input id="storage-days" type="number" min="1" value="${p.generated_days}"></div><div class="field"><label>${tr('缓存保留天数','Cache retention days')}</label><input id="storage-cache-days" type="number" min="1" value="${p.cache_days}"></div><div class="field"><label>${tr('容量目标 MiB','Target size MiB')}</label><input id="storage-size" type="number" min="1" value="${p.max_bytes/1024/1024}"></div></div><div class="actions"><button type="submit">${t('save')}</button><button id="storage-preview" type="button">${tr('预估清理','Preview cleanup')}</button></div><p id="storage-estimate"></p></form>`;$('#main').append(card);$('#storage-policy').onsubmit=busy(async e=>{e.preventDefault();await api('/api/v1/storage/policy',{method:'PUT',body:{enabled:$('#storage-enabled').checked,generated_days:Number($('#storage-days').value),cache_days:Number($('#storage-cache-days').value),max_bytes:Number($('#storage-size').value)*1024*1024}});toast(t('done'));});bind('storage-preview',async()=>{const result=await api('/api/v1/storage/cleanup?dry_run=true',{method:'POST'});$('#storage-estimate').textContent=result.disabled?tr('策略未启用;不会清理','Policy disabled; nothing is removed'):tr('可清理 ','Eligible: ')+result.deleted+' · '+(result.bytes_freed/1024/1024).toFixed(1)+' MiB';});
|
const data=await api('/api/v1/storage');const p=data.policy;const card=document.createElement('section');card.className='card';card.innerHTML=`<h3>${tr('本地图库保留策略','Local storage retention')}</h3><p>${data.asset_count} ${t('count')} · ${(data.total_bytes/1024/1024).toFixed(1)} MiB · ${tr('受保护','Protected')}: ${data.protected_count}</p><p class="hint">${tr('仅清理生成图和预览缓存;手动上传、星标、当前/恢复图片以及任务/模板引用会保留。不会删除 NAS 原照片或云端图片。先查看清理预估,再开启自动清理。','Only generated images and preview cache are cleaned. Manual uploads, stars, current/restore content and task/template references are retained. NAS originals and cloud images are untouched. Preview cleanup before enabling it.')}</p><form id="storage-policy"><label class="check-row"><input id="storage-enabled" type="checkbox" ${p.enabled?'checked':''}>${t('enabled')}</label><div class="form-grid"><div class="field"><label for="storage-days">${tr('生成图保留天数','Generated image retention days')}</label><input id="storage-days" type="number" min="1" value="${p.generated_days}"></div><div class="field"><label for="storage-cache-days">${tr('缓存保留天数','Cache retention days')}</label><input id="storage-cache-days" type="number" min="1" value="${p.cache_days}"></div><div class="field"><label for="storage-size">${tr('容量目标 MiB','Target size MiB')}</label><input id="storage-size" type="number" min="1" value="${p.max_bytes/1024/1024}"></div></div><div class="actions"><button type="submit">${t('save')}</button><button id="storage-preview" type="button">${tr('预估清理','Preview cleanup')}</button></div><p id="storage-estimate"></p></form>`;$('#main').append(card);$('#storage-policy').onsubmit=busy(async e=>{e.preventDefault();await api('/api/v1/storage/policy',{method:'PUT',body:{enabled:$('#storage-enabled').checked,generated_days:Number($('#storage-days').value),cache_days:Number($('#storage-cache-days').value),max_bytes:Number($('#storage-size').value)*1024*1024}});toast(t('done'));});bind('storage-preview',async()=>{const result=await api('/api/v1/storage/cleanup?dry_run=true',{method:'POST'});$('#storage-estimate').textContent=result.disabled?tr('策略未启用;不会清理','Policy disabled; nothing is removed'):tr('可清理 ','Eligible: ')+result.deleted+' · '+(result.bytes_freed/1024/1024).toFixed(1)+' MiB';});
|
||||||
}
|
}
|
||||||
async function clientsPanel(){
|
async function clientsPanel(){
|
||||||
const clients=await api('/api/v1/clients');const scopes=['devices:read','images:read','display:write','templates:read','render:write','jobs:read','jobs:write','history:read'];const card=document.createElement('section');card.className='card';card.innerHTML=`<h3>${tr('外部客户端权限','External client permissions')}</h3><p class="hint">${tr('网页继续使用账号登录。这里只为其他程序创建独立凭据,可随时撤销。','The web UI still uses account login. These credentials are for other programs and can be revoked.')}</p>${clients.map(c=>`<p>${esc(c.name)} · ${esc(c.client_id)} · ${t(c.enabled?'enabled':'disabled')} ${c.client_id!=='admin'&&c.enabled?`<button data-revoke="${esc(c.client_id)}">${tr('撤销','Revoke')}</button>`:''}</p>`).join('')}<form id="client-form"><div class="field"><label>Client ID</label><input id="client-id" required pattern="[a-z0-9-]{1,60}"></div><div class="field"><label>${t('name')}</label><input id="client-name" required></div>${scopes.map(s=>`<label class="check-row"><input type="checkbox" name="client-scope" value="${s}" ${['devices:read','display:write','templates:read','render:write'].includes(s)?'checked':''}>${s}</label>`).join('')}<button type="submit">${tr('创建客户端','Create client')}</button><div id="client-secret" class="notice" hidden></div></form>`;$('#main').append(card);document.querySelectorAll('[data-revoke]').forEach(b=>b.onclick=busy(async()=>{await api('/api/v1/clients/'+b.dataset.revoke,{method:'DELETE'});await navigate();}));$('#client-form').onsubmit=busy(async e=>{e.preventDefault();const r=await api('/api/v1/clients',{method:'POST',body:{client_id:$('#client-id').value,name:$('#client-name').value,permissions:[...document.querySelectorAll('[name="client-scope"]:checked')].map(x=>x.value)}});$('#client-secret').hidden=false;$('#client-secret').textContent=tr('仅显示一次,请保存:','Shown once; save it: ')+r.token;});
|
const clients=await api('/api/v1/clients');const scopes=['devices:read','images:read','display:write','templates:read','render:write','jobs:read','jobs:write','history:read'];const card=document.createElement('section');card.className='card';card.innerHTML=`<h3>${tr('外部客户端权限','External client permissions')}</h3><p class="hint">${tr('网页继续使用账号登录。这里只为其他程序创建独立凭据,可随时撤销。','The web UI still uses account login. These credentials are for other programs and can be revoked.')}</p>${clients.map(c=>`<p>${esc(c.name)} · ${esc(c.client_id)} · ${t(c.enabled?'enabled':'disabled')} ${c.client_id!=='admin'&&c.enabled?`<button data-revoke="${esc(c.client_id)}">${tr('撤销','Revoke')}</button>`:''}</p>`).join('')}<form id="client-form"><div class="field"><label for="client-id">Client ID</label><input id="client-id" required pattern="[a-z0-9-]{1,60}"></div><div class="field"><label for="client-name">${t('name')}</label><input id="client-name" required></div>${scopes.map(s=>`<label class="check-row"><input type="checkbox" name="client-scope" value="${s}" ${['devices:read','display:write','templates:read','render:write'].includes(s)?'checked':''}>${s}</label>`).join('')}<button type="submit">${tr('创建客户端','Create client')}</button><div id="client-secret" class="notice" hidden></div></form>`;$('#main').append(card);document.querySelectorAll('[data-revoke]').forEach(b=>b.onclick=busy(async()=>{await api('/api/v1/clients/'+b.dataset.revoke,{method:'DELETE'});await navigate();}));$('#client-form').onsubmit=busy(async e=>{e.preventDefault();const r=await api('/api/v1/clients',{method:'POST',body:{client_id:$('#client-id').value,name:$('#client-name').value,permissions:[...document.querySelectorAll('[name="client-scope"]:checked')].map(x=>x.value)}});$('#client-secret').hidden=false;$('#client-secret').textContent=tr('仅显示一次,请保存:','Shown once; save it: ')+r.token;});
|
||||||
}
|
}
|
||||||
async function webhooksPanel(){
|
async function webhooksPanel(){
|
||||||
const hooks=await api('/api/v1/webhooks');const card=document.createElement('section');card.className='card';card.innerHTML=`<h3>Webhook</h3><p class="hint">${tr('HTTPS 地址须先加入设置中的允许主机。事件带 HMAC 签名,最多重试三次;接收端应按事件 ID 去重。','Add the HTTPS host to the Settings allowlist first. Events are HMAC signed, with up to three attempts; deduplicate by event ID.')}</p>${hooks.map(h=>`<p>${esc(h.callback_url)} <button data-hook-delete="${h.id}">${t('delete')}</button></p>`).join('')}<form id="hook-form"><div class="field"><label>Callback URL</label><input id="hook-url" type="url" required></div><div class="field"><label>${tr('事件(逗号分隔)','Events (comma separated)')}</label><input id="hook-events" value="operation.completed,operation.failed"></div><button type="submit">${t('save')}</button><p id="hook-secret"></p></form>`;$('#main').append(card);document.querySelectorAll('[data-hook-delete]').forEach(b=>b.onclick=busy(async()=>{await api('/api/v1/webhooks/'+b.dataset.hookDelete,{method:'DELETE'});await navigate();}));$('#hook-form').onsubmit=busy(async e=>{e.preventDefault();const r=await api('/api/v1/webhooks',{method:'POST',body:{callback_url:$('#hook-url').value,event_types:$('#hook-events').value.split(',').map(x=>x.trim()).filter(Boolean)}});$('#hook-secret').textContent=tr('签名密钥仅显示一次:','Signing key shown once: ')+r.signing_secret;});
|
const hooks=await api('/api/v1/webhooks');const card=document.createElement('section');card.className='card';card.innerHTML=`<h3>Webhook</h3><p class="hint">${tr('HTTPS 地址须先加入设置中的允许主机。事件带 HMAC 签名,最多重试三次;接收端应按事件 ID 去重。','Add the HTTPS host to the Settings allowlist first. Events are HMAC signed, with up to three attempts; deduplicate by event ID.')}</p>${hooks.map(h=>`<p>${esc(h.callback_url)} <button data-hook-delete="${h.id}">${t('delete')}</button></p>`).join('')}<form id="hook-form"><div class="field"><label for="hook-url">Callback URL</label><input id="hook-url" type="url" required></div><div class="field"><label for="hook-events">${tr('事件(逗号分隔)','Events (comma separated)')}</label><input id="hook-events" value="operation.completed,operation.failed"></div><button type="submit">${t('save')}</button><p id="hook-secret"></p></form>`;$('#main').append(card);document.querySelectorAll('[data-hook-delete]').forEach(b=>b.onclick=busy(async()=>{await api('/api/v1/webhooks/'+b.dataset.hookDelete,{method:'DELETE'});await navigate();}));$('#hook-form').onsubmit=busy(async e=>{e.preventDefault();const r=await api('/api/v1/webhooks',{method:'POST',body:{callback_url:$('#hook-url').value,event_types:$('#hook-events').value.split(',').map(x=>x.trim()).filter(Boolean)}});$('#hook-secret').textContent=tr('签名密钥仅显示一次:','Signing key shown once: ')+r.signing_secret;});
|
||||||
}
|
}
|
||||||
async function externalProvidersPanel(){
|
async function externalProvidersPanel(){
|
||||||
const providers=await api('/api/v1/providers/external');const card=document.createElement('section');card.className='card';card.innerHTML=`<h3>${tr('日历、家庭状态与监控','Calendars, home state and monitoring')}</h3><p class="hint">${tr('Google Calendar 使用 OAuth Token;家庭日历可用 ICS。Home Assistant 和 NAS/树莓派/服务器监控可以通过只读 JSON 接口提供数据,不访问外部数据库。LAN 访问必须明确开启。','Google Calendar uses an OAuth token; family calendars can use ICS. Home Assistant and NAS/Pi/server monitoring supply read-only JSON data without database access. LAN access requires explicit opt-in.')}</p>${providers.map(p=>`<p>${esc(p.name)} · ${esc(p.kind)} <button data-provider-read="${p.id}">${tr('读取','Read')}</button><button data-provider-job="${p.id}">${tr('创建展示任务','Create display job')}</button></p>`).join('')}<form id="provider-form"><div class="field"><label>ID</label><input id="provider-id" required pattern="[a-z0-9-]{1,60}"></div><div class="field"><label>${t('name')}</label><input id="provider-name" required></div><div class="field"><label>${tr('类型','Type')}</label><select id="provider-kind"><option value="google-calendar">Google Calendar</option><option value="ics">ICS · ${tr('家庭日历','Family calendar')}</option><option value="home-assistant">Home Assistant</option><option value="http-json">HTTP JSON · NAS / Pi / Server</option></select></div><div class="field"><label>${tr('地址(Google 日历填写 Calendar ID)','URL (Calendar ID for Google)')}</label><input id="provider-url" required></div><div class="field"><label>${tr('Token(可选)','Token (optional)')}</label><input id="provider-key" type="password" autocomplete="off"></div><label class="check-row"><input id="provider-lan" type="checkbox">${tr('允许访问指定 LAN 地址','Allow access to this LAN address')}</label><button type="submit">${t('save')}</button></form><pre id="provider-result"></pre>`;$('#main').append(card);$('#provider-form').onsubmit=busy(async e=>{e.preventDefault();const id=$('#provider-id').value;await api('/api/v1/providers/external/'+id,{method:'PUT',body:{kind:$('#provider-kind').value,name:$('#provider-name').value,endpoint:$('#provider-url').value,allow_insecure_lan:$('#provider-lan').checked}});const key=$('#provider-key').value;$('#provider-key').value='';if(key)await api('/api/v1/providers/external/'+id+'/key',{method:'PUT',body:{key}});await navigate();});document.querySelectorAll('[data-provider-read]').forEach(b=>b.onclick=busy(async()=>{$('#provider-result').textContent=JSON.stringify(await api('/api/v1/providers/external/'+b.dataset.providerRead+'/data'),null,2);}));document.querySelectorAll('[data-provider-job]').forEach(b=>b.onclick=busy(async()=>{await api('/api/v1/jobs',{method:'POST',body:{device_id:state.device,name:tr('外部信息板','External dashboard'),enabled:false,schedule:{type:'daily',time:'07:00'},source:{type:'provider',provider_id:b.dataset.providerJob,template:'daily-dashboard',data:{title:tr('家庭信息','Home information')}},display_duration:0,restore_previous:false,priority:50}});await navigate('automation');}));
|
const providers=await api('/api/v1/providers/external');const card=document.createElement('section');card.className='card';card.innerHTML=`<h3>${tr('日历、家庭状态与监控','Calendars, home state and monitoring')}</h3><p class="hint">${tr('Google Calendar 使用 OAuth Token;家庭日历可用 ICS。Home Assistant 和 NAS/树莓派/服务器监控可以通过只读 JSON 接口提供数据,不访问外部数据库。LAN 访问必须明确开启。','Google Calendar uses an OAuth token; family calendars can use ICS. Home Assistant and NAS/Pi/server monitoring supply read-only JSON data without database access. LAN access requires explicit opt-in.')}</p>${providers.map(p=>`<p>${esc(p.name)} · ${esc(p.kind)} <button data-provider-read="${p.id}">${tr('读取','Read')}</button><button data-provider-job="${p.id}">${tr('创建展示任务','Create display job')}</button></p>`).join('')}<form id="provider-form"><div class="field"><label for="provider-id">ID</label><input id="provider-id" required pattern="[a-z0-9-]{1,60}"></div><div class="field"><label for="provider-name">${t('name')}</label><input id="provider-name" required></div><div class="field"><label for="provider-kind">${tr('类型','Type')}</label><select id="provider-kind"><option value="google-calendar">Google Calendar</option><option value="ics">ICS · ${tr('家庭日历','Family calendar')}</option><option value="home-assistant">Home Assistant</option><option value="http-json">HTTP JSON · NAS / Pi / Server</option></select></div><div class="field"><label for="provider-url">${tr('地址(Google 日历填写 Calendar ID)','URL (Calendar ID for Google)')}</label><input id="provider-url" required></div><div class="field"><label for="provider-key">${tr('Token(可选)','Token (optional)')}</label><input id="provider-key" type="password" autocomplete="off"></div><label class="check-row"><input id="provider-lan" type="checkbox">${tr('允许访问指定 LAN 地址','Allow access to this LAN address')}</label><button type="submit">${t('save')}</button></form><pre id="provider-result"></pre>`;$('#main').append(card);$('#provider-form').onsubmit=busy(async e=>{e.preventDefault();const id=$('#provider-id').value;await api('/api/v1/providers/external/'+id,{method:'PUT',body:{kind:$('#provider-kind').value,name:$('#provider-name').value,endpoint:$('#provider-url').value,allow_insecure_lan:$('#provider-lan').checked}});const key=$('#provider-key').value;$('#provider-key').value='';if(key)await api('/api/v1/providers/external/'+id+'/key',{method:'PUT',body:{key}});await navigate();});document.querySelectorAll('[data-provider-read]').forEach(b=>b.onclick=busy(async()=>{$('#provider-result').textContent=JSON.stringify(await api('/api/v1/providers/external/'+b.dataset.providerRead+'/data'),null,2);}));document.querySelectorAll('[data-provider-job]').forEach(b=>b.onclick=busy(async()=>{await api('/api/v1/jobs',{method:'POST',body:{device_id:state.device,name:tr('外部信息板','External dashboard'),enabled:false,schedule:{type:'daily',time:'07:00'},source:{type:'provider',provider_id:b.dataset.providerJob,template:'daily-dashboard',data:{title:tr('家庭信息','Home information')}},display_duration:0,restore_previous:false,priority:50}});await navigate('automation');}));
|
||||||
}
|
}
|
||||||
async function officialWidgetControls(info,data){
|
async function officialWidgetControls(info,data){
|
||||||
const panel=document.createElement('section');panel.className='card';panel.innerHTML=`<h3>${tr('订阅管理','Subscription management')}</h3><p class="hint">${tr('这与本地模板独立。请选择官方目录中的小组件,填写其参数后再确认。取消订阅不会自动恢复之前的照片。','This is separate from local templates. Choose a widget from the official catalog and fill its parameters before confirming. Cancelling does not automatically restore a previous photo.')}</p><div class="field"><label>${tr('官方小组件','Official widget')}</label><select id="official-widget-choice">${data.catalog.map(w=>`<option value="${w.id}">${esc(w.name)}</option>`).join('')}</select></div><div id="official-widget-args"></div><div class="actions"><button id="official-widget-use" class="primary">${tr('确认使用','Apply widget')}</button><button id="official-widget-cancel">${tr('取消订阅','Cancel subscription')}</button></div>`;info.append(panel);const disabled=!data.configured||!liveWriteAllowed();$('#official-widget-use').disabled=disabled;$('#official-widget-cancel').disabled=disabled;
|
const panel=document.createElement('section');panel.className='card';panel.innerHTML=`<h3>${tr('订阅管理','Subscription management')}</h3><p class="hint">${tr('这与本地模板独立。请选择官方目录中的小组件,填写其参数后再确认。取消订阅不会自动恢复之前的照片。','This is separate from local templates. Choose a widget from the official catalog and fill its parameters before confirming. Cancelling does not automatically restore a previous photo.')}</p><div class="field"><label for="official-widget-choice">${tr('官方小组件','Official widget')}</label><select id="official-widget-choice">${data.catalog.map(w=>`<option value="${w.id}">${esc(w.name)}</option>`).join('')}</select></div><div id="official-widget-args"></div><div class="actions"><button id="official-widget-use" class="primary">${tr('确认使用','Apply widget')}</button><button id="official-widget-cancel">${tr('取消订阅','Cancel subscription')}</button></div>`;info.append(panel);const disabled=!data.configured||!liveWriteAllowed();$('#official-widget-use').disabled=disabled;$('#official-widget-cancel').disabled=disabled;
|
||||||
const fields=()=>{const w=data.catalog.find(w=>w.id===Number($('#official-widget-choice').value));$('#official-widget-args').innerHTML=(w?.arg_keys||[]).map(k=>`<div class="field"><label>${esc(k)}</label><input data-widget-arg="${esc(k)}" maxlength="2000"></div>`).join('');};if(data.current)$('#official-widget-choice').value=data.current.id;fields();$('#official-widget-choice').onchange=fields;
|
const fields=()=>{const w=data.catalog.find(w=>w.id===Number($('#official-widget-choice').value));$('#official-widget-args').innerHTML=(w?.arg_keys||[]).map(k=>`<div class="field"><label>${esc(k)}</label><input data-widget-arg="${esc(k)}" maxlength="2000"></div>`).join('');};if(data.current)$('#official-widget-choice').value=data.current.id;fields();$('#official-widget-choice').onchange=fields;
|
||||||
const send=cover_id=>confirmDialog(tr('此操作会改变官方订阅和画框内容,是否继续?','This changes the official subscription and frame content. Continue?'),async()=>{const args=cover_id?Object.fromEntries([...document.querySelectorAll('[data-widget-arg]')].filter(x=>x.value).map(x=>[x.dataset.widgetArg,x.value])):{};const r=await api('/api/v1/devices/'+state.device+'/widgets/selection',{method:'POST',body:{cover_id,args},headers:{'Idempotency-Key':'widget-'+clientUUID()}});await waitOperation(r.operation_id);await navigate('templates');});if(!disabled){$('#official-widget-use').onclick=busy(()=>send(Number($('#official-widget-choice').value)));$('#official-widget-cancel').onclick=busy(()=>send(null));}
|
const send=cover_id=>confirmDialog(tr('此操作会改变官方订阅和画框内容,是否继续?','This changes the official subscription and frame content. Continue?'),async()=>{const args=cover_id?Object.fromEntries([...document.querySelectorAll('[data-widget-arg]')].filter(x=>x.value).map(x=>[x.dataset.widgetArg,x.value])):{};const r=await api('/api/v1/devices/'+state.device+'/widgets/selection',{method:'POST',body:{cover_id,args},headers:{'Idempotency-Key':'widget-'+clientUUID()}});await waitOperation(r.operation_id);await navigate('templates');});if(!disabled){$('#official-widget-use').onclick=busy(()=>send(Number($('#official-widget-choice').value)));$('#official-widget-cancel').onclick=busy(()=>send(null));}
|
||||||
}
|
}
|
||||||
function addPhotoQualityFields(source){
|
function addPhotoQualityFields(source){
|
||||||
const box=document.createElement('section');box.innerHTML=`<h3>${tr('照片筛选','Photo filtering')}</h3><p class="hint">${tr('按小图清晰度、亮度和相似度筛选,不改动或删除 NAS 原照片;无法保证识别闭眼。建议先用低阈值。个人空间还需要将相应目录只读挂载到 /photos。','Filters thumbnail sharpness, brightness and similarity without modifying or deleting originals. Closed-eye detection is not guaranteed. Start with low thresholds. Personal space also requires mounting its folder read-only at /photos.')}</p><div class="field"><label>${tr('人物空间','People space')}</label><select id="source-people-space"><option value="shared">${tr('共享空间','Shared space')}</option><option value="personal">${tr('个人空间','Personal space')}</option></select></div><div class="form-grid"><div class="field"><label>${tr('最低清晰度(0 不筛选)','Minimum sharpness (0 disables)')}</label><input id="source-sharpness" type="number" min="0" max="10000" value="${source?.minimum_sharpness||0}"></div><div class="field"><label>${tr('最低亮度','Minimum brightness')}</label><input id="source-bright-min" type="number" min="0" max="255" value="${source?.minimum_brightness||0}"></div><div class="field"><label>${tr('最高亮度','Maximum brightness')}</label><input id="source-bright-max" type="number" min="0" max="255" value="${source?.maximum_brightness??255}"></div></div><label class="check-row"><input id="source-dedup" type="checkbox" ${source?.avoid_duplicates?'checked':''}>${tr('避开最近 200 张的相似照片','Avoid photos similar to the last 200 selections')}</label><div class="field"><label>${tr('网盘 OAuth 凭据 JSON(可选;仅原生网盘)','Drive OAuth credentials JSON (optional; native drives only)')}</label><input id="source-oauth" type="password" autocomplete="off" placeholder='{"access_token":"…","drive_id":"…"}'></textarea></div>`;$('#photo-source-form .modal-actions').before(box);$('#source-people-space').value=source?.people_space||'shared';
|
const box=document.createElement('section');box.innerHTML=`<div id="source-local-quality"><h3>${tr('照片筛选','Photo filtering')}</h3><p class="hint">${tr('对 API 获取的预览图按清晰度、亮度和相似度筛选,不修改或删除 NAS 原照片;无法保证识别闭眼。建议先使用较低阈值。','Filters API previews by sharpness, brightness and similarity without modifying or deleting NAS originals. Closed-eye detection is not guaranteed. Start with low thresholds.')}</p><div class="field"><label for="source-people-space">${tr('照片空间','Photo space')}</label><select id="source-people-space"><option value="shared">${tr('共享空间','Shared space')}</option><option value="personal">${tr('个人空间','Personal space')}</option></select></div><div class="form-grid"><div class="field"><label for="source-sharpness">${tr('最低清晰度(0 不筛选)','Minimum sharpness (0 disables)')}</label><input id="source-sharpness" type="number" min="0" max="10000" value="${source?.minimum_sharpness||0}"></div><div class="field"><label for="source-bright-min">${tr('最低亮度','Minimum brightness')}</label><input id="source-bright-min" type="number" min="0" max="255" value="${source?.minimum_brightness||0}"></div><div class="field"><label for="source-bright-max">${tr('最高亮度','Maximum brightness')}</label><input id="source-bright-max" type="number" min="0" max="255" value="${source?.maximum_brightness??255}"></div></div><label class="check-row"><input id="source-dedup" type="checkbox" ${source?.avoid_duplicates?'checked':''}>${tr('避开最近 200 张的相似照片','Avoid photos similar to the last 200 selections')}</label></div><div class="field"><label for="source-oauth">${tr('网盘 OAuth 凭据 JSON(可选;仅原生网盘)','Drive OAuth credentials JSON (optional; native drives only)')}</label><input id="source-oauth" type="password" autocomplete="off" placeholder='{"access_token":"…","drive_id":"…"}'></div>`;$('#photo-source-form .modal-actions').before(box);$('#source-people-space').value=source?.people_space||'shared';
|
||||||
|
|
||||||
}
|
}
|
||||||
async function aiImagePanel(){
|
async function aiImagePanel(){
|
||||||
const info=await api('/api/v1/settings/ai-images');const conf=info.config||{};const card=document.createElement('section');card.className='card';card.innerHTML=`<h3>${tr('AI 生图','AI image generation')}</h3><p class="hint">${tr('独立配置 images/generations 接口。每次仅生成一张并保存本地,不会自动显示到画框。请求可能收费,失败不自动重试。','Configure a separate images/generations endpoint. One image is saved locally per request, never automatically displayed. Requests may be billed; failures are not retried.')}</p><form id="image-ai-config"><div class="field"><label>Endpoint</label><input id="image-ai-url" type="url" required value="${esc(conf.endpoint||'')}"></div><div class="field"><label>Model</label><input id="image-ai-model" required value="${esc(conf.model||'')}"></div><div class="field"><label>Size</label><select id="image-ai-size"><option>1024x1536</option><option>1536x1024</option><option>1024x1024</option></select></div><div class="field"><label>API Key</label><input id="image-ai-key" type="password" autocomplete="off"><p class="hint">${t('keyConfigured')}: ${t(info.key_configured?'yes':'no')}</p></div><button type="submit">${t('save')}</button></form><form id="image-ai-generate"><div class="field"><label>${tr('画面描述','Image prompt')}</label><textarea id="image-ai-prompt" required maxlength="4000"></textarea></div><button type="submit">${tr('生成一张(可能收费)','Generate one image (may incur charges)')}</button></form><div id="image-ai-preview"></div>`;$('#main').append(card);$('#image-ai-size').value=conf.size||'1024x1536';$('#image-ai-config').onsubmit=busy(async e=>{e.preventDefault();await api('/api/v1/settings/ai-images',{method:'PUT',body:{endpoint:$('#image-ai-url').value,model:$('#image-ai-model').value,size:$('#image-ai-size').value}});const key=$('#image-ai-key').value;$('#image-ai-key').value='';if(key)await api('/api/v1/settings/ai-images/key',{method:'PUT',body:{key}});toast(t('done'));});$('#image-ai-generate').onsubmit=busy(async e=>{e.preventDefault();const result=await api('/api/v1/ai/images',{method:'POST',body:{prompt:$('#image-ai-prompt').value},headers:{'Idempotency-Key':'ai-image-'+clientUUID()}});const op=await waitOperation(result.operation_id);$('#image-ai-preview').innerHTML='<img class="preview" id="image-ai-result" alt="Generated image">';await blobImage($('#image-ai-result'),op.result.url);toast(tr('已存入本地图库','Saved to local gallery'));});
|
const info=await api('/api/v1/settings/ai-images');const conf=info.config||{};const card=document.createElement('section');card.className='card';card.innerHTML=`<h3>${tr('AI 生图','AI image generation')}</h3><p class="hint">${tr('独立配置 images/generations 接口。每次仅生成一张并保存本地,不会自动显示到画框。请求可能收费,失败不自动重试。','Configure a separate images/generations endpoint. One image is saved locally per request, never automatically displayed. Requests may be billed; failures are not retried.')}</p><form id="image-ai-config"><div class="field"><label for="image-ai-url">Endpoint</label><input id="image-ai-url" type="url" required value="${esc(conf.endpoint||'')}"></div><div class="field"><label for="image-ai-model">Model</label><input id="image-ai-model" required value="${esc(conf.model||'')}"></div><div class="field"><label for="image-ai-size">Size</label><select id="image-ai-size"><option>1024x1536</option><option>1536x1024</option><option>1024x1024</option></select></div><div class="field"><label for="image-ai-key">API Key</label><input id="image-ai-key" type="password" autocomplete="off"><p class="hint">${t('apiKeyConfigured')}: ${t(info.key_configured?'yes':'no')}</p></div><button type="submit">${t('save')}</button></form><form id="image-ai-generate"><div class="field"><label for="image-ai-prompt">${tr('画面描述','Image prompt')}</label><textarea id="image-ai-prompt" required maxlength="4000"></textarea></div><button type="submit">${tr('生成一张(可能收费)','Generate one image (may incur charges)')}</button></form><div id="image-ai-preview"></div>`;$('#main').append(card);$('#image-ai-size').value=conf.size||'1024x1536';$('#image-ai-config').onsubmit=busy(async e=>{e.preventDefault();await api('/api/v1/settings/ai-images',{method:'PUT',body:{endpoint:$('#image-ai-url').value,model:$('#image-ai-model').value,size:$('#image-ai-size').value}});const key=$('#image-ai-key').value;$('#image-ai-key').value='';if(key)await api('/api/v1/settings/ai-images/key',{method:'PUT',body:{key}});toast(t('done'));});$('#image-ai-generate').onsubmit=busy(async e=>{e.preventDefault();const result=await api('/api/v1/ai/images',{method:'POST',body:{prompt:$('#image-ai-prompt').value},headers:{'Idempotency-Key':'ai-image-'+clientUUID()}});const op=await waitOperation(result.operation_id);$('#image-ai-preview').innerHTML='<img class="preview" id="image-ai-result" alt="Generated image">';await blobImage($('#image-ai-result'),op.result.url);toast(tr('已存入本地图库','Saved to local gallery'));});
|
||||||
}
|
}
|
||||||
async function mqttPanel(){
|
async function mqttPanel(){
|
||||||
const status=await api('/api/v1/integrations/mqtt');const c=status.config;const card=document.createElement('section');card.className='card';card.innerHTML=`<h3>MQTT · ${t(status.connected?'connected':'disconnected')}</h3><p class="hint">${tr('默认关闭。须配置环境 Secret FRAME_FLOW_MQTT_TOKEN(有 display:write 权限的客户端 Token),以及可选 FRAME_FLOW_MQTT_PASSWORD。消息必须携带 request_id;retained 消息被拒绝。结果发送到命令主题的 /result。','Disabled by default. Configure FRAME_FLOW_MQTT_TOKEN with display:write scope and optional FRAME_FLOW_MQTT_PASSWORD as environment secrets. Commands require request_id; retained commands are rejected. Results are published to the command topic plus /result.')}</p><form id="mqtt-config"><label class="check-row"><input id="mqtt-enabled" type="checkbox" ${c.enabled?'checked':''}>${t('enabled')}</label><div class="field"><label>Host</label><input id="mqtt-host" value="${esc(c.host)}"></div><div class="field"><label>Port</label><input id="mqtt-port" type="number" min="1" max="65535" value="${c.port}"></div><div class="field"><label>Topic</label><input id="mqtt-topic" value="${esc(c.topic)}"></div><div class="field"><label>${t('username')}</label><input id="mqtt-username" value="${esc(c.username)}"></div><label class="check-row"><input id="mqtt-tls" type="checkbox" ${c.tls?'checked':''}>TLS</label><label class="check-row"><input id="mqtt-lan" type="checkbox" ${c.allow_insecure_lan?'checked':''}>${tr('明确允许 LAN 明文连接','Explicitly allow plaintext LAN connection')}</label><button type="submit">${t('save')}</button></form>`;$('#main').append(card);$('#mqtt-config').onsubmit=busy(async e=>{e.preventDefault();await api('/api/v1/integrations/mqtt',{method:'PUT',body:{enabled:$('#mqtt-enabled').checked,host:$('#mqtt-host').value,port:Number($('#mqtt-port').value),topic:$('#mqtt-topic').value,username:$('#mqtt-username').value,tls:$('#mqtt-tls').checked,allow_insecure_lan:$('#mqtt-lan').checked}});toast(t('done'));});
|
const status=await api('/api/v1/integrations/mqtt');const c=status.config;const card=document.createElement('section');card.className='card';card.innerHTML=`<h3>MQTT · ${t(status.connected?'connected':'disconnected')}</h3><p class="hint">${tr('默认关闭。须配置环境 Secret FRAME_FLOW_MQTT_TOKEN(有 display:write 权限的客户端 Token),以及可选 FRAME_FLOW_MQTT_PASSWORD。消息必须携带 request_id;retained 消息被拒绝。结果发送到命令主题的 /result。','Disabled by default. Configure FRAME_FLOW_MQTT_TOKEN with display:write scope and optional FRAME_FLOW_MQTT_PASSWORD as environment secrets. Commands require request_id; retained commands are rejected. Results are published to the command topic plus /result.')}</p><form id="mqtt-config"><label class="check-row"><input id="mqtt-enabled" type="checkbox" ${c.enabled?'checked':''}>${t('enabled')}</label><div class="field"><label for="mqtt-host">Host</label><input id="mqtt-host" value="${esc(c.host)}"></div><div class="field"><label for="mqtt-port">Port</label><input id="mqtt-port" type="number" min="1" max="65535" value="${c.port}"></div><div class="field"><label for="mqtt-topic">Topic</label><input id="mqtt-topic" value="${esc(c.topic)}"></div><div class="field"><label for="mqtt-username">${t('username')}</label><input id="mqtt-username" value="${esc(c.username)}"></div><label class="check-row"><input id="mqtt-tls" type="checkbox" ${c.tls?'checked':''}>TLS</label><label class="check-row"><input id="mqtt-lan" type="checkbox" ${c.allow_insecure_lan?'checked':''}>${tr('明确允许 LAN 明文连接','Explicitly allow plaintext LAN connection')}</label><button type="submit">${t('save')}</button></form>`;$('#main').append(card);$('#mqtt-config').onsubmit=busy(async e=>{e.preventDefault();await api('/api/v1/integrations/mqtt',{method:'PUT',body:{enabled:$('#mqtt-enabled').checked,host:$('#mqtt-host').value,port:Number($('#mqtt-port').value),topic:$('#mqtt-topic').value,username:$('#mqtt-username').value,tls:$('#mqtt-tls').checked,allow_insecure_lan:$('#mqtt-lan').checked}});toast(t('done'));});
|
||||||
|
}
|
||||||
|
|
||||||
|
async function autoCollagePanel(){
|
||||||
|
const sources=await api('/api/v1/photo-sources');const card=document.createElement('section');card.className='card auto-collage';
|
||||||
|
card.innerHTML=`<h2>${tr('自动拼图','Automatic collage')}</h2><p class="hint">${tr('选择照片来源和数量,系统每次随机选取不同照片,并自动排版生成一张图片。无需手动拼接。预览不会上传或切换画框。','Choose a photo source and count. Each run randomly selects distinct photos and automatically creates one composition. Preview never uploads to or changes the frame.')}</p><form id="auto-collage-form"><div class="form-grid"><div class="field"><label for="collage-source">${tr('照片来源','Photo source')}</label><select id="collage-source"><option value="">${tr('本地手动上传照片','Locally uploaded photos')}</option>${sources.filter(x=>x.enabled).map(x=>`<option value="${esc(x.id)}">${esc(x.name)}</option>`).join('')}</select></div><div class="field"><label for="collage-count">${tr('拼图数量(1–12)','Photo count (1–12)')}</label><input id="collage-count" type="number" min="1" max="12" value="4" required></div></div><div class="field"><label for="collage-title">${tr('标题(可选)','Title (optional)')}</label><input id="collage-title" maxlength="100"></div><div class="field"><label for="collage-prompt">${tr('排版要求(可选)','Layout instructions (optional)')}</label><textarea id="collage-prompt" maxlength="1500"></textarea></div><label class="check-row"><input id="collage-ai" type="checkbox" checked>${tr('AI 自动排版','AI layout')}</label><p class="hint">${tr('AI 需先在连接中心配置,只接收尺寸与文字,不发送照片。未配置时可取消勾选,使用自动网格。','Configure AI in Connections first. Only dimensions and text are sent, never photos. Uncheck AI to use an automatic grid.')}</p><div class="actions"><button type="submit" class="primary">${tr('随机选图并生成预览','Pick photos and create preview')}</button><button id="collage-job" type="button">${tr('创建自动化任务','Create automation')}</button></div></form><div id="collage-preview"></div><div class="actions"><button id="collage-display" hidden>${t('display')}</button></div>`;
|
||||||
|
$('#main').prepend(card);if(sources.some(x=>x.enabled))$('#collage-source').value=sources.find(x=>x.enabled).id;let asset=null;
|
||||||
|
$('#auto-collage-form').oninput=()=>{asset=null;$('#collage-display').hidden=true;};
|
||||||
|
const content=()=>({type:'auto_collage',source_id:$('#collage-source').value||null,count:Number($('#collage-count').value),title:$('#collage-title').value,prompt:$('#collage-prompt').value,use_ai:$('#collage-ai').checked});
|
||||||
|
$('#auto-collage-form').onsubmit=busy(async e=>{e.preventDefault();asset=null;$('#collage-display').hidden=true;$('#collage-preview').textContent=t('previewLoading');try{const id=await accepted('/api/v1/render',content());const op=await waitOperation(id);asset=op.result;$('#collage-preview').innerHTML='<img class="preview" id="collage-image" alt="Collage">';await blobImage($('#collage-image'),asset.url);$('#collage-display').hidden=false;$('#collage-display').disabled=!liveWriteAllowed();}catch(error){$('#collage-preview').textContent=error.message;}});
|
||||||
|
bind('collage-display',()=>displayDialog({type:'image',asset_id:asset.asset_id}));
|
||||||
|
bind('collage-job',async()=>{if(!$('#auto-collage-form').reportValidity())return;await api('/api/v1/jobs',{method:'POST',body:{device_id:state.device,name:$('#collage-title').value||tr('自动随机拼图','Automatic random collage'),enabled:false,schedule:{type:'daily',time:'08:00'},source:content(),display_duration:0,restore_previous:false,priority:50}});await navigate('automation');toast(tr('任务已创建并暂停;编辑时间后启用。每次执行重新随机选图。','Created paused. Edit the schedule, then enable. Each run picks new photos.'));});
|
||||||
|
const manual=document.createElement('details');manual.className='card manual-collage';manual.innerHTML=`<summary>${tr('高级:手动选图与调整布局','Advanced: manual photos and layout')}</summary>`;const columns=$('#main>.columns');columns.before(manual);manual.append(columns);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,7 +1,9 @@
|
|||||||
'use strict';
|
'use strict';
|
||||||
// Page features share the same authenticated API and display operation pipeline.
|
// Page features share the same authenticated API and display operation pipeline.
|
||||||
async function currentPanel(container){
|
async function currentPanel(container){
|
||||||
|
const epoch=state.epoch;
|
||||||
const content=await api('/api/v1/devices/'+state.device+'/current-content');
|
const content=await api('/api/v1/devices/'+state.device+'/current-content');
|
||||||
|
if(epoch!==state.epoch||!container.isConnected)return content;
|
||||||
state.currentDisplay=content;
|
state.currentDisplay=content;
|
||||||
const known=content.source_known&&content.source?.type==='template';
|
const known=content.source_known&&content.source?.type==='template';
|
||||||
container.innerHTML=`<h3>${t('currentContent')}</h3><p>#${esc(content.image_id??'—')} · ${t(content.synced?'synced':'syncing')}</p><p>${known?`${t('currentTemplate')}: <strong>${esc(content.source.template)}</strong>`:content.source_known?t('sourceKnown'):t('sourceUnknown')}</p>${known?buttons('edit-current-template','editCurrent'):''}${content.overrides.length?`<div class="notice"><strong>${t('temporaryDisplay')}</strong>${content.overrides.map(x=>`<p>#${esc(x.image_id)} · ${t('priority')}: ${x.priority} · ${fmt(x.expires_at)}</p>`).join('')}</div>`:''}`;
|
container.innerHTML=`<h3>${t('currentContent')}</h3><p>#${esc(content.image_id??'—')} · ${t(content.synced?'synced':'syncing')}</p><p>${known?`${t('currentTemplate')}: <strong>${esc(content.source.template)}</strong>`:content.source_known?t('sourceKnown'):t('sourceUnknown')}</p>${known?buttons('edit-current-template','editCurrent'):''}${content.overrides.length?`<div class="notice"><strong>${t('temporaryDisplay')}</strong>${content.overrides.map(x=>`<p>#${esc(x.image_id)} · ${t('priority')}: ${x.priority} · ${fmt(x.expires_at)}</p>`).join('')}</div>`:''}`;
|
||||||
@@ -12,7 +14,7 @@ function editTemplateSource(source){state.selectedTemplate=source.template;state
|
|||||||
async function enhanceDashboard(){
|
async function enhanceDashboard(){
|
||||||
const epoch=state.epoch;const frame=$('.frame-demo');const panel=document.createElement('section');panel.className='card';$('#main').append(panel);
|
const epoch=state.epoch;const frame=$('.frame-demo');const panel=document.createElement('section');panel.className='card';$('#main').append(panel);
|
||||||
const current=await currentPanel(panel);if(epoch!==state.epoch)return;
|
const current=await currentPanel(panel);if(epoch!==state.epoch)return;
|
||||||
if(current.preview_url){frame.innerHTML=`<img id="current-frame-image" alt="${t('currentContent')}" style="width:100%;height:100%;object-fit:contain"><span class="frame-label">${t('currentContent')} #${current.image_id}</span>`;await blobImage($('#current-frame-image'),current.preview_url);}
|
if(current.preview_url){frame.innerHTML=`<button id="current-frame-preview" class="current-frame-preview" aria-label="${t('original')} · ${t('currentContent')} #${esc(current.image_id)}"><img id="current-frame-image" alt="${t('currentContent')}"></button><span class="frame-label">${t('currentContent')} #${esc(current.image_id)}</span>`;const original=new URL(current.preview_url,location.origin);original.searchParams.delete('thumbnail');bind('current-frame-preview',()=>openImageViewer(original.pathname+original.search,`${t('currentContent')} #${current.image_id}`));void blobImage($('#current-frame-image'),current.preview_url);}else{frame.innerHTML=`<div class="mini-art"><div class="sun"></div></div><span class="frame-label">${t('testLabel')}</span>`;}
|
||||||
const weather=await api('/api/v1/providers/weather');if(epoch!==state.epoch)return;const box=document.createElement('section');box.className='card';box.innerHTML=`<h3>${t('weather')}</h3><p>${esc(weather.current.location)} · ${esc(weather.current.temperature)} · ${esc(weather.current.summary)}</p><p class="hint">${weather.current.mock?t('weatherMock'):t('weatherAttribution')}${weather.current.stale?' · '+t('stale'):''}</p>`;$('#main').append(box);
|
const weather=await api('/api/v1/providers/weather');if(epoch!==state.epoch)return;const box=document.createElement('section');box.className='card';box.innerHTML=`<h3>${t('weather')}</h3><p>${esc(weather.current.location)} · ${esc(weather.current.temperature)} · ${esc(weather.current.summary)}</p><p class="hint">${weather.current.mock?t('weatherMock'):t('weatherAttribution')}${weather.current.stale?' · '+t('stale'):''}</p>`;$('#main').append(box);
|
||||||
}
|
}
|
||||||
async function enhanceTemplates(){
|
async function enhanceTemplates(){
|
||||||
@@ -26,34 +28,36 @@ async function enhanceTemplates(){
|
|||||||
async function downloadImage(path,name){const blob=await api(path,{binary:true});const url=URL.createObjectURL(blob);const link=document.createElement('a');link.href=url;link.download=name;document.body.append(link);link.click();link.remove();setTimeout(()=>URL.revokeObjectURL(url),10000);}
|
async function downloadImage(path,name){const blob=await api(path,{binary:true});const url=URL.createObjectURL(blob);const link=document.createElement('a');link.href=url;link.download=name;document.body.append(link);link.click();link.remove();setTimeout(()=>URL.revokeObjectURL(url),10000);}
|
||||||
function displayDialog(content){
|
function displayDialog(content){
|
||||||
if(!liveWriteAllowed()){toast(t('readOnlyWarning'));return;}
|
if(!liveWriteAllowed()){toast(t('readOnlyWarning'));return;}
|
||||||
showModal(`<h2>${t('displayOptions')}</h2><form id="display-options"><label class="check-row"><input id="override-restore" type="checkbox">${t('restoreAfter')}</label><div class="form-grid"><div class="field"><label for="override-duration">${t('duration')}</label><input id="override-duration" type="number" min="1" max="604800" value="1800"></div><div class="field"><label for="override-priority">${t('priority')}</label><input id="override-priority" type="number" min="0" max="100" value="50"></div></div><div class="modal-actions">${buttons('modal-cancel','cancel')}<button id="confirm-display" type="submit" class="primary">${t('display')}</button></div></form>`);
|
showModal(`<h2>${t('displayOptions')}</h2><form id="display-options"><p class="hint">${t('temporaryOptionsHint')}</p><label class="check-row"><input id="override-restore" type="checkbox">${t('restoreAfter')}</label><div class="form-grid"><div class="field"><label for="override-duration">${t('duration')}</label><input id="override-duration" type="number" min="1" max="604800" value="1800"></div><div class="field"><label for="override-priority">${t('priority')}</label><input id="override-priority" type="number" min="0" max="100" value="50"></div></div><div class="modal-actions">${buttons('modal-cancel','cancel')}<button id="confirm-display" type="submit" class="primary">${t('display')}</button></div></form>`);
|
||||||
$('#display-options').onsubmit=busy(async e=>{e.preventDefault();const restore=$('#override-restore').checked;const options={duration:restore?Number($('#override-duration').value):0,restore_previous:restore,priority:Number($('#override-priority').value)};await accepted('/api/v1/display',{device_id:state.device,content,options});$('#modal').close();await navigate('history');});
|
$('#display-options').onsubmit=busy(async e=>{e.preventDefault();const restore=$('#override-restore').checked;const options={duration:restore?Number($('#override-duration').value):0,restore_previous:restore,priority:Number($('#override-priority').value)};await accepted('/api/v1/display',{device_id:state.device,content,options});$('#modal').close();await navigate('history');});
|
||||||
}
|
}
|
||||||
async function enhanceGallery(){
|
function enhanceGallery(){
|
||||||
const grid=$('.gallery');if(!grid)return;
|
const grid=$('.gallery');if(!grid)return;
|
||||||
const controls=document.createElement('div');controls.className='form-grid';controls.innerHTML=`<div class="field"><label for="gallery-search">${t('searchImages')}</label><input id="gallery-search" type="search"></div><div class="field"><label for="gallery-sort">${t('mode')}</label><select id="gallery-sort"><option value="newest">${t('sortNewest')}</option><option value="oldest">${t('sortOldest')}</option><option value="name">${t('sortName')}</option></select></div>`;grid.before(controls);
|
const controls=document.createElement('div');controls.className='form-grid';controls.innerHTML=`<div class="field"><label for="gallery-search">${t('searchImages')}</label><input id="gallery-search" type="search"></div><div class="field"><label for="gallery-sort">${t('sortOrder')}</label><select id="gallery-sort"><option value="newest">${t('sortNewest')}</option><option value="oldest">${t('sortOldest')}</option><option value="name">${t('sortName')}</option></select></div>`;grid.before(controls);
|
||||||
if(state.tab==='local'){const bar=document.createElement('div');bar.className='actions';bar.innerHTML=`<select id="asset-origin" aria-label="${t('originFilter')}">${['all','manual','task','external','template','unknown'].map(x=>`<option value="${x}">${t('origin_'+x)}</option>`).join('')}</select><select id="asset-job" aria-label="${t('taskOrigin')}"><option value="">${t('allTasks')}</option></select><button id="asset-prev">${t('previousPage')}</button><button id="asset-next">${t('nextPage')}</button><button id="asset-all">${t('selectAll')}</button><button id="asset-batch-star">${t('star')}</button><button id="asset-batch-unstar">${t('unstar')}</button><button id="asset-batch-delete" class="danger">${t('deleteSelected')}</button>`;grid.before(bar);$('#asset-origin').value=state.assetOrigin||'all';const jobs=await api('/api/v1/jobs');for(const job of jobs){const option=document.createElement('option');option.value=job.id;option.textContent=job.name;$('#asset-job').append(option);}$('#asset-job').value=state.assetJob||'';$('#asset-origin').onchange=()=>{state.assetOffset=0;state.assetOrigin=$('#asset-origin').value;return navigate();};$('#asset-job').onchange=()=>{state.assetOffset=0;state.assetJob=$('#asset-job').value;state.assetOrigin=state.assetJob?'task':state.assetOrigin;return navigate();};$('#asset-prev').disabled=!(state.assetOffset||0);$('#asset-next').disabled=state.gallery.length<200;bind('asset-prev',()=>{state.assetOffset=Math.max(0,(state.assetOffset||0)-200);return navigate();});bind('asset-next',()=>{state.assetOffset=(state.assetOffset||0)+200;return navigate();});$('#asset-all').onclick=()=>{const boxes=[...document.querySelectorAll('.asset-select')].filter(x=>!x.closest('.image-card').hidden);const checked=boxes.some(x=>!x.checked);boxes.forEach(x=>x.checked=checked);};for(const action of ['star','unstar','delete']){bind('asset-batch-'+action,async()=>{const ids=[...document.querySelectorAll('.asset-select:checked')].map(x=>x.dataset.asset);if(!ids.length){toast(t('selectImagesFirst'));return;}if(action==='delete'&&!confirm(t('deleteSelectedConfirm')))return;const results=[];for(let i=0;i<ids.length;i+=100){const r=await api('/api/v1/assets/batch',{method:'POST',body:{asset_ids:ids.slice(i,i+100),action}});results.push(...r.results);}const failed=results.filter(x=>x.status==='failed');if(failed.length)toast(t('batchFailed')+' '+failed.length);await navigate();});}}
|
if(state.tab==='local'){const bar=document.createElement('div');bar.className='actions';bar.innerHTML=`<select id="asset-origin" aria-label="${t('originFilter')}">${['all','manual','task','external','template','unknown'].map(x=>`<option value="${x}">${t('origin_'+x)}</option>`).join('')}</select><select id="asset-job" aria-label="${t('taskOrigin')}"><option value="">${t('allTasks')}</option></select><button id="asset-prev">${t('previousPage')}</button><button id="asset-next">${t('nextPage')}</button><button id="asset-all">${t('selectAll')}</button><button id="asset-invert">${t('invertSelection')}</button><button id="asset-batch-star">${t('star')}</button><button id="asset-batch-unstar">${t('unstar')}</button><button id="asset-batch-delete" class="danger">${t('deleteSelected')}</button>`;grid.before(bar);const help=document.createElement('p');help.className='hint';help.id='gallery-selection-help';help.textContent=t('gallerySelectionHelp')+' '+t('starHelp');grid.before(help);bar.setAttribute('aria-describedby',help.id);$('#asset-origin').value=state.assetOrigin||'all';if(state.galleryJobsEpoch!==state.epoch){state.galleryJobsEpoch=state.epoch;state.galleryJobsRequest=api('/api/v1/jobs');}void state.galleryJobsRequest.then(jobs=>{if(!bar.isConnected)return;const picker=bar.querySelector('#asset-job');for(const job of jobs){const option=document.createElement('option');option.value=job.id;option.textContent=job.name;picker.append(option);}picker.value=state.assetJob||'';}).catch(error=>{if(bar.isConnected)toast(error.message);});$('#asset-origin').onchange=()=>{state.assetOffset=0;state.assetOrigin=$('#asset-origin').value;return navigate();};$('#asset-job').onchange=()=>{state.assetOffset=0;state.assetJob=$('#asset-job').value;state.assetOrigin=state.assetJob?'task':state.assetOrigin;return navigate();};$('#asset-prev').disabled=!(state.assetOffset||0);$('#asset-next').disabled=state.gallery.length<200;bind('asset-prev',()=>{state.assetOffset=Math.max(0,(state.assetOffset||0)-200);return navigate();});bind('asset-next',()=>{state.assetOffset=(state.assetOffset||0)+200;return navigate();});const visibleSelection=()=>[...grid.querySelectorAll('.asset-select')].filter(x=>!x.closest('.image-card').hidden);$('#asset-all').onclick=()=>{const boxes=visibleSelection();const checked=boxes.some(x=>!x.checked);boxes.forEach(x=>x.checked=checked);};$('#asset-invert').onclick=()=>visibleSelection().forEach(x=>x.checked=!x.checked);for(const action of ['star','unstar','delete']){bind('asset-batch-'+action,async()=>{const ids=[...document.querySelectorAll('.asset-select:checked')].map(x=>x.dataset.asset);if(!ids.length){toast(t('selectImagesFirst'));return;}if(action==='delete'&&!confirm(t('deleteSelectedConfirm')))return;const results=[];for(let i=0;i<ids.length;i+=100){const r=await api('/api/v1/assets/batch',{method:'POST',body:{asset_ids:ids.slice(i,i+100),action}});results.push(...r.results);}const failed=results.filter(x=>x.status==='failed');if(failed.length)toast(t('batchFailed')+' '+failed.length);await navigate();});}}
|
||||||
const cards=[...grid.querySelectorAll('.image-card')];$('#gallery-search').oninput=()=>{const query=$('#gallery-search').value.toLowerCase();cards.forEach(card=>card.hidden=!card.textContent.toLowerCase().includes(query));};$('#gallery-sort').onchange=()=>{const order=$('#gallery-sort').value;const indexes=cards.map((card,index)=>({card,item:state.gallery[index]}));indexes.sort((a,b)=>order==='name'?a.item.name.localeCompare(b.item.name):order==='oldest'?String(a.item.created_at).localeCompare(String(b.item.created_at)):String(b.item.created_at).localeCompare(String(a.item.created_at)));indexes.forEach(x=>grid.append(x.card));};
|
const cards=[...grid.querySelectorAll('.image-card')];$('#gallery-search').oninput=()=>{state.galleryQuery=$('#gallery-search').value;const query=state.galleryQuery.toLowerCase();cards.forEach(card=>card.hidden=!card.textContent.toLowerCase().includes(query));};$('#gallery-sort').onchange=()=>{const order=$('#gallery-sort').value;state.galleryOrder=order;const indexes=cards.map((card,index)=>({card,item:state.gallery[index]}));indexes.sort((a,b)=>order==='name'?a.item.name.localeCompare(b.item.name):order==='oldest'?String(a.item.created_at).localeCompare(String(b.item.created_at)):String(b.item.created_at).localeCompare(String(a.item.created_at)));indexes.forEach(x=>grid.append(x.card));};
|
||||||
cards.forEach((card,i)=>{const item=state.gallery[i];if(state.tab==='local'){const star=document.createElement('button');star.textContent=t(item.starred?'unstar':'star');star.setAttribute('aria-pressed',String(item.starred));card.querySelector('.actions').append(star);star.onclick=busy(async()=>{await api('/api/v1/assets/'+item.asset_id+'/star',{method:'PUT',body:{starred:!item.starred}});await navigate();});const label=document.createElement('small');label.textContent=item.origin==='task'?t('taskOrigin')+' · '+(item.job_name||item.job_id):t('origin_'+item.origin);card.querySelector('h3').after(label);const select=document.createElement('input');select.type='checkbox';select.className='asset-select';select.dataset.asset=item.asset_id;select.setAttribute('aria-label',t('selectImage'));card.prepend(select);}if(item.width&&item.height){const dimensions=document.createElement('small');dimensions.textContent=item.width+' × '+item.height;card.querySelector('h3').after(dimensions);}const download=document.createElement('button');download.textContent=t('download');card.querySelector('.actions').append(download);download.onclick=busy(()=>downloadImage(item.url,item.name));if(state.tab==='local'){const edit=document.createElement('button');edit.textContent=t('continueEdit');card.querySelector('.actions').append(edit);edit.onclick=busy(async()=>{const meta=await api('/api/v1/assets/'+item.asset_id+'/source');if(meta.source?.type==='template')await editTemplateSource(meta.source);else toast(t('sourceUnknown'));});}});
|
cards.forEach((card,i)=>{const item=state.gallery[i];if(state.tab==='local'){const star=document.createElement('button');star.textContent=t(item.starred?'unstar':'star');star.setAttribute('aria-pressed',String(item.starred));card.querySelector('.actions').append(star);star.onclick=busy(async()=>{await api('/api/v1/assets/'+item.asset_id+'/star',{method:'PUT',body:{starred:!item.starred}});await navigate();});const label=document.createElement('small');label.textContent=item.origin==='task'?t('taskOrigin')+' · '+(item.job_name||item.job_id):t('origin_'+item.origin);card.querySelector('h3').after(label);const select=document.createElement('input');select.type='checkbox';select.className='asset-select';select.dataset.asset=item.asset_id;select.setAttribute('aria-label',t('selectImage'));card.prepend(select);}if(item.width&&item.height){const dimensions=document.createElement('small');dimensions.textContent=item.width+' × '+item.height;card.querySelector('h3').after(dimensions);}const download=document.createElement('button');download.textContent=t('download');card.querySelector('.actions').append(download);download.onclick=busy(()=>downloadImage(item.url,item.name));if(state.tab==='local'){const edit=document.createElement('button');edit.textContent=t('continueEdit');card.querySelector('.actions').append(edit);edit.onclick=busy(async()=>{const meta=await api('/api/v1/assets/'+item.asset_id+'/source');if(meta.source?.type==='template')await editTemplateSource(meta.source);else toast(t('templateSourceUnavailable'));});}});
|
||||||
|
$('#gallery-search').value=state.galleryQuery||'';$('#gallery-sort').value=state.galleryOrder||'newest';$('#gallery-search').oninput();$('#gallery-sort').onchange();
|
||||||
}
|
}
|
||||||
async function weatherSettings(){
|
async function weatherSettings(){
|
||||||
const weather=await api('/api/v1/providers/weather');const box=document.createElement('section');box.className='card';box.innerHTML=`<h3>${t('weatherSettings')}</h3><form id="weather-form"><div class="field"><label for="weather-provider">Provider</label><select id="weather-provider"><option value="mock">${t('weatherMock')}</option><option value="open-meteo">Open-Meteo</option></select></div><div class="field"><label for="weather-location">${t('location')}</label><input id="weather-location" required maxlength="120" value="${esc(weather.config.location)}"></div><div class="form-grid">${['latitude','longitude'].map(k=>`<div class="field"><label for="weather-${k}">${t(k)}</label><input id="weather-${k}" required type="number" step="any" min="${k==='latitude'?-90:-180}" max="${k==='latitude'?90:180}" value="${weather.config[k]}"></div>`).join('')}</div><button type="submit" class="primary">${t('save')}</button></form><div id="weather-result"></div>`;$('#main').append(box);$('#weather-provider').value=weather.config.provider;
|
const weather=await api('/api/v1/providers/weather');const box=document.createElement('section');box.className='card';box.innerHTML=`<h3>${t('weatherSettings')}</h3><form id="weather-form"><div class="field"><label for="weather-provider">${t('weatherSettings')}</label><select id="weather-provider"><option value="mock">${t('weatherMock')}</option><option value="open-meteo">Open-Meteo</option></select></div><div class="field"><label for="weather-location">${t('location')}</label><input id="weather-location" required maxlength="120" value="${esc(weather.config.location)}"></div><div class="form-grid">${['latitude','longitude'].map(k=>`<div class="field"><label for="weather-${k}">${t(k)}</label><input id="weather-${k}" required type="number" step="any" min="${k==='latitude'?-90:-180}" max="${k==='latitude'?90:180}" value="${weather.config[k]}"></div>`).join('')}</div><button type="submit" class="primary">${t('save')}</button></form><div id="weather-result"></div>`;$('#main').append(box);$('#weather-provider').value=weather.config.provider;
|
||||||
function result(w){$('#weather-result').innerHTML=`<p>${esc(w.current.temperature)} · ${esc(w.current.summary)}</p><p class="hint">${w.current.mock?t('weatherMock'):t('weatherAttribution')}${w.current.stale?' · '+t('stale'):''}</p><h4>${t('forecast')}</h4>${w.forecast.map(x=>`<p>${esc(x.date)} · ${esc(x.summary)} · ${x.minimum_c}–${x.maximum_c}°C · ${x.rain_probability}%</p>`).join('')}`;}
|
function result(w){$('#weather-result').innerHTML=`<p>${esc(w.current.temperature)} · ${esc(w.current.summary)}</p><p class="hint">${w.current.mock?t('weatherMock'):t('weatherAttribution')}${w.current.stale?' · '+t('stale'):''}</p><h4>${t('forecast')}</h4>${w.forecast.map(x=>`<p>${esc(x.date)} · ${esc(x.summary)} · ${x.minimum_c}–${x.maximum_c}°C · ${x.rain_probability}%</p>`).join('')}`;}
|
||||||
result(weather);$('#weather-form').onsubmit=busy(async e=>{e.preventDefault();await api('/api/v1/settings/weather',{method:'PUT',body:{provider:$('#weather-provider').value,location:$('#weather-location').value,latitude:Number($('#weather-latitude').value),longitude:Number($('#weather-longitude').value)}});result(await api('/api/v1/providers/weather'));toast(t('done'));});
|
result(weather);$('#weather-form').onsubmit=busy(async e=>{e.preventDefault();await api('/api/v1/settings/weather',{method:'PUT',body:{provider:$('#weather-provider').value,location:$('#weather-location').value,latitude:Number($('#weather-latitude').value),longitude:Number($('#weather-longitude').value)}});result(await api('/api/v1/providers/weather'));toast(t('done'));});
|
||||||
}
|
}
|
||||||
async function enhanceHistory(){
|
async function enhanceHistory(){
|
||||||
const table=document.querySelector('#main table');if(!table)return;table.classList.add('history-table');const heading=document.createElement('th');heading.textContent=t('operation');table.querySelector('thead tr').append(heading);const rows=[...table.querySelectorAll('tbody tr')];const ops=await api('/api/v1/operations');rows.forEach((row,i)=>{const op=ops[i];if(!op)return;const button=document.createElement('button');button.textContent=t('details');const actions=document.createElement('td');actions.className='history-actions';actions.append(button);row.append(actions);button.onclick=busy(async()=>{const current=await api('/api/v1/operations/'+op.operation_id);showModal(`<h2>${t('details')}</h2><p>${t(current.status)} · ${esc(current.action)}</p><p>${esc(current.error?.message||'')}</p><pre style="white-space:pre-wrap;overflow-wrap:anywhere">${esc(JSON.stringify({operation_id:current.operation_id,request_id:current.request_id,created_at:current.created_at,updated_at:current.updated_at,result:current.result},null,2))}</pre>${current.result?.url?'<img id="operation-preview" class="preview" alt="Preview">':''}<div class="modal-actions">${buttons('modal-cancel','cancel')}</div>`);if(current.result?.url)await blobImage($('#operation-preview'),current.result.url);});});}
|
const table=document.querySelector('#main table');if(!table)return;table.classList.add('history-table');const heading=document.createElement('th');heading.textContent=t('operation');table.querySelector('thead tr').append(heading);const rows=[...table.querySelectorAll('tbody tr')];const ops=await api('/api/v1/operations');rows.forEach((row,i)=>{const op=ops[i];if(!op)return;const button=document.createElement('button');button.textContent=t('details');const actions=document.createElement('td');actions.className='history-actions';actions.append(button);row.append(actions);button.onclick=busy(async()=>{const current=await api('/api/v1/operations/'+op.operation_id);showModal(`<h2>${t('details')}</h2><p>${t(current.status)} · ${esc(operationActionLabel(current.action))}</p><p>${esc(operationErrorLabel(current.error)||current.error?.message||'')}</p><pre style="white-space:pre-wrap;overflow-wrap:anywhere">${esc(JSON.stringify({action:current.action,device_id:current.device_id,error_code:current.error?.code,operation_id:current.operation_id,request_id:current.request_id,created_at:current.created_at,updated_at:current.updated_at,result:current.result},null,2))}</pre>${current.result?.url?'<img id="operation-preview" class="preview" alt="Preview">':''}<div class="modal-actions">${buttons('modal-cancel','cancel')}</div>`);if(current.result?.url)await blobImage($('#operation-preview'),current.result.url);});});}
|
||||||
async function enhanceAutomation(){
|
async function enhanceAutomation(){
|
||||||
const jobs=await api('/api/v1/jobs');const rows=[...document.querySelectorAll('tbody tr')];rows.forEach((row,i)=>{const job=jobs[i];if(!job)return;const actions=row.querySelector('.row-actions');const run=document.createElement('button');run.textContent=t('runNow');run.disabled=!liveWriteAllowed();run.title=run.disabled?t('readOnlyWarning'):'';actions.append(run);run.onclick=()=>confirmDialog(t('runConfirm'),async()=>{await accepted('/api/v1/jobs/'+job.id+'/run',{});await navigate('history');});if(job.source.type==='template'){const preview=document.createElement('button');preview.textContent=t('jobPreview');actions.append(preview);preview.onclick=busy(async()=>{const id=await accepted('/api/v1/jobs/'+job.id+'/preview',{});const op=await waitOperation(id);showModal(`<h2>${t('jobPreview')}</h2><img id="job-preview-image" class="preview" alt="Preview"><div class="modal-actions">${buttons('modal-cancel','cancel')}</div>`);await blobImage($('#job-preview-image'),op.result.url);});}});
|
const jobs=await api('/api/v1/jobs');const rows=[...document.querySelectorAll('tbody tr')];rows.forEach((row,i)=>{const job=jobs[i];if(!job)return;const actions=row.querySelector('.row-actions');const run=document.createElement('button');run.textContent=t('runNow');run.disabled=!liveWriteAllowed();run.title=run.disabled?t('readOnlyWarning'):'';actions.append(run);run.onclick=()=>confirmDialog(t('runConfirm'),async()=>{await accepted('/api/v1/jobs/'+job.id+'/run',{});await navigate('history');});if(['template','auto_collage'].includes(job.source.type)){const preview=document.createElement('button');preview.textContent=t('jobPreview');actions.append(preview);preview.onclick=busy(async()=>{const id=await accepted('/api/v1/jobs/'+job.id+'/preview',{});const op=await waitOperation(id);showModal(`<h2>${t('jobPreview')}</h2><img id="job-preview-image" class="preview" alt="Preview"><div class="modal-actions">${buttons('modal-cancel','cancel')}</div>`);await blobImage($('#job-preview-image'),op.result.url);});}});
|
||||||
}
|
}
|
||||||
async function jobSourceEditor(job){
|
async function jobSourceEditor(job){
|
||||||
const raw=$('#job-source');const advanced=document.createElement('details');advanced.innerHTML=`<summary>${t('advanced')}</summary>`;raw.parentElement.before(advanced);advanced.append(raw.parentElement);
|
const raw=$('#job-source');const advanced=document.createElement('details');advanced.innerHTML=`<summary>${t('advanced')}</summary>`;raw.parentElement.before(advanced);advanced.append(raw.parentElement);
|
||||||
const box=document.createElement('div');advanced.before(box);let source=structuredClone(job.source);let images=[],assets=[],photoSources=[];try{[images,assets,photoSources]=await Promise.all([api('/api/v1/devices/'+state.device+'/images'),api('/api/v1/assets'),api('/api/v1/photo-sources')]);}catch(e){toast(e.message);}if(!raw.isConnected)return;
|
const box=document.createElement('div');advanced.before(box);let source=structuredClone(job.source);let images=[],assets=[],photoSources=[];try{[images,assets,photoSources]=await Promise.all([api('/api/v1/devices/'+state.device+'/images'),api('/api/v1/assets'),api('/api/v1/photo-sources')]);}catch(e){toast(e.message);}if(!raw.isConnected)return;
|
||||||
box.innerHTML=`<div class="field"><label for="job-content-type">${t('sourceType')}</label><select id="job-content-type">${['template','image','image_url','photo_source','restore'].map(k=>`<option value="${k}">${k==='template'?t('template'):k==='image'?t('imageChoice'):k==='restore'?t('restoreSource'):k==='photo_source'?t('photoSources'):t('imageURL')}</option>`).join('')}</select></div><div id="job-content-fields"></div>`;
|
box.innerHTML=`<div class="field"><label for="job-content-type">${t('sourceType')}</label><select id="job-content-type">${['template','image','image_url','photo_source','auto_collage','restore'].map(k=>`<option value="${k}">${k==='auto_collage'?(state.lang==='zh'?'自动随机拼图':'Automatic collage'):k==='template'?t('template'):k==='image'?t('imageChoice'):k==='restore'?t('restoreSource'):k==='photo_source'?t('photoSources'):t('imageURL')}</option>`).join('')}</select></div><div id="job-content-fields"></div>`;
|
||||||
$('#job-content-type').value=source.type;const old=$('#job-template')?.parentElement;if(old)old.remove();
|
$('#job-content-type').value=source.type;const old=$('#job-template')?.parentElement;if(old)old.remove();
|
||||||
function update(){raw.value=JSON.stringify(source,null,2);}
|
function update(){raw.value=JSON.stringify(source,null,2);}
|
||||||
function fields(){const type=$('#job-content-type').value;const panel=$('#job-content-fields');if(type==='restore'){source={type};panel.innerHTML='';$('#job-restore').checked=false;$('#job-duration').value=0;update();return;}
|
function fields(){const type=$('#job-content-type').value;const panel=$('#job-content-fields');if(type==='restore'){source={type};panel.innerHTML='';$('#job-restore').checked=false;$('#job-duration').value=0;update();return;}
|
||||||
if(type==='template'){const selected=state.templates.find(tpl=>tpl.id===source.template)||state.templates[0];source={type,template:selected.id,data:source.type==='template'?source.data||{}:{},profile:source.profile||'color'};panel.innerHTML=`<div class="field"><label for="job-template">${t('template')}</label><select id="job-template">${state.templates.map(x=>`<option value="${x.id}" ${selected.id===x.id?'selected':''}>${esc(x.name)}</option>`).join('')}</select></div><div class="field"><label for="job-source-profile">${t('profile')}</label><select id="job-source-profile"><option value="color">${t('color')}</option><option value="grayscale">${t('grayscale')}</option></select></div><div id="job-data-fields"></div>`;$('#job-source-profile').value=source.profile;$('#job-source-profile').onchange=()=>{source.profile=$('#job-source-profile').value;update();};const defaults={...selected.defaults,...source.data};const keys=[...new Set([...Object.keys(defaults).filter(k=>typeof defaults[k]!=='object'||Array.isArray(defaults[k])),...(['calendar','daily-dashboard'].includes(selected.id)?['events']:[])])];$('#job-data-fields').innerHTML=keys.map(k=>`<div class="field"><label for="job-field-${k}">${esc({title:state.lang==='zh'?'标题':'Title',message:state.lang==='zh'?'正文':'Message',quote:state.lang==='zh'?'一句话':'Quote',author:state.lang==='zh'?'作者':'Author',events:t('eventsHelp')}[k]||k)}</label><textarea id="job-field-${k}" data-job-field="${k}" rows="2">${esc(Array.isArray(defaults[k])?defaults[k].map(x=>typeof x==='object'?x.title:x).join('\n'):defaults[k]||'')}</textarea></div>`).join('');$('#job-template').onchange=()=>{source={type:'template',template:$('#job-template').value,data:{}};fields();};panel.querySelectorAll('[data-job-field]').forEach(el=>el.oninput=()=>{source.data[el.dataset.jobField]=el.dataset.jobField==='events'?el.value.split('\n').filter(x=>x.trim()):el.value;update();});update();}
|
if(type==='template'){const selected=state.templates.find(tpl=>tpl.id===source.template)||state.templates[0];source={type,template:selected.id,data:source.type==='template'?source.data||{}:{},profile:source.profile||'color'};panel.innerHTML=`<div class="field"><label for="job-template">${t('template')}</label><select id="job-template">${state.templates.map(x=>`<option value="${x.id}" ${selected.id===x.id?'selected':''}>${esc(x.name)}</option>`).join('')}</select></div><div class="field"><label for="job-source-profile">${t('profile')}</label><select id="job-source-profile"><option value="color">${t('color')}</option><option value="grayscale">${t('grayscale')}</option></select></div><div id="job-data-fields"></div>`;$('#job-source-profile').value=source.profile;$('#job-source-profile').onchange=()=>{source.profile=$('#job-source-profile').value;update();};const defaults={...selected.defaults,...source.data};const keys=[...new Set([...Object.keys(defaults).filter(k=>typeof defaults[k]!=='object'||Array.isArray(defaults[k])),...(['calendar','daily-dashboard'].includes(selected.id)?['events']:[])])];$('#job-data-fields').innerHTML=keys.map(k=>`<div class="field"><label for="job-field-${k}">${esc({title:state.lang==='zh'?'标题':'Title',message:state.lang==='zh'?'正文':'Message',quote:state.lang==='zh'?'一句话':'Quote',author:state.lang==='zh'?'作者':'Author',events:t('eventsHelp')}[k]||k)}</label><textarea id="job-field-${k}" data-job-field="${k}" rows="2">${esc(Array.isArray(defaults[k])?defaults[k].map(x=>typeof x==='object'?x.title:x).join('\n'):defaults[k]||'')}</textarea></div>`).join('');$('#job-template').onchange=()=>{source={type:'template',template:$('#job-template').value,data:{}};fields();};panel.querySelectorAll('[data-job-field]').forEach(el=>el.oninput=()=>{source.data[el.dataset.jobField]=el.dataset.jobField==='events'?el.value.split('\n').filter(x=>x.trim()):el.value;update();});update();}
|
||||||
|
else if(type==='auto_collage'){source={count:4,use_ai:true,...source,type};panel.innerHTML=`<div class="field"><label for="job-collage-source">${t('photoSources')}</label><select id="job-collage-source"><option value="">${state.lang==='zh'?'本地手动上传照片':'Locally uploaded photos'}</option>${photoSources.filter(x=>x.enabled).map(x=>`<option value="${esc(x.id)}">${esc(x.name)}</option>`).join('')}</select></div><div class="field"><label for="job-collage-count">${state.lang==='zh'?'拼图数量(1–12)':'Photo count (1–12)'}</label><input id="job-collage-count" type="number" min="1" max="12" required value="${source.count}"></div><div class="field"><label for="job-collage-title">${state.lang==='zh'?'标题':'Title'}</label><input id="job-collage-title" maxlength="100" value="${esc(source.title||'')}"></div><div class="field"><label for="job-collage-prompt">${state.lang==='zh'?'排版要求':'Layout instructions'}</label><textarea id="job-collage-prompt" maxlength="1500">${esc(source.prompt||'')}</textarea></div><label class="check-row"><input id="job-collage-ai" type="checkbox" ${source.use_ai?'checked':''}>${state.lang==='zh'?'AI 自动排版(需先配置连接中心)':'AI layout (configure Connections first)'}</label><p class="hint">${state.lang==='zh'?'每次执行重新随机选图;取消 AI 使用自动网格。':'Each run picks new photos; uncheck AI for an automatic grid.'}</p>`;$('#job-collage-source').value=source.source_id||'';for(const id of ['source','count','title','prompt','ai'])$('#job-collage-'+id).oninput=()=>{source={...source,source_id:$('#job-collage-source').value||null,count:Number($('#job-collage-count').value),title:$('#job-collage-title').value,prompt:$('#job-collage-prompt').value,use_ai:$('#job-collage-ai').checked};update();};update();}
|
||||||
else if(type==='image'){const selected=source.image_id?'cloud:'+source.image_id:source.asset_id?'local:'+source.asset_id:'';panel.innerHTML=`<div class="field"><label for="job-image">${t('imageChoice')}</label><select id="job-image" required><option value="">—</option>${images.map(i=>`<option value="cloud:${i.image_id}">${esc(i.name)} · #${i.image_id}</option>`).join('')}${assets.map(a=>`<option value="local:${a.asset_id}">${esc(a.name)} · LOCAL</option>`).join('')}</select></div>`;$('#job-image').value=selected;$('#job-image').onchange=()=>{const [kind,id]=$('#job-image').value.split(':');source=kind==='cloud'?{type:'image',image_id:Number(id)}:{type:'image',asset_id:id};update();};}
|
else if(type==='image'){const selected=source.image_id?'cloud:'+source.image_id:source.asset_id?'local:'+source.asset_id:'';panel.innerHTML=`<div class="field"><label for="job-image">${t('imageChoice')}</label><select id="job-image" required><option value="">—</option>${images.map(i=>`<option value="cloud:${i.image_id}">${esc(i.name)} · #${i.image_id}</option>`).join('')}${assets.map(a=>`<option value="local:${a.asset_id}">${esc(a.name)} · LOCAL</option>`).join('')}</select></div>`;$('#job-image').value=selected;$('#job-image').onchange=()=>{const [kind,id]=$('#job-image').value.split(':');source=kind==='cloud'?{type:'image',image_id:Number(id)}:{type:'image',asset_id:id};update();};}
|
||||||
else if(type==='photo_source'){panel.innerHTML=`<div class="field"><label for="job-photo-source">${t('photoSources')}</label><select id="job-photo-source" required><option value="">—</option>${photoSources.map(x=>`<option value="${esc(x.id)}">${esc(x.name)}</option>`).join('')}</select><p class="hint">${t('sourceJobHint')}</p></div>`;$('#job-photo-source').value=source.source_id||'';$('#job-photo-source').onchange=()=>{source={type:'photo_source',source_id:$('#job-photo-source').value,fit:'contain',profile:'color'};update();};}
|
else if(type==='photo_source'){panel.innerHTML=`<div class="field"><label for="job-photo-source">${t('photoSources')}</label><select id="job-photo-source" required><option value="">—</option>${photoSources.map(x=>`<option value="${esc(x.id)}">${esc(x.name)}</option>`).join('')}</select><p class="hint">${t('sourceJobHint')}</p></div>`;$('#job-photo-source').value=source.source_id||'';$('#job-photo-source').onchange=()=>{source={type:'photo_source',source_id:$('#job-photo-source').value,fit:'contain',profile:'color'};update();};}
|
||||||
else{panel.innerHTML=`<div class="field"><label for="job-url">${t('imageURL')}</label><input id="job-url" type="url" placeholder="https://…" value="${esc(source.type==='image_url'?source.url:'')}" required></div>`;$('#job-url').oninput=()=>{source={type:'image_url',url:$('#job-url').value};update();};}}
|
else{panel.innerHTML=`<div class="field"><label for="job-url">${t('imageURL')}</label><input id="job-url" type="url" placeholder="https://…" value="${esc(source.type==='image_url'?source.url:'')}" required></div>`;$('#job-url').oninput=()=>{source={type:'image_url',url:$('#job-url').value};update();};}}
|
||||||
@@ -110,19 +114,34 @@ async function photosPeoplePicker(selected){
|
|||||||
const status=await api(path);
|
const status=await api(path);
|
||||||
if(!status.configured){target.innerHTML=`<p class="hint">${t('photosConfigure')}</p>`;return;}
|
if(!status.configured){target.innerHTML=`<p class="hint">${t('photosConfigure')}</p>`;return;}
|
||||||
if(!status.connected){
|
if(!status.connected){
|
||||||
target.innerHTML=`<div class="field"><label for="photos-username">${t('username')}</label><input id="photos-username" autocomplete="username"></div><div class="field"><label for="photos-password">${t('password')}</label><input id="photos-password" type="password" autocomplete="current-password"></div><p class="hint">${t('photosSessionHint')}</p><button type="button" id="photos-connect">${t('photosConnect')}</button>`;
|
target.innerHTML=`<div class="field"><label for="photos-username">${t('nasUsername')}</label><input id="photos-username" autocomplete="username"></div><div class="field"><label for="photos-password">${t('nasPassword')}</label><input id="photos-password" type="password" autocomplete="current-password"></div><p class="hint">${t('photosSessionHint')}</p><button type="button" id="photos-connect">${t('photosConnect')}</button>`;
|
||||||
$('#photos-connect').onclick=busy(async()=>{const password=$('#photos-password').value;$('#photos-password').value='';await api(path,{method:'POST',body:{username:$('#photos-username').value,password}});await photosPeoplePicker(selected);});return;
|
$('#photos-connect').onclick=busy(async()=>{const password=$('#photos-password').value;$('#photos-password').value='';await api(path,{method:'POST',body:{username:$('#photos-username').value,password}});await photosPeoplePicker(selected);});return;
|
||||||
}
|
}
|
||||||
const people=await api(path+'/people?space='+encodeURIComponent($('#source-people-space')?.value||'shared'));
|
const people=await api(path+'/people?space='+encodeURIComponent($('#source-people-space')?.value||'shared'));
|
||||||
target.innerHTML=`<div class="field"><label for="people-search">${t('peopleSearch')}</label><input id="people-search" type="search"></div><label class="check-row"><input id="people-unnamed" type="checkbox">${t('peopleUnnamed')}</label><div id="people-list" style="max-height:260px;overflow:auto"></div><p id="people-selected" class="hint"></p><button type="button" id="photos-disconnect">${t('photosDisconnect')}</button>`;
|
target.innerHTML=`<div class="field"><label for="people-search">${t('peopleSearch')}</label><input id="people-search" type="search"></div><label class="check-row"><input id="people-unnamed" type="checkbox">${t('peopleUnnamed')}</label><div id="people-list" style="max-height:260px;overflow:auto"></div><p id="people-selected" class="hint"></p>`;
|
||||||
const render=()=>{const query=$('#people-search').value.toLowerCase();const rows=people.filter(p=>(p.named||selected.has(p.id)||$('#people-unnamed').checked)&&(p.name.toLowerCase().includes(query)||String(p.id).includes(query)));$('#people-list').innerHTML=rows.map(p=>`<label class="check-row"><input type="checkbox" data-person="${p.id}" ${selected.has(p.id)?'checked':''}>${esc(p.name)} · ${p.count}</label>`).join('');$('#people-selected').textContent=t('peopleSelected')+selected.size;$('#people-list').querySelectorAll('[data-person]').forEach(box=>box.onchange=()=>{const id=Number(box.dataset.person);box.checked?selected.add(id):selected.delete(id);$('#people-selected').textContent=t('peopleSelected')+selected.size;});};
|
const render=()=>{const query=$('#people-search').value.toLowerCase();const rows=people.filter(p=>(p.named||selected.has(p.id)||$('#people-unnamed').checked)&&(p.name.toLowerCase().includes(query)||String(p.id).includes(query)));$('#people-list').innerHTML=rows.map(p=>`<label class="check-row"><input type="checkbox" data-person="${p.id}" ${selected.has(p.id)?'checked':''}>${esc(p.name)} · ${p.count}</label>`).join('');$('#people-selected').textContent=t('peopleSelected')+selected.size;$('#people-list').querySelectorAll('[data-person]').forEach(box=>box.onchange=()=>{const id=Number(box.dataset.person);box.checked?selected.add(id):selected.delete(id);$('#people-selected').textContent=t('peopleSelected')+selected.size;});};
|
||||||
$('#people-search').oninput=render;$('#people-unnamed').onchange=render;$('#photos-disconnect').onclick=busy(async()=>{await api(path,{method:'DELETE'});await photosPeoplePicker(selected);});render();
|
$('#people-search').oninput=render;$('#people-unnamed').onchange=render;render();
|
||||||
|
}
|
||||||
|
|
||||||
|
async function photosConnectionPanel(){
|
||||||
|
const status=await api('/api/v1/integrations/synology-photos');
|
||||||
|
const box=$('#photos-connection');if(!box)return;
|
||||||
|
box.innerHTML=`<div class="section-heading"><div><h3>Synology Photos · ${t('photosSharedConnection')}</h3><p class="hint">${t('photosConnectionHelp')}</p></div><span class="badge ${status.connected?'ok':'warning'}">${t(status.connected?'photosConnected':'photosDisconnected')}</span></div><p class="notice ${status.connected?'':'warning'}">${t(!status.configured?'photosSetupHelp':status.connected?'photosConnectedHelp':'photosReconnectHelp')}</p><div class="actions">${buttons('photos-login',status.connected?'photosReconnect':'photosConnect',true)}${buttons('photos-status-refresh','refresh')}${status.connected?buttons('photos-disconnect','photosDisconnect'):''}</div>`;
|
||||||
|
$('#photos-login').disabled=!status.configured;
|
||||||
|
bind('photos-login',()=>photosLoginDialog());
|
||||||
|
bind('photos-status-refresh',()=>photosConnectionPanel());
|
||||||
|
bind('photos-disconnect',()=>confirmDialog(t('photosSharedDisconnectWarning'),async()=>{await api('/api/v1/integrations/synology-photos',{method:'DELETE'});await navigate('photo-sources');}));
|
||||||
|
}
|
||||||
|
function photosLoginDialog(){
|
||||||
|
showModal(`<h2>${t('photosConnect')}</h2><p class="hint">${t('photosLoginHelp')}</p><form id="photos-login-form"><div class="field"><label for="photos-login-user">${t('nasUsername')}</label><input id="photos-login-user" required autocomplete="username"></div><div class="field"><label for="photos-login-password">${t('nasPassword')}</label><input id="photos-login-password" required type="password" autocomplete="current-password"></div><p class="hint">${t('photosSessionHint')}</p><p id="photos-login-error" role="alert" hidden></p><div class="modal-actions">${buttons('modal-cancel','cancel')}<button type="submit" class="primary">${t('photosConnect')}</button></div></form>`);
|
||||||
|
$('#photos-login-form').onsubmit=busy(async e=>{e.preventDefault();const password=$('#photos-login-password').value;$('#photos-login-password').value='';try{await api('/api/v1/integrations/synology-photos',{method:'POST',body:{username:$('#photos-login-user').value,password}});$('#modal').close();await photosConnectionPanel();toast(t('photosConnectedHelp'));}catch(error){const box=$('#photos-login-error');box.hidden=false;box.className='notice warning';box.textContent=error.message;}});
|
||||||
}
|
}
|
||||||
|
|
||||||
async function photoSourcesPanel(){
|
async function photoSourcesPanel(){
|
||||||
const section=document.createElement('section');section.className='card photo-sources-panel';$('#main').append(section);
|
const section=document.createElement('section');section.className='card photo-sources-panel';$('#main').append(section);
|
||||||
const sources=await api('/api/v1/photo-sources');if(!section.isConnected)return;
|
const sources=await api('/api/v1/photo-sources');if(!section.isConnected)return;
|
||||||
section.innerHTML=`<div class="section-heading"><div><h3>${t('photoSources')}</h3><p class="hint">${t('sourceHint')}</p></div>${buttons('add-photo-source','addSource')}</div><div class="source-list">${sources.length?sources.map(s=>`<article class="source-card"><h4>${esc(s.name)}</h4><p class="hint">${esc(s.kind)} · ${t(s.enabled?'enabled':'disabled')}${s.people_filter?' · '+t('peopleFilter'):''}${s.orientation?' · '+t({auto:'orientationAuto',landscape:'orientationLandscape',portrait:'orientationPortrait'}[s.orientation]):''}</p><div class="actions"><button data-source-browse="${esc(s.id)}">${t('browse')}</button><button data-source-random="${esc(s.id)}" ${s.enabled?'':'disabled'}>${t('randomPreview')}</button><button data-source-job="${esc(s.id)}">${t('sourceJob')}</button><button data-source-edit="${esc(s.id)}">${t('edit')}</button><button class="danger" data-source-delete="${esc(s.id)}">${t('remove')}</button></div></article>`).join(''):`<p class="hint">${t('noSources')}</p>`}</div><div id="source-browser"></div>`;
|
section.innerHTML=`<div class="section-heading"><div><h3>${t('photoSources')}</h3><p class="hint">${t('sourceHint')}</p></div>${buttons('add-photo-source','addSource')}</div><section id="photos-connection" class="photos-connection" aria-label="Synology Photos"></section><div class="source-list">${sources.length?sources.map(s=>`<article class="source-card"><h4>${esc(s.name)}</h4><p class="hint source-identity">${t('sourceIdLabel')}: ${esc(s.id)} · ${t('sourceLocation')}: ${esc(s.location)}</p><p class="hint">${s.kind==='synology-photos'?t('sourcePhotosAPI'):t('sourceOwnCredentials')}</p><p class="hint">${esc(s.kind==='synology-photos'?'Synology Photos':s.kind)} · ${t(s.enabled?'enabled':'disabled')}${s.people_filter?' · '+t('peopleFilter'):''}${s.orientation?' · '+t({auto:'orientationAuto',landscape:'orientationLandscape',portrait:'orientationPortrait'}[s.orientation]):''}</p><div class="actions"><button data-source-browse="${esc(s.id)}">${t('browse')}</button><button data-source-random="${esc(s.id)}" ${s.enabled?'':'disabled'}>${t('randomPreview')}</button><button data-source-job="${esc(s.id)}">${t('sourceJob')}</button><button data-source-edit="${esc(s.id)}">${t('edit')}</button><button class="danger" data-source-delete="${esc(s.id)}">${t('remove')}</button></div></article>`).join(''):`<p class="hint">${t('noSources')}</p>`}</div><div id="source-browser"></div>`;
|
||||||
|
await photosConnectionPanel();
|
||||||
bind('add-photo-source',()=>photoSourceForm());
|
bind('add-photo-source',()=>photoSourceForm());
|
||||||
section.querySelectorAll('[data-source-edit]').forEach(b=>b.onclick=()=>photoSourceForm(sources.find(s=>s.id===b.dataset.sourceEdit)));
|
section.querySelectorAll('[data-source-edit]').forEach(b=>b.onclick=()=>photoSourceForm(sources.find(s=>s.id===b.dataset.sourceEdit)));
|
||||||
section.querySelectorAll('[data-source-delete]').forEach(b=>b.onclick=()=>confirmDialog(t('removeConfirm'),async()=>{await api('/api/v1/photo-sources/'+b.dataset.sourceDelete,{method:'DELETE'});await navigate('photo-sources');}));
|
section.querySelectorAll('[data-source-delete]').forEach(b=>b.onclick=()=>confirmDialog(t('removeConfirm'),async()=>{await api('/api/v1/photo-sources/'+b.dataset.sourceDelete,{method:'DELETE'});await navigate('photo-sources');}));
|
||||||
@@ -131,19 +150,19 @@ async function photoSourcesPanel(){
|
|||||||
section.querySelectorAll('[data-source-job]').forEach(b=>b.onclick=()=>sourceJobForm(b.dataset.sourceJob));
|
section.querySelectorAll('[data-source-job]').forEach(b=>b.onclick=()=>sourceJobForm(b.dataset.sourceJob));
|
||||||
}
|
}
|
||||||
async function photoSourceForm(source=null){
|
async function photoSourceForm(source=null){
|
||||||
showModal(`<h2>${t(source?'edit':'addSource')}</h2><form id="photo-source-form"><div class="field"><label for="source-id">ID</label><input id="source-id" pattern="[a-z0-9-]{1,60}" required value="${esc(source?.id||'')}" ${source?'readonly':''}></div><div class="field"><label for="source-name">${t('name')}</label><input id="source-name" required maxlength="120" value="${esc(source?.name||'')}"></div><div class="field"><label for="source-kind">${t('sourceKind')}</label><select id="source-kind"><option value="local">${t('nasDirectory')}</option><option value="webdav">WebDAV</option><option value="google-drive">Google Drive</option><option value="alipan">阿里云盘 / AliPan</option><option value="baidu">百度网盘 / Baidu</option></select></div><div class="field"><label for="source-location">${t('sourceLocation')}</label><input id="source-location" required maxlength="2048" value="${esc(source?.location||'.')}"><p class="hint">${t('sourceLocationHint')}</p></div><div class="field"><label for="source-credential">${t('sourceCredential')}</label><input id="source-credential" pattern="FRAME_FLOW_SOURCE_[A-Z0-9_]+" value="${esc(source?.credential_env||'')}" placeholder="FRAME_FLOW_SOURCE_CLOUD"><p class="hint">${t('sourceCredentialHint')}</p></div><div class="field"><label for="source-orientation">${t('photoOrientation')}</label><select id="source-orientation">${source&&!source.orientation?`<option value="">${t('orientationLegacy')}</option>`:''}<option value="auto">${t('orientationAuto')}</option><option value="landscape">${t('orientationLandscape')}</option><option value="portrait">${t('orientationPortrait')}</option></select><p class="hint">${t('orientationHint')}</p></div><div class="field"><label class="check-row"><input id="source-organized" type="checkbox" ${source?.organized_only?'checked':''}>${t('organizedPhotos')}</label><label class="check-row"><input id="source-caption" type="checkbox" ${source?.folder_caption?'checked':''}>${t('folderCaption')}</label><label class="check-row"><input id="source-synology-previews" type="checkbox" ${source?.synology_previews?'checked':''}>${t('synologyPreviews')}</label><p class="hint">${t('folderCaptionHint')}</p></div><div class="field"><label class="check-row"><input id="source-people-filter" type="checkbox" ${source?.people_filter?'checked':''}>${t('peopleFilter')}</label><p class="hint">${t('peopleHint')}</p><button id="source-people-load" type="button">${t('choosePeople')}</button><div id="source-people-panel"><p class="hint">${t('peopleSelected')}${(source?.person_ids||[]).length}</p></div><label for="source-person-match">${t('personMatch')}</label><select id="source-person-match"><option value="any">${t('personAny')}</option><option value="all">${t('personAll')}</option></select></div><div class="field"><label class="check-row"><input id="source-recursive" type="checkbox" ${source?.recursive===false?'':'checked'}>${t('sourceRecursive')}</label><label class="check-row"><input id="source-enabled" type="checkbox" ${source?.enabled===false?'':'checked'}>${t('enabled')}</label></div><div class="modal-actions">${buttons('modal-cancel','cancel')}<button type="submit" class="primary">${t('save')}</button></div></form>`);
|
showModal(`<h2>${t(source?'edit':'addSource')}</h2><p class="notice">${t('sourceIndependentHelp')}</p><form id="photo-source-form"><input id="source-id" type="hidden" value="${esc(source?.id||'photos-'+clientUUID())}"><div class="field"><label for="source-name">${t('name')}</label><input id="source-name" required maxlength="120" value="${esc(source?.name||'')}"></div><div class="field" ${!source||source.kind==='synology-photos'?'hidden':''}><label for="source-kind">${t('sourceKind')}</label><select id="source-kind"><option value="synology-photos">${t('synologyAPISource')}</option><option value="webdav">WebDAV</option><option value="google-drive">Google Drive</option><option value="alipan">阿里云盘 / AliPan</option><option value="baidu">百度网盘 / Baidu</option></select></div><div class="field"><label for="source-location">${t('sourceLocation')}</label><input id="source-location" required maxlength="2048" value="${esc(source?.location||'.')}"><p class="hint">${t('sourceLocationHint')}</p></div><div class="field"><label for="source-credential">${t('sourceCredential')}</label><input id="source-credential" pattern="FRAME_FLOW_SOURCE_[A-Z0-9_]+" value="${esc(source?.credential_env||'')}" placeholder="FRAME_FLOW_SOURCE_CLOUD"><p class="hint">${t('sourceCredentialHint')}</p></div><div class="field"><label for="source-orientation">${t('photoOrientation')}</label><select id="source-orientation">${source&&!source.orientation?`<option value="">${t('orientationLegacy')}</option>`:''}<option value="auto">${t('orientationAuto')}</option><option value="landscape">${t('orientationLandscape')}</option><option value="portrait">${t('orientationPortrait')}</option></select><p class="hint">${t('orientationHint')}</p></div><div class="field"><label class="check-row"><input id="source-organized" type="checkbox" ${source?.organized_only?'checked':''}>${t('organizedPhotos')}</label><label class="check-row"><input id="source-caption" type="checkbox" ${source?.folder_caption?'checked':''}>${t('folderCaption')}</label><label hidden><input id="source-synology-previews" type="checkbox" disabled></label><p class="hint">${t('folderCaptionHint')}</p></div><div class="field"><label class="check-row"><input id="source-people-filter" type="checkbox" ${source?.people_filter?'checked':''}>${t('peopleFilter')}</label><p class="hint">${t('peopleHint')}</p><button id="source-people-load" type="button">${t('choosePeople')}</button><div id="source-people-panel"><p class="hint">${t('peopleSelected')}${(source?.person_ids||[]).length}</p></div><label for="source-person-match">${t('personMatch')}</label><select id="source-person-match"><option value="any">${t('personAny')}</option><option value="all">${t('personAll')}</option></select></div><div class="field"><label class="check-row"><input id="source-recursive" type="checkbox" ${source?.recursive===false?'':'checked'}>${t('sourceRecursive')}</label><label class="check-row"><input id="source-enabled" type="checkbox" ${source?.enabled===false?'':'checked'}>${t('enabled')}</label></div><div class="modal-actions">${buttons('modal-cancel','cancel')}<button type="submit" class="primary">${t('save')}</button></div></form>`);
|
||||||
$('#source-orientation').value=source?(source.orientation||''):'auto';const selectedPeople=new Set(source?.person_ids||[]);$('#source-person-match').value=source?.person_match||'any';$('#source-people-load').onclick=busy(async()=>{await photosPeoplePicker(selectedPeople);});$('#source-kind').value=source?.kind||'local';const update=()=>{const dav=$('#source-kind').value!=='local';$('#source-orientation').disabled=dav;$('#source-credential').disabled=!dav;$('#source-recursive').disabled=$('#source-kind').value==='webdav';$('#source-synology-previews').disabled=dav;$('#source-organized').disabled=dav;$('#source-caption').disabled=dav;$('#source-people-filter').disabled=dav;$('#source-people-load').disabled=dav;};update();$('#source-kind').onchange=update;addPhotoQualityFields(source);$('#source-people-space').onchange=()=>{selectedPeople.clear();$('#source-people-panel').innerHTML='';};
|
$('#source-orientation').value=source?(source.orientation||''):'auto';const selectedPeople=new Set(source?.person_ids||[]);$('#source-person-match').value=source?.person_match||'any';$('#source-people-load').onclick=busy(async()=>{await photosPeoplePicker(selectedPeople);});$('#source-kind').value=source?.kind||'synology-photos';const update=()=>{const photosAPI=$('#source-kind').value==='synology-photos';$('#source-location').labels[0].textContent=photosAPI?tr('照片目录','Photo folder'):t('sourceLocation');$('#source-location').nextElementSibling.textContent=photosAPI?tr('填写所选空间内的目录路径,. 表示整个空间。按需获取 XL 预览图,不下载原图。','Folder path within the selected space; . means the whole space. Downloads XL previews on demand, not originals.'):t('sourceLocationHint');const dav=!['local','synology-photos'].includes($('#source-kind').value);$('#source-orientation').disabled=dav;$('#source-credential').disabled=!dav;$('#source-credential').closest('.field').hidden=$('#source-kind').value!=='webdav';const oauth=$('#source-oauth');if(oauth)oauth.closest('.field').hidden=!['google-drive','alipan','baidu'].includes($('#source-kind').value);const quality=$('#source-local-quality');if(quality)quality.hidden=dav;$('#source-recursive').disabled=$('#source-kind').value==='webdav';$('#source-synology-previews').disabled=$('#source-kind').value!=='local';$('#source-organized').disabled=dav;$('#source-caption').disabled=dav;$('#source-people-filter').disabled=dav;$('#source-people-load').disabled=dav;};addPhotoQualityFields(source);$('#source-location').closest('.field').before($('#source-people-space').closest('.field'));update();$('#source-kind').onchange=update;$('#source-people-space').onchange=()=>{selectedPeople.clear();$('#source-people-panel').innerHTML='';};
|
||||||
$('#photo-source-form').onsubmit=busy(async e=>{e.preventDefault();const oauth=$('#source-oauth').value;const sourceId=$('#source-id').value;const native=['google-drive','alipan','baidu'].includes($('#source-kind').value);if(oauth&&native)JSON.parse(oauth);const dav=$('#source-kind').value!=='local';await api('/api/v1/photo-sources/'+$('#source-id').value,{method:'PUT',body:{name:$('#source-name').value,kind:$('#source-kind').value,location:$('#source-location').value,recursive:$('#source-kind').value!=='webdav'&&$('#source-recursive').checked,synology_previews:!dav&&$('#source-synology-previews').checked,catalog_limit:$('#source-organized').checked?100000:(source?.catalog_limit||10000),organized_only:!dav&&$('#source-organized').checked,folder_caption:!dav&&$('#source-caption').checked,orientation:dav?null:($('#source-orientation').value||null),people_filter:!dav&&$('#source-people-filter').checked,person_ids:[...selectedPeople],person_match:$('#source-person-match').value,people_space:$('#source-people-space').value,minimum_sharpness:Number($('#source-sharpness').value),minimum_brightness:Number($('#source-bright-min').value),maximum_brightness:Number($('#source-bright-max').value),avoid_duplicates:$('#source-dedup').checked,enabled:$('#source-enabled').checked,credential_env:dav?($('#source-credential').value||null):null}});if(oauth&&native){$('#source-oauth').value='';await api('/api/v1/photo-sources/'+sourceId+'/credentials',{method:'PUT',body:{key:oauth}});}$('#modal').close();await navigate('photo-sources');});
|
$('#photo-source-form').onsubmit=busy(async e=>{e.preventDefault();const oauth=$('#source-oauth').value;const sourceId=$('#source-id').value;const native=['google-drive','alipan','baidu'].includes($('#source-kind').value);if(oauth&&native)JSON.parse(oauth);const dav=!['local','synology-photos'].includes($('#source-kind').value);await api('/api/v1/photo-sources/'+$('#source-id').value,{method:'PUT',body:{name:$('#source-name').value,kind:$('#source-kind').value,location:$('#source-location').value,recursive:$('#source-kind').value!=='webdav'&&$('#source-recursive').checked,synology_previews:false,catalog_limit:$('#source-organized').checked?100000:(source?.catalog_limit||10000),organized_only:!dav&&$('#source-organized').checked,folder_caption:!dav&&$('#source-caption').checked,orientation:dav?null:($('#source-orientation').value||null),people_filter:!dav&&$('#source-people-filter').checked,person_ids:[...selectedPeople],person_match:$('#source-person-match').value,people_space:$('#source-people-space').value,minimum_sharpness:Number($('#source-sharpness').value),minimum_brightness:Number($('#source-bright-min').value),maximum_brightness:Number($('#source-bright-max').value),avoid_duplicates:$('#source-dedup').checked,enabled:$('#source-enabled').checked,credential_env:dav?($('#source-credential').value||null):null}});if(oauth&&native){$('#source-oauth').value='';await api('/api/v1/photo-sources/'+sourceId+'/credentials',{method:'PUT',body:{key:oauth}});}$('#modal').close();await navigate('photo-sources');});
|
||||||
}
|
}
|
||||||
async function browseSource(id,offset=0,refresh=false){
|
async function browseSource(id,offset=0,refresh=false){
|
||||||
const result=await api('/api/v1/photo-sources/'+id+'/images?device_id='+encodeURIComponent(state.device)+'&offset='+offset+'&limit=50&refresh='+refresh);const box=$('#source-browser');if(!box)return;
|
const result=await api('/api/v1/photo-sources/'+id+'/images?device_id='+encodeURIComponent(state.device)+'&offset='+offset+'&limit=50&refresh='+refresh);const box=$('#source-browser');if(!box)return;
|
||||||
box.innerHTML=`<h4>${t('sourceImages')} · ${result.total}${result.total>=result.catalog_limit?' (limit)':''}</h4><p class="hint">${t('sourceBrowseHint')}</p><div class="source-items">${result.items.map((x,i)=>`<button data-source-item="${i}">${esc(x.name)}${x.width?`<small>${x.width} × ${x.height}</small>`:''}${x.caption?`<small>${esc([x.caption.title,x.caption.date,x.caption.place].filter(Boolean).join(' · '))}</small>`:''}</button>`).join('')||t('noSources')}</div><div class="actions"><button id="source-prev" ${offset?'':'disabled'}>${t('previousPage')}</button><button id="source-next" ${offset+result.items.length<result.total?'':'disabled'}>${t('nextPage')}</button>${buttons('source-refresh','refresh')}</div>`;
|
box.innerHTML=`<h4>${t('sourceImages')} · ${result.total}${result.total>=result.catalog_limit?' (limit)':''}</h4><p class="hint">${t('sourceBrowseHint')}</p><div class="source-items">${result.items.map((x,i)=>`<button data-source-item="${i}">${esc(x.name)}${x.width?`<small>${x.width} × ${x.height}</small>`:''}${x.caption?`<small>${esc([x.caption.title,x.caption.date,x.caption.place].filter(Boolean).join(' · '))}</small>`:''}</button>`).join('')||t('noSourcePhotos')}</div><div class="actions"><button id="source-prev" ${offset?'':'disabled'}>${t('previousPage')}</button><button id="source-next" ${offset+result.items.length<result.total?'':'disabled'}>${t('nextPage')}</button>${buttons('source-refresh','refresh')}</div>`;
|
||||||
box.querySelectorAll('[data-source-item]').forEach(b=>b.onclick=busy(()=>previewSource(id,result.items[Number(b.dataset.sourceItem)].id)));bind('source-prev',()=>browseSource(id,Math.max(0,offset-50)));bind('source-next',()=>browseSource(id,offset+50));bind('source-refresh',()=>browseSource(id,0,true));
|
box.querySelectorAll('[data-source-item]').forEach(b=>b.onclick=busy(()=>previewSource(id,result.items[Number(b.dataset.sourceItem)].id)));bind('source-prev',()=>browseSource(id,Math.max(0,offset-50)));bind('source-next',()=>browseSource(id,offset+50));bind('source-refresh',()=>browseSource(id,0,true));
|
||||||
}
|
}
|
||||||
async function previewSource(id,item_id=null){
|
async function previewSource(id,item_id=null){
|
||||||
const acceptedResult=await api('/api/v1/devices/'+state.device+'/upload',{method:'POST',body:{type:'photo_source',source_id:id,item_id,fit:'contain',profile:'color'},headers:{'Idempotency-Key':clientUUID()}});const op=await waitOperation(acceptedResult.operation_id);
|
const acceptedResult=await api('/api/v1/devices/'+state.device+'/upload',{method:'POST',body:{type:'photo_source',source_id:id,item_id,fit:'contain',profile:'color'},headers:{'Idempotency-Key':clientUUID()}});const op=await waitOperation(acceptedResult.operation_id);
|
||||||
showModal(`<h2>${t('preview')}</h2><img id="source-preview" class="preview" alt="${t('preview')}"><p class="hint">${t('sourcePreviewHint')}</p><div class="modal-actions">${buttons('modal-cancel','cancel')}${buttons('source-display','display',true)}</div>`);await blobImage($('#source-preview'),op.result.url);$('#source-display').disabled=!liveWriteAllowed();bind('source-display',()=>displayDialog({type:'image',asset_id:op.result.asset_id}));
|
showModal(`<h2>${t('preview')}</h2><img id="source-preview" class="preview" alt="${t('preview')}"><p class="hint">${t('sourcePreviewHint')}</p><div class="modal-actions">${buttons('modal-cancel','cancel')}${buttons('source-display','display',true)}</div>`);await blobImage($('#source-preview'),op.result.url);$('#source-display').disabled=!liveWriteAllowed();bind('source-display',()=>displayDialog({type:'image',asset_id:op.result.asset_id}));
|
||||||
}
|
}
|
||||||
function sourceJobForm(id){
|
async function sourceJobForm(id){
|
||||||
showModal(`<h2>${t('sourceJob')}</h2><form id="source-job-form"><div class="field"><label for="source-job-name">${t('name')}</label><input id="source-job-name" required maxlength="120" value="${t('randomPhoto')}"></div><div class="field"><label for="source-job-cron">Cron · Asia/Shanghai</label><input id="source-job-cron" required value="0 8 * * *"><p class="hint">${t('sourceJobHint')}</p></div><div class="field"><label class="check-row"><input id="source-job-enabled" type="checkbox">${t('enabled')}</label></div><p class="hint">${t('cloudKeepLatest')}</p><div class="modal-actions">${buttons('modal-cancel','cancel')}<button class="primary" type="submit">${t('save')}</button></div></form>`);$('#source-job-form').onsubmit=busy(async e=>{e.preventDefault();await api('/api/v1/jobs',{method:'POST',body:{name:$('#source-job-name').value,device_id:state.device,enabled:$('#source-job-enabled').checked,cleanup_unstarred:false,schedule:{type:'cron',cron:$('#source-job-cron').value},source:{type:'photo_source',source_id:id,fit:'contain',profile:'color'}}});$('#modal').close();await navigate('automation');});
|
await jobEditor({name:t('randomPhoto'),device_id:state.device,enabled:false,schedule:{type:'interval',interval_minutes:120},source:{type:'photo_source',source_id:id,fit:'contain',profile:'color'},display_duration:0,restore_previous:false,priority:50});
|
||||||
}
|
}
|
||||||
|
|||||||
File diff suppressed because one or more lines are too long
@@ -1,3 +1,3 @@
|
|||||||
<!doctype html>
|
<!doctype html>
|
||||||
<html lang="zh-CN"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="color-scheme" content="light dark"><title>Pigway Frame Flow</title><link rel="stylesheet" href="/ui/style.css"></head>
|
<html lang="zh-CN"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover"><meta name="color-scheme" content="light dark"><title>Pigway Frame Flow</title><link rel="stylesheet" href="/ui/style.css"></head>
|
||||||
<body><aside class="sidebar"><a class="brand" href="/"><span class="brand-icon">F<span>↗</span></span><span>Frame Flow<small>Pigway · Smart Frame Automation</small></span></a><nav id="nav"></nav><div class="sidebar-bottom"><small>Version 0.1.0</small></div></aside><div class="workspace"><header><div><span class="eyebrow">PIGWAY FRAME FLOW</span><h1 id="page-title"></h1></div><div class="toolbar"><select id="device" aria-label="Device"></select><button id="lang" class="icon-button" aria-label="Change language">EN</button><button id="theme" class="icon-button" aria-label="Change theme">◐</button></div></header><main id="main"></main><footer id="footer"></footer></div><div id="toast" role="status" aria-live="polite"></div><dialog id="modal"><div id="modal-content"></div></dialog><script src="/ui/i18n.js"></script><script src="/ui/features.js"></script><script src="/ui/extensions.js"></script><script src="/ui/app.js"></script></body></html>
|
<body><aside class="sidebar"><a class="brand" href="/"><span class="brand-icon">F<span>↗</span></span><span>Frame Flow<small>Pigway · Smart Frame Automation</small></span></a><nav id="nav"></nav><div class="sidebar-bottom"><small>Version 0.1.9</small></div></aside><div class="workspace"><header><div><span class="eyebrow">PIGWAY FRAME FLOW</span><h1 id="page-title"></h1></div><div class="toolbar"><select id="device" aria-label="Device"></select><button id="lang" class="icon-button" aria-label="Change language">EN</button><button id="theme" class="icon-button" aria-label="Change theme">◐</button></div></header><main id="main"></main><footer id="footer"></footer></div><div id="toast" role="status" aria-live="polite"></div><dialog id="modal"><div id="modal-content"></div></dialog><script src="/ui/i18n.js?v=audit-ui-20261017-history"></script><script src="/ui/features.js?v=audit-ui-20261017-history"></script><script src="/ui/extensions.js?v=audit-ui-20261017-history"></script><script src="/ui/app.js?v=audit-ui-20261017-history"></script></body></html>
|
||||||
|
|||||||
File diff suppressed because one or more lines are too long
+1
-1
@@ -1,6 +1,6 @@
|
|||||||
[project]
|
[project]
|
||||||
name = "pigway-frame-flow"
|
name = "pigway-frame-flow"
|
||||||
version = "0.1.0"
|
version = "0.1.9"
|
||||||
requires-python = ">=3.12"
|
requires-python = ">=3.12"
|
||||||
dependencies = ["paho-mqtt==2.1.0", "python-dateutil==2.9.0.post0", "fastapi==0.142.2", "uvicorn==0.54.0", "pillow==12.3.0", "requests==2.34.2", "croniter==6.2.4", "python-multipart==0.0.32", "pyyaml==6.0.3"]
|
dependencies = ["paho-mqtt==2.1.0", "python-dateutil==2.9.0.post0", "fastapi==0.142.2", "uvicorn==0.54.0", "pillow==12.3.0", "requests==2.34.2", "croniter==6.2.4", "python-multipart==0.0.32", "pyyaml==6.0.3"]
|
||||||
[project.optional-dependencies]
|
[project.optional-dependencies]
|
||||||
|
|||||||
@@ -0,0 +1,83 @@
|
|||||||
|
"""Offline, explicit local-to-Photos-API source conversion; defaults to dry run."""
|
||||||
|
|
||||||
|
import argparse
|
||||||
|
import json
|
||||||
|
import sqlite3
|
||||||
|
from datetime import UTC, datetime
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
from pigway_frame_flow.providers.photo_sources import PhotoSourceInput
|
||||||
|
|
||||||
|
|
||||||
|
def convert(database, source_ids, *, apply=False):
|
||||||
|
connection = sqlite3.connect(f"file:{database}?mode=rw", uri=True)
|
||||||
|
try:
|
||||||
|
updates = []
|
||||||
|
for source_id in source_ids:
|
||||||
|
key = "photo_source:" + source_id
|
||||||
|
row = connection.execute(
|
||||||
|
"SELECT payload FROM app_config WHERE key=?", (key,)
|
||||||
|
).fetchone()
|
||||||
|
if not row:
|
||||||
|
raise ValueError("Source not found: " + source_id)
|
||||||
|
source = PhotoSourceInput.model_validate_json(row[0])
|
||||||
|
if source.kind != "local":
|
||||||
|
raise ValueError(
|
||||||
|
"Only explicitly selected local sources can be converted"
|
||||||
|
)
|
||||||
|
location = source.location.strip("/")
|
||||||
|
if (
|
||||||
|
source.location.startswith("/")
|
||||||
|
or "\\" in location
|
||||||
|
or ".." in location.split("/")
|
||||||
|
):
|
||||||
|
raise ValueError(
|
||||||
|
"Review the source's relative Photos folder path first"
|
||||||
|
)
|
||||||
|
payload = source.model_copy(
|
||||||
|
update={"kind": "synology-photos", "synology_previews": False}
|
||||||
|
)
|
||||||
|
updates.append((payload.model_dump_json(), key))
|
||||||
|
backup = None
|
||||||
|
if apply:
|
||||||
|
backup = database.with_name(
|
||||||
|
database.name
|
||||||
|
+ ".before-photos-api-"
|
||||||
|
+ datetime.now(UTC).strftime("%Y%m%dT%H%M%S%fZ")
|
||||||
|
)
|
||||||
|
with sqlite3.connect(backup) as snapshot:
|
||||||
|
connection.backup(snapshot)
|
||||||
|
backup.chmod(0o600)
|
||||||
|
with connection:
|
||||||
|
connection.executemany(
|
||||||
|
"UPDATE app_config SET payload=? WHERE key=?", updates
|
||||||
|
)
|
||||||
|
return {
|
||||||
|
"applied": apply,
|
||||||
|
"sources": source_ids,
|
||||||
|
"backup": str(backup) if backup else None,
|
||||||
|
}
|
||||||
|
finally:
|
||||||
|
connection.close()
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
parser = argparse.ArgumentParser(description=__doc__)
|
||||||
|
parser.add_argument("--database", type=Path, required=True)
|
||||||
|
parser.add_argument("--source", action="append", required=True)
|
||||||
|
parser.add_argument("--apply", action="store_true")
|
||||||
|
parser.add_argument(
|
||||||
|
"--service-stopped",
|
||||||
|
action="store_true",
|
||||||
|
help="Confirm the target service is stopped before changing its database",
|
||||||
|
)
|
||||||
|
args = parser.parse_args()
|
||||||
|
if args.apply and not args.service_stopped:
|
||||||
|
parser.error(
|
||||||
|
"Stop the target service and pass --service-stopped before applying"
|
||||||
|
)
|
||||||
|
print(json.dumps(convert(args.database, args.source, apply=args.apply), indent=2))
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
@@ -10,7 +10,7 @@ from urllib.request import Request, urlopen
|
|||||||
parser = argparse.ArgumentParser()
|
parser = argparse.ArgumentParser()
|
||||||
parser.add_argument("mode", choices=["record", "check"])
|
parser.add_argument("mode", choices=["record", "check"])
|
||||||
args = parser.parse_args()
|
args = parser.parse_args()
|
||||||
base = os.getenv("FRAME_FLOW_URL", "http://127.0.0.1:18787").rstrip("/")
|
base = os.getenv("FRAME_FLOW_URL", "http://127.0.0.1:6005").rstrip("/")
|
||||||
token = os.getenv("FRAME_FLOW_TOKEN", "")
|
token = os.getenv("FRAME_FLOW_TOKEN", "")
|
||||||
if not token:
|
if not token:
|
||||||
for line in Path(".env").read_text().splitlines():
|
for line in Path(".env").read_text().splitlines():
|
||||||
|
|||||||
+114
-28
@@ -37,7 +37,19 @@ class Deploy:
|
|||||||
self.lock_id = None
|
self.lock_id = None
|
||||||
self.state = None
|
self.state = None
|
||||||
self.old_image = None
|
self.old_image = None
|
||||||
self.secret_values = []
|
self.old_image_tag = ""
|
||||||
|
self.secret_values = [
|
||||||
|
self.env[key]
|
||||||
|
for key in (
|
||||||
|
"PROD_DATA_DIR",
|
||||||
|
"PROD_CONFIG_DIR",
|
||||||
|
"PROD_PHOTOS_DIR",
|
||||||
|
"PROD_WEB_BIND",
|
||||||
|
"SYNOLOGY_PHOTOS_URL",
|
||||||
|
"SYNOLOGY_PHOTOS_CERT_SHA256",
|
||||||
|
)
|
||||||
|
if self.env.get(key)
|
||||||
|
]
|
||||||
self.docker = self.env.get("DOCKER_BIN", "docker")
|
self.docker = self.env.get("DOCKER_BIN", "docker")
|
||||||
|
|
||||||
def run(self, *args, data=None, check=True):
|
def run(self, *args, data=None, check=True):
|
||||||
@@ -58,6 +70,13 @@ class Deploy:
|
|||||||
return json.loads(self.run("inspect", name).stdout)[0]
|
return json.loads(self.run("inspect", name).stdout)[0]
|
||||||
|
|
||||||
def settings(self):
|
def settings(self):
|
||||||
|
if any(
|
||||||
|
self.env.get(key, "").startswith("/volume2/docker/pigway-frame-flow")
|
||||||
|
for key in ("PROD_DATA_DIR", "PROD_CONFIG_DIR")
|
||||||
|
):
|
||||||
|
raise ValueError(
|
||||||
|
"NAS Frame deployment is retired; target the Ubuntu Server"
|
||||||
|
)
|
||||||
missing = [key for key in REQUIRED if not self.env.get(key)]
|
missing = [key for key in REQUIRED if not self.env.get(key)]
|
||||||
if missing:
|
if missing:
|
||||||
raise ValueError("Missing Variables: " + ", ".join(missing))
|
raise ValueError("Missing Variables: " + ", ".join(missing))
|
||||||
@@ -106,20 +125,9 @@ class Deploy:
|
|||||||
or not m.get("RW")
|
or not m.get("RW")
|
||||||
):
|
):
|
||||||
raise ValueError("Production mount mismatch: " + key)
|
raise ValueError("Production mount mismatch: " + key)
|
||||||
photos = self.env.get("PROD_PHOTOS_DIR")
|
if self.env.get("PROD_PHOTOS_DIR") or "/photos" in mounts:
|
||||||
if "/photos" in mounts and (
|
raise ValueError("Filesystem photo mounts are retired; use the Photos API")
|
||||||
not photos
|
if set(mounts) != {"/data", "/config"}:
|
||||||
or mounts["/photos"]["Source"] != photos
|
|
||||||
or mounts["/photos"]["RW"]
|
|
||||||
):
|
|
||||||
raise ValueError(
|
|
||||||
"Confirm PROD_PHOTOS_DIR for the existing read-only photo mount"
|
|
||||||
)
|
|
||||||
if photos and "/photos" not in mounts:
|
|
||||||
raise ValueError(
|
|
||||||
"Configured photos directory does not match current container"
|
|
||||||
)
|
|
||||||
if set(mounts) != {"/data", "/config"} | ({"/photos"} if photos else set()):
|
|
||||||
raise ValueError("Unrecognized persistent mount; review before adopting CD")
|
raise ValueError("Unrecognized persistent mount; review before adopting CD")
|
||||||
bindings = old["HostConfig"].get("PortBindings", {}).get("18787/tcp")
|
bindings = old["HostConfig"].get("PortBindings", {}).get("18787/tcp")
|
||||||
if bindings != [
|
if bindings != [
|
||||||
@@ -168,16 +176,6 @@ class Deploy:
|
|||||||
)
|
)
|
||||||
]
|
]
|
||||||
service["group_add"] = old["HostConfig"].get("GroupAdd") or []
|
service["group_add"] = old["HostConfig"].get("GroupAdd") or []
|
||||||
if photos:
|
|
||||||
service["volumes"].append(
|
|
||||||
{
|
|
||||||
"type": "bind",
|
|
||||||
"source": photos,
|
|
||||||
"target": "/photos",
|
|
||||||
"read_only": True,
|
|
||||||
"bind": {"create_host_path": False},
|
|
||||||
}
|
|
||||||
)
|
|
||||||
# Adoption must preserve runtime constraints, not silently change them.
|
# Adoption must preserve runtime constraints, not silently change them.
|
||||||
if (
|
if (
|
||||||
old["Config"]["User"] != service["user"]
|
old["Config"]["User"] != service["user"]
|
||||||
@@ -185,6 +183,7 @@ class Deploy:
|
|||||||
):
|
):
|
||||||
raise ValueError("Production user/restart policy differs from repository")
|
raise ValueError("Production user/restart policy differs from repository")
|
||||||
self.old_image = old["Image"]
|
self.old_image = old["Image"]
|
||||||
|
self.old_image_tag = old["Config"].get("Image", "")
|
||||||
volume = self.run(
|
volume = self.run(
|
||||||
"volume", "inspect", self.env["PROD_STATE_VOLUME"], check=False
|
"volume", "inspect", self.env["PROD_STATE_VOLUME"], check=False
|
||||||
)
|
)
|
||||||
@@ -324,6 +323,12 @@ class Deploy:
|
|||||||
def rollback(self, previous):
|
def rollback(self, previous):
|
||||||
self.activate(previous)
|
self.activate(previous)
|
||||||
self.verify(previous)
|
self.verify(previous)
|
||||||
|
self.run(
|
||||||
|
"image",
|
||||||
|
"tag",
|
||||||
|
previous["services"]["pigway-frame-flow"]["image"],
|
||||||
|
self.env["PROD_IMAGE_REPO"] + ":latest",
|
||||||
|
)
|
||||||
print("ROLLBACK VERIFIED", flush=True)
|
print("ROLLBACK VERIFIED", flush=True)
|
||||||
|
|
||||||
def secret_config(self):
|
def secret_config(self):
|
||||||
@@ -379,10 +384,16 @@ class Deploy:
|
|||||||
command += ["--build-arg", key + "=" + value]
|
command += ["--build-arg", key + "=" + value]
|
||||||
self.run(*command, str(ROOT))
|
self.run(*command, str(ROOT))
|
||||||
service = config["services"]["pigway-frame-flow"]
|
service = config["services"]["pigway-frame-flow"]
|
||||||
service["image"] = image
|
latest = self.env["PROD_IMAGE_REPO"] + ":latest"
|
||||||
|
self.run("image", "tag", image, latest)
|
||||||
|
service["image"] = latest
|
||||||
proposed = self.secret_config()
|
proposed = self.secret_config()
|
||||||
service["environment"].update(proposed)
|
service["environment"].update(proposed)
|
||||||
for key in ("SYNOLOGY_PHOTOS_URL", "SYNOLOGY_PHOTOS_CERT_SHA256"):
|
for key in (
|
||||||
|
"SYNOLOGY_PHOTOS_URL",
|
||||||
|
"SYNOLOGY_PHOTOS_CERT_SHA256",
|
||||||
|
"FRAME_FLOW_STORAGE_NAME",
|
||||||
|
):
|
||||||
if self.env.get(key):
|
if self.env.get(key):
|
||||||
service["environment"][key] = self.env[key]
|
service["environment"][key] = self.env[key]
|
||||||
service["environment"].update(
|
service["environment"].update(
|
||||||
@@ -653,6 +664,7 @@ class Deploy:
|
|||||||
self.state["status"] = "success"
|
self.state["status"] = "success"
|
||||||
self.state_io(self.state)
|
self.state_io(self.state)
|
||||||
print("BOOTSTRAP VERIFIED", flush=True)
|
print("BOOTSTRAP VERIFIED", flush=True)
|
||||||
|
self.cleanup_images()
|
||||||
except BaseException:
|
except BaseException:
|
||||||
print("BOOTSTRAP FAILED", flush=True)
|
print("BOOTSTRAP FAILED", flush=True)
|
||||||
self.diagnostics()
|
self.diagnostics()
|
||||||
@@ -712,6 +724,68 @@ class Deploy:
|
|||||||
text = re.sub(r"https?://[^\s\"'<>]+", "[REDACTED-URL]", text)
|
text = re.sub(r"https?://[^\s\"'<>]+", "[REDACTED-URL]", text)
|
||||||
print("Scoped container logs (redacted):", text, flush=True)
|
print("Scoped container logs (redacted):", text, flush=True)
|
||||||
|
|
||||||
|
def cleanup_images(self):
|
||||||
|
"""Keep only latest after verification; protect unrelated container images."""
|
||||||
|
try:
|
||||||
|
protected = set()
|
||||||
|
referenced_tags = set()
|
||||||
|
container_ids = self.run("ps", "-aq").stdout.decode().split()
|
||||||
|
if container_ids:
|
||||||
|
containers = json.loads(self.run("inspect", *container_ids).stdout)
|
||||||
|
protected.update(container["Image"] for container in containers)
|
||||||
|
referenced_tags.update(
|
||||||
|
container.get("Config", {}).get("Image", "")
|
||||||
|
for container in containers
|
||||||
|
)
|
||||||
|
repo = self.env["PROD_IMAGE_REPO"]
|
||||||
|
image_ids = (
|
||||||
|
self.run("image", "ls", "--no-trunc", "-q", repo)
|
||||||
|
.stdout.decode()
|
||||||
|
.split()
|
||||||
|
)
|
||||||
|
if not image_ids:
|
||||||
|
return
|
||||||
|
images = json.loads(
|
||||||
|
self.run("image", "inspect", *sorted(set(image_ids))).stdout
|
||||||
|
)
|
||||||
|
removed = 0
|
||||||
|
for image in images:
|
||||||
|
tags = image.get("RepoTags") or []
|
||||||
|
# Shared images and unrelated tags are never cleanup targets.
|
||||||
|
if not tags:
|
||||||
|
continue
|
||||||
|
if not all(
|
||||||
|
re.fullmatch(
|
||||||
|
re.escape(repo)
|
||||||
|
+ r":(?:latest|release-[0-9a-f]{40}-[0-9a-f]{8}(?:-rollback)?|rollback-[0-9a-f]{32})",
|
||||||
|
tag,
|
||||||
|
)
|
||||||
|
for tag in tags
|
||||||
|
):
|
||||||
|
continue
|
||||||
|
latest = repo + ":latest"
|
||||||
|
if image["Id"] in protected:
|
||||||
|
# Current production uses latest. Other containers retain
|
||||||
|
# their referenced tags and images, even when stopped.
|
||||||
|
if latest not in tags:
|
||||||
|
continue
|
||||||
|
tags = [
|
||||||
|
tag
|
||||||
|
for tag in tags
|
||||||
|
if tag != latest and tag not in referenced_tags
|
||||||
|
]
|
||||||
|
if not tags:
|
||||||
|
continue
|
||||||
|
result = self.run("image", "rm", *tags, check=False)
|
||||||
|
if result.returncode:
|
||||||
|
print("IMAGE RETENTION: referenced image retained", flush=True)
|
||||||
|
else:
|
||||||
|
removed += 1
|
||||||
|
print(f"IMAGE RETENTION: removed {removed} obsolete images", flush=True)
|
||||||
|
except Exception:
|
||||||
|
# Cleanup failure must never roll back an already verified deployment.
|
||||||
|
print("IMAGE RETENTION WARNING: cleanup deferred", flush=True)
|
||||||
|
|
||||||
def deploy(self):
|
def deploy(self):
|
||||||
previous = self.preflight()
|
previous = self.preflight()
|
||||||
self.lock()
|
self.lock()
|
||||||
@@ -721,7 +795,15 @@ class Deploy:
|
|||||||
# Refresh baseline under the daemon-level lock.
|
# Refresh baseline under the daemon-level lock.
|
||||||
previous = self.preflight()
|
previous = self.preflight()
|
||||||
version = self.verify(previous)
|
version = self.verify(previous)
|
||||||
pin = self.env["PROD_IMAGE_REPO"] + ":rollback-" + self.owner
|
release = self.old_image_tag.removesuffix("-rollback")
|
||||||
|
if re.fullmatch(
|
||||||
|
re.escape(self.env["PROD_IMAGE_REPO"])
|
||||||
|
+ r":release-[0-9a-f]{40}-[0-9a-f]{8}",
|
||||||
|
release,
|
||||||
|
):
|
||||||
|
pin = release + "-rollback"
|
||||||
|
else:
|
||||||
|
pin = self.env["PROD_IMAGE_REPO"] + ":rollback-" + self.owner
|
||||||
self.run("image", "tag", self.old_image, pin)
|
self.run("image", "tag", self.old_image, pin)
|
||||||
candidate = self.build(json.loads(json.dumps(previous)))
|
candidate = self.build(json.loads(json.dumps(previous)))
|
||||||
self.state = {
|
self.state = {
|
||||||
@@ -780,6 +862,10 @@ class Deploy:
|
|||||||
if safe_unlock:
|
if safe_unlock:
|
||||||
self.unlock()
|
self.unlock()
|
||||||
|
|
||||||
|
# The deployment lock itself references the old image. Release it
|
||||||
|
# before retention; other container references remain protected.
|
||||||
|
self.cleanup_images()
|
||||||
|
|
||||||
def recover(self, manual=False):
|
def recover(self, manual=False):
|
||||||
self.settings()
|
self.settings()
|
||||||
lock = self.run(
|
lock = self.run(
|
||||||
|
|||||||
@@ -40,5 +40,8 @@ os.environ["BUILD_COMMIT"] = (
|
|||||||
|
|
||||||
os.environ["BUILD_TIME"] = datetime.now(UTC).isoformat()
|
os.environ["BUILD_TIME"] = datetime.now(UTC).isoformat()
|
||||||
uvicorn.run(
|
uvicorn.run(
|
||||||
"pigway_frame_flow.main:app", host="127.0.0.1", port=18787, access_log=False
|
"pigway_frame_flow.main:app",
|
||||||
|
host="127.0.0.1",
|
||||||
|
port=int(os.getenv("WEB_PORT", "6005")),
|
||||||
|
access_log=False,
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -0,0 +1,255 @@
|
|||||||
|
"""Release a verified source bundle on the Ubuntu T7 host; never write to frames."""
|
||||||
|
|
||||||
|
import datetime
|
||||||
|
import fcntl
|
||||||
|
import hashlib
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import re
|
||||||
|
import shutil
|
||||||
|
import sqlite3
|
||||||
|
import subprocess
|
||||||
|
import time
|
||||||
|
import urllib.request
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
APP = Path("/srv/pigway/apps/pigway-frame-flow")
|
||||||
|
RECOVERY = Path("/srv/pigway/recovery/frame-flow")
|
||||||
|
CONTAINER = "pigway-frame-flow"
|
||||||
|
ORIGIN = "http://192.0.2.10:81"
|
||||||
|
|
||||||
|
|
||||||
|
def run(*args):
|
||||||
|
return subprocess.check_output(args, text=True, timeout=600).strip()
|
||||||
|
|
||||||
|
|
||||||
|
def inspect():
|
||||||
|
return json.loads(run("docker", "inspect", CONTAINER))[0]
|
||||||
|
|
||||||
|
|
||||||
|
def archive_staging(backup, ctx):
|
||||||
|
# These are retired Frame-only inputs, never shared console migration files.
|
||||||
|
names = [
|
||||||
|
"frame-schedule-ui",
|
||||||
|
"frame-photos-ui",
|
||||||
|
"frame-final-status.sh",
|
||||||
|
"frame-compose.candidate.private.json",
|
||||||
|
"frame-fresh-compose.private.json",
|
||||||
|
"frame-image.tar",
|
||||||
|
"frame-prepare.sh",
|
||||||
|
"frame-nfs-setup.sh",
|
||||||
|
"frame.unit",
|
||||||
|
"compose.ubuntu-photos-api.yml",
|
||||||
|
]
|
||||||
|
archive = backup / "retired-frame-staging"
|
||||||
|
archive.mkdir(mode=0o700)
|
||||||
|
moved = []
|
||||||
|
for name in names:
|
||||||
|
source = ctx.parent / name
|
||||||
|
if source.exists():
|
||||||
|
assert not source.is_symlink(), name
|
||||||
|
source.rename(archive / name)
|
||||||
|
moved.append(name)
|
||||||
|
for p in archive.rglob("*"):
|
||||||
|
if not p.is_symlink():
|
||||||
|
p.chmod(0o700 if p.is_dir() else 0o600)
|
||||||
|
# Remove only disposable aliases, preserving every recovery reference and image.
|
||||||
|
references = "\n".join(
|
||||||
|
p.read_text(errors="replace")
|
||||||
|
for p in RECOVERY.rglob("*")
|
||||||
|
if p.is_file() and p.suffix in {".json", ".txt"}
|
||||||
|
)
|
||||||
|
removed = []
|
||||||
|
for tag in [
|
||||||
|
"pigway-frame-flow:history-ui-local-base",
|
||||||
|
"pigway-frame-flow:final-audit-local-base",
|
||||||
|
"pigway-frame-flow:0.1.9-5d2171b9be3e",
|
||||||
|
]:
|
||||||
|
tags = run(
|
||||||
|
"docker", "image", "ls", "--format", "{{.Repository}}:{{.Tag}}"
|
||||||
|
).splitlines()
|
||||||
|
if (
|
||||||
|
tag in tags
|
||||||
|
and tag not in references
|
||||||
|
and not run("docker", "ps", "-aq", "--filter", "ancestor=" + tag)
|
||||||
|
):
|
||||||
|
run("docker", "image", "rm", tag)
|
||||||
|
removed.append(tag)
|
||||||
|
return {
|
||||||
|
"archived_frame_inputs": moved,
|
||||||
|
"removed_temporary_aliases": removed,
|
||||||
|
"shared_inputs_and_recovery_preserved": True,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def wait_ready():
|
||||||
|
for attempt in range(30):
|
||||||
|
try:
|
||||||
|
with urllib.request.urlopen(ORIGIN + "/ready", timeout=4) as r:
|
||||||
|
assert json.load(r)["status"] == "ready"
|
||||||
|
break
|
||||||
|
except Exception:
|
||||||
|
if attempt == 29:
|
||||||
|
raise
|
||||||
|
time.sleep(2)
|
||||||
|
|
||||||
|
|
||||||
|
def verify_runtime(commit):
|
||||||
|
c = inspect()
|
||||||
|
env = dict(s.split("=", 1) for s in c["Config"]["Env"])
|
||||||
|
assert env["KOKONNA_MOCK"] == "false"
|
||||||
|
assert env["KOKONNA_WRITE_ENABLED"] == "true"
|
||||||
|
assert env["BUILD_COMMIT"] == commit
|
||||||
|
assert c["State"]["Running"]
|
||||||
|
assert c["Config"]["User"] == "10333:10333"
|
||||||
|
assert c["HostConfig"]["ReadonlyRootfs"]
|
||||||
|
assert set(c["HostConfig"]["CapDrop"]) == {"ALL"}
|
||||||
|
assert {m["Destination"] for m in c["Mounts"]} == {"/data", "/config"}
|
||||||
|
for mount in c["Mounts"]:
|
||||||
|
assert Path(mount["Source"]).resolve() == APP / mount["Destination"][1:]
|
||||||
|
return c
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
assert os.geteuid() == 0, "Run with sudo on the Ubuntu Server"
|
||||||
|
os.umask(0o077)
|
||||||
|
run("/usr/local/libexec/pigway-guard-mount")
|
||||||
|
assert run("findmnt", "-n", "-o", "UUID", "/srv/pigway") == (
|
||||||
|
"00000000-0000-4000-8000-000000000001"
|
||||||
|
)
|
||||||
|
with (RECOVERY / ".release.lock").open("a") as lock:
|
||||||
|
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
||||||
|
release(lock)
|
||||||
|
|
||||||
|
|
||||||
|
def release(lock):
|
||||||
|
ctx = Path(__file__).resolve().parent.parent
|
||||||
|
assert ctx.parent == Path("/srv/pigway/migration-inbox")
|
||||||
|
commit = (ctx / "RELEASE_COMMIT").read_text().strip()
|
||||||
|
assert re.fullmatch("[0-9a-f]{40}", commit)
|
||||||
|
hashes = json.loads((ctx / "RELEASE_HASHES.json").read_text())
|
||||||
|
for name, expected in hashes.items():
|
||||||
|
p = (ctx / name).resolve()
|
||||||
|
assert p.is_relative_to(ctx)
|
||||||
|
assert hashlib.sha256(p.read_bytes()).hexdigest() == expected, name
|
||||||
|
before = inspect()
|
||||||
|
old_env = dict(s.split("=", 1) for s in before["Config"]["Env"])
|
||||||
|
verify_runtime(old_env["BUILD_COMMIT"])
|
||||||
|
assert run("docker", "exec", CONTAINER, "cat", "/app/requirements.lock") == (
|
||||||
|
(ctx / "requirements.lock").read_text().strip()
|
||||||
|
), "Dependencies differ; full build required"
|
||||||
|
stamp = datetime.datetime.now(datetime.timezone.utc).strftime("%Y%m%dT%H%M%SZ")
|
||||||
|
backup = RECOVERY / ("release-" + stamp + "-" + commit[:12])
|
||||||
|
backup.mkdir(mode=0o700)
|
||||||
|
shutil.copy2(APP / "compose.json", backup / "compose.before.json")
|
||||||
|
shutil.copytree(APP / "config", backup / "config")
|
||||||
|
with sqlite3.connect(
|
||||||
|
"file:" + str(APP / "data/frameflow.db") + "?mode=ro", uri=True
|
||||||
|
) as src:
|
||||||
|
with sqlite3.connect(backup / "frameflow.before.db") as dst:
|
||||||
|
src.backup(dst)
|
||||||
|
assert dst.execute("pragma quick_check").fetchone()[0] == "ok"
|
||||||
|
base = "pigway-frame-flow:release-base-" + commit[:12]
|
||||||
|
run("docker", "image", "tag", before["Image"], base)
|
||||||
|
image = "pigway-frame-flow:0.1.9-" + commit[:12]
|
||||||
|
try:
|
||||||
|
run(
|
||||||
|
"docker",
|
||||||
|
"build",
|
||||||
|
"--pull=false",
|
||||||
|
"--network=none",
|
||||||
|
"-f",
|
||||||
|
str(ctx / "deploy/Dockerfile.runtime-update"),
|
||||||
|
"--build-arg",
|
||||||
|
"BASE_IMAGE=" + base,
|
||||||
|
"--build-arg",
|
||||||
|
"BUILD_COMMIT=" + commit,
|
||||||
|
"--build-arg",
|
||||||
|
"BUILD_TIME=" + stamp,
|
||||||
|
"-t",
|
||||||
|
image,
|
||||||
|
str(ctx),
|
||||||
|
)
|
||||||
|
finally:
|
||||||
|
run("docker", "image", "rm", base)
|
||||||
|
compose = json.loads((APP / "compose.json").read_text())
|
||||||
|
service = compose["services"][CONTAINER]
|
||||||
|
service["image"] = image
|
||||||
|
service["environment"]["BUILD_COMMIT"] = commit
|
||||||
|
service["environment"]["BUILD_TIME"] = stamp
|
||||||
|
changed = False
|
||||||
|
try:
|
||||||
|
changed = True
|
||||||
|
(APP / "compose.json").write_text(json.dumps(compose, indent=2) + "\n")
|
||||||
|
print("Restarting Frame Flow; checking " + ORIGIN + "/ready", flush=True)
|
||||||
|
run("systemctl", "restart", "pigway-frame-flow.service")
|
||||||
|
wait_ready()
|
||||||
|
current = verify_runtime(commit)
|
||||||
|
assert current["Image"] == run(
|
||||||
|
"docker", "image", "inspect", "--format", "{{.Id}}", image
|
||||||
|
)
|
||||||
|
# Verify all deployed project files, not just a version string or an image tag.
|
||||||
|
project_hashes = {
|
||||||
|
n: h
|
||||||
|
for n, h in hashes.items()
|
||||||
|
if n.startswith(("pigway_frame_flow/", "vendor/"))
|
||||||
|
or n == "requirements.lock"
|
||||||
|
}
|
||||||
|
code = 'import hashlib,json,pathlib,sys; h=json.load(sys.stdin); assert all(hashlib.sha256((pathlib.Path("/app")/n).read_bytes()).hexdigest()==v for n,v in h.items())'
|
||||||
|
subprocess.run(
|
||||||
|
["docker", "exec", "-i", CONTAINER, "python", "-c", code],
|
||||||
|
input=json.dumps(project_hashes),
|
||||||
|
text=True,
|
||||||
|
check=True,
|
||||||
|
timeout=60,
|
||||||
|
)
|
||||||
|
for name in [
|
||||||
|
"app.js",
|
||||||
|
"features.js",
|
||||||
|
"extensions.js",
|
||||||
|
"i18n.js",
|
||||||
|
"index.html",
|
||||||
|
"style.css",
|
||||||
|
]:
|
||||||
|
url = ORIGIN + "/" + ("" if name == "index.html" else "ui/" + name)
|
||||||
|
with urllib.request.urlopen(url, timeout=10) as response:
|
||||||
|
assert (
|
||||||
|
response.read()
|
||||||
|
== (ctx / "pigway_frame_flow/web" / name).read_bytes()
|
||||||
|
)
|
||||||
|
run("systemctl", "is-active", "pigway-frame-flow.service")
|
||||||
|
except BaseException:
|
||||||
|
print("Release verification failed; restoring previous Compose", flush=True)
|
||||||
|
if changed:
|
||||||
|
shutil.copy2(backup / "compose.before.json", APP / "compose.json")
|
||||||
|
run("systemctl", "restart", "pigway-frame-flow.service")
|
||||||
|
raise
|
||||||
|
shutil.copy2(APP / "compose.json", RECOVERY / "compose.json")
|
||||||
|
(RECOVERY / "image.txt").write_text(image + "\n")
|
||||||
|
shutil.copy2(ctx / "source.tar.gz", backup / "source.tar.gz")
|
||||||
|
cleanup = archive_staging(backup, ctx)
|
||||||
|
receipt = {
|
||||||
|
"result": "PASS",
|
||||||
|
"commit": commit,
|
||||||
|
"image": image,
|
||||||
|
"image_id": current["Image"],
|
||||||
|
"backup": str(backup),
|
||||||
|
"mock": False,
|
||||||
|
"write_enabled": True,
|
||||||
|
"checked_at": stamp,
|
||||||
|
"cleanup": cleanup,
|
||||||
|
}
|
||||||
|
output = APP / "release-verification.json"
|
||||||
|
output.write_text(json.dumps(receipt, indent=2) + "\n")
|
||||||
|
owner = ctx.stat()
|
||||||
|
os.chown(output, owner.st_uid, owner.st_gid)
|
||||||
|
shutil.copy2(output, backup / "release-verification.json")
|
||||||
|
public_receipt = ctx.parent / "frame-release-verification.json"
|
||||||
|
shutil.copy2(output, public_receipt)
|
||||||
|
os.chown(public_receipt, owner.st_uid, owner.st_gid)
|
||||||
|
shutil.rmtree(ctx)
|
||||||
|
print(json.dumps(receipt, indent=2))
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
@@ -1,3 +1,3 @@
|
|||||||
/* Mock vendor expiration must preserve first-party login and show reconnect. */
|
/* Mock vendor expiration must preserve first-party login and show reconnect. */
|
||||||
const assert=require('assert'),{chromium}=require('playwright');
|
const assert=require('assert'),{chromium}=require('playwright');
|
||||||
(async()=>{const browser=await chromium.launch({headless:true,executablePath:'/Applications/Google Chrome.app/Contents/MacOS/Google Chrome'});const page=await browser.newPage();const errors=[];page.on('pageerror',e=>errors.push(e.message));await page.goto('http://127.0.0.1:18787');await page.locator('#username').fill(process.env.FRAME_FLOW_TEST_USERNAME);await page.locator('#password').fill(process.env.FRAME_FLOW_TEST_PASSWORD);await page.locator('#login-form button').click();await page.locator('.hero').waitFor();assert(await page.evaluate(()=>state.settings.mock));await page.route('**/api/v1/devices/*/widgets',r=>r.fulfill({status:401,json:{error:{code:'OFFICIAL_AUTH_REQUIRED',message:'Official account session expired',request_id:'fixture',details:{}}}}));await page.route('**/api/v1/devices/*/official/connection',r=>r.fulfill({json:{authorized:false,username:'fixture',robot_id:null,mock:true,devices:[]}}));await page.locator('[data-page="templates"]').click();await page.locator('.official-content-info summary').click();await page.locator('#official-login-form').waitFor();assert(await page.evaluate(()=>Boolean(state.token&&state.csrf)));assert(await page.evaluate(async()=>Boolean((await api('/api/v1/auth/me')).username)));await page.route('**/api/v1/test-first-party-expired',r=>r.fulfill({status:401,json:{error:{code:'UNAUTHORIZED',message:'Expired',request_id:'fixture',details:{}}}}));await page.evaluate(async()=>{try{await api('/api/v1/test-first-party-expired');}catch{}});assert(await page.evaluate(()=>state.token===''));assert(errors.length===0);await browser.close();console.log('Audit UI: official expiry preserves login, reconnect visible, own expiry clears login; PASS');})().catch(e=>{console.error(e.message);process.exit(1)});
|
(async()=>{const browser=await chromium.launch({headless:true,executablePath:'/Applications/Google Chrome.app/Contents/MacOS/Google Chrome'});const page=await browser.newPage();const errors=[];page.on('pageerror',e=>errors.push(e.message));await page.goto(process.env.FRAME_FLOW_URL||'http://127.0.0.1:6005');await page.locator('#username').fill(process.env.FRAME_FLOW_TEST_USERNAME);await page.locator('#password').fill(process.env.FRAME_FLOW_TEST_PASSWORD);await page.locator('#login-form button').click();await page.locator('.hero').waitFor();assert(await page.evaluate(()=>state.settings.mock));await page.route('**/api/v1/devices/*/widgets',r=>r.fulfill({status:401,json:{error:{code:'OFFICIAL_AUTH_REQUIRED',message:'Official account session expired',request_id:'fixture',details:{}}}}));await page.route('**/api/v1/devices/*/official/connection',r=>r.fulfill({json:{authorized:false,username:'fixture',robot_id:null,mock:true,devices:[]}}));await page.locator('[data-page="templates"]').click();await page.locator('.official-content-info summary').click();await page.locator('#official-login-form').waitFor();assert(await page.evaluate(()=>Boolean(state.token&&state.csrf)));assert(await page.evaluate(async()=>Boolean((await api('/api/v1/auth/me')).username)));await page.route('**/api/v1/test-first-party-expired',r=>r.fulfill({status:401,json:{error:{code:'UNAUTHORIZED',message:'Expired',request_id:'fixture',details:{}}}}));await page.evaluate(async()=>{try{await api('/api/v1/test-first-party-expired');}catch{}});assert(await page.evaluate(()=>state.token===''));assert(errors.length===0);await browser.close();console.log('Audit UI: official expiry preserves login, reconnect visible, own expiry clears login; PASS');})().catch(e=>{console.error(e.message);process.exit(1)});
|
||||||
|
|||||||
@@ -0,0 +1,14 @@
|
|||||||
|
/* Isolated Mock-only automatic collage workflow. */
|
||||||
|
const assert=require('assert');const fs=require('fs');const{chromium}=require('playwright');
|
||||||
|
(async()=>{
|
||||||
|
const base=process.env.FRAME_FLOW_URL;assert(base);const token=fs.readFileSync(process.env.FRAME_FLOW_ENV_FILE,'utf8').split('\n').find(x=>x.startsWith('FRAME_FLOW_TOKEN=')).slice(17);const headers={Authorization:'Bearer '+token};assert((await(await fetch(base+'/api/v1/settings',{headers})).json()).mock===true);
|
||||||
|
const form=new FormData();for(let i=0;i<4;i++)form.append('files',new Blob([Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+a1OIAAAAASUVORK5CYII=','base64')],{type:'image/png'}),'fixture-'+i+'.png');assert((await fetch(base+'/api/v1/layout/images',{method:'POST',headers,body:form})).status===201);
|
||||||
|
const browser=await chromium.launch({executablePath:process.env.CHROME_EXECUTABLE||'/Applications/Google Chrome.app/Contents/MacOS/Google Chrome'});try{
|
||||||
|
const page=await browser.newPage();const errors=[];page.on('pageerror',e=>errors.push(e.message));await page.goto(base);await page.locator('#username').fill(process.env.FRAME_FLOW_TEST_USERNAME);await page.locator('#password').fill(process.env.FRAME_FLOW_TEST_PASSWORD);await page.locator('#login-form button').click();await page.locator('.hero').waitFor();assert(await page.locator('#nav button').first().getAttribute('data-page')==='dashboard');
|
||||||
|
await page.evaluate(()=>navigate('studio'));assert(await page.locator('#studio-plan').isHidden());await page.locator('#collage-ai').uncheck();await page.locator('#collage-count').fill('3');await page.locator('#collage-title').fill('Collage fixture');await page.locator('#auto-collage-form button[type=submit]').click();await page.locator('#collage-image').waitFor({timeout:30000});assert(await page.locator('#collage-display').isVisible());
|
||||||
|
const uploads=await(await fetch(base+'/api/v1/devices/living-room/images',{headers})).json();assert(uploads.length===1,'Preview must not upload');
|
||||||
|
await page.locator('#collage-job').click();await page.locator('[data-job-edit]').last().click();await page.locator('#job-collage-count').waitFor();assert(await page.locator('#job-collage-count').inputValue()==='3');assert(await page.locator('#job-collage-ai').isChecked()===false);await page.locator('#modal-cancel').click();
|
||||||
|
const jobs=await(await fetch(base+'/api/v1/jobs',{headers})).json();const job=jobs.find(j=>j.name==='Collage fixture');assert(job&&job.source.type==='auto_collage'&&job.source.count===3&&!job.enabled);
|
||||||
|
assert.deepStrictEqual(errors,[]);console.log('Automatic collage: 8 workflow checks passed; no frame writes or console errors');
|
||||||
|
}finally{await browser.close();}
|
||||||
|
})().catch(e=>{console.error(e.message);process.exit(1)});
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
/* Copy must describe actual storage targets and actions; run against isolated Mock only. */
|
||||||
|
const assert=require('assert'),fs=require('fs'),vm=require('vm'),{chromium}=require('playwright');
|
||||||
|
const context={};context.window=context;vm.createContext(context);vm.runInContext(fs.readFileSync('pigway_frame_flow/web/i18n.js','utf8'),context);
|
||||||
|
for(const file of ['app.js','features.js','extensions.js'])for(const match of fs.readFileSync('pigway_frame_flow/web/'+file,'utf8').matchAll(/\bt\('([^']+)'\)/g))for(const lang of ['zh','en'])assert(context.MESSAGES[lang][match[1]],`${file}: missing ${lang}.${match[1]}`);
|
||||||
|
(async()=>{const b=await chromium.launch({headless:true,executablePath:'/Applications/Google Chrome.app/Contents/MacOS/Google Chrome'});try{const p=await b.newPage();let deletes=0;await p.route('**/api/v1/assets?*',r=>r.fulfill({json:[{asset_id:'fixture-local',name:'Local fixture',origin:'manual',starred:false,current:true,url:'/fixture.jpg'}]}));p.on('request',r=>{if(r.method()==='DELETE')deletes++;});await p.goto(process.env.FRAME_FLOW_URL||'http://127.0.0.1:6005');await p.locator('#username').fill(process.env.FRAME_FLOW_TEST_USERNAME);await p.locator('#password').fill(process.env.FRAME_FLOW_TEST_PASSWORD);await p.locator('#login-form button').click();await p.locator('.hero').waitFor();assert(await p.evaluate(()=>state.settings.mock));for(const lang of ['zh','en']){await p.evaluate(async lang=>{state.lang=lang;state.tab='local';await navigate('gallery')},lang);await p.locator('[data-delete="0"]').click();assert(await p.locator('#modal-content').textContent().then(x=>x.includes(lang==='zh'?'不会切换画框':'frame display is unchanged')));await p.locator('#modal-cancel').click();assert.equal(await p.locator('label[for="gallery-sort"]').textContent(),lang==='zh'?'排序方式':'Sort order');assert(await p.locator('#gallery-selection-help').textContent().then(x=>x.includes(lang==='zh'?'手动删除仍有效':'manual deletion still applies')));await p.evaluate(()=>navigate('playlists'));await p.locator('#new-playlist').click();assert.equal(await p.locator('label[for="playlist-mode"]').textContent(),lang==='zh'?'播放顺序':'Playback order');await p.locator('#modal-cancel').click();await p.evaluate(()=>navigate('dashboard'));await p.waitForFunction(()=>document.querySelector('#main').textContent.includes(t('weather')));assert(await p.locator('#main').textContent().then(x=>x.includes(lang==='zh'?'型号信息来源':'Model information source')));}assert.equal(deletes,0);console.log('Copy audit PASS: all literal translations present; bilingual sort/playback/model labels, local deletion and star scope verified; no deletions');}finally{await b.close()}})().catch(e=>{console.error(e);process.exit(1)});
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
/* Isolated Mock only: dashboard and gallery share the same read-only image viewer. */
|
||||||
|
const assert=require('assert'),{chromium}=require('playwright');
|
||||||
|
(async()=>{const browser=await chromium.launch({headless:true,executablePath:'/Applications/Google Chrome.app/Contents/MacOS/Google Chrome'});let checks=0;
|
||||||
|
try{for(const width of [1440,768,390]){const p=await browser.newPage({viewport:{width,height:1000}}),errors=[];p.on('pageerror',e=>errors.push(e.message));await p.route('**/api/v1/devices/*/current-content',r=>r.fulfill({json:{image_id:42,preview_url:'/fixture-preview.svg?thumbnail=true',synced:true,source_known:false,overrides:[]}}));await p.route('**/fixture-preview.svg*',r=>r.fulfill({contentType:'image/svg+xml',body:'<svg xmlns="http://www.w3.org/2000/svg" width="1200" height="900"><rect width="1200" height="900" fill="#6c9c83"/><circle cx="600" cy="450" r="220" fill="#e9d9af"/></svg>'}));await p.route('**/api/v1/devices/*/images',r=>r.fulfill({json:[{image_id:42,name:'Fixture gallery',current:true,url:'/fixture-preview.svg'}]}));
|
||||||
|
await p.goto(process.env.FRAME_FLOW_URL||'http://127.0.0.1:6005');await p.locator('#username').fill(process.env.FRAME_FLOW_TEST_USERNAME);await p.locator('#password').fill(process.env.FRAME_FLOW_TEST_PASSWORD);await p.locator('#login-form button').click();await p.locator('#current-frame-preview').waitFor();assert(await p.evaluate(()=>state.settings.mock));
|
||||||
|
for(const lang of ['zh','en'])for(const theme of ['dark','light']){await p.evaluate(async({lang,theme})=>{state.lang=lang;document.documentElement.dataset.theme=theme;await navigate('dashboard')},{lang,theme});await p.waitForFunction(()=>document.querySelector('#current-frame-image')?.naturalWidth===1200);assert(await p.locator('#current-frame-preview').evaluate(e=>e.getBoundingClientRect().height)>=(width<=720?320:400));assert(await p.evaluate(()=>document.documentElement.scrollWidth<=innerWidth));await p.locator('#current-frame-preview').focus();const fullImage=p.waitForRequest(r=>new URL(r.url()).pathname==='/fixture-preview.svg'&&!new URL(r.url()).searchParams.has('thumbnail'));await p.keyboard.press('Enter');await fullImage;await p.locator('dialog.image-viewer[open]').waitFor();await p.waitForFunction(()=>document.querySelector('#original-image')?.naturalWidth===1200);assert.equal(await p.locator('.image-viewer-name').textContent(),(lang==='zh'?'当前显示内容':'Currently displayed content')+' #42');assert.equal(await p.locator('.image-viewer-actions button').count(),3);const sizing=p.locator('.image-viewer-actions button[aria-pressed]');await sizing.nth(1).click();assert(await p.locator('.image-viewer-viewport').evaluate(e=>e.classList.contains('actual-size')));await sizing.nth(0).click();assert(!await p.locator('.image-viewer-viewport').evaluate(e=>e.classList.contains('actual-size')));await p.keyboard.press('Escape');assert(!await p.locator('#modal').evaluate(e=>e.open));await p.waitForFunction(()=>!document.body.classList.contains('image-viewer-open'));if(process.env.FRAME_FLOW_SCREENSHOT_DIR&&lang==='zh'&&theme==='dark'){require('fs').mkdirSync(process.env.FRAME_FLOW_SCREENSHOT_DIR,{recursive:true});await p.screenshot({path:process.env.FRAME_FLOW_SCREENSHOT_DIR+'/dashboard-'+width+'.png',fullPage:true});}await p.evaluate(()=>navigate('gallery'));await p.locator('[data-original="0"]').click();await p.locator('dialog.image-viewer[open]').waitFor();assert.equal(await p.locator('.image-viewer-actions button').count(),3);await p.locator('#modal-cancel').click();checks++;}assert.deepEqual(errors,[]);await p.close();}console.log('Dashboard preview: '+checks+' profiles PASS; larger preview, keyboard opening, shared gallery viewer, fit/actual size, Escape, no overflow');}finally{await browser.close()}})().catch(e=>{console.error(e);process.exit(1)});
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
/* Mock-only: slow device status and cloud metadata must not block real gallery controls. */
|
||||||
|
const assert=require('assert'),fs=require('fs'),{chromium}=require('playwright');
|
||||||
|
(async()=>{const base=process.env.FRAME_FLOW_URL;assert(base);const token=fs.readFileSync(process.env.FRAME_FLOW_ENV_FILE,'utf8').split('\n').find(x=>x.startsWith('FRAME_FLOW_TOKEN=')).slice(17);assert((await(await fetch(base+'/api/v1/settings',{headers:{Authorization:'Bearer '+token}})).json()).mock===true);const b=await chromium.launch({headless:true,executablePath:process.env.CHROME_EXECUTABLE||'/Applications/Google Chrome.app/Contents/MacOS/Google Chrome'});
|
||||||
|
try{const p=await b.newPage({extraHTTPHeaders:{Authorization:'Bearer '+token}}),errors=[];p.on('pageerror',e=>errors.push(e.message));await p.route('**/api/v1/auth/me',r=>r.fulfill({json:{username:'fixture',csrf_token:''}}));let releaseStatus,releaseList;const pending=[];let checks=0;
|
||||||
|
await p.route('**/api/v1/devices',async r=>{pending.push('device');await new Promise(resolve=>releaseStatus=resolve);await r.fulfill({json:[{id:'living-room',name:'Fixture frame'}]});});
|
||||||
|
await p.route('**/api/v1/devices/*/images',async r=>{pending.push('list');await new Promise(resolve=>releaseList=resolve);await r.fulfill({json:[]});});
|
||||||
|
await p.goto(base+'/#gallery');await p.locator('#gallery-search').waitFor({timeout:5000});for(let i=0;i<100&&pending.length<2;i++)await p.waitForTimeout(20);assert.deepEqual(pending.sort(),['device','list']);assert(await p.locator('#gallery-upload').isEnabled());assert(await p.locator('#local-tab').isEnabled());assert.equal(await p.locator('.image-card,.placeholder-line,.image-pending,.page-loading').count(),0);checks++;if(process.env.FRAME_FLOW_SCREENSHOT_DIR){fs.mkdirSync(process.env.FRAME_FLOW_SCREENSHOT_DIR,{recursive:true});await p.screenshot({path:process.env.FRAME_FLOW_SCREENSHOT_DIR+'/gallery-list-pending.png'});}
|
||||||
|
await p.locator('#gallery-search').fill('kept query');await p.locator('#gallery-sort').selectOption('name');releaseStatus();releaseList();await p.waitForFunction(()=>document.querySelector('.gallery')?.getAttribute('aria-busy')==='false');assert.equal(await p.locator('#gallery-search').inputValue(),'kept query');assert.equal(await p.locator('#gallery-sort').inputValue(),'name');assert.equal(await p.locator('.card.empty').count(),1);checks++;
|
||||||
|
assert.deepEqual(errors,[]);console.log('Cold gallery bootstrap:',checks,'checks PASS; device/cloud requests blocked independently, real controls ready, input preserved');
|
||||||
|
}finally{await b.close();}})().catch(e=>{console.error(e.message);process.exit(1)});
|
||||||
@@ -5,7 +5,7 @@ const assert=require('assert'),{chromium}=require('playwright');
|
|||||||
await page.route('**/api/v1/devices/*/images',r=>r.fulfill({json:[{image_id:1,name:'Current fixture',current:true,url:'/mock-image.jpg',created_at:null},{image_id:2,name:'Other fixture',current:false,url:'/mock-image.jpg',created_at:null}]}));
|
await page.route('**/api/v1/devices/*/images',r=>r.fulfill({json:[{image_id:1,name:'Current fixture',current:true,url:'/mock-image.jpg',created_at:null},{image_id:2,name:'Other fixture',current:false,url:'/mock-image.jpg',created_at:null}]}));
|
||||||
page.on('request',r=>{if(r.method()==='POST'&&r.url().endsWith('/display'))writes++;});
|
page.on('request',r=>{if(r.method()==='POST'&&r.url().endsWith('/display'))writes++;});
|
||||||
try{
|
try{
|
||||||
await page.goto('http://127.0.0.1:18787');await page.locator('#username').fill(process.env.FRAME_FLOW_TEST_USERNAME);await page.locator('#password').fill(process.env.FRAME_FLOW_TEST_PASSWORD);await page.locator('#login-form button').click();await page.locator('.hero').waitFor();assert(await page.evaluate(()=>state.settings.mock));
|
await page.goto(process.env.FRAME_FLOW_URL||'http://127.0.0.1:6005');await page.locator('#username').fill(process.env.FRAME_FLOW_TEST_USERNAME);await page.locator('#password').fill(process.env.FRAME_FLOW_TEST_PASSWORD);await page.locator('#login-form button').click();await page.locator('.hero').waitFor();assert(await page.evaluate(()=>state.settings.mock));
|
||||||
for(const lang of ['zh','en'])for(const width of [1440,390])for(const theme of ['dark','light']){
|
for(const lang of ['zh','en'])for(const width of [1440,390])for(const theme of ['dark','light']){
|
||||||
await page.setViewportSize({width,height:1000});await page.evaluate(({lang,theme})=>{state.lang=lang;document.documentElement.dataset.theme=theme;shell();},{lang,theme});await page.locator('[data-page="gallery"]').click();await page.locator('[data-show="0"]').waitFor();assert(await page.locator('[data-show="0"]').isDisabled());assert(await page.locator('[data-show="0"]').textContent()===(lang==='zh'?'当前图片':'Current image'));assert(await page.locator('[data-show="1"]').isEnabled());await page.locator('[data-show="0"]').evaluate(b=>b.onclick());assert(!await page.locator('#modal').evaluate(d=>d.open));assert(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth));checks++;
|
await page.setViewportSize({width,height:1000});await page.evaluate(({lang,theme})=>{state.lang=lang;document.documentElement.dataset.theme=theme;shell();},{lang,theme});await page.locator('[data-page="gallery"]').click();await page.locator('[data-show="0"]').waitFor();assert(await page.locator('[data-show="0"]').isDisabled());assert(await page.locator('[data-show="0"]').textContent()===(lang==='zh'?'当前图片':'Current image'));assert(await page.locator('[data-show="1"]').isEnabled());await page.locator('[data-show="0"]').evaluate(b=>b.onclick());assert(!await page.locator('#modal').evaluate(d=>d.open));assert(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth));checks++;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,18 @@
|
|||||||
|
/* Mock-only: real writable destinations, concrete names and responsive labels. */
|
||||||
|
const assert=require('assert'),fs=require('fs'),{chromium}=require('playwright');
|
||||||
|
(async()=>{
|
||||||
|
const base=process.env.FRAME_FLOW_URL;assert(base);const token=fs.readFileSync(process.env.FRAME_FLOW_ENV_FILE,'utf8').split('\n').find(x=>x.startsWith('FRAME_FLOW_TOKEN=')).slice(17);
|
||||||
|
assert((await(await fetch(base+'/api/v1/settings',{headers:{Authorization:'Bearer '+token}})).json()).mock===true);
|
||||||
|
const browser=await chromium.launch({headless:true,executablePath:process.env.CHROME_EXECUTABLE||'/Applications/Google Chrome.app/Contents/MacOS/Google Chrome'});
|
||||||
|
try{
|
||||||
|
const page=await browser.newPage();const errors=[];page.on('pageerror',e=>errors.push(e.message));await page.goto(base);await page.locator('#username').fill(process.env.FRAME_FLOW_TEST_USERNAME);await page.locator('#password').fill(process.env.FRAME_FLOW_TEST_PASSWORD);await page.locator('#login-form button').click();await page.locator('.hero').waitFor();
|
||||||
|
await page.evaluate(()=>{state.settings.storage_name='FixtureNAS';state.settings.gallery_destinations=[{id:'cloud',adapter:'kokonna',name:'KoKonna',storage:'cloud',connected:true,supports_upload:true},{id:'local',adapter:'local-assets',name:'FixtureNAS',storage:'local',connected:true,supports_upload:true},{id:'read-only-drive',adapter:'kokonna',name:'Read-only fixture',storage:'cloud',connected:true,supports_upload:false},{id:'offline-drive',adapter:'kokonna',name:'Offline fixture',storage:'cloud',connected:false,supports_upload:true},{id:'unimplemented-drive',adapter:'unimplemented',name:'Future fixture',storage:'cloud',connected:true,supports_upload:true}];});let checks=0;
|
||||||
|
for(const width of [320,390,768,1440])for(const lang of ['zh','en'])for(const theme of ['light','dark']){
|
||||||
|
await page.setViewportSize({width,height:900});await page.evaluate(({lang,theme})=>{state.lang=lang;document.documentElement.dataset.theme=theme;return navigate('gallery');},{lang,theme});
|
||||||
|
assert.equal(await page.locator('#cloud-tab').innerText(),lang==='zh'?'KoKonna 云端图库':'KoKonna cloud gallery');assert.equal(await page.locator('#local-tab').innerText(),lang==='zh'?'FixtureNAS 本地图库':'FixtureNAS Local gallery');assert.equal(await page.locator('[data-gallery-destination]').count(),2);assert(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth));checks++;
|
||||||
|
}
|
||||||
|
await page.setViewportSize({width:320,height:740});await page.evaluate(()=>{state.settings.gallery_destinations.find(d=>d.id==='local').name='家庭照片存储服务器名称很长的NAS';return navigate('gallery');});assert(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth));checks++;
|
||||||
|
await page.locator('#local-tab').click();assert.equal(await page.evaluate(()=>state.tab),'local');await page.locator('#cloud-tab').click();assert.equal(await page.evaluate(()=>state.tab),'cloud');checks++;
|
||||||
|
assert.deepEqual(errors,[]);console.log('Gallery destinations:',checks,'checks PASS; concrete labels, capability/connection/adapter gates, responsive layout and tab switching');
|
||||||
|
}finally{await browser.close();}
|
||||||
|
})().catch(e=>{console.error(e.message);process.exit(1)});
|
||||||
@@ -6,10 +6,13 @@ const assert=require('assert'),{chromium}=require('playwright');
|
|||||||
await page.route('**/api/v1/assets/local-1/star',r=>{starred=r.request().postDataJSON().starred;return r.fulfill({json:{starred,expires_at:null}});});
|
await page.route('**/api/v1/assets/local-1/star',r=>{starred=r.request().postDataJSON().starred;return r.fulfill({json:{starred,expires_at:null}});});
|
||||||
page.on('request',r=>{if(r.method()==='POST'&&r.url().endsWith('/display'))writes++;});
|
page.on('request',r=>{if(r.method()==='POST'&&r.url().endsWith('/display'))writes++;});
|
||||||
try{
|
try{
|
||||||
await page.goto('http://127.0.0.1:18787');await page.locator('#username').fill(process.env.FRAME_FLOW_TEST_USERNAME);await page.locator('#password').fill(process.env.FRAME_FLOW_TEST_PASSWORD);await page.locator('#login-form button').click();await page.locator('.hero').waitFor();assert(await page.evaluate(()=>state.settings.mock));
|
await page.goto(process.env.FRAME_FLOW_URL||'http://127.0.0.1:6005');await page.locator('#username').fill(process.env.FRAME_FLOW_TEST_USERNAME);await page.locator('#password').fill(process.env.FRAME_FLOW_TEST_PASSWORD);await page.locator('#login-form button').click();await page.locator('.hero').waitFor();assert(await page.evaluate(()=>state.settings.mock));
|
||||||
for(const lang of ['zh','en'])for(const width of [1440,390])for(const theme of ['dark','light']){
|
for(const lang of ['zh','en'])for(const width of [1440,390])for(const theme of ['dark','light']){
|
||||||
await page.setViewportSize({width,height:1000});await page.evaluate(({lang,theme})=>{state.lang=lang;document.documentElement.dataset.theme=theme;shell();},{lang,theme});await page.locator('[data-page="gallery"]').click();await page.locator('#local-tab').click();await page.locator('[data-show="0"]').waitFor();const star=page.locator('.image-card').first().locator('button[aria-pressed]');assert(await star.count()===1);const original=await star.getAttribute('aria-pressed');await star.click();await page.waitForFunction(expected=>document.querySelector('.image-card button[aria-pressed]')?.getAttribute('aria-pressed')===expected,original==='true'?'false':'true');assert(await page.locator('[data-show="0"]').isDisabled());assert(await page.locator('[data-show="0"]').textContent()===(lang==='zh'?'当前图片':'Current image'));assert(await page.locator('[data-show="1"]').isEnabled());await page.locator('[data-show="0"]').evaluate(b=>b.onclick());assert(!await page.locator('#modal').evaluate(d=>d.open));assert(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth));checks++;
|
await page.setViewportSize({width,height:1000});await page.evaluate(({lang,theme})=>{state.lang=lang;document.documentElement.dataset.theme=theme;shell();},{lang,theme});await page.locator('[data-page="gallery"]').click();await page.locator('#local-tab').click();await page.locator('[data-show="0"]').waitFor();const boxes=page.locator('.asset-select');const selected=()=>boxes.evaluateAll(xs=>xs.map(x=>x.checked));
|
||||||
|
assert.equal(await page.locator('#asset-invert').textContent(),lang==='zh'?'反选':'Invert selection');await boxes.nth(0).check();await page.locator('#asset-invert').click();assert.deepEqual(await selected(),[false,true]);await page.locator('#asset-invert').click();assert.deepEqual(await selected(),[true,false]);
|
||||||
|
await page.locator('#gallery-search').fill('Current fixture');await page.locator('#asset-invert').click();assert.deepEqual(await selected(),[false,false]);await page.locator('#asset-invert').click();assert.deepEqual(await selected(),[true,false]);await page.locator('#gallery-search').fill('no matching fixture');await page.locator('#asset-invert').click();assert.deepEqual(await selected(),[true,false]);await page.locator('#gallery-search').fill('');await page.locator('#asset-all').click();assert.deepEqual(await selected(),[true,true]);await page.locator('#asset-invert').click();assert.deepEqual(await selected(),[false,false]);
|
||||||
|
const star=page.locator('.image-card').first().locator('button[aria-pressed]');assert(await star.count()===1);const original=await star.getAttribute('aria-pressed');await star.click();await page.waitForFunction(expected=>document.querySelector('.image-card button[aria-pressed]')?.getAttribute('aria-pressed')===expected,original==='true'?'false':'true');assert(await page.locator('[data-show="0"]').isDisabled());assert(await page.locator('[data-show="0"]').textContent()===(lang==='zh'?'当前图片':'Current image'));assert(await page.locator('[data-show="1"]').isEnabled());await page.locator('[data-show="0"]').evaluate(b=>b.onclick());assert(!await page.locator('#modal').evaluate(d=>d.open));assert(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth));checks++;
|
||||||
}
|
}
|
||||||
assert(writes===0);console.log('Current-image gallery button: '+checks+' profiles passed; disabled label, other image enabled, no display request');
|
assert(writes===0);console.log('Gallery inversion and current-image star: '+checks+' profiles passed; disabled label, other image enabled, no display request');
|
||||||
}finally{await browser.close();}
|
}finally{await browser.close();}
|
||||||
})().catch(e=>{console.error(e);process.exit(1)});
|
})().catch(e=>{console.error(e);process.exit(1)});
|
||||||
|
|||||||
@@ -1,3 +1,3 @@
|
|||||||
/* Mock history fixtures only; verifies long identifiers and detail actions. */
|
/* Mock history fixtures only; verifies long identifiers and detail actions. */
|
||||||
const assert=require('assert'),{chromium}=require('playwright');
|
const assert=require('assert'),{chromium}=require('playwright');
|
||||||
(async()=>{const browser=await chromium.launch({headless:true,executablePath:'/Applications/Google Chrome.app/Contents/MacOS/Google Chrome'});const page=await browser.newPage();const op={operation_id:'a'.repeat(64),request_id:'b'.repeat(64),action:'render',device_id:'living-room',client_id:'user:way',created_at:'2026-10-05T00:28:05Z',status:'COMPLETED',result:{asset_id:'c'.repeat(64)}};await page.route('**/api/v1/operations',r=>r.fulfill({json:[op,op]}));await page.route('**/api/v1/operations/'+op.operation_id,r=>r.fulfill({json:op}));await page.goto('http://127.0.0.1:18787');await page.locator('#username').fill(process.env.FRAME_FLOW_TEST_USERNAME);await page.locator('#password').fill(process.env.FRAME_FLOW_TEST_PASSWORD);await page.locator('#login-form button').click();await page.locator('.hero').waitFor();let checks=0;for(const lang of ['zh','en'])for(const width of [1440,768,390])for(const theme of ['dark','light']){await page.setViewportSize({width,height:1000});await page.evaluate(({lang,theme})=>{state.lang=lang;document.documentElement.dataset.theme=theme;shell();},{lang,theme});await page.locator('[data-page="history"]').click();await page.locator('.history-actions button').first().waitFor();assert(await page.evaluate(()=>{const table=document.querySelector('.history-table');return table.querySelectorAll('th').length===7&&[...table.querySelectorAll('tbody tr')].every(row=>row.children.length===7&&row.lastElementChild.classList.contains('history-actions')&&row.lastElementChild.previousElementSibling.querySelector('button')===null)&&document.documentElement.scrollWidth<=innerWidth;}));await page.locator('.history-actions button').first().click();await page.locator('#modal[open]').waitFor();await page.locator('#modal-cancel').click();checks++;}await browser.close();console.log('History layout and detail dialog: '+checks+' passed');})().catch(e=>{console.error(e);process.exit(1)});
|
(async()=>{const browser=await chromium.launch({headless:true,executablePath:'/Applications/Google Chrome.app/Contents/MacOS/Google Chrome'});const page=await browser.newPage();const op={operation_id:'a'.repeat(64),request_id:'b'.repeat(64),action:'render',device_id:'living-room',client_id:'user:way',created_at:'2026-10-05T00:28:05Z',status:'COMPLETED',result:{asset_id:'c'.repeat(64)}};await page.route('**/api/v1/operations',r=>r.fulfill({json:[op,op]}));await page.route('**/api/v1/operations/'+op.operation_id,r=>r.fulfill({json:op}));await page.goto(process.env.FRAME_FLOW_URL||'http://127.0.0.1:6005');await page.locator('#username').fill(process.env.FRAME_FLOW_TEST_USERNAME);await page.locator('#password').fill(process.env.FRAME_FLOW_TEST_PASSWORD);await page.locator('#login-form button').click();await page.locator('.hero').waitFor();let checks=0;for(const lang of ['zh','en'])for(const width of [1440,768,390])for(const theme of ['dark','light']){await page.setViewportSize({width,height:1000});await page.evaluate(({lang,theme})=>{state.lang=lang;document.documentElement.dataset.theme=theme;shell();},{lang,theme});await page.locator('[data-page="history"]').click();await page.locator('.history-actions button').first().waitFor();assert(await page.evaluate(()=>{const table=document.querySelector('.history-table');return table.querySelectorAll('th').length===7&&[...table.querySelectorAll('tbody tr')].every(row=>row.children.length===7&&row.lastElementChild.classList.contains('history-actions')&&row.lastElementChild.previousElementSibling.querySelector('button')===null)&&document.documentElement.scrollWidth<=innerWidth;}));await page.locator('.history-actions button').first().click();await page.locator('#modal[open]').waitFor();await page.locator('#modal-cancel').click();checks++;}await browser.close();console.log('History layout and detail dialog: '+checks+' passed');})().catch(e=>{console.error(e);process.exit(1)});
|
||||||
|
|||||||
@@ -0,0 +1,17 @@
|
|||||||
|
const {chromium}=require('playwright');const fs=require('fs'),path=require('path'),assert=require('assert');
|
||||||
|
const root=path.join(__dirname,'../pigway_frame_flow/web');
|
||||||
|
(async()=>{const b=await chromium.launch({headless:true,executablePath:'/Applications/Google Chrome.app/Contents/MacOS/Google Chrome'});try{for(const width of [1440,768,390])for(const lang of ['zh','en']){
|
||||||
|
const p=await b.newPage({viewport:{width,height:900}});let errors=[];p.on('pageerror',e=>errors.push(e.message));let saved;
|
||||||
|
await p.addInitScript(lang=>localStorage.setItem('ff-language',lang),lang);
|
||||||
|
await p.route('**/*',async r=>{const u=new URL(r.request().url());if(u.pathname.startsWith('/api/')){
|
||||||
|
if(['PUT','POST'].includes(r.request().method())){saved=r.request().postDataJSON();return r.fulfill({json:{}})}
|
||||||
|
if(['/api/v1/jobs','/api/v1/assets','/api/v1/devices/living-room/images'].includes(u.pathname))return r.fulfill({json:[]});
|
||||||
|
if(u.pathname==='/api/v1/photo-sources')return r.fulfill({json:[]});
|
||||||
|
if(u.pathname==='/api/v1/integrations/synology-photos')return r.fulfill({json:{configured:true,connected:true}});
|
||||||
|
if(u.pathname.endsWith('/people'))return r.fulfill({json:[{id:1,name:'Test Person',count:5}]});
|
||||||
|
return r.fulfill({status:401,json:{error:{code:'UNAUTHORIZED',message:'Sign in required'}}});}
|
||||||
|
const f=u.pathname==='/'?'index.html':u.pathname.replace(/^\/ui\//,'');return r.fulfill({body:fs.readFileSync(path.join(root,f)),contentType:f.endsWith('.js')?'application/javascript':f.endsWith('.css')?'text/css':'text/html'});});
|
||||||
|
await p.goto('http://frame.test/');await p.locator('#login-form').waitFor();
|
||||||
|
await p.evaluate(async()=>{const previous=api;api=async()=>[{operation_id:'fixture',action:'display',device_id:'living-room',status:'FAILED',client_id:'scheduler',error:{code:'WRITE_DISABLED'},request_id:'fixture'}];state.devices=[{id:'living-room',name:'living-room'}];try{await views.history(state.epoch);}finally{api=previous;}});
|
||||||
|
const text=await p.locator('#main').innerText();assert(!text.includes('living-room'));assert(!text.includes('WRITE_DISABLED'));assert(text.includes(lang==='zh'?'客厅':'Living room'));assert(text.includes(lang==='zh'?'显示图片':'Display image'));assert(text.includes(lang==='zh'?'自动调度':'Scheduler'));assert.equal(errors.length,0);console.log('PASS history',width,lang);await p.close();
|
||||||
|
}}finally{await b.close()}})().catch(e=>{console.error(e);process.exit(1)});
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
/* Isolated Mock UI audit: delayed images stay inside their own placeholders. */
|
||||||
|
const assert=require('assert');
|
||||||
|
const fs=require('fs');
|
||||||
|
const {chromium}=require('playwright');
|
||||||
|
(async()=>{
|
||||||
|
const base=process.env.FRAME_FLOW_URL;assert(base);
|
||||||
|
const token=fs.readFileSync(process.env.FRAME_FLOW_ENV_FILE,'utf8').split('\n').find(x=>x.startsWith('FRAME_FLOW_TOKEN=')).slice(17);
|
||||||
|
assert((await(await fetch(base+'/api/v1/settings',{headers:{Authorization:'Bearer '+token}})).json()).mock===true);
|
||||||
|
const browser=await chromium.launch({headless:true,executablePath:process.env.CHROME_EXECUTABLE||'/Applications/Google Chrome.app/Contents/MacOS/Google Chrome'});
|
||||||
|
try{
|
||||||
|
const page=await browser.newPage();const errors=[];page.on('pageerror',e=>errors.push(e.message));
|
||||||
|
await page.route('**/api/v1/devices/*/images',r=>r.fulfill({json:[{image_id:1,name:'Loading fixture',url:'/ui-audit-image.svg',current:false}]}));
|
||||||
|
let release;let requested;
|
||||||
|
await page.route('**/ui-audit-image.svg*',async r=>{requested();await new Promise(resolve=>release=resolve);await r.fulfill({contentType:'image/svg+xml',body:'<svg xmlns="http://www.w3.org/2000/svg" width="300" height="400"><rect width="300" height="400" fill="#167253"/></svg>'});});
|
||||||
|
await page.goto(base);await page.locator('#username').fill(process.env.FRAME_FLOW_TEST_USERNAME);await page.locator('#password').fill(process.env.FRAME_FLOW_TEST_PASSWORD);await page.locator('#login-form button').click();await page.locator('.hero').waitFor();
|
||||||
|
let checks=0;
|
||||||
|
async function centered(){
|
||||||
|
const result=await page.locator('.image-loading').evaluate(box=>{
|
||||||
|
const spinner=box.querySelector('.spinner'),img=box.querySelector('img'),a=box.getBoundingClientRect(),b=spinner.getBoundingClientRect();
|
||||||
|
return {centered:Math.abs(a.x+a.width/2-b.x-b.width/2)<1&&Math.abs(a.y+a.height/2-b.y-b.height/2)<1,hidden:getComputedStyle(img).visibility==='hidden',contained:box.querySelector('.image-loading-status').offsetParent===box,overflow:document.documentElement.scrollWidth>innerWidth};
|
||||||
|
});assert.deepStrictEqual(result,{centered:true,hidden:true,contained:true,overflow:false});checks++;
|
||||||
|
assert.equal(await page.locator('.spinner:not(.image-loading .spinner)').count(),0);checks++;
|
||||||
|
}
|
||||||
|
for(const width of [1440,768,390])for(const theme of ['light','dark']){
|
||||||
|
await page.setViewportSize({width,height:900});await page.evaluate(theme=>document.documentElement.dataset.theme=theme,theme);
|
||||||
|
const request=new Promise(resolve=>requested=resolve);await page.evaluate(()=>navigate('gallery'));await request;await centered();
|
||||||
|
const before=await page.locator('.image-loading').boundingBox();release();await page.waitForFunction(()=>document.querySelector('.thumb')?.naturalWidth===300&&!document.querySelector('.image-loading'));
|
||||||
|
const after=await page.locator('.thumb').boundingBox();assert(Math.abs(before.height-after.height)<1,'Thumbnail placeholder changes height');checks++;
|
||||||
|
const originalRequest=new Promise(resolve=>requested=resolve);await page.locator('[data-original]').click();await originalRequest;await centered();release();await page.waitForFunction(()=>document.querySelector('#original-image')?.naturalWidth===300&&!document.querySelector('.image-loading'));await page.locator('#modal-cancel').click();checks++;
|
||||||
|
await page.evaluate(async()=>{const img=document.querySelector('.thumb');await blobImage(img,'/ui-audit-missing-image');});
|
||||||
|
assert.equal(await page.locator('.image-load-error').count(),1);assert.equal(await page.locator('.image-load-error .spinner').count(),0);assert(await page.locator('.image-load-error').innerText());checks++;
|
||||||
|
}
|
||||||
|
await page.evaluate(()=>navigate('connections'));
|
||||||
|
assert.deepStrictEqual(await page.locator('#main input,#main select,#main textarea').evaluateAll(nodes=>nodes.filter(e=>e.checkVisibility()&&!e.labels.length&&!e.getAttribute('aria-label')&&!e.getAttribute('aria-labelledby')).map(e=>e.id)),[]);checks++;
|
||||||
|
assert.equal(await page.locator('nav [aria-current="page"]').count(),1);checks++;
|
||||||
|
const nav=await page.locator('nav button').evaluateAll(nodes=>nodes.map(e=>({height:e.getBoundingClientRect().height,nowrap:getComputedStyle(e).whiteSpace})));assert(nav.every(e=>e.height>=44&&e.nowrap==='nowrap'));checks++;
|
||||||
|
assert.deepStrictEqual(errors,[]);console.log('Image/UI consistency audit:',checks,'passed; desktop/tablet/mobile, light/dark; no page errors');
|
||||||
|
}finally{await browser.close();}
|
||||||
|
})().catch(e=>{console.error(e);process.exit(1)});
|
||||||
@@ -12,13 +12,13 @@ const assert=require('assert');const fs=require('fs');const {chromium}=require('
|
|||||||
for(const width of [1440,768,390])for(const lang of ['zh','en'])for(const theme of ['light','dark']){
|
for(const width of [1440,768,390])for(const lang of ['zh','en'])for(const theme of ['light','dark']){
|
||||||
await page.setViewportSize({width,height:900});await page.evaluate(({lang,theme})=>{state.lang=lang;document.documentElement.dataset.theme=theme;shell();},{lang,theme});
|
await page.setViewportSize({width,height:900});await page.evaluate(({lang,theme})=>{state.lang=lang;document.documentElement.dataset.theme=theme;shell();},{lang,theme});
|
||||||
for(const view of ['studio','connections']){
|
for(const view of ['studio','connections']){
|
||||||
await page.evaluate(view=>navigate(view),view);await page.locator(view==='studio'?'#studio-plan':'#mqtt-config').waitFor();
|
await page.evaluate(view=>navigate(view),view);if(view==='studio')await page.locator('.manual-collage summary').click();await page.locator(view==='studio'?'#studio-plan':'#mqtt-config').waitFor();
|
||||||
assert(await page.evaluate(()=>document.documentElement.scrollWidth<=window.innerWidth),view+' overflow '+width);checks++;
|
assert(await page.evaluate(()=>document.documentElement.scrollWidth<=window.innerWidth),view+' overflow '+width);checks++;
|
||||||
const gaps=await page.locator('.actions').evaluateAll(rows=>rows.flatMap(row=>{const nodes=[...row.querySelectorAll('button')];return nodes.slice(1).map((node,i)=>{const a=nodes[i].getBoundingClientRect(),b=node.getBoundingClientRect();return Math.abs(a.top-b.top)<4?b.left-a.right:b.top-a.bottom;});}));
|
const gaps=await page.locator('.actions').evaluateAll(rows=>rows.flatMap(row=>{const nodes=[...row.querySelectorAll('button')];return nodes.slice(1).map((node,i)=>{const a=nodes[i].getBoundingClientRect(),b=node.getBoundingClientRect();return Math.abs(a.top-b.top)<4?b.left-a.right:b.top-a.bottom;});}));
|
||||||
assert(gaps.every(g=>g>=8),view+' buttons touch '+width);checks++;
|
assert(gaps.every(g=>g>=8),view+' buttons touch '+width);checks++;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
await page.evaluate(()=>navigate('studio'));await page.locator('#studio-files').setInputFiles({name:'fixture.png',mimeType:'image/png',buffer:Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+a1OIAAAAASUVORK5CYII=','base64')});
|
await page.evaluate(()=>navigate('studio'));await page.locator('.manual-collage summary').click();await page.locator('#studio-files').setInputFiles({name:'fixture.png',mimeType:'image/png',buffer:Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+a1OIAAAAASUVORK5CYII=','base64')});
|
||||||
await page.locator('#studio-assets input:checked').waitFor();await page.locator('#studio-plan').click();await page.locator('#studio-layout img').waitFor();await page.locator('#studio-render').click();await page.locator('#studio-result').waitFor({timeout:30000});assert(await page.locator('#studio-download').isEnabled());checks++;
|
await page.locator('#studio-assets input:checked').waitFor();await page.locator('#studio-plan').click();await page.locator('#studio-layout img').waitFor();await page.locator('#studio-render').click();await page.locator('#studio-result').waitFor({timeout:30000});assert(await page.locator('#studio-download').isEnabled());checks++;
|
||||||
await page.locator('#studio-title').fill('Changed');assert(await page.locator('#studio-display').isDisabled());checks++;
|
await page.locator('#studio-title').fill('Changed');assert(await page.locator('#studio-display').isDisabled());checks++;
|
||||||
assert.deepStrictEqual(errors,[]);checks++;
|
assert.deepStrictEqual(errors,[]);checks++;
|
||||||
|
|||||||
@@ -0,0 +1,28 @@
|
|||||||
|
const {chromium}=require('playwright');const fs=require('fs'),path=require('path'),assert=require('assert');
|
||||||
|
const root=path.join(__dirname,'../pigway_frame_flow/web');
|
||||||
|
(async()=>{const b=await chromium.launch({headless:true,executablePath:'/Applications/Google Chrome.app/Contents/MacOS/Google Chrome'});try{for(const width of [1440,768,390])for(const lang of ['zh','en']){
|
||||||
|
const p=await b.newPage({viewport:{width,height:900}});let errors=[];p.on('pageerror',e=>errors.push(e.message));let saved;
|
||||||
|
await p.addInitScript(lang=>localStorage.setItem('ff-language',lang),lang);
|
||||||
|
await p.route('**/*',async r=>{const u=new URL(r.request().url());if(u.pathname.startsWith('/api/')){
|
||||||
|
if(['PUT','POST'].includes(r.request().method())){saved=r.request().postDataJSON();return r.fulfill({json:{}})}
|
||||||
|
if(['/api/v1/jobs','/api/v1/assets','/api/v1/devices/living-room/images'].includes(u.pathname))return r.fulfill({json:[]});
|
||||||
|
if(u.pathname==='/api/v1/photo-sources')return r.fulfill({json:[]});
|
||||||
|
if(u.pathname==='/api/v1/integrations/synology-photos')return r.fulfill({json:{configured:true,connected:true}});
|
||||||
|
if(u.pathname.endsWith('/people'))return r.fulfill({json:[{id:1,name:'Test Person',count:5}]});
|
||||||
|
return r.fulfill({status:401,json:{error:{code:'UNAUTHORIZED',message:'Sign in required'}}});}
|
||||||
|
const f=u.pathname==='/'?'index.html':u.pathname.replace(/^\/ui\//,'');return r.fulfill({body:fs.readFileSync(path.join(root,f)),contentType:f.endsWith('.js')?'application/javascript':f.endsWith('.css')?'text/css':'text/html'});});
|
||||||
|
await p.goto('http://frame.test/');await p.locator('#login-form').waitFor();
|
||||||
|
await p.evaluate(async()=>{state.templates=[{id:'daily-dashboard',name:'Dashboard',defaults:{}}];await jobEditor();});
|
||||||
|
for(const unit of ['hours','minutes']){
|
||||||
|
await p.locator('#job-schedule').selectOption(unit);await p.locator('#schedule-value').fill('2');
|
||||||
|
assert.equal(await p.locator('#schedule-value').getAttribute('type'),'number');
|
||||||
|
assert(await p.locator('#schedule-hint').innerText());
|
||||||
|
}
|
||||||
|
assert(!await p.evaluate(()=>document.documentElement.scrollWidth>innerWidth));
|
||||||
|
await p.locator('#job-name').fill('Test interval');
|
||||||
|
await p.locator('#job-form button[type=submit]').click();await p.waitForTimeout(100);
|
||||||
|
assert(saved);assert.deepEqual(saved.schedule,{type:'interval',interval_minutes:2});
|
||||||
|
await p.evaluate(async()=>{await jobEditor({id:'existing',name:'Existing',schedule:{type:'interval',interval_minutes:120},source:{type:'template',template:'daily-dashboard',data:{}},enabled:false,display_duration:0,restore_previous:false,priority:50});});
|
||||||
|
assert.equal(await p.locator('#job-schedule').inputValue(),'hours');assert.equal(await p.locator('#schedule-value').inputValue(),'2');
|
||||||
|
await p.evaluate(()=>{state.devices=[{id:'living-room',name:'我的相框'}];});assert.equal(await p.evaluate(()=>deviceDisplayName(state.devices[0])),'我的相框');assert.equal(await p.evaluate(()=>deviceDisplayName({id:'living-room',name:'living-room'})),lang==='zh'?'客厅':'Living room');await p.locator('#modal-cancel').click();await p.evaluate(async()=>{const previous=api;api=async()=>[{id:'fixture',name:'Family',device_id:'living-room',schedule:{type:'interval',interval_minutes:120},enabled:false}];try{await views.automation(state.epoch);}finally{api=previous;}});assert.equal(await p.locator('tbody td small').first().innerText(),'我的相框');assert.equal(errors.length,0,errors.join('\n'));console.log('PASS',width,lang);await p.close();
|
||||||
|
}}finally{await b.close()}})().catch(e=>{console.error(e);process.exit(1)});
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
/* Full-page and modal layout audit in an isolated Mock service only. */
|
||||||
|
const assert=require('assert');const fs=require('fs');const {chromium}=require('playwright');
|
||||||
|
(async()=>{
|
||||||
|
const base=process.env.FRAME_FLOW_URL;assert(base);const token=fs.readFileSync(process.env.FRAME_FLOW_ENV_FILE,'utf8').split('\n').find(x=>x.startsWith('FRAME_FLOW_TOKEN=')).slice(17);
|
||||||
|
assert((await (await fetch(base+'/api/v1/settings',{headers:{Authorization:'Bearer '+token}})).json()).mock===true);
|
||||||
|
const browser=await chromium.launch({headless:true,executablePath:process.env.CHROME_EXECUTABLE||'/Applications/Google Chrome.app/Contents/MacOS/Google Chrome'});
|
||||||
|
try{
|
||||||
|
const page=await browser.newPage();const errors=[];page.on('pageerror',e=>errors.push(e.message));let connected=false;let logins=0;
|
||||||
|
await page.route('**/api/v1/integrations/synology-photos',async route=>{if(route.request().method()==='POST'){assert.deepStrictEqual(route.request().postDataJSON(),{username:'fixture-nas',password:'fixture-only'});connected=true;logins++;}await route.fulfill({json:{configured:true,connected}});});
|
||||||
|
await page.route('**/api/v1/photo-sources',async route=>{assert(route.request().method()==='GET');await route.fulfill({json:[{id:'fixture-source',name:'NAS photos / NAS 照片',kind:'local',location:'.',enabled:false,people_filter:true,orientation:'auto'}]});});
|
||||||
|
await page.goto(base);await page.locator('#username').fill(process.env.FRAME_FLOW_TEST_USERNAME);await page.locator('#password').fill(process.env.FRAME_FLOW_TEST_PASSWORD);await page.locator('#login-form button').click();await page.locator('.hero').waitFor();
|
||||||
|
const viewports=process.env.FRAME_FLOW_VIEWPORTS?JSON.parse(process.env.FRAME_FLOW_VIEWPORTS):[1440,768,390].map(width=>({width,height:900}));
|
||||||
|
let checks=0;const failures=[];const out=process.env.FRAME_FLOW_SCREENSHOT_DIR;if(out)fs.mkdirSync(out,{recursive:true});
|
||||||
|
async function inspect(label){
|
||||||
|
const result=await page.evaluate(()=>{
|
||||||
|
const root=document.querySelector('dialog[open]')||document.querySelector('#main');const controls=[...root.querySelectorAll('button,select,input:not([type=checkbox]):not([type=radio]):not([type=file]),textarea')].filter(e=>e.checkVisibility({checkOpacity:true,checkVisibilityCSS:true})&&!e.closest('[hidden]')).map(e=>({id:e.id||e.textContent.trim().slice(0,24),r:e.getBoundingClientRect()}));const close=[];
|
||||||
|
for(let i=0;i<controls.length;i++)for(let j=i+1;j<controls.length;j++){const a=controls[i].r,b=controls[j].r;const x=Math.min(a.right,b.right)-Math.max(a.left,b.left),y=Math.min(a.bottom,b.bottom)-Math.max(a.top,b.top);const dx=Math.max(a.left,b.left)-Math.min(a.right,b.right),dy=Math.max(a.top,b.top)-Math.min(a.bottom,b.bottom);if((x>1&&dy<7.5)||(y>1&&dx<7.5))close.push([controls[i].id,controls[j].id]);}
|
||||||
|
const dialog=document.querySelector('dialog[open]');const rect=dialog?.getBoundingClientRect();
|
||||||
|
const clippedDialog=!!rect&&(rect.left<0||rect.right>innerWidth||rect.top<0||rect.bottom>innerHeight);
|
||||||
|
const clippedNav=innerWidth<=720&&[...document.querySelectorAll('nav button')].some(button=>{const r=button.getBoundingClientRect();return button.scrollHeight>button.clientHeight||r.height<44;});
|
||||||
|
return {clippedDialog,clippedNav,overflow:document.documentElement.scrollWidth>innerWidth,close,small:innerWidth<=720?controls.filter(e=>e.r.height<43.5).map(e=>e.id):[]};
|
||||||
|
});checks++;if(result.clippedDialog||result.clippedNav||result.overflow||result.close.length||result.small.length)failures.push({label,...result});
|
||||||
|
}
|
||||||
|
for(const {width,height} of viewports)for(const lang of ['zh','en'])for(const theme of ['light','dark']){
|
||||||
|
await page.setViewportSize({width,height});await page.evaluate(({lang,theme})=>{state.lang=lang;document.documentElement.dataset.theme=theme;shell();},{lang,theme});
|
||||||
|
for(const view of ['dashboard','gallery','photo-sources','upload','templates','automation','playlists','history','settings','studio','connections']){await page.evaluate(view=>navigate(view),view);await inspect(`${view}/${width}/${lang}/${theme}`);}
|
||||||
|
await page.evaluate(()=>navigate('studio'));await page.locator('.manual-collage summary').click();await inspect(`Manual collage/${width}/${lang}/${theme}`);await page.evaluate(()=>navigate('photo-sources'));await page.locator('#photos-login').click();await inspect(`Photos login/${width}/${lang}/${theme}`);await page.locator('#modal-cancel').click();
|
||||||
|
await page.locator('#add-photo-source').click();assert(await page.locator('#source-credential').isHidden());assert(await page.locator('#source-oauth').isHidden());await inspect(`NAS source/${width}/${lang}/${theme}`);await page.locator('#source-kind').selectOption('google-drive');assert(await page.locator('#source-oauth').isVisible());assert(await page.locator('#source-local-quality').isHidden());await inspect(`Drive source/${width}/${lang}/${theme}`);await page.locator('#modal-cancel').click();
|
||||||
|
await page.evaluate(()=>navigate('automation'));await page.locator('#new-job').click();await inspect(`Job/${width}/${lang}/${theme}`);await page.locator('#modal-cancel').click();
|
||||||
|
await page.evaluate(()=>navigate('playlists'));await page.locator('#new-playlist').click();await inspect(`Playlist/${width}/${lang}/${theme}`);await page.locator('#modal-cancel').click();
|
||||||
|
await page.evaluate(()=>displayDialog({type:'image',image_id:1}));await inspect(`Display options/${width}/${lang}/${theme}`);await page.locator('#modal-cancel').click();
|
||||||
|
await page.evaluate(()=>{state.tab='local';return navigate('gallery');});await inspect(`Local gallery/${width}/${lang}/${theme}`);await page.evaluate(()=>{state.tab='cloud';});
|
||||||
|
if(out&&lang==='zh'&&theme==='dark'){await page.evaluate(()=>navigate('photo-sources'));await page.screenshot({path:out+`/photos-${width}.png`,fullPage:true});}
|
||||||
|
}
|
||||||
|
await page.evaluate(()=>navigate('photo-sources'));await page.locator('#photos-login').click();await page.locator('#photos-login-user').fill('fixture-nas');await page.locator('#photos-login-password').fill('fixture-only');await page.locator('#photos-login-form button[type=submit]').click();await page.locator('#photos-login').filter({hasText:'Sign in again'}).waitFor();assert(logins===1);checks++;
|
||||||
|
assert.deepStrictEqual(errors,[]);assert.deepStrictEqual(failures,[],JSON.stringify(failures));console.log('Layout audit:',checks,'passed; 11 pages plus local gallery, 6 modal states, '+(viewports.length*4)+' viewport/language/theme combinations; console errors:',errors.length);
|
||||||
|
}finally{await browser.close();}
|
||||||
|
})().catch(e=>{console.error(e.message);process.exit(1)});
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
/* All-page layout and daily-poetry checks; Mock only, no real device writes. */
|
/* All-page layout and daily-poetry checks; Mock only, no real device writes. */
|
||||||
const assert=require('assert'),{chromium}=require('playwright');
|
const assert=require('assert'),{chromium}=require('playwright');
|
||||||
(async()=>{const browser=await chromium.launch({headless:true,executablePath:'/Applications/Google Chrome.app/Contents/MacOS/Google Chrome'});const page=await browser.newPage();let unintended=0;page.on('request',r=>{if(r.method()==='POST'&&/\/(jobs|playlists|display)$/.test(r.url()))unintended++;});const base='http://127.0.0.1:18787';await page.goto(base);await page.locator('#username').fill(process.env.FRAME_FLOW_TEST_USERNAME);await page.locator('#password').fill(process.env.FRAME_FLOW_TEST_PASSWORD);await page.locator('#login-form button').click();await page.locator('.hero').waitFor();assert(await page.evaluate(()=>state.settings.mock));let checks=0;for(const lang of ['zh','en'])for(const writable of [false,true]){const clean=await page.evaluate(({lang,writable})=>{const previous={lang:state.lang,settings:state.settings};state.lang=lang;state.settings={...state.settings,mock:false,write_enabled:writable};shell();const clean=notice()===''&&!document.querySelector('#connection')&&!document.querySelector('.sidebar-bottom .live-dot');state.lang=previous.lang;state.settings=previous.settings;shell();return clean;},{lang,writable});assert(clean,'Live-device status must not appear in either language');checks++;}for(const width of [1440,390])for(const theme of ['light','dark']){await page.setViewportSize({width,height:1000});await page.evaluate(theme=>{localStorage.setItem('ff-theme',theme);document.documentElement.dataset.theme=theme;},theme);for(const name of ['dashboard','gallery','photo-sources','upload','templates','automation','playlists','history','settings']){await page.locator(`[data-page="${name}"]`).click();await page.waitForTimeout(350);if(name==='settings')await page.locator('#image-host-form').waitFor();const result=await page.evaluate(()=>{const children=[...document.querySelector('#main').children].filter(x=>x.getBoundingClientRect().height>0);return {overflow:document.documentElement.scrollWidth>innerWidth,buttonGaps:[...document.querySelectorAll('#main button')].flatMap(b=>{const next=b.nextElementSibling;if(next?.tagName!=='BUTTON')return [];const a=b.getBoundingClientRect(),c=next.getBoundingClientRect();if(!a.width||!c.width)return [];return [Math.abs(a.top-c.top)<4?c.left-a.right:c.top-a.bottom];}),gaps:children.slice(1).map((x,i)=>x.getBoundingClientRect().top-children[i].getBoundingClientRect().bottom)};});const controls=await page.evaluate(()=>{const nodes=[...document.querySelectorAll('#main input:not([type="checkbox"]):not([type="radio"]),#main select,#main textarea,#main button')].filter(x=>{const r=x.getBoundingClientRect();return r.width&&r.height&&getComputedStyle(x).visibility!=='hidden';});const issues=[];for(let i=0;i<nodes.length;i++)for(let j=i+1;j<nodes.length;j++){const a=nodes[i].getBoundingClientRect(),b=nodes[j].getBoundingClientRect();const ox=Math.min(a.right,b.right)-Math.max(a.left,b.left),oy=Math.min(a.bottom,b.bottom)-Math.max(a.top,b.top);const dy=Math.max(a.top,b.top)-Math.min(a.bottom,b.bottom),dx=Math.max(a.left,b.left)-Math.min(a.right,b.right);if((ox>Math.min(a.width,b.width)/2&&dy>=0&&dy<8)||(oy>Math.min(a.height,b.height)/2&&dx>=0&&dx<8))issues.push({a:nodes[i].id,b:nodes[j].id,gap:ox>0?dy:dx});}return issues;});assert(controls.length===0,`${name} ${width} ${theme} controls ${JSON.stringify(controls)}`);checks++;
|
(async()=>{const browser=await chromium.launch({headless:true,executablePath:'/Applications/Google Chrome.app/Contents/MacOS/Google Chrome'});const page=await browser.newPage();let unintended=0;page.on('request',r=>{if(r.method()==='POST'&&/\/(jobs|playlists|display)$/.test(r.url()))unintended++;});const base=process.env.FRAME_FLOW_URL||'http://127.0.0.1:6005';await page.goto(base);await page.locator('#username').fill(process.env.FRAME_FLOW_TEST_USERNAME);await page.locator('#password').fill(process.env.FRAME_FLOW_TEST_PASSWORD);await page.locator('#login-form button').click();await page.locator('.hero').waitFor();assert(await page.evaluate(()=>state.settings.mock));let checks=0;for(const lang of ['zh','en'])for(const writable of [false,true]){const clean=await page.evaluate(({lang,writable})=>{const previous={lang:state.lang,settings:state.settings};state.lang=lang;state.settings={...state.settings,mock:false,write_enabled:writable};shell();const clean=notice()===''&&!document.querySelector('#connection')&&!document.querySelector('.sidebar-bottom .live-dot');state.lang=previous.lang;state.settings=previous.settings;shell();return clean;},{lang,writable});assert(clean,'Live-device status must not appear in either language');checks++;}for(const width of [1440,390])for(const theme of ['light','dark']){await page.setViewportSize({width,height:1000});await page.evaluate(theme=>{localStorage.setItem('ff-theme',theme);document.documentElement.dataset.theme=theme;},theme);for(const name of ['dashboard','gallery','photo-sources','upload','templates','automation','playlists','history','settings']){await page.locator(`[data-page="${name}"]`).click();await page.waitForTimeout(350);if(name==='settings')await page.locator('#image-host-form').waitFor();const result=await page.evaluate(()=>{const children=[...document.querySelector('#main').children].filter(x=>x.getBoundingClientRect().height>0);return {overflow:document.documentElement.scrollWidth>innerWidth,buttonGaps:[...document.querySelectorAll('#main button')].flatMap(b=>{const next=b.nextElementSibling;if(next?.tagName!=='BUTTON')return [];const a=b.getBoundingClientRect(),c=next.getBoundingClientRect();if(!a.width||!c.width)return [];return [Math.abs(a.top-c.top)<4?c.left-a.right:c.top-a.bottom];}),gaps:children.slice(1).map((x,i)=>x.getBoundingClientRect().top-children[i].getBoundingClientRect().bottom)};});const controls=await page.evaluate(()=>{const nodes=[...document.querySelectorAll('#main input:not([type="checkbox"]):not([type="radio"]),#main select,#main textarea,#main button')].filter(x=>{const r=x.getBoundingClientRect();return r.width&&r.height&&getComputedStyle(x).visibility!=='hidden';});const issues=[];for(let i=0;i<nodes.length;i++)for(let j=i+1;j<nodes.length;j++){const a=nodes[i].getBoundingClientRect(),b=nodes[j].getBoundingClientRect();const ox=Math.min(a.right,b.right)-Math.max(a.left,b.left),oy=Math.min(a.bottom,b.bottom)-Math.max(a.top,b.top);const dy=Math.max(a.top,b.top)-Math.min(a.bottom,b.bottom),dx=Math.max(a.left,b.left)-Math.min(a.right,b.right);if((ox>Math.min(a.width,b.width)/2&&dy>=0&&dy<8)||(oy>Math.min(a.height,b.height)/2&&dx>=0&&dx<8))issues.push({a:nodes[i].id,b:nodes[j].id,gap:ox>0?dy:dx});}return issues;});assert(controls.length===0,`${name} ${width} ${theme} controls ${JSON.stringify(controls)}`);checks++;
|
||||||
assert(result.buttonGaps.every(x=>x>=8),`${name} ${width} button gaps ${result.buttonGaps}`);assert(!result.overflow,`${name} ${width} overflow`);assert(result.gaps.every(x=>x>=16),`${name} ${width} gaps ${result.gaps}`);checks++;if(name==='templates'||name==='settings')await page.screenshot({path:`docs/screenshots/${name}-${width}-${theme}.png`,fullPage:true});}}
|
assert(result.buttonGaps.every(x=>x>=8),`${name} ${width} button gaps ${result.buttonGaps}`);assert(!result.overflow,`${name} ${width} overflow`);assert(result.gaps.every(x=>x>=16),`${name} ${width} gaps ${result.gaps}`);checks++;if(name==='templates'||name==='settings')await page.screenshot({path:`docs/screenshots/${name}-${width}-${theme}.png`,fullPage:true});}}
|
||||||
await page.locator('[data-page="templates"]').click();await page.locator('[data-template="daily-poetry"]').click();await page.locator('#poem-choice').waitFor();assert(await page.locator('#poem-choice option').count()===21);checks++;await page.locator('#poem-choice').selectOption('jing-ye-si');await page.locator('#render-template').click();await page.locator('#template-image').waitFor();await page.waitForFunction(()=>document.querySelector('#template-image')?.naturalWidth===1200);checks++;await page.locator('#daily-poetry-job').click();assert(!await page.locator('#poetry-job-enabled').isChecked());checks++;const gap=await page.evaluate(()=>{const a=document.querySelector('#daily-poetry-job').getBoundingClientRect(),b=document.querySelector('#template-fields').getBoundingClientRect();return b.top-a.bottom;});assert(gap>=20,'Poetry action touches fields');checks++;await page.locator('#modal-cancel').click();await page.screenshot({path:'docs/screenshots/daily-poetry-controls-mobile-dark.png',fullPage:true});for(const width of [1440,390])for(const theme of ['light','dark']){await page.setViewportSize({width,height:1000});await page.evaluate(theme=>document.documentElement.dataset.theme=theme,theme);await page.locator('[data-page="templates"]').click();for(const id of ['calendar','daily-dashboard','daily-poetry','photo-text','quote','system-alert','weather']){await page.locator(`[data-template="${id}"]`).click();await page.waitForTimeout(250);await page.locator('#download-template').waitFor();if(id==='photo-text'){const photoGap=await page.evaluate(()=>document.querySelector('#template-photo-upload').getBoundingClientRect().top-document.querySelector('#field-photo_id').getBoundingClientRect().bottom);assert(photoGap>=12,`${width} ${theme} photo controls touch`);checks++;}const gap=await page.evaluate(()=>{const a=document.querySelector('#display-template').getBoundingClientRect(),b=document.querySelector('#download-template').getBoundingClientRect();return Math.abs(a.top-b.top)<4?b.left-a.right:b.top-a.bottom;});assert(gap>=8,`${id} ${width} preview buttons touch`);checks++;}for(const [name,button] of [['automation','new-job'],['playlists','new-playlist'],['templates','daily-poetry-job']]){await page.locator(`[data-page="${name}"]`).click();if(name==='templates'){await page.locator('[data-template="daily-poetry"]').click();await page.locator('#poem-choice').waitFor();}await page.locator('#'+button).click();const gap=await page.evaluate(()=>{const [a,b]=[...document.querySelectorAll('#modal .modal-actions button')].map(x=>x.getBoundingClientRect());return Math.abs(a.top-b.top)<4?b.left-a.right:b.top-a.bottom;});assert(gap>=8,`${name} ${width} modal buttons touch`);checks++;await page.locator('#modal-cancel').click();}}assert(unintended===0,`Cancel submitted ${unintended} requests`);checks++;await browser.close();console.log(`Layout/poetry browser: ${checks} passed (32 page/profile combinations)`);})().catch(e=>{console.error(e.message);process.exit(1)});
|
await page.locator('[data-page="templates"]').click();await page.locator('[data-template="daily-poetry"]').click();await page.locator('#poem-choice').waitFor();assert(await page.locator('#poem-choice option').count()===21);checks++;await page.locator('#poem-choice').selectOption('jing-ye-si');await page.locator('#render-template').click();await page.locator('#template-image').waitFor();await page.waitForFunction(()=>document.querySelector('#template-image')?.naturalWidth===1200);checks++;await page.locator('#daily-poetry-job').click();assert(!await page.locator('#poetry-job-enabled').isChecked());checks++;const gap=await page.evaluate(()=>{const a=document.querySelector('#daily-poetry-job').getBoundingClientRect(),b=document.querySelector('#template-fields').getBoundingClientRect();return b.top-a.bottom;});assert(gap>=20,'Poetry action touches fields');checks++;await page.locator('#modal-cancel').click();await page.screenshot({path:'docs/screenshots/daily-poetry-controls-mobile-dark.png',fullPage:true});for(const width of [1440,390])for(const theme of ['light','dark']){await page.setViewportSize({width,height:1000});await page.evaluate(theme=>document.documentElement.dataset.theme=theme,theme);await page.locator('[data-page="templates"]').click();for(const id of ['calendar','daily-dashboard','daily-poetry','photo-text','quote','system-alert','weather']){await page.locator(`[data-template="${id}"]`).click();await page.waitForTimeout(250);await page.locator('#download-template').waitFor();if(id==='photo-text'){const photoGap=await page.evaluate(()=>document.querySelector('#template-photo-upload').getBoundingClientRect().top-document.querySelector('#field-photo_id').getBoundingClientRect().bottom);assert(photoGap>=12,`${width} ${theme} photo controls touch`);checks++;}const gap=await page.evaluate(()=>{const a=document.querySelector('#display-template').getBoundingClientRect(),b=document.querySelector('#download-template').getBoundingClientRect();return Math.abs(a.top-b.top)<4?b.left-a.right:b.top-a.bottom;});assert(gap>=8,`${id} ${width} preview buttons touch`);checks++;}for(const [name,button] of [['automation','new-job'],['playlists','new-playlist'],['templates','daily-poetry-job']]){await page.locator(`[data-page="${name}"]`).click();if(name==='templates'){await page.locator('[data-template="daily-poetry"]').click();await page.locator('#poem-choice').waitFor();}await page.locator('#'+button).click();const gap=await page.evaluate(()=>{const [a,b]=[...document.querySelectorAll('#modal .modal-actions button')].map(x=>x.getBoundingClientRect());return Math.abs(a.top-b.top)<4?b.left-a.right:b.top-a.bottom;});assert(gap>=8,`${name} ${width} modal buttons touch`);checks++;await page.locator('#modal-cancel').click();}}assert(unintended===0,`Cancel submitted ${unintended} requests`);checks++;await browser.close();console.log(`Layout/poetry browser: ${checks} passed (32 page/profile combinations)`);})().catch(e=>{console.error(e.message);process.exit(1)});
|
||||||
|
|||||||
@@ -0,0 +1,17 @@
|
|||||||
|
const {chromium}=require('playwright');const fs=require('fs');const path=require('path');const assert=require('assert');
|
||||||
|
const root=path.resolve(__dirname,'../pigway_frame_flow/web');const out=process.env.FRAME_FLOW_SCREENSHOT_DIR;if(out)fs.mkdirSync(out,{recursive:true});
|
||||||
|
(async()=>{const b=await chromium.launch({headless:true,executablePath:'/Applications/Google Chrome.app/Contents/MacOS/Google Chrome'});let count=0;
|
||||||
|
try{for(const width of [1440,768,390,320])for(const lang of ['zh','en'])for(const theme of ['dark','light']){
|
||||||
|
const p=await b.newPage({viewport:{width,height:900}});const errors=[];p.on('pageerror',e=>errors.push(e.message));
|
||||||
|
await p.addInitScript(({lang,theme})=>{localStorage.setItem('ff-language',lang);localStorage.setItem('ff-theme',theme)},{lang,theme});
|
||||||
|
await p.route('**/*',async r=>{const u=new URL(r.request().url());if(u.pathname.startsWith('/api/')){if(u.pathname==='/api/v1/version')return r.fulfill({json:{version:'0.1.9',commit:'ba9424a-ui',build_time:'validation'}});return r.fulfill({status:401,json:{error:{code:'UNAUTHORIZED',message:'Sign in required'}}});}let f=u.pathname==='/'?'index.html':u.pathname.replace(/^\/ui\//,'');const file=path.join(root,f);if(!file.startsWith(root)||!fs.existsSync(file))return r.fulfill({status:404,body:''});return r.fulfill({body:fs.readFileSync(file),contentType:f.endsWith('.css')?'text/css':f.endsWith('.js')?'application/javascript':'text/html'});});
|
||||||
|
await p.goto('http://frame.test/');await p.locator('#login-form').waitFor();await p.waitForTimeout(60);
|
||||||
|
assert.equal(await p.locator('#device option:checked').innerText(),lang==='zh'?'客厅':'Living room');
|
||||||
|
const layout=await p.evaluate(()=>{const q=s=>document.querySelector(s).getBoundingClientRect();return {overflow:document.documentElement.scrollWidth>innerWidth,card:q('.login-card').toJSON(),form:q('#login-form').toJSON(),user:q('#username').toJSON(),password:q('#password').toJSON(),remember:document.querySelector('#remember-login').closest('label').getBoundingClientRect().toJSON(),button:q('#login-form button').toJSON(),label:document.querySelector('#remember-login').labels[0].innerText}});
|
||||||
|
assert(!layout.overflow,JSON.stringify({width,lang,theme,layout}));assert(layout.password.top-layout.user.bottom>=24);assert(layout.button.top-layout.remember.bottom>=20);assert(layout.button.width>=layout.form.width-1);assert.equal(errors.length,0,errors.join('\n'));
|
||||||
|
// Language switching and custom names must not change the internal device ID.
|
||||||
|
await p.evaluate(()=>{state.devices=[{id:'living-room',name:'我的画框'}];shell()});assert.equal(await p.locator('#device option:checked').innerText(),'我的画框');
|
||||||
|
await p.evaluate(()=>{state.devices=[];shell();login()});
|
||||||
|
if(out&&lang==='zh'&&theme==='dark'&&[1440,390].includes(width))await p.screenshot({path:path.join(out,`login-${width}.png`),fullPage:true});
|
||||||
|
console.log('PASS',width,lang,theme);count++;await p.close();}
|
||||||
|
console.log('TOTAL',count,'profiles');}finally{await b.close()}})().catch(e=>{console.error(e);process.exit(1)});
|
||||||
@@ -1,3 +1,3 @@
|
|||||||
/* Local Mock only. No real official account or frame writes. */
|
/* Local Mock only. No real official account or frame writes. */
|
||||||
const assert=require('assert'),{chromium}=require('playwright');
|
const assert=require('assert'),{chromium}=require('playwright');
|
||||||
(async()=>{const browser=await chromium.launch({headless:true,executablePath:'/Applications/Google Chrome.app/Contents/MacOS/Google Chrome'});const page=await browser.newPage();const errors=[];let frameWrites=0;page.on('pageerror',e=>errors.push(e.message));await page.route('**/api/**',route=>{const r=route.request();if(r.method()!=='GET'&&!r.url().includes('/auth/')&&!r.url().endsWith('/official/connection')){frameWrites++;return route.abort();}return route.continue();});await page.goto('http://127.0.0.1:18787');await page.locator('#username').fill(process.env.FRAME_FLOW_TEST_USERNAME);await page.locator('#password').fill(process.env.FRAME_FLOW_TEST_PASSWORD);await page.locator('#login-form button').click();await page.locator('.hero').waitFor();assert(await page.evaluate(()=>state.settings.mock));await page.locator('[data-page="templates"]').click();await page.locator('.official-content-info summary').click();await page.waitForTimeout(300);if(await page.locator('#official-disconnect').count())await page.locator('#official-disconnect').click();await page.locator('#official-username').fill('mock-official-user');await page.locator('#official-password').fill('mock-password-not-saved');await page.locator('#official-login-form button').click();await page.locator('#official-device').waitFor();await page.locator('#official-select-form button').click();await page.locator('.official-account-panel').waitFor();await page.reload();await page.locator('.official-content-info summary').click();await page.locator('#official-disconnect').waitFor();assert((await page.locator('.official-account-panel').textContent()).includes('已关联画框'));for(const width of [1440,390]){await page.setViewportSize({width,height:1000});assert(!await page.evaluate(()=>document.documentElement.scrollWidth>innerWidth));}await page.locator('#official-disconnect').click();await page.locator('#official-login-form').waitFor();assert(await page.locator('#official-password').inputValue()==='');assert(!await page.evaluate(()=>JSON.stringify(localStorage).includes('mock-password-not-saved')));assert(errors.length===0&&frameWrites===0);await browser.close();console.log('Official connection UI: login, discover, select, reload, disconnect, 2 sizes PASS; 0 page errors, 0 frame writes');})().catch(e=>{console.error(e.message);process.exit(1)});
|
(async()=>{const browser=await chromium.launch({headless:true,executablePath:'/Applications/Google Chrome.app/Contents/MacOS/Google Chrome'});const page=await browser.newPage();const errors=[];let frameWrites=0;page.on('pageerror',e=>errors.push(e.message));await page.route('**/api/**',route=>{const r=route.request();if(r.method()!=='GET'&&!r.url().includes('/auth/')&&!r.url().endsWith('/official/connection')){frameWrites++;return route.abort();}return route.continue();});await page.goto(process.env.FRAME_FLOW_URL||'http://127.0.0.1:6005');await page.locator('#username').fill(process.env.FRAME_FLOW_TEST_USERNAME);await page.locator('#password').fill(process.env.FRAME_FLOW_TEST_PASSWORD);await page.locator('#login-form button').click();await page.locator('.hero').waitFor();assert(await page.evaluate(()=>state.settings.mock));await page.locator('[data-page="templates"]').click();await page.locator('.official-content-info summary').click();await page.waitForTimeout(300);if(await page.locator('#official-disconnect').count())await page.locator('#official-disconnect').click();await page.locator('#official-username').fill('mock-official-user');await page.locator('#official-password').fill('mock-password-not-saved');await page.locator('#official-login-form button').click();await page.locator('#official-device').waitFor();await page.locator('#official-select-form button').click();await page.locator('.official-account-panel').waitFor();await page.reload();await page.locator('.official-content-info summary').click();await page.locator('#official-disconnect').waitFor();assert((await page.locator('.official-account-panel').textContent()).includes('已关联画框'));for(const width of [1440,390]){await page.setViewportSize({width,height:1000});assert(!await page.evaluate(()=>document.documentElement.scrollWidth>innerWidth));}await page.locator('#official-disconnect').click();await page.locator('#official-login-form').waitFor();assert(await page.locator('#official-password').inputValue()==='');assert(!await page.evaluate(()=>JSON.stringify(localStorage).includes('mock-password-not-saved')));assert(errors.length===0&&frameWrites===0);await browser.close();console.log('Official connection UI: login, discover, select, reload, disconnect, 2 sizes PASS; 0 page errors, 0 frame writes');})().catch(e=>{console.error(e.message);process.exit(1)});
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ const assert=require('assert'),{chromium}=require('playwright');
|
|||||||
await page.route('**/api/v1/integrations/synology-photos',route=>route.fulfill({json:{configured:true,connected:true}}));
|
await page.route('**/api/v1/integrations/synology-photos',route=>route.fulfill({json:{configured:true,connected:true}}));
|
||||||
await page.route('**/api/v1/integrations/synology-photos/people',route=>route.fulfill({json:[{id:1,name:'Family A',count:20,named:true},{id:2,name:'Family B',count:15,named:true},{id:3,name:'3',count:2,named:false}]}));
|
await page.route('**/api/v1/integrations/synology-photos/people',route=>route.fulfill({json:[{id:1,name:'Family A',count:20,named:true},{id:2,name:'Family B',count:15,named:true},{id:3,name:'3',count:2,named:false}]}));
|
||||||
try{
|
try{
|
||||||
await page.goto('http://127.0.0.1:18787');await page.locator('#username').fill(process.env.FRAME_FLOW_TEST_USERNAME);await page.locator('#password').fill(process.env.FRAME_FLOW_TEST_PASSWORD);await page.locator('#login-form button').click();await page.locator('.hero').waitFor();assert(await page.evaluate(()=>state.settings.mock));
|
await page.goto(process.env.FRAME_FLOW_URL||'http://127.0.0.1:6005');await page.locator('#username').fill(process.env.FRAME_FLOW_TEST_USERNAME);await page.locator('#password').fill(process.env.FRAME_FLOW_TEST_PASSWORD);await page.locator('#login-form button').click();await page.locator('.hero').waitFor();assert(await page.evaluate(()=>state.settings.mock));
|
||||||
for(const lang of ['zh','en'])for(const width of [1440,390])for(const theme of ['dark','light']){
|
for(const lang of ['zh','en'])for(const width of [1440,390])for(const theme of ['dark','light']){
|
||||||
await page.setViewportSize({width,height:1000});await page.evaluate(({lang,theme})=>{state.lang=lang;document.documentElement.dataset.theme=theme;shell();},{lang,theme});await page.locator('[data-page="photo-sources"]').click();await page.locator('#add-photo-source').click();await page.locator('#source-id').fill(id);await page.locator('#source-name').fill('People fixture');await page.locator('#source-people-load').click();await page.locator('[data-person="1"]').waitFor();assert(await page.locator('[data-person]').count()===2);await page.locator('#people-unnamed').check();assert(await page.locator('[data-person]').count()===3);await page.locator('#people-search').fill('Family B');assert(await page.locator('[data-person]').count()===1);await page.locator('[data-person="2"]').check();await page.locator('#source-people-filter').check();await page.locator('#source-person-match').selectOption('all');assert(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth));
|
await page.setViewportSize({width,height:1000});await page.evaluate(({lang,theme})=>{state.lang=lang;document.documentElement.dataset.theme=theme;shell();},{lang,theme});await page.locator('[data-page="photo-sources"]').click();await page.locator('#add-photo-source').click();await page.locator('#source-id').fill(id);await page.locator('#source-name').fill('People fixture');await page.locator('#source-people-load').click();await page.locator('[data-person="1"]').waitFor();assert(await page.locator('[data-person]').count()===2);await page.locator('#people-unnamed').check();assert(await page.locator('[data-person]').count()===3);await page.locator('#people-search').fill('Family B');assert(await page.locator('[data-person]').count()===1);await page.locator('[data-person="2"]').check();await page.locator('#source-people-filter').check();await page.locator('#source-person-match').selectOption('all');assert(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth));
|
||||||
if(checks===0){await page.locator('#photo-source-form button[type="submit"]').click();await page.locator(`[data-source-edit="${id}"]`).waitFor();const saved=await page.evaluate(async id=>(await api('/api/v1/photo-sources')).find(s=>s.id===id),id);assert(saved.people_filter&&saved.person_match==='all'&&saved.person_ids.join(',')==='2');await page.locator(`[data-source-edit="${id}"]`).click();assert(await page.locator('#source-people-filter').isChecked());assert(await page.locator('#source-person-match').inputValue()==='all');}
|
if(checks===0){await page.locator('#photo-source-form button[type="submit"]').click();await page.locator(`[data-source-edit="${id}"]`).waitFor();const saved=await page.evaluate(async id=>(await api('/api/v1/photo-sources')).find(s=>s.id===id),id);assert(saved.people_filter&&saved.person_match==='all'&&saved.person_ids.join(',')==='2');await page.locator(`[data-source-edit="${id}"]`).click();assert(await page.locator('#source-people-filter').isChecked());assert(await page.locator('#source-person-match').inputValue()==='all');}
|
||||||
|
|||||||
@@ -1,3 +1,3 @@
|
|||||||
/* Local mock server only; no vendor/cloud writes. PHOTO_ROOT must contain a fixture image. */
|
/* Local mock server only; no vendor/cloud writes. PHOTO_ROOT must contain a fixture image. */
|
||||||
const assert=require('assert'),{chromium}=require('playwright');
|
const assert=require('assert'),{chromium}=require('playwright');
|
||||||
(async()=>{const browser=await chromium.launch({headless:true,executablePath:'/Applications/Google Chrome.app/Contents/MacOS/Google Chrome'});const page=await browser.newPage();await page.goto('http://127.0.0.1:18787');await page.locator('#username').fill(process.env.FRAME_FLOW_TEST_USERNAME);await page.locator('#password').fill(process.env.FRAME_FLOW_TEST_PASSWORD);await page.locator('#login-form button').click();await page.locator('.hero').waitFor();assert(await page.evaluate(()=>state.settings.mock));const id='ui-photo-'+Date.now();let jobId;let checks=0;try{await page.locator('[data-page="photo-sources"]').click();await page.locator('#add-photo-source').click();await page.locator('#source-id').fill(id);await page.locator('#source-name').fill('UI photo fixture');await page.locator('#source-location').fill('.');await page.locator('#source-orientation').selectOption('landscape');await page.locator('#source-organized').check();await page.locator('#source-caption').check();await page.locator('#source-synology-previews').check();await page.locator('#photo-source-form button[type="submit"]').click();await page.locator(`[data-source-browse="${id}"]`).waitFor();for(const lang of ['zh','en'])for(const width of [1440,390])for(const theme of ['dark','light']){await page.setViewportSize({width,height:1000});await page.evaluate(({lang,theme})=>{state.lang=lang;document.documentElement.dataset.theme=theme;shell();},{lang,theme});await page.locator('[data-page="photo-sources"]').click();await page.locator(`[data-source-browse="${id}"]`).click();await page.locator('[data-source-item]').first().waitFor();assert(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth));await page.locator(`[data-source-edit="${id}"]`).click();assert(await page.locator('#source-id').inputValue()===id);assert(await page.locator('#source-orientation').inputValue()==='landscape');assert(await page.locator('#source-organized').isChecked());assert(await page.locator('#source-caption').isChecked());assert(await page.locator('#source-synology-previews').isChecked());await page.locator('#modal-cancel').click();checks++;}await page.locator(`[data-source-random="${id}"]`).click();await page.locator('#source-preview').waitFor();await page.waitForFunction(()=>document.querySelector('#source-preview')?.naturalWidth>0);assert(await page.locator('#source-preview').evaluate(img=>img.naturalWidth===1600&&img.naturalHeight===1200));const before=await page.evaluate(()=>api('/api/v1/devices/'+state.device));await page.locator('#modal-cancel').click();await page.locator(`[data-source-job="${id}"]`).click();assert(!await page.locator('#source-job-enabled').isChecked());await page.locator('#source-job-name').fill(id);await page.locator('#source-job-form button[type="submit"]').click();await page.locator('#new-job').waitFor();jobId=await page.evaluate(async id=>(await api('/api/v1/jobs')).find(j=>j.name===id).id,id);await page.evaluate(async jobId=>{const job=(await api('/api/v1/jobs')).find(j=>j.id===jobId);await jobEditor(job);},jobId);await page.locator('#job-photo-source').waitFor();assert(await page.locator('#job-form').textContent().then(x=>x.includes('最新成功图')||x.includes('latest confirmed')));assert(await page.locator('#job-content-type').inputValue()==='photo_source');assert(await page.locator('#job-photo-source').inputValue()===id);await page.locator('#modal-cancel').click();const after=await page.evaluate(()=>api('/api/v1/devices/'+state.device));assert(before.current_content.id===after.current_content.id);checks+=3;console.log('Photo sources browser: '+checks+' passed (8 language/size/theme profiles, preview and scheduler editing)');}finally{await page.evaluate(async({id,jobId})=>{if(jobId)await api('/api/v1/jobs/'+jobId,{method:'DELETE'});await api('/api/v1/photo-sources/'+id,{method:'DELETE'});},{id,jobId});await browser.close();}})().catch(e=>{console.error(e);process.exit(1)});
|
(async()=>{const browser=await chromium.launch({headless:true,executablePath:'/Applications/Google Chrome.app/Contents/MacOS/Google Chrome'});const page=await browser.newPage();await page.goto(process.env.FRAME_FLOW_URL||'http://127.0.0.1:6005');await page.locator('#username').fill(process.env.FRAME_FLOW_TEST_USERNAME);await page.locator('#password').fill(process.env.FRAME_FLOW_TEST_PASSWORD);await page.locator('#login-form button').click();await page.locator('.hero').waitFor();assert(await page.evaluate(()=>state.settings.mock));const id='ui-photo-'+Date.now();let jobId;let checks=0;try{await page.locator('[data-page="photo-sources"]').click();await page.locator('#add-photo-source').click();await page.locator('#source-id').fill(id);await page.locator('#source-name').fill('UI photo fixture');await page.locator('#source-location').fill('.');await page.locator('#source-orientation').selectOption('landscape');await page.locator('#source-organized').check();await page.locator('#source-caption').check();await page.locator('#source-synology-previews').check();await page.locator('#photo-source-form button[type="submit"]').click();await page.locator(`[data-source-browse="${id}"]`).waitFor();for(const lang of ['zh','en'])for(const width of [1440,390])for(const theme of ['dark','light']){await page.setViewportSize({width,height:1000});await page.evaluate(({lang,theme})=>{state.lang=lang;document.documentElement.dataset.theme=theme;shell();},{lang,theme});await page.locator('[data-page="photo-sources"]').click();await page.locator(`[data-source-browse="${id}"]`).click();await page.locator('[data-source-item]').first().waitFor();assert(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth));await page.locator(`[data-source-edit="${id}"]`).click();assert(await page.locator('#source-id').inputValue()===id);assert(await page.locator('#source-orientation').inputValue()==='landscape');assert(await page.locator('#source-organized').isChecked());assert(await page.locator('#source-caption').isChecked());assert(await page.locator('#source-synology-previews').isChecked());await page.locator('#modal-cancel').click();checks++;}await page.locator(`[data-source-random="${id}"]`).click();await page.locator('#source-preview').waitFor();await page.waitForFunction(()=>document.querySelector('#source-preview')?.naturalWidth>0);assert(await page.locator('#source-preview').evaluate(img=>img.naturalWidth===1600&&img.naturalHeight===1200));const before=await page.evaluate(()=>api('/api/v1/devices/'+state.device));await page.locator('#modal-cancel').click();await page.locator(`[data-source-job="${id}"]`).click();assert(!await page.locator('#source-job-enabled').isChecked());await page.locator('#source-job-name').fill(id);await page.locator('#source-job-form button[type="submit"]').click();await page.locator('#new-job').waitFor();jobId=await page.evaluate(async id=>(await api('/api/v1/jobs')).find(j=>j.name===id).id,id);await page.evaluate(async jobId=>{const job=(await api('/api/v1/jobs')).find(j=>j.id===jobId);await jobEditor(job);},jobId);await page.locator('#job-photo-source').waitFor();assert(await page.locator('#job-form').textContent().then(x=>x.includes('最新成功图')||x.includes('latest confirmed')));assert(await page.locator('#job-content-type').inputValue()==='photo_source');assert(await page.locator('#job-photo-source').inputValue()===id);await page.locator('#modal-cancel').click();const after=await page.evaluate(()=>api('/api/v1/devices/'+state.device));assert(before.current_content.id===after.current_content.id);checks+=3;console.log('Photo sources browser: '+checks+' passed (8 language/size/theme profiles, preview and scheduler editing)');}finally{await page.evaluate(async({id,jobId})=>{if(jobId)await api('/api/v1/jobs/'+jobId,{method:'DELETE'});await api('/api/v1/photo-sources/'+id,{method:'DELETE'});},{id,jobId});await browser.close();}})().catch(e=>{console.error(e);process.exit(1)});
|
||||||
|
|||||||
@@ -1,3 +1,3 @@
|
|||||||
/* Local mock server only; no vendor/cloud writes. PHOTO_ROOT must contain a fixture image. */
|
/* Local mock server only; no vendor/cloud writes. PHOTO_ROOT must contain a fixture image. */
|
||||||
const assert=require('assert'),{chromium}=require('playwright');
|
const assert=require('assert'),{chromium}=require('playwright');
|
||||||
(async()=>{const browser=await chromium.launch({headless:true,executablePath:'/Applications/Google Chrome.app/Contents/MacOS/Google Chrome'});const page=await browser.newPage();await page.goto('http://127.0.0.1:18787');await page.locator('#username').fill(process.env.FRAME_FLOW_TEST_USERNAME);await page.locator('#password').fill(process.env.FRAME_FLOW_TEST_PASSWORD);await page.locator('#login-form button').click();await page.locator('.hero').waitFor();assert(await page.evaluate(()=>state.settings.mock));const id='ui-photo-'+Date.now();let jobId;let checks=0;try{await page.locator('[data-page="photo-sources"]').click();await page.locator('#add-photo-source').click();await page.locator('#source-id').fill(id);await page.locator('#source-name').fill('UI photo fixture');await page.locator('#source-location').fill('.');await page.locator('#source-orientation').selectOption('landscape');await page.locator('#source-organized').check();await page.locator('#source-caption').check();await page.locator('#source-synology-previews').check();await page.locator('#photo-source-form button[type="submit"]').click();await page.locator(`[data-source-browse="${id}"]`).waitFor();for(const lang of ['zh','en'])for(const width of [1440,390])for(const theme of ['dark','light']){await page.setViewportSize({width,height:1000});await page.evaluate(({lang,theme})=>{state.lang=lang;document.documentElement.dataset.theme=theme;shell();},{lang,theme});await page.locator('[data-page="photo-sources"]').click();await page.locator(`[data-source-browse="${id}"]`).click();await page.locator('[data-source-item]').first().waitFor();assert(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth));await page.locator(`[data-source-edit="${id}"]`).click();assert(await page.locator('#source-id').inputValue()===id);assert(await page.locator('#source-orientation').inputValue()==='landscape');assert(await page.locator('#source-organized').isChecked());assert(await page.locator('#source-caption').isChecked());assert(await page.locator('#source-synology-previews').isChecked());await page.locator('#modal-cancel').click();checks++;}await page.locator(`[data-source-random="${id}"]`).click();await page.locator('#source-preview').waitFor();await page.waitForFunction(()=>document.querySelector('#source-preview')?.naturalWidth>0);assert(await page.locator('#source-preview').evaluate(img=>img.naturalWidth===1600&&img.naturalHeight===1200));const before=await page.evaluate(()=>api('/api/v1/devices/'+state.device));await page.locator('#modal-cancel').click();await page.locator(`[data-source-job="${id}"]`).click();assert(!await page.locator('#source-job-enabled').isChecked());await page.locator('#source-job-name').fill(id);await page.locator('#source-job-form button[type="submit"]').click();await page.locator('#new-job').waitFor();jobId=await page.evaluate(async id=>(await api('/api/v1/jobs')).find(j=>j.name===id).id,id);await page.evaluate(async jobId=>{const job=(await api('/api/v1/jobs')).find(j=>j.id===jobId);await jobEditor(job);},jobId);await page.locator('#job-photo-source').waitFor();assert(await page.locator('#job-content-type').inputValue()==='photo_source');assert(await page.locator('#job-photo-source').inputValue()===id);await page.locator('#modal-cancel').click();const after=await page.evaluate(()=>api('/api/v1/devices/'+state.device));assert(before.current_content.id===after.current_content.id);checks+=3;console.log('Photo sources browser: '+checks+' passed (8 language/size/theme profiles, preview and scheduler editing)');}finally{await page.evaluate(async({id,jobId})=>{if(jobId)await api('/api/v1/jobs/'+jobId,{method:'DELETE'});await api('/api/v1/photo-sources/'+id,{method:'DELETE'});},{id,jobId});await browser.close();}})().catch(e=>{console.error(e);process.exit(1)});
|
(async()=>{const browser=await chromium.launch({headless:true,executablePath:'/Applications/Google Chrome.app/Contents/MacOS/Google Chrome'});const page=await browser.newPage();await page.goto(process.env.FRAME_FLOW_URL||'http://127.0.0.1:6005');await page.locator('#username').fill(process.env.FRAME_FLOW_TEST_USERNAME);await page.locator('#password').fill(process.env.FRAME_FLOW_TEST_PASSWORD);await page.locator('#login-form button').click();await page.locator('.hero').waitFor();assert(await page.evaluate(()=>state.settings.mock));const id='ui-photo-'+Date.now();let jobId;let checks=0;try{await page.locator('[data-page="photo-sources"]').click();await page.locator('#add-photo-source').click();await page.locator('#source-id').fill(id);await page.locator('#source-name').fill('UI photo fixture');await page.locator('#source-location').fill('.');await page.locator('#source-orientation').selectOption('landscape');await page.locator('#source-organized').check();await page.locator('#source-caption').check();await page.locator('#source-synology-previews').check();await page.locator('#photo-source-form button[type="submit"]').click();await page.locator(`[data-source-browse="${id}"]`).waitFor();for(const lang of ['zh','en'])for(const width of [1440,390])for(const theme of ['dark','light']){await page.setViewportSize({width,height:1000});await page.evaluate(({lang,theme})=>{state.lang=lang;document.documentElement.dataset.theme=theme;shell();},{lang,theme});await page.locator('[data-page="photo-sources"]').click();await page.locator(`[data-source-browse="${id}"]`).click();await page.locator('[data-source-item]').first().waitFor();assert(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth));await page.locator(`[data-source-edit="${id}"]`).click();assert(await page.locator('#source-id').inputValue()===id);assert(await page.locator('#source-orientation').inputValue()==='landscape');assert(await page.locator('#source-organized').isChecked());assert(await page.locator('#source-caption').isChecked());assert(await page.locator('#source-synology-previews').isChecked());await page.locator('#modal-cancel').click();checks++;}await page.locator(`[data-source-random="${id}"]`).click();await page.locator('#source-preview').waitFor();await page.waitForFunction(()=>document.querySelector('#source-preview')?.naturalWidth>0);assert(await page.locator('#source-preview').evaluate(img=>img.naturalWidth===1600&&img.naturalHeight===1200));const before=await page.evaluate(()=>api('/api/v1/devices/'+state.device));await page.locator('#modal-cancel').click();await page.locator(`[data-source-job="${id}"]`).click();assert(!await page.locator('#source-job-enabled').isChecked());await page.locator('#source-job-name').fill(id);await page.locator('#source-job-form button[type="submit"]').click();await page.locator('#new-job').waitFor();jobId=await page.evaluate(async id=>(await api('/api/v1/jobs')).find(j=>j.name===id).id,id);await page.evaluate(async jobId=>{const job=(await api('/api/v1/jobs')).find(j=>j.id===jobId);await jobEditor(job);},jobId);await page.locator('#job-photo-source').waitFor();assert(await page.locator('#job-content-type').inputValue()==='photo_source');assert(await page.locator('#job-photo-source').inputValue()===id);await page.locator('#modal-cancel').click();const after=await page.evaluate(()=>api('/api/v1/devices/'+state.device));assert(before.current_content.id===after.current_content.id);checks+=3;console.log('Photo sources browser: '+checks+' passed (8 language/size/theme profiles, preview and scheduler editing)');}finally{await page.evaluate(async({id,jobId})=>{if(jobId)await api('/api/v1/jobs/'+jobId,{method:'DELETE'});await api('/api/v1/photo-sources/'+id,{method:'DELETE'});},{id,jobId});await browser.close();}})().catch(e=>{console.error(e);process.exit(1)});
|
||||||
|
|||||||
@@ -0,0 +1,23 @@
|
|||||||
|
const {chromium}=require('playwright');const fs=require('fs'),path=require('path'),assert=require('assert');
|
||||||
|
const root=path.join(__dirname,'../pigway_frame_flow/web');
|
||||||
|
(async()=>{const b=await chromium.launch({headless:true,executablePath:'/Applications/Google Chrome.app/Contents/MacOS/Google Chrome'});try{for(const width of [1440,768,390])for(const lang of ['zh','en']){
|
||||||
|
const p=await b.newPage({viewport:{width,height:900}});let errors=[];p.on('pageerror',e=>errors.push(e.message));let saved;
|
||||||
|
await p.addInitScript(lang=>localStorage.setItem('ff-language',lang),lang);
|
||||||
|
await p.route('**/*',async r=>{const u=new URL(r.request().url());if(u.pathname.startsWith('/api/')){
|
||||||
|
if(r.request().method()==='PUT'){saved=r.request().postDataJSON();return r.fulfill({json:{}})}
|
||||||
|
if(u.pathname==='/api/v1/photo-sources')return r.fulfill({json:[]});
|
||||||
|
if(u.pathname==='/api/v1/integrations/synology-photos')return r.fulfill({json:{configured:true,connected:true}});
|
||||||
|
if(u.pathname.endsWith('/people'))return r.fulfill({json:[{id:1,name:'Test Person',count:5}]});
|
||||||
|
return r.fulfill({status:401,json:{error:{code:'UNAUTHORIZED',message:'Sign in required'}}});}
|
||||||
|
const f=u.pathname==='/'?'index.html':u.pathname.replace(/^\/ui\//,'');return r.fulfill({body:fs.readFileSync(path.join(root,f)),contentType:f.endsWith('.js')?'application/javascript':f.endsWith('.css')?'text/css':'text/html'});});
|
||||||
|
await p.goto('http://frame.test/');await p.locator('#login-form').waitFor();await p.evaluate(()=>photoSourceForm());
|
||||||
|
assert(!(await p.locator('#source-kind').isVisible()));assert(!(await p.locator('#source-id').isVisible()));assert(!(await p.locator('#source-synology-previews').isVisible()));
|
||||||
|
assert.equal(await p.locator('#source-kind').inputValue(),'synology-photos');assert.match(await p.locator('#source-id').inputValue(),/^photos-[a-z0-9-]+$/);
|
||||||
|
const text=await p.locator('#modal').innerText();assert(!/\/photos|本地目录|local.folder|mounted/i.test(text));
|
||||||
|
assert(await p.locator('#source-people-space').isVisible());await p.locator('#source-people-load').click();await p.locator('[data-person-id], #source-people-panel input[type=checkbox]').last().waitFor();
|
||||||
|
assert(!await p.evaluate(()=>document.documentElement.scrollWidth>innerWidth));
|
||||||
|
await p.locator('#source-name').fill('Family');
|
||||||
|
await p.locator('#photo-source-form button[type=submit]').click();await p.waitForTimeout(100);
|
||||||
|
assert(saved);assert.equal(saved.kind,'synology-photos');assert.equal(saved.synology_previews,false);
|
||||||
|
await p.evaluate(()=>photoSourceForm({id:'family-photos',name:'Family',kind:'synology-photos',location:'.',people_filter:true,person_ids:[1],people_space:'personal',person_match:'all'}));assert.equal(await p.locator('#source-id').inputValue(),'family-photos');assert.equal(await p.locator('#source-people-space').inputValue(),'personal');assert.equal(await p.locator('#source-person-match').inputValue(),'all');assert(await p.locator('#source-people-filter').isChecked());if(lang==='zh')await p.screenshot({path:'/tmp/frame-source-'+width+'.png',fullPage:true});assert.equal(errors.length,0,errors.join('\n'));console.log('PASS',width,lang);await p.close();
|
||||||
|
}}finally{await b.close()}})().catch(e=>{console.error(e);process.exit(1)});
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
/* Isolated Mock UI only: explicit API type, people spaces, payload and no mount wording. */
|
||||||
|
const assert=require('assert'),{chromium}=require('playwright');
|
||||||
|
(async()=>{const b=await chromium.launch({headless:true,executablePath:'/Applications/Google Chrome.app/Contents/MacOS/Google Chrome'});let checks=0;
|
||||||
|
try{for(const width of [1440,390])for(const lang of ['zh','en'])for(const theme of ['light','dark']){const p=await b.newPage({viewport:{width,height:1000}}),errors=[];let saved;const spaces=[];p.on('pageerror',e=>errors.push(e.message));await p.route('**/api/v1/photo-sources',r=>r.fulfill({json:[]}));await p.route('**/api/v1/photo-sources/api-fixture',r=>{saved=r.request().postDataJSON();return r.fulfill({json:{...saved,id:'api-fixture'}})});await p.route('**/api/v1/integrations/synology-photos',r=>r.fulfill({json:{configured:true,connected:true}}));await p.route('**/api/v1/integrations/synology-photos/people?*',r=>{spaces.push(new URL(r.request().url()).searchParams.get('space'));return r.fulfill({json:[{id:7,name:'Fixture person',count:3,named:true}]})});await p.goto(process.env.FRAME_FLOW_URL||'http://127.0.0.1:6005');await p.locator('#username').fill(process.env.FRAME_FLOW_TEST_USERNAME);await p.locator('#password').fill(process.env.FRAME_FLOW_TEST_PASSWORD);await p.locator('#login-form button').click();await p.locator('.hero').waitFor();assert(await p.evaluate(()=>state.settings.mock));await p.evaluate(async({lang,theme})=>{state.lang=lang;document.documentElement.dataset.theme=theme;await navigate('photo-sources')},{lang,theme});await p.locator('#add-photo-source').click();await p.locator('#source-kind').selectOption('synology-photos');await p.locator('#source-id').fill('api-fixture');await p.locator('#source-name').fill('Photos API');assert(await p.locator('#source-credential').isHidden());assert(await p.locator('#source-oauth').isHidden());assert(await p.locator('#source-synology-previews').isHidden());assert(await p.locator('#source-orientation').isEnabled());await p.locator('#source-people-filter').check();await p.locator('#source-people-load').click();await p.locator('[data-person="7"]').check();await p.locator('#source-people-space').selectOption('personal');await p.locator('#source-people-load').click();assert(!await p.locator('[data-person="7"]').isChecked());await p.locator('[data-person="7"]').check();await p.locator('#source-person-match').selectOption('all');assert(await p.evaluate(()=>document.documentElement.scrollWidth<=innerWidth));if(process.env.FRAME_FLOW_SCREENSHOT_DIR&&lang==='zh'&&theme==='dark'){require('fs').mkdirSync(process.env.FRAME_FLOW_SCREENSHOT_DIR,{recursive:true});await p.screenshot({path:process.env.FRAME_FLOW_SCREENSHOT_DIR+'/photos-api-'+width+'.png'});}await p.locator('#photo-source-form button[type="submit"]').click();await p.waitForFunction(()=>!document.querySelector('#modal').open);assert.equal(saved.kind,'synology-photos');assert.equal(saved.people_space,'personal');assert.equal(saved.person_match,'all');assert.deepEqual(saved.person_ids,[7]);assert.equal(saved.credential_env,null);assert.equal(saved.synology_previews,false);assert.deepEqual(spaces,['shared','personal']);assert.deepEqual(errors,[]);await p.close();checks++;}console.log('Photos API UI:',checks,'profiles PASS; type/space/person any-all/config and responsive layout verified');}finally{await b.close()}})().catch(e=>{console.error(e);process.exit(1)});
|
||||||
@@ -0,0 +1,54 @@
|
|||||||
|
/* Mock-only: known image metadata renders real slots; no synthetic skeletons. */
|
||||||
|
const assert=require('assert'),fs=require('fs'),{chromium}=require('playwright');
|
||||||
|
(async()=>{
|
||||||
|
const base=process.env.FRAME_FLOW_URL;assert(base);
|
||||||
|
const token=fs.readFileSync(process.env.FRAME_FLOW_ENV_FILE,'utf8').split('\n').find(x=>x.startsWith('FRAME_FLOW_TOKEN=')).slice(17);
|
||||||
|
assert((await(await fetch(base+'/api/v1/settings',{headers:{Authorization:'Bearer '+token}})).json()).mock===true);
|
||||||
|
const browser=await chromium.launch({headless:true,executablePath:process.env.CHROME_EXECUTABLE||'/Applications/Google Chrome.app/Contents/MacOS/Google Chrome'});
|
||||||
|
try{
|
||||||
|
const page=await browser.newPage();const errors=[];page.on('pageerror',e=>errors.push(e.message));
|
||||||
|
let releaseAccount;await page.route('**/api/v1/auth/me',async r=>{await new Promise(resolve=>releaseAccount=resolve);await r.continue();});
|
||||||
|
await page.goto(base);await page.locator('#nav button').first().waitFor();assert.equal(await page.locator('.image-pending,.placeholder-line,.page-placeholder').count(),0);assert.equal(await page.locator('.page-loading').count(),0);releaseAccount();
|
||||||
|
await page.locator('#username').fill(process.env.FRAME_FLOW_TEST_USERNAME);await page.locator('#password').fill(process.env.FRAME_FLOW_TEST_PASSWORD);await page.locator('#login-form button').click();await page.locator('.hero').waitFor();
|
||||||
|
let checks=1;
|
||||||
|
for(const width of [1440,390]){
|
||||||
|
await page.setViewportSize({width,height:844});await page.evaluate(()=>state.galleryCache?.clear());let releaseMetadata,metadataRequested,releaseImage,imageRequested;
|
||||||
|
await page.route('**/api/v1/devices/*/images',async r=>{metadataRequested();await new Promise(resolve=>releaseMetadata=resolve);await r.fulfill({json:[{image_id:1,name:'Progressive fixture',url:'/progressive-fixture.svg',current:false}]});});
|
||||||
|
await page.route('**/progressive-fixture.svg*',async r=>{assert.equal(await page.locator('#gallery-search').count(),1,'Search must precede image requests');assert(await page.locator('#gallery-search').evaluate(e=>typeof e.oninput==='function'));imageRequested();await new Promise(resolve=>releaseImage=resolve);await r.fulfill({contentType:'image/svg+xml',body:'<svg xmlns="http://www.w3.org/2000/svg" width="300" height="400"/>'});});
|
||||||
|
const metadata=new Promise(resolve=>metadataRequested=resolve);const image=new Promise(resolve=>imageRequested=resolve);
|
||||||
|
await page.evaluate(()=>{window.navigation=navigate('gallery');});await metadata;
|
||||||
|
assert.equal(await page.locator('.image-pending,.placeholder-line,.page-placeholder').count(),0);assert.equal(await page.locator('.image-card').count(),0);assert.equal(await page.locator('.page-loading').count(),0);checks++;
|
||||||
|
assert(await page.locator('#cloud-tab').isVisible());assert(await page.locator('#local-tab').isEnabled());assert(await page.locator('#gallery-upload').isEnabled());assert(await page.locator('#gallery-search').isVisible());assert(await page.locator('#gallery-sort').isEnabled());assert(await page.locator('#gallery-list-status').isVisible());assert.equal(await page.locator('.card.empty').count(),0);await page.locator('#gallery-search').fill('Progressive');await page.locator('#gallery-sort').selectOption('name');checks++;
|
||||||
|
releaseMetadata();await image;await page.evaluate(()=>window.navigation);
|
||||||
|
assert.equal(await page.locator('#gallery-search').inputValue(),'Progressive');assert.equal(await page.locator('#gallery-sort').inputValue(),'name');assert(await page.locator('#gallery-upload').isEnabled());assert.equal(await page.locator('.image-loading .spinner').count(),1);assert.equal(await page.locator('.image-pending').count(),0);checks++;
|
||||||
|
assert(await page.locator('.image-loading').evaluate(box=>{const a=box.getBoundingClientRect(),b=box.querySelector('.spinner').getBoundingClientRect();return Math.abs(a.x+a.width/2-b.x-b.width/2)<1&&Math.abs(a.y+a.height/2-b.y-b.height/2)<1;}));checks++;
|
||||||
|
releaseImage();await page.waitForFunction(()=>document.querySelector('.thumb')?.naturalWidth===300&&!document.querySelector('.image-loading'));checks++;
|
||||||
|
await page.evaluate(()=>navigate('upload'));
|
||||||
|
const cachedMetadata=new Promise(resolve=>metadataRequested=resolve);const cachedImage=new Promise(resolve=>imageRequested=resolve);
|
||||||
|
await page.evaluate(()=>{window.navigation=navigate('gallery');});await cachedMetadata;await cachedImage;
|
||||||
|
assert.equal(await page.locator('#gallery-search').count(),1,'Search must exist while cached metadata refresh is pending');assert(await page.locator('#gallery-search').evaluate(e=>typeof e.oninput==='function'),'Search must be interactive');assert.equal(await page.locator('.image-card').count(),1);assert.equal(await page.locator('.image-loading .spinner').count(),1);assert.equal(await page.locator('.image-pending,.placeholder-line,.page-placeholder').count(),0);checks++;
|
||||||
|
releaseMetadata();await page.evaluate(()=>window.navigation);releaseImage();await page.waitForFunction(()=>document.querySelector('.thumb')?.naturalWidth===300&&!document.querySelector('.image-loading'));
|
||||||
|
|
||||||
|
await page.unroute('**/api/v1/devices/*/images');await page.unroute('**/progressive-fixture.svg*');
|
||||||
|
let releaseDevice,deviceRequested;await page.route('**/api/v1/devices/living-room',async r=>{deviceRequested();await new Promise(resolve=>releaseDevice=resolve);await r.continue();});
|
||||||
|
const device=new Promise(resolve=>deviceRequested=resolve);await page.evaluate(()=>{window.navigation=navigate('dashboard');});await device;
|
||||||
|
assert.equal(await page.locator('.image-pending,.placeholder-line,.page-placeholder').count(),0);assert.equal(await page.locator('.page-loading').count(),0);checks++;
|
||||||
|
releaseDevice();await page.evaluate(()=>window.navigation);await page.unroute('**/api/v1/devices/living-room');
|
||||||
|
}
|
||||||
|
await page.evaluate(()=>{state.galleryCache?.clear();state.tab='cloud';});
|
||||||
|
let releaseSlow,slowRequested;const slow=new Promise(resolve=>slowRequested=resolve);
|
||||||
|
await page.route('**/api/v1/devices/*/images',async r=>{slowRequested();await new Promise(resolve=>releaseSlow=resolve);await r.fulfill({json:[]});});
|
||||||
|
await page.evaluate(()=>{window.slowNavigation=navigate('gallery');});await slow;await page.locator('#local-tab').click();await page.waitForFunction(()=>state.tab==='local'&&document.querySelector('#local-tab')?.classList.contains('active'));releaseSlow();await page.evaluate(()=>window.slowNavigation);assert.equal(await page.evaluate(()=>state.tab),'local');assert(await page.locator('#gallery-search').isVisible());checks++;
|
||||||
|
await page.unroute('**/api/v1/devices/*/images');
|
||||||
|
await page.evaluate(()=>{state.galleryCache?.clear();state.tab='cloud';});
|
||||||
|
await page.route('**/api/v1/devices/*/images',r=>r.fulfill({status:503,json:{error:{code:'CLOUD_UNAVAILABLE',message:'fixture unavailable'}}}));
|
||||||
|
await page.evaluate(()=>navigate('gallery'));assert(await page.locator('#gallery-search').isVisible());assert(await page.locator('#local-tab').isEnabled());assert.equal(await page.locator('#gallery-list-status').getAttribute('role'),'alert');checks++;
|
||||||
|
await page.unroute('**/api/v1/devices/*/images');
|
||||||
|
let releaseJobs,jobsRequested;await page.route('**/api/v1/jobs',async r=>{jobsRequested();await new Promise(resolve=>releaseJobs=resolve);await r.fulfill({json:[]});});
|
||||||
|
await page.route('**/api/v1/assets?*',r=>r.fulfill({json:[{asset_id:'local-fixture',name:'Local fixture',url:'/local-fixture.svg',origin:'manual',starred:false}]}));
|
||||||
|
await page.route('**/local-fixture.svg',r=>r.fulfill({contentType:'image/svg+xml',body:'<svg xmlns="http://www.w3.org/2000/svg" width="300" height="400"/>'}));
|
||||||
|
const jobs=new Promise(resolve=>jobsRequested=resolve);await page.evaluate(()=>{state.tab='local';return navigate('gallery');});await jobs;
|
||||||
|
assert.equal(await page.locator('.asset-select').count(),1);assert(await page.locator('#gallery-search').evaluate(e=>typeof e.oninput==='function'));await page.locator('#gallery-search').fill('no-match');assert(await page.locator('.image-card').evaluate(e=>e.hidden));releaseJobs();checks++;
|
||||||
|
assert.deepEqual(errors,[]);console.log('Known image positions without skeletons:',checks,'checks PASS; delayed bootstrap, metadata and images; no page errors');
|
||||||
|
}finally{await browser.close();}
|
||||||
|
})().catch(e=>{console.error(e.message);process.exit(1)});
|
||||||
@@ -2,7 +2,7 @@
|
|||||||
const fs=require('fs');const path=require('path');const assert=require('assert');const {chromium}=require('playwright');
|
const fs=require('fs');const path=require('path');const assert=require('assert');const {chromium}=require('playwright');
|
||||||
(async()=>{
|
(async()=>{
|
||||||
const uploadName='browser-upload-'+Date.now();const root=path.resolve(__dirname,'..');const env=fs.readFileSync(process.env.FRAME_FLOW_ENV_FILE||path.join(root,'.env'),'utf8');const token=env.split('\n').find(x=>x.startsWith('FRAME_FLOW_TOKEN=')).slice('FRAME_FLOW_TOKEN='.length);
|
const uploadName='browser-upload-'+Date.now();const root=path.resolve(__dirname,'..');const env=fs.readFileSync(process.env.FRAME_FLOW_ENV_FILE||path.join(root,'.env'),'utf8');const token=env.split('\n').find(x=>x.startsWith('FRAME_FLOW_TOKEN=')).slice('FRAME_FLOW_TOKEN='.length);
|
||||||
const base=process.env.FRAME_FLOW_URL||'http://127.0.0.1:18787';const response=await fetch(base+'/api/v1/settings',{headers:{Authorization:'Bearer '+token}});const settings=await response.json();assert(settings.mock===true,'UI smoke requires Mock mode');
|
const base=process.env.FRAME_FLOW_URL||'http://127.0.0.1:6005';const response=await fetch(base+'/api/v1/settings',{headers:{Authorization:'Bearer '+token}});const settings=await response.json();assert(settings.mock===true,'UI smoke requires Mock mode');
|
||||||
const browser=await chromium.launch({headless:true,executablePath:'/Applications/Google Chrome.app/Contents/MacOS/Google Chrome'});
|
const browser=await chromium.launch({headless:true,executablePath:'/Applications/Google Chrome.app/Contents/MacOS/Google Chrome'});
|
||||||
const context=await browser.newContext({viewport:{width:1440,height:1000}});const page=await context.newPage();const errors=[];page.on('pageerror',e=>errors.push(e.message.replaceAll(token,'[REDACTED]')));let checks=0;
|
const context=await browser.newContext({viewport:{width:1440,height:1000}});const page=await context.newPage();const errors=[];page.on('pageerror',e=>errors.push(e.message.replaceAll(token,'[REDACTED]')));let checks=0;
|
||||||
await page.addInitScript(()=>Object.defineProperty(window.crypto,'randomUUID',{value:undefined,configurable:true}));await page.goto(base);await page.locator('#username').fill(process.env.FRAME_FLOW_TEST_USERNAME);await page.locator('#password').fill(process.env.FRAME_FLOW_TEST_PASSWORD);await page.locator('#login-form button').click();await page.locator('.hero').waitFor();assert(await page.locator('h2').first().innerText()==='客厅相框');checks++;
|
await page.addInitScript(()=>Object.defineProperty(window.crypto,'randomUUID',{value:undefined,configurable:true}));await page.goto(base);await page.locator('#username').fill(process.env.FRAME_FLOW_TEST_USERNAME);await page.locator('#password').fill(process.env.FRAME_FLOW_TEST_PASSWORD);await page.locator('#login-form button').click();await page.locator('.hero').waitFor();assert(await page.locator('h2').first().innerText()==='客厅相框');checks++;
|
||||||
@@ -17,9 +17,9 @@ const fs=require('fs');const path=require('path');const assert=require('assert')
|
|||||||
await page.locator('#make-preview').click();await page.waitForFunction(()=>!document.querySelector('#save-local').disabled);checks++;
|
await page.locator('#make-preview').click();await page.waitForFunction(()=>!document.querySelector('#save-local').disabled);checks++;
|
||||||
await page.locator('#save-local').click();const uploaded=page.locator('.image-card').filter({hasText:uploadName+'.jpg'});await uploaded.waitFor();checks++;
|
await page.locator('#save-local').click();const uploaded=page.locator('.image-card').filter({hasText:uploadName+'.jpg'});await uploaded.waitFor();checks++;
|
||||||
await uploaded.locator('[data-delete]').click();await page.locator('#modal-confirm').click();await uploaded.waitFor({state:'hidden'});checks++;
|
await uploaded.locator('[data-delete]').click();await page.locator('#modal-confirm').click();await uploaded.waitFor({state:'hidden'});checks++;
|
||||||
await page.locator('[data-page="templates"]').click();await page.locator('.template-card').first().waitFor();assert(await page.locator('.template-card').count()===7);checks++;
|
await page.locator('[data-page="templates"]').click();await page.locator('.template-card').first().waitFor();assert(await page.locator('.template-card').count()===9);checks++;
|
||||||
await page.locator('#render-template').click();await page.locator('#template-image').waitFor({timeout:30000});assert(await page.locator('#display-template').isEnabled());checks++;
|
await page.locator('#render-template').click();await page.locator('#template-image').waitFor({timeout:30000});assert(await page.locator('#display-template').isEnabled());checks++;
|
||||||
await page.locator('#field-title').fill('Edited title');assert(await page.locator('#display-template').isDisabled());checks++;await page.locator('#save-template').click();await page.reload();await page.locator('#field-title').waitFor();assert(await page.locator('#field-title').inputValue()==='Edited title');checks++;await page.locator('#reset-template').click();await page.locator('#modal-confirm').click();await page.waitForFunction(()=>document.querySelector('#field-title')?.value!=='Edited title'&&document.querySelector('#field-title'));assert(await page.locator('#field-title').inputValue()!=='Edited title');checks++;await page.locator('#field-title').fill('Provenance UI title');await page.locator('#render-template').click();await page.locator('#template-image').waitFor();await page.locator('#display-template').click();await page.locator('#confirm-display').click();await page.locator('[data-page="history"]').click();await page.locator('tbody tr').first().waitFor();checks++;await page.locator('tbody tr button').first().click();await page.locator('#modal-cancel').click();checks++;await page.locator('[data-page="dashboard"]').click();await page.locator('#edit-current-template').waitFor({timeout:30000});await page.locator('#edit-current-template').click();await page.locator('#field-title').waitFor();assert(await page.locator('#field-title').inputValue()==='Provenance UI title');checks++;
|
await page.locator('#field-title').fill('Edited title');assert(await page.locator('#display-template').isDisabled());checks++;await page.locator('#save-template').click();await page.reload();await page.locator('#field-title').waitFor();assert(await page.locator('#field-title').inputValue()==='Edited title');checks++;await page.locator('#reset-template').click();await page.locator('#modal-confirm').click();await page.waitForFunction(()=>document.querySelector('#field-title')?.value!=='Edited title'&&document.querySelector('#field-title'));assert(await page.locator('#field-title').inputValue()!=='Edited title');checks++;await page.locator('#field-title').fill('Provenance UI title');await page.locator('#render-template').click();await page.locator('#template-image').waitFor();await page.locator('#display-template').click();await page.locator('#confirm-display').click();await page.locator('[data-page="history"]').click();await page.locator('tbody tr').first().waitFor();checks++;await page.locator('tbody tr button').first().click();await page.locator('#modal-cancel').click();checks++;await page.waitForFunction(async()=>{const response=await fetch('/api/v1/devices/living-room/current-content');const content=await response.json();return content.source?.data?.title==='Provenance UI title';});await page.locator('[data-page="dashboard"]').click();await page.locator('#edit-current-template').waitFor({timeout:30000});await page.locator('#edit-current-template').click();await page.locator('#field-title').waitFor();assert(await page.locator('#field-title').inputValue()==='Provenance UI title');checks++;
|
||||||
await page.locator('[data-page="automation"]').click();await page.locator('#new-job').click();await page.locator('#job-content-type').waitFor();await page.locator('#job-template').selectOption('quote');checks++;await page.locator('#job-name').fill('UI acceptance');await page.locator('#job-form button[type=submit]').click();await page.locator('td strong').filter({hasText:'UI acceptance'}).waitFor();checks++;
|
await page.locator('[data-page="automation"]').click();await page.locator('#new-job').click();await page.locator('#job-content-type').waitFor();await page.locator('#job-template').selectOption('quote');checks++;await page.locator('#job-name').fill('UI acceptance');await page.locator('#job-form button[type=submit]').click();await page.locator('td strong').filter({hasText:'UI acceptance'}).waitFor();checks++;
|
||||||
await page.locator('[data-job-toggle]').first().click();await page.getByText('Paused',{exact:true}).first().waitFor();checks++;
|
await page.locator('[data-job-toggle]').first().click();await page.getByText('Paused',{exact:true}).first().waitFor();checks++;
|
||||||
await page.locator('[data-job-delete]').first().click();await page.locator('#modal-confirm').click();await page.locator('td strong').filter({hasText:'UI acceptance'}).waitFor({state:'hidden'});checks++;
|
await page.locator('[data-job-delete]').first().click();await page.locator('#modal-confirm').click();await page.locator('td strong').filter({hasText:'UI acceptance'}).waitFor({state:'hidden'});checks++;
|
||||||
|
|||||||
@@ -0,0 +1,32 @@
|
|||||||
|
/* Mock-only editor regression: parallel image requests, stable regions and live controls. */
|
||||||
|
const assert=require('assert'),fs=require('fs'),{chromium}=require('playwright');
|
||||||
|
(async()=>{
|
||||||
|
const base=process.env.FRAME_FLOW_URL;assert(base);const token=fs.readFileSync(process.env.FRAME_FLOW_ENV_FILE,'utf8').split('\n').find(x=>x.startsWith('FRAME_FLOW_TOKEN=')).slice(17);
|
||||||
|
assert((await(await fetch(base+'/api/v1/settings',{headers:{Authorization:'Bearer '+token}})).json()).mock===true);
|
||||||
|
const browser=await chromium.launch({headless:true,executablePath:process.env.CHROME_EXECUTABLE||'/Applications/Google Chrome.app/Contents/MacOS/Google Chrome'});
|
||||||
|
try{
|
||||||
|
const page=await browser.newPage();const errors=[];page.on('pageerror',e=>errors.push(e.message));
|
||||||
|
await page.route('**/api/v1/assets?*',r=>r.fulfill({json:[{asset_id:'studio-fixture-a',name:'A'},{asset_id:'studio-fixture-b',name:'B'}]}));
|
||||||
|
await page.route('**/api/v1/layout/plan',r=>r.fulfill({json:{width:1200,height:1600,regions:[{asset_id:'studio-fixture-a',x:20,y:200,width:550,height:900},{asset_id:'studio-fixture-b',x:620,y:200,width:550,height:900}]}}));
|
||||||
|
let requests,releases,failSecond=false;
|
||||||
|
await page.route('**/api/v1/assets/studio-fixture-*',async r=>{const key=r.request().url().split('-').pop();requests.add(key);await new Promise(resolve=>releases[key]=resolve);await r.fulfill({contentType:'image/svg+xml',body:failSecond&&key==='b'?'invalid image':'<svg xmlns="http://www.w3.org/2000/svg" width="300" height="400"><rect width="300" height="400" fill="#167253"/></svg>'});});
|
||||||
|
await page.goto(base);await page.locator('#username').fill(process.env.FRAME_FLOW_TEST_USERNAME);await page.locator('#password').fill(process.env.FRAME_FLOW_TEST_PASSWORD);await page.locator('#login-form button').click();await page.locator('.hero').waitFor();let checks=0;
|
||||||
|
for(const width of [1440,390])for(const theme of ['light','dark']){
|
||||||
|
requests=new Set();releases={};await page.setViewportSize({width,height:900});await page.evaluate(theme=>{document.documentElement.dataset.theme=theme;return navigate('studio');},theme);await page.locator('.manual-collage summary').click();
|
||||||
|
await page.locator('#studio-assets input').nth(0).check();await page.locator('#studio-assets input').nth(1).check();await page.locator('#studio-plan').click();
|
||||||
|
await page.waitForFunction(()=>document.querySelectorAll('.studio-region .spinner').length===2);for(let n=0;n<100&&requests.size<2;n++)await page.waitForTimeout(20);assert.equal(requests.size,2,'Both requests must start before either finishes');assert(await page.locator('#studio-render').isEnabled());checks++;
|
||||||
|
assert(await page.locator('.studio-region').evaluateAll(regions=>regions.every(region=>{const a=region.getBoundingClientRect(),b=region.querySelector('.spinner').getBoundingClientRect();return Math.abs(a.x+a.width/2-b.x-b.width/2)<1&&Math.abs(a.y+a.height/2-b.y-b.height/2)<1;})));checks++;
|
||||||
|
const field=page.locator('[data-region="0"][data-key="x"]');await field.fill('40');await field.dispatchEvent('input');assert(await page.locator('.studio-region').first().evaluate(e=>Math.abs(parseFloat(e.style.left)-40/1200*100)<0.01));checks++;
|
||||||
|
const before=await page.locator('.studio-region').nth(1).boundingBox();releases.b();await page.waitForFunction(()=>document.querySelectorAll('.studio-region')[1].querySelector('img').naturalWidth===300&&!document.querySelectorAll('.studio-region')[1].querySelector('.image-loading'));
|
||||||
|
assert.equal(await page.locator('.studio-region').first().locator('.spinner').count(),1);assert.deepEqual(await page.locator('.studio-region').nth(1).boundingBox(),before);checks++;
|
||||||
|
const region=page.locator('.studio-region').nth(1);await region.scrollIntoViewIfNeeded();const point=await region.boundingBox();const old=await page.locator('[data-region="1"][data-key="x"]').inputValue();await page.mouse.move(point.x+point.width/2,point.y+Math.min(point.height/2,80));await page.mouse.down();await page.mouse.move(point.x+point.width/2-10,point.y+Math.min(point.height/2,80)+5,{steps:3});await page.mouse.up();assert.notEqual(await page.locator('[data-region="1"][data-key="x"]').inputValue(),old);checks++;
|
||||||
|
releases.a();await page.waitForFunction(()=>document.querySelectorAll('.studio-region img').length===2&&[...document.querySelectorAll('.studio-region img')].every(img=>img.naturalWidth===300)&&!document.querySelector('.studio-region .image-loading'));checks++;
|
||||||
|
assert(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth));checks++;
|
||||||
|
}
|
||||||
|
requests=new Set();releases={};failSecond=true;await page.locator('#studio-plan').click();for(let n=0;n<100&&requests.size<2;n++)await page.waitForTimeout(20);assert.equal(requests.size,2);
|
||||||
|
releases.b();await page.locator('.studio-region .image-load-error').waitFor();assert.equal(await page.locator('.studio-region').first().locator('.spinner').count(),1);assert(await page.locator('#studio-render').isEnabled());checks++;
|
||||||
|
const errorField=page.locator('[data-region="1"][data-key="x"]');await errorField.fill('600');await errorField.dispatchEvent('input');assert.equal(await page.locator('.studio-region').nth(1).evaluate(e=>e.style.left),'50%');checks++;
|
||||||
|
releases.a();await page.waitForFunction(()=>document.querySelector('.studio-region img')?.naturalWidth===300);assert.equal(await page.locator('.studio-region .spinner').count(),0);checks++;
|
||||||
|
assert.deepEqual(errors,[]);console.log('Studio image loading:',checks,'checks PASS; parallel requests, independent completion, local spinners, coordinate editing and dragging; no page errors');
|
||||||
|
}finally{await browser.close();}
|
||||||
|
})().catch(e=>{console.error(e.message);process.exit(1)});
|
||||||
@@ -4,7 +4,7 @@ const assert=require('assert'),{chromium}=require('playwright');
|
|||||||
const browser=await chromium.launch({headless:true,executablePath:'/Applications/Google Chrome.app/Contents/MacOS/Google Chrome'});
|
const browser=await chromium.launch({headless:true,executablePath:'/Applications/Google Chrome.app/Contents/MacOS/Google Chrome'});
|
||||||
const page=await browser.newPage();const errors=[];page.on('pageerror',e=>errors.push(e.message));let status='AUTH_REQUIRED',checks=0;
|
const page=await browser.newPage();const errors=[];page.on('pageerror',e=>errors.push(e.message));let status='AUTH_REQUIRED',checks=0;
|
||||||
await page.route('**/api/v1/devices/*/widgets',route=>route.fulfill({json:{source:status==='AUTH_REQUIRED'?'snapshot':'live',configured:status!=='AUTH_REQUIRED',status,observed_at:'2026-10-02',catalog:[],current:null,current_verified:status==='NO_WIDGET',writable:false}}));
|
await page.route('**/api/v1/devices/*/widgets',route=>route.fulfill({json:{source:status==='AUTH_REQUIRED'?'snapshot':'live',configured:status!=='AUTH_REQUIRED',status,observed_at:'2026-10-02',catalog:[],current:null,current_verified:status==='NO_WIDGET',writable:false}}));
|
||||||
await page.goto('http://127.0.0.1:18787');await page.locator('#username').fill(process.env.FRAME_FLOW_TEST_USERNAME);await page.locator('#password').fill(process.env.FRAME_FLOW_TEST_PASSWORD);await page.locator('#login-form button').click();await page.locator('.hero').waitFor();
|
await page.goto(process.env.FRAME_FLOW_URL||'http://127.0.0.1:6005');await page.locator('#username').fill(process.env.FRAME_FLOW_TEST_USERNAME);await page.locator('#password').fill(process.env.FRAME_FLOW_TEST_PASSWORD);await page.locator('#login-form button').click();await page.locator('.hero').waitFor();
|
||||||
for(const lang of ['zh','en'])for(const value of ['AUTH_REQUIRED','NO_WIDGET','CURRENT_UNVERIFIED']){
|
for(const lang of ['zh','en'])for(const value of ['AUTH_REQUIRED','NO_WIDGET','CURRENT_UNVERIFIED']){
|
||||||
status=value;await page.evaluate(lang=>{state.lang=lang;return navigate('templates');},lang);
|
status=value;await page.evaluate(lang=>{state.lang=lang;return navigate('templates');},lang);
|
||||||
await page.locator('.widget-auth-notice').waitFor({state:'attached'});
|
await page.locator('.widget-auth-notice').waitFor({state:'attached'});
|
||||||
|
|||||||
@@ -0,0 +1,45 @@
|
|||||||
|
"""Smoke-check an already running isolated Mock container, via its loopback HTTP."""
|
||||||
|
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import time
|
||||||
|
import urllib.request
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
assert os.getuid() == 10333 and os.getgid() == 10333
|
||||||
|
assert not Path("/photos").exists()
|
||||||
|
for _ in range(30):
|
||||||
|
try:
|
||||||
|
with urllib.request.urlopen(
|
||||||
|
"http://127.0.0.1:18787/ready", timeout=2
|
||||||
|
) as response:
|
||||||
|
assert json.load(response)["status"] == "ready"
|
||||||
|
break
|
||||||
|
except OSError:
|
||||||
|
time.sleep(1)
|
||||||
|
else:
|
||||||
|
raise SystemExit("Mock readiness failed")
|
||||||
|
with urllib.request.urlopen(
|
||||||
|
"http://127.0.0.1:18787/api/v1/version", timeout=2
|
||||||
|
) as response:
|
||||||
|
version = json.load(response)
|
||||||
|
assert version["version"] == "0.1.9"
|
||||||
|
assert Path("/data/frameflow.db").is_file()
|
||||||
|
print(
|
||||||
|
json.dumps(
|
||||||
|
{
|
||||||
|
"ready": True,
|
||||||
|
"version": version["version"],
|
||||||
|
"commit": version["commit"],
|
||||||
|
"uid": os.getuid(),
|
||||||
|
"gid": os.getgid(),
|
||||||
|
"no_photos_mount": True,
|
||||||
|
}
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
@@ -0,0 +1,112 @@
|
|||||||
|
"""Read-only live Photos check. Never creates an app, worker, job or frame driver."""
|
||||||
|
|
||||||
|
import argparse
|
||||||
|
import io
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
from PIL import Image
|
||||||
|
|
||||||
|
from pigway_frame_flow.errors import FlowError
|
||||||
|
from pigway_frame_flow.providers.photo_sources import PhotoSourceInput, PhotoSources
|
||||||
|
from pigway_frame_flow.settings import Settings
|
||||||
|
from pigway_frame_flow.storage.database import Database
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
parser = argparse.ArgumentParser(description=__doc__)
|
||||||
|
parser.add_argument("--bootstrap", type=Path, required=True)
|
||||||
|
parser.add_argument("--output", type=Path, required=True)
|
||||||
|
args = parser.parse_args()
|
||||||
|
if Path("/photos").exists():
|
||||||
|
raise SystemExit("Verification requires /photos to be absent")
|
||||||
|
bootstrap = json.loads(args.bootstrap.read_text())
|
||||||
|
os.environ["SYNOLOGY_PHOTOS_URL"] = bootstrap["url"]
|
||||||
|
os.environ["SYNOLOGY_PHOTOS_CERT_SHA256"] = bootstrap["pin"]
|
||||||
|
settings = Settings(mock=True, write_enabled=False, api_key="", api_token="")
|
||||||
|
settings.data_dir.mkdir(parents=True, exist_ok=True)
|
||||||
|
settings.config_dir.mkdir(parents=True, exist_ok=True)
|
||||||
|
session = settings.config_dir / "synology-photos-session.json"
|
||||||
|
session.write_text(json.dumps(bootstrap["session"]))
|
||||||
|
session.chmod(0o600)
|
||||||
|
db = Database(settings.data_dir / "verification.db")
|
||||||
|
photos = PhotoSources(db, settings, None)
|
||||||
|
report = {"no_photos_mount": True, "device_writes": 0, "spaces": {}}
|
||||||
|
try:
|
||||||
|
for space in ("shared", "personal"):
|
||||||
|
people = photos.synology.people(space)
|
||||||
|
candidates = sorted(
|
||||||
|
(p for p in people if p["count"] > 1), key=lambda p: p["count"]
|
||||||
|
)
|
||||||
|
if len(candidates) < 2:
|
||||||
|
raise RuntimeError("Need two accessible populated person albums")
|
||||||
|
selected = [p["id"] for p in candidates[:2]]
|
||||||
|
one = photos.synology.items(selected[:1], space=space)
|
||||||
|
two = photos.synology.items(selected[1:], space=space)
|
||||||
|
ids_one, ids_two = {r["id"] for r in one}, {r["id"] for r in two}
|
||||||
|
any_rows = photos.synology.items(selected, "any", space=space)
|
||||||
|
all_rows = photos.synology.items(selected, "all", space=space)
|
||||||
|
assert {r["id"] for r in any_rows} == ids_one | ids_two
|
||||||
|
assert {r["id"] for r in all_rows} == ids_one & ids_two
|
||||||
|
source_id = "live-" + space
|
||||||
|
photos.save(
|
||||||
|
source_id,
|
||||||
|
PhotoSourceInput(
|
||||||
|
name="Read-only verification",
|
||||||
|
kind="synology-photos",
|
||||||
|
location=".",
|
||||||
|
people_space=space,
|
||||||
|
people_filter=True,
|
||||||
|
person_ids=selected,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
catalog = photos.catalog(source_id)
|
||||||
|
assert catalog
|
||||||
|
data, _, _ = photos.read(source_id, catalog[0]["id"])
|
||||||
|
with Image.open(io.BytesIO(data)) as image:
|
||||||
|
image.load()
|
||||||
|
decoded = {
|
||||||
|
"width": image.width,
|
||||||
|
"height": image.height,
|
||||||
|
"format": image.format,
|
||||||
|
}
|
||||||
|
cache = photos.synology.image_cache
|
||||||
|
before = cache.downloads
|
||||||
|
assert photos.read(source_id, catalog[0]["id"])[0] == data
|
||||||
|
assert cache.downloads == before
|
||||||
|
report["spaces"][space] = {
|
||||||
|
"people": len(people),
|
||||||
|
"any_count": len(any_rows),
|
||||||
|
"all_count": len(all_rows),
|
||||||
|
"catalog_count": len(catalog),
|
||||||
|
"bytes": len(data),
|
||||||
|
"decoded": decoded,
|
||||||
|
"cache_reused": True,
|
||||||
|
}
|
||||||
|
# A deliberately invalid session is isolated to this verification config;
|
||||||
|
# no logout request or change is made to the original NAS session.
|
||||||
|
photos.synology.path.write_text(
|
||||||
|
json.dumps({"sid": "frameflow-deliberately-invalid-session"})
|
||||||
|
)
|
||||||
|
try:
|
||||||
|
photos.synology.people()
|
||||||
|
except FlowError as error:
|
||||||
|
assert error.status == 409
|
||||||
|
report["expired_session"] = "explicit_reconnect_required"
|
||||||
|
else:
|
||||||
|
raise RuntimeError("Invalid session unexpectedly accepted")
|
||||||
|
report["cache_bytes"] = sum(
|
||||||
|
p.stat().st_size
|
||||||
|
for p in (settings.data_dir / "cache/synology-photos").glob("*.image")
|
||||||
|
)
|
||||||
|
assert report["cache_bytes"] <= settings.photos_cache_bytes
|
||||||
|
report["original_download"] = "not_supported_by_this_verified_implementation"
|
||||||
|
args.output.write_text(json.dumps(report, indent=2) + "\n")
|
||||||
|
print(json.dumps(report, indent=2))
|
||||||
|
finally:
|
||||||
|
session.unlink(missing_ok=True)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
@@ -30,3 +30,17 @@ def client(app):
|
|||||||
@pytest.fixture
|
@pytest.fixture
|
||||||
def service(app):
|
def service(app):
|
||||||
return app.state.service
|
return app.state.service
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def legacy_photo_engine(monkeypatch):
|
||||||
|
"""Exercise retained legacy internals without weakening production policy.
|
||||||
|
|
||||||
|
These fixtures cover rendering, retention and migration algorithms that used
|
||||||
|
filesystem inputs historically. API boundary tests never use this override.
|
||||||
|
"""
|
||||||
|
from pigway_frame_flow.providers.photo_sources import PhotoSources
|
||||||
|
|
||||||
|
monkeypatch.setattr(
|
||||||
|
PhotoSources, "require_api_source", staticmethod(lambda source: None)
|
||||||
|
)
|
||||||
|
|||||||
@@ -373,6 +373,9 @@
|
|||||||
{
|
{
|
||||||
"$ref": "#/components/schemas/PhotoSourceContent"
|
"$ref": "#/components/schemas/PhotoSourceContent"
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
"$ref": "#/components/schemas/AutoCollageContent"
|
||||||
|
},
|
||||||
{
|
{
|
||||||
"$ref": "#/components/schemas/ProviderContent"
|
"$ref": "#/components/schemas/ProviderContent"
|
||||||
},
|
},
|
||||||
@@ -384,6 +387,7 @@
|
|||||||
"discriminator": {
|
"discriminator": {
|
||||||
"propertyName": "type",
|
"propertyName": "type",
|
||||||
"mapping": {
|
"mapping": {
|
||||||
|
"auto_collage": "#/components/schemas/AutoCollageContent",
|
||||||
"html": "#/components/schemas/FutureContent",
|
"html": "#/components/schemas/FutureContent",
|
||||||
"image": "#/components/schemas/ImageContent",
|
"image": "#/components/schemas/ImageContent",
|
||||||
"image_url": "#/components/schemas/URLContent",
|
"image_url": "#/components/schemas/URLContent",
|
||||||
@@ -609,6 +613,16 @@
|
|||||||
},
|
},
|
||||||
"Operation": {
|
"Operation": {
|
||||||
"properties": {
|
"properties": {
|
||||||
|
"recovery": {
|
||||||
|
"anyOf": [
|
||||||
|
{
|
||||||
|
"$ref": "#/components/schemas/RecoveryState"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "null"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
"operation_id": {
|
"operation_id": {
|
||||||
"type": "string",
|
"type": "string",
|
||||||
"title": "Operation Id"
|
"title": "Operation Id"
|
||||||
@@ -855,6 +869,7 @@
|
|||||||
"type": "string",
|
"type": "string",
|
||||||
"enum": [
|
"enum": [
|
||||||
"local",
|
"local",
|
||||||
|
"synology-photos",
|
||||||
"webdav",
|
"webdav",
|
||||||
"google-drive",
|
"google-drive",
|
||||||
"alipan",
|
"alipan",
|
||||||
@@ -1007,6 +1022,7 @@
|
|||||||
"type": "string",
|
"type": "string",
|
||||||
"enum": [
|
"enum": [
|
||||||
"local",
|
"local",
|
||||||
|
"synology-photos",
|
||||||
"webdav",
|
"webdav",
|
||||||
"google-drive",
|
"google-drive",
|
||||||
"alipan",
|
"alipan",
|
||||||
@@ -1337,5 +1353,129 @@
|
|||||||
"name"
|
"name"
|
||||||
],
|
],
|
||||||
"title": "PhotosPerson"
|
"title": "PhotosPerson"
|
||||||
|
},
|
||||||
|
"AutoCollageContent": {
|
||||||
|
"properties": {
|
||||||
|
"type": {
|
||||||
|
"type": "string",
|
||||||
|
"const": "auto_collage",
|
||||||
|
"title": "Type"
|
||||||
|
},
|
||||||
|
"source_id": {
|
||||||
|
"anyOf": [
|
||||||
|
{
|
||||||
|
"type": "string",
|
||||||
|
"pattern": "^[a-z0-9-]{1,60}$"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "null"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"title": "Source Id"
|
||||||
|
},
|
||||||
|
"count": {
|
||||||
|
"type": "integer",
|
||||||
|
"maximum": 12.0,
|
||||||
|
"minimum": 1.0,
|
||||||
|
"title": "Count",
|
||||||
|
"default": 4
|
||||||
|
},
|
||||||
|
"title": {
|
||||||
|
"type": "string",
|
||||||
|
"maxLength": 100,
|
||||||
|
"title": "Title",
|
||||||
|
"default": ""
|
||||||
|
},
|
||||||
|
"message": {
|
||||||
|
"type": "string",
|
||||||
|
"maxLength": 500,
|
||||||
|
"title": "Message",
|
||||||
|
"default": ""
|
||||||
|
},
|
||||||
|
"orientation": {
|
||||||
|
"type": "string",
|
||||||
|
"enum": [
|
||||||
|
"auto",
|
||||||
|
"portrait",
|
||||||
|
"landscape"
|
||||||
|
],
|
||||||
|
"title": "Orientation",
|
||||||
|
"default": "auto"
|
||||||
|
},
|
||||||
|
"style": {
|
||||||
|
"type": "string",
|
||||||
|
"enum": [
|
||||||
|
"grid",
|
||||||
|
"hero",
|
||||||
|
"poster"
|
||||||
|
],
|
||||||
|
"title": "Style",
|
||||||
|
"default": "grid"
|
||||||
|
},
|
||||||
|
"use_ai": {
|
||||||
|
"type": "boolean",
|
||||||
|
"title": "Use Ai",
|
||||||
|
"default": true
|
||||||
|
},
|
||||||
|
"prompt": {
|
||||||
|
"type": "string",
|
||||||
|
"maxLength": 1500,
|
||||||
|
"title": "Prompt",
|
||||||
|
"default": ""
|
||||||
|
},
|
||||||
|
"profile": {
|
||||||
|
"$ref": "#/components/schemas/Profile",
|
||||||
|
"default": "color"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"additionalProperties": false,
|
||||||
|
"type": "object",
|
||||||
|
"required": [
|
||||||
|
"type"
|
||||||
|
],
|
||||||
|
"title": "AutoCollageContent"
|
||||||
|
},
|
||||||
|
"RecoveryState": {
|
||||||
|
"properties": {
|
||||||
|
"state": {
|
||||||
|
"type": "string",
|
||||||
|
"enum": [
|
||||||
|
"checking",
|
||||||
|
"manual_review",
|
||||||
|
"resolved"
|
||||||
|
],
|
||||||
|
"title": "State"
|
||||||
|
},
|
||||||
|
"reason": {
|
||||||
|
"type": "string",
|
||||||
|
"title": "Reason"
|
||||||
|
},
|
||||||
|
"first_checked_at": {
|
||||||
|
"type": "string",
|
||||||
|
"title": "First Checked At"
|
||||||
|
},
|
||||||
|
"last_checked_at": {
|
||||||
|
"type": "string",
|
||||||
|
"title": "Last Checked At"
|
||||||
|
},
|
||||||
|
"checks": {
|
||||||
|
"type": "integer",
|
||||||
|
"title": "Checks"
|
||||||
|
},
|
||||||
|
"requires_manual_review": {
|
||||||
|
"type": "boolean",
|
||||||
|
"title": "Requires Manual Review"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"type": "object",
|
||||||
|
"required": [
|
||||||
|
"state",
|
||||||
|
"reason",
|
||||||
|
"first_checked_at",
|
||||||
|
"last_checked_at",
|
||||||
|
"checks",
|
||||||
|
"requires_manual_review"
|
||||||
|
],
|
||||||
|
"title": "RecoveryState"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -50,6 +50,7 @@ def test_generation_queued_once_and_never_displays(client, service, monkeypatch)
|
|||||||
operation = service.operation(first.json()["operation_id"])
|
operation = service.operation(first.json()["operation_id"])
|
||||||
assert operation["status"] == "COMPLETED"
|
assert operation["status"] == "COMPLETED"
|
||||||
assert len(calls) == 1
|
assert len(calls) == 1
|
||||||
|
assert calls[0]["timeout"] == 180
|
||||||
assert json.loads(calls[0]["body"])["n"] == 1
|
assert json.loads(calls[0]["body"])["n"] == 1
|
||||||
assert service.registry.get("living-room").client.uploads == 0
|
assert service.registry.get("living-room").client.uploads == 0
|
||||||
assert "private-ai-key" not in client.get("/api/v1/settings/ai-images").text
|
assert "private-ai-key" not in client.get("/api/v1/settings/ai-images").text
|
||||||
|
|||||||
@@ -423,3 +423,35 @@ def test_scoped_client_operation_isolation(client, service):
|
|||||||
assert [op["operation_id"] for op in client.get("/api/v1/operations").json()] == [
|
assert [op["operation_id"] for op in client.get("/api/v1/operations").json()] == [
|
||||||
own
|
own
|
||||||
]
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def test_settings_exposes_storage_display_name(client, service):
|
||||||
|
service.settings.storage_name = "Family NAS"
|
||||||
|
result = client.get("/api/v1/settings").json()
|
||||||
|
assert result["storage_name"] == "Family NAS"
|
||||||
|
destinations = {d["id"]: d for d in result["gallery_destinations"]}
|
||||||
|
assert set(destinations) == {"cloud", "local"}
|
||||||
|
assert destinations["cloud"]["name"] == "KoKonna"
|
||||||
|
assert destinations["local"]["name"] == "Family NAS"
|
||||||
|
assert all(d["connected"] and d["supports_upload"] for d in destinations.values())
|
||||||
|
assert "test-frame-token" not in str(result)
|
||||||
|
|
||||||
|
|
||||||
|
def test_storage_display_name_environment(monkeypatch):
|
||||||
|
monkeypatch.setenv("FRAME_FLOW_STORAGE_NAME", " Family NAS ")
|
||||||
|
assert Settings().storage_name == "Family NAS"
|
||||||
|
monkeypatch.setenv("FRAME_FLOW_STORAGE_NAME", " ")
|
||||||
|
assert Settings().storage_name == "NAS"
|
||||||
|
|
||||||
|
|
||||||
|
def test_settings_device_catalog_does_not_fetch_cloud_status(
|
||||||
|
client, service, monkeypatch
|
||||||
|
):
|
||||||
|
registry = service.registry
|
||||||
|
for driver in registry.drivers.values():
|
||||||
|
monkeypatch.setattr(
|
||||||
|
driver, "device", lambda *a, **kw: pytest.fail("Cloud status fetched")
|
||||||
|
)
|
||||||
|
result = client.get("/api/v1/settings")
|
||||||
|
assert result.status_code == 200
|
||||||
|
assert {d["id"] for d in result.json()["device_catalog"]} == set(registry.drivers)
|
||||||
|
|||||||
@@ -0,0 +1,160 @@
|
|||||||
|
from io import BytesIO
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
from PIL import Image
|
||||||
|
from pydantic import ValidationError
|
||||||
|
|
||||||
|
from pigway_frame_flow.models import AutoCollageContent
|
||||||
|
|
||||||
|
|
||||||
|
def photos(service, count=4):
|
||||||
|
for i in range(count):
|
||||||
|
data = BytesIO()
|
||||||
|
Image.new("RGB", (320 + i, 200), (i * 50, 60, 100)).save(data, "JPEG")
|
||||||
|
service.assets.put(data.getvalue(), f"photo-{i}.jpg")
|
||||||
|
|
||||||
|
|
||||||
|
def test_auto_preview_selects_exact_distinct_photos_without_frame_write(
|
||||||
|
client, service
|
||||||
|
):
|
||||||
|
photos(service)
|
||||||
|
result = client.post(
|
||||||
|
"/api/v1/render", json={"type": "auto_collage", "count": 3, "use_ai": False}
|
||||||
|
)
|
||||||
|
assert result.status_code == 202
|
||||||
|
service.process_one()
|
||||||
|
operation = service.operation(result.json()["operation_id"])
|
||||||
|
assert operation["status"] == "COMPLETED"
|
||||||
|
asset = operation["result"]["asset_id"]
|
||||||
|
import json
|
||||||
|
|
||||||
|
source = json.loads(
|
||||||
|
service.db.one("SELECT payload FROM asset_sources WHERE asset_id=?", (asset,))[
|
||||||
|
"payload"
|
||||||
|
]
|
||||||
|
)
|
||||||
|
regions = source["data"]["layout"]["regions"]
|
||||||
|
assert len({x["asset_id"] for x in regions}) == 3
|
||||||
|
assert service.registry.get("living-room").client.uploads == 0
|
||||||
|
|
||||||
|
|
||||||
|
def test_insufficient_photos_and_unconfigured_ai_fail_before_upload(service):
|
||||||
|
from pigway_frame_flow.errors import FlowError
|
||||||
|
|
||||||
|
photos(service, 1)
|
||||||
|
for content in [
|
||||||
|
AutoCollageContent(type="auto_collage", count=2, use_ai=False),
|
||||||
|
AutoCollageContent(type="auto_collage", count=1),
|
||||||
|
]:
|
||||||
|
with pytest.raises(FlowError):
|
||||||
|
service.content_asset(content)
|
||||||
|
assert service.registry.get("living-room").client.uploads == 0
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("count", [0, 13])
|
||||||
|
def test_count_bounds(count):
|
||||||
|
with pytest.raises(ValidationError):
|
||||||
|
AutoCollageContent(type="auto_collage", count=count)
|
||||||
|
|
||||||
|
|
||||||
|
def test_auto_collage_job_contract_and_preview(client, service):
|
||||||
|
photos(service, 2)
|
||||||
|
job = client.post(
|
||||||
|
"/api/v1/jobs",
|
||||||
|
json={
|
||||||
|
"name": "Collage",
|
||||||
|
"device_id": "living-room",
|
||||||
|
"enabled": False,
|
||||||
|
"schedule": {"type": "daily", "time": "08:00"},
|
||||||
|
"source": {"type": "auto_collage", "count": 2, "use_ai": False},
|
||||||
|
},
|
||||||
|
)
|
||||||
|
assert job.status_code == 201
|
||||||
|
result = client.post("/api/v1/jobs/" + job.json()["id"] + "/preview")
|
||||||
|
assert result.status_code == 202
|
||||||
|
service.process_one()
|
||||||
|
assert service.operation(result.json()["operation_id"])["status"] == "COMPLETED"
|
||||||
|
assert service.registry.get("living-room").client.uploads == 0
|
||||||
|
|
||||||
|
|
||||||
|
def test_source_selection_respects_quality_and_keeps_inputs_out_of_manual_library(
|
||||||
|
service, monkeypatch
|
||||||
|
):
|
||||||
|
from types import SimpleNamespace
|
||||||
|
|
||||||
|
source = SimpleNamespace(
|
||||||
|
minimum_sharpness=0,
|
||||||
|
minimum_brightness=50,
|
||||||
|
maximum_brightness=255,
|
||||||
|
avoid_duplicates=False,
|
||||||
|
)
|
||||||
|
monkeypatch.setattr(service.photo_sources, "get", lambda _: source)
|
||||||
|
monkeypatch.setattr(
|
||||||
|
service.photo_sources, "catalog", lambda _: [{"id": str(i)} for i in range(3)]
|
||||||
|
)
|
||||||
|
|
||||||
|
def read(_, item):
|
||||||
|
data = BytesIO()
|
||||||
|
Image.new("RGB", (320, 240), (int(item) * 80,) * 3).save(data, "JPEG")
|
||||||
|
return data.getvalue(), item + ".jpg", None
|
||||||
|
|
||||||
|
monkeypatch.setattr(service.photo_sources, "read", read)
|
||||||
|
content = AutoCollageContent(
|
||||||
|
type="auto_collage", source_id="nas", count=2, use_ai=False
|
||||||
|
)
|
||||||
|
for _ in range(2):
|
||||||
|
asset = service.content_asset(content)
|
||||||
|
assert asset["source"] == "generated"
|
||||||
|
assert (
|
||||||
|
service.db.one("SELECT COUNT(*) AS n FROM assets WHERE kind='images'")["n"] == 0
|
||||||
|
)
|
||||||
|
assert (
|
||||||
|
service.db.one("SELECT COUNT(*) AS n FROM assets WHERE kind='cache'")["n"] == 4
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def test_ai_receives_only_selected_asset_metadata(service, monkeypatch):
|
||||||
|
from pigway_frame_flow.extensions.layout import LayoutStudio, local_plan
|
||||||
|
|
||||||
|
photos(service, 3)
|
||||||
|
calls = []
|
||||||
|
|
||||||
|
def plan(_, request):
|
||||||
|
calls.append(request)
|
||||||
|
assert request.use_ai is True
|
||||||
|
assert len(set(request.asset_ids)) == 3
|
||||||
|
return local_plan(request)
|
||||||
|
|
||||||
|
monkeypatch.setattr(LayoutStudio, "plan", plan)
|
||||||
|
service.content_asset(
|
||||||
|
AutoCollageContent(type="auto_collage", count=3, title="Family")
|
||||||
|
)
|
||||||
|
assert len(calls) == 1
|
||||||
|
assert calls[0].title == "Family"
|
||||||
|
assert service.registry.get("living-room").client.uploads == 0
|
||||||
|
|
||||||
|
|
||||||
|
def test_scheduled_collage_executes_once_and_tracks_cloud_task_head(app, service):
|
||||||
|
from datetime import UTC, datetime, timedelta
|
||||||
|
|
||||||
|
from pigway_frame_flow.models import JobInput
|
||||||
|
|
||||||
|
photos(service, 3)
|
||||||
|
scheduler = app.state.scheduler
|
||||||
|
job = scheduler.save_job(
|
||||||
|
JobInput(
|
||||||
|
name="Scheduled collage",
|
||||||
|
schedule={"type": "daily", "time": "08:00"},
|
||||||
|
source={"type": "auto_collage", "count": 3, "use_ai": False},
|
||||||
|
)
|
||||||
|
)
|
||||||
|
due = (datetime.now(UTC) - timedelta(seconds=2)).isoformat()
|
||||||
|
service.db.execute("UPDATE jobs SET next_run=? WHERE id=?", (due, job["id"]))
|
||||||
|
scheduler.tick()
|
||||||
|
scheduler.tick()
|
||||||
|
assert len(service.db.all("SELECT * FROM job_runs")) == 1
|
||||||
|
service.process_one()
|
||||||
|
service.sync()
|
||||||
|
assert service.registry.get("living-room").client.uploads == 1
|
||||||
|
row = service.db.one("SELECT job_id FROM managed_cloud_uploads")
|
||||||
|
assert row["job_id"] == job["id"]
|
||||||
+199
-6
@@ -1,3 +1,4 @@
|
|||||||
|
from types import SimpleNamespace
|
||||||
from unittest.mock import Mock
|
from unittest.mock import Mock
|
||||||
|
|
||||||
import pytest
|
import pytest
|
||||||
@@ -7,11 +8,28 @@ from pigway_frame_flow.drivers.kokonna.client import KokonnaClient
|
|||||||
from pigway_frame_flow.errors import FlowError
|
from pigway_frame_flow.errors import FlowError
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture(autouse=True)
|
||||||
|
def transport_clock(monkeypatch):
|
||||||
|
import pigway_frame_flow.drivers.kokonna.client as module
|
||||||
|
|
||||||
|
clock = SimpleNamespace(now=0.0, waits=[])
|
||||||
|
|
||||||
|
def sleep(seconds):
|
||||||
|
clock.waits.append(seconds)
|
||||||
|
clock.now += seconds
|
||||||
|
|
||||||
|
monkeypatch.setattr(
|
||||||
|
module, "time", SimpleNamespace(monotonic=lambda: clock.now, sleep=sleep)
|
||||||
|
)
|
||||||
|
return clock
|
||||||
|
|
||||||
|
|
||||||
def session(body=None, status=200):
|
def session(body=None, status=200):
|
||||||
s = Mock()
|
s = Mock()
|
||||||
s.request.return_value.status_code = status
|
s.request.return_value.status_code = status
|
||||||
s.request.return_value.json.return_value = body or {}
|
s.request.return_value.json.return_value = body or {}
|
||||||
s.request.return_value.content = b"image"
|
s.request.return_value.content = b"image"
|
||||||
|
s.request.return_value.headers = {}
|
||||||
return s
|
return s
|
||||||
|
|
||||||
|
|
||||||
@@ -88,7 +106,7 @@ def test_timeout_redaction_no_retry(write):
|
|||||||
c.display(1) if write else c.get_device()
|
c.display(1) if write else c.get_device()
|
||||||
assert "secret" not in str(e.value)
|
assert "secret" not in str(e.value)
|
||||||
assert e.value.code == ("WRITE_RESULT_UNKNOWN" if write else "CLOUD_UNAVAILABLE")
|
assert e.value.code == ("WRITE_RESULT_UNKNOWN" if write else "CLOUD_UNAVAILABLE")
|
||||||
assert s.request.call_count == 1
|
assert s.request.call_count == (1 if write else 3)
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.parametrize("status", [401, 429, 500, 530])
|
@pytest.mark.parametrize("status", [401, 429, 500, 530])
|
||||||
@@ -109,12 +127,187 @@ def test_invalid_upload_id(tmp_path):
|
|||||||
assert e.value.code == "WRITE_RESULT_UNKNOWN"
|
assert e.value.code == "WRITE_RESULT_UNKNOWN"
|
||||||
|
|
||||||
|
|
||||||
def test_rate_budget():
|
def test_rate_budget(transport_clock):
|
||||||
s = session({"nickname": "x"})
|
s = session({"nickname": "x"})
|
||||||
c = KokonnaClient("secret", session=s)
|
c = KokonnaClient("secret", session=s)
|
||||||
for _ in range(18):
|
for _ in range(18):
|
||||||
c.get_device()
|
c.get_device()
|
||||||
with pytest.raises(FlowError) as e:
|
c.get_device()
|
||||||
c.get_device()
|
assert s.request.call_count == 19
|
||||||
assert e.value.code == "RATE_LIMITED"
|
assert transport_clock.waits == [60]
|
||||||
assert s.request.call_count == 18
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
"exception,category",
|
||||||
|
[
|
||||||
|
(requests.ConnectTimeout, "connect_timeout"),
|
||||||
|
(requests.ReadTimeout, "read_timeout"),
|
||||||
|
(requests.exceptions.SSLError, "tls_error"),
|
||||||
|
(requests.ConnectionError, "connection_error"),
|
||||||
|
(requests.Timeout, "timeout"),
|
||||||
|
(requests.RequestException, "request_error"),
|
||||||
|
],
|
||||||
|
)
|
||||||
|
def test_transport_failure_records_safe_category_without_replay(exception, category):
|
||||||
|
s = session()
|
||||||
|
s.request.side_effect = exception("secret https://host/secret")
|
||||||
|
c = KokonnaClient("secret", True, s)
|
||||||
|
with pytest.raises(FlowError) as error:
|
||||||
|
c.display(1)
|
||||||
|
assert error.value.code == (
|
||||||
|
"CLOUD_UNAVAILABLE" if category == "connect_timeout" else "WRITE_RESULT_UNKNOWN"
|
||||||
|
)
|
||||||
|
assert error.value.details["transport_error"] == category
|
||||||
|
assert error.value.details["attempts"] == (
|
||||||
|
3 if category == "connect_timeout" else 1
|
||||||
|
)
|
||||||
|
assert "secret" not in str(error.value.details)
|
||||||
|
assert s.request.call_count == (3 if category == "connect_timeout" else 1)
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("write", [False, True])
|
||||||
|
def test_connect_timeout_retries_then_succeeds(write, transport_clock):
|
||||||
|
s = session({"success": True})
|
||||||
|
response = s.request.return_value
|
||||||
|
s.request.side_effect = [requests.ConnectTimeout("private"), response]
|
||||||
|
c = KokonnaClient("private", True, s)
|
||||||
|
c.display(1) if write else c.get_device()
|
||||||
|
assert s.request.call_count == 2
|
||||||
|
assert transport_clock.waits == [1]
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
"message,code,kind",
|
||||||
|
[
|
||||||
|
("image not found", "NOT_FOUND", "image_not_found"),
|
||||||
|
("imageId is empty", "INVALID_REQUEST", "invalid_image_id"),
|
||||||
|
("can not find robot private", "CONFIG_REQUIRED", "device_key_invalid"),
|
||||||
|
],
|
||||||
|
)
|
||||||
|
def test_documented_500_rejection_does_not_lock_or_retry(message, code, kind):
|
||||||
|
s = session({"message": message}, 500)
|
||||||
|
c = KokonnaClient("private", True, s)
|
||||||
|
with pytest.raises(FlowError) as error:
|
||||||
|
c.display(1)
|
||||||
|
assert error.value.code == code
|
||||||
|
assert error.value.details["write_outcome"] == "rejected"
|
||||||
|
assert error.value.details["failure_kind"] == kind
|
||||||
|
assert "private" not in str(error.value.details)
|
||||||
|
assert s.request.call_count == 1
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("status", [500, 502, 503, 530])
|
||||||
|
def test_generic_5xx_read_retries_but_write_never_replays(status):
|
||||||
|
for write in [False, True]:
|
||||||
|
s = session({"message": "unknown failure private"}, status)
|
||||||
|
c = KokonnaClient("private", True, s)
|
||||||
|
with pytest.raises(FlowError) as error:
|
||||||
|
c.display(1) if write else c.get_device()
|
||||||
|
assert s.request.call_count == (1 if write else 3)
|
||||||
|
assert error.value.code == (
|
||||||
|
"WRITE_RESULT_UNKNOWN" if write else "CLOUD_UNAVAILABLE"
|
||||||
|
)
|
||||||
|
assert "private" not in str(error.value.details)
|
||||||
|
|
||||||
|
|
||||||
|
def test_rate_limit_honors_retry_after_and_closes_response(transport_clock):
|
||||||
|
s = session({"message": "rate limited"}, 429)
|
||||||
|
first = s.request.return_value
|
||||||
|
first.headers = {"Retry-After": "7"}
|
||||||
|
second = session({"success": True}).request.return_value
|
||||||
|
s.request.side_effect = [first, second]
|
||||||
|
KokonnaClient("private", True, s).display(1)
|
||||||
|
assert s.request.call_count == 2
|
||||||
|
assert transport_clock.waits == [7]
|
||||||
|
first.close.assert_called_once()
|
||||||
|
second.close.assert_called_once()
|
||||||
|
|
||||||
|
|
||||||
|
def test_long_retry_after_preserves_cooldown_without_early_request(transport_clock):
|
||||||
|
s = session({"message": "rate limited"}, 429)
|
||||||
|
s.request.return_value.headers = {"Retry-After": "120"}
|
||||||
|
c = KokonnaClient("private", True, s)
|
||||||
|
for _ in range(2):
|
||||||
|
with pytest.raises(FlowError) as error:
|
||||||
|
c.display(1)
|
||||||
|
assert error.value.code == "RATE_LIMITED"
|
||||||
|
assert s.request.call_count == 1
|
||||||
|
assert transport_clock.waits == []
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("header", [None, "bad", "nan", "inf"])
|
||||||
|
def test_invalid_retry_after_defaults_to_one_minute(header):
|
||||||
|
from pigway_frame_flow.drivers.kokonna.client import SafeTransport
|
||||||
|
|
||||||
|
assert SafeTransport._retry_after(header) == 60
|
||||||
|
|
||||||
|
|
||||||
|
def test_retry_after_accepts_http_date():
|
||||||
|
from datetime import UTC, datetime, timedelta
|
||||||
|
from email.utils import format_datetime
|
||||||
|
|
||||||
|
from pigway_frame_flow.drivers.kokonna.client import SafeTransport
|
||||||
|
|
||||||
|
future = format_datetime(datetime.now(UTC) + timedelta(seconds=30), usegmt=True)
|
||||||
|
assert 28 <= SafeTransport._retry_after(future) <= 30
|
||||||
|
|
||||||
|
|
||||||
|
def test_invalid_write_response_is_never_retried():
|
||||||
|
s = session({"success": False, "message": "private"})
|
||||||
|
with pytest.raises(FlowError) as error:
|
||||||
|
KokonnaClient("private", True, s).display(1)
|
||||||
|
assert error.value.code == "WRITE_RESULT_UNKNOWN"
|
||||||
|
assert error.value.details["failure_kind"] == "invalid_response"
|
||||||
|
assert s.request.call_count == 1
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
"failure,expected",
|
||||||
|
[
|
||||||
|
("connect_timeout", "CLOUD_UNAVAILABLE"),
|
||||||
|
("business_rejection", "CONFIG_REQUIRED"),
|
||||||
|
("rate_limit", "RATE_LIMITED"),
|
||||||
|
],
|
||||||
|
)
|
||||||
|
def test_proven_upload_failures_end_failed_without_device_lock(
|
||||||
|
service, monkeypatch, failure, expected
|
||||||
|
):
|
||||||
|
from test_display import submit
|
||||||
|
|
||||||
|
s = session({"message": "can not find robot private"}, 500)
|
||||||
|
if failure == "rate_limit":
|
||||||
|
s.request.return_value.status_code = 429
|
||||||
|
if failure == "connect_timeout":
|
||||||
|
s.request.side_effect = requests.ConnectTimeout("private")
|
||||||
|
c = KokonnaClient("private", True, s)
|
||||||
|
monkeypatch.setattr(service.registry.get("living-room"), "upload", c.upload)
|
||||||
|
operation = submit(service)
|
||||||
|
service.process_one()
|
||||||
|
op = service.operation(operation)
|
||||||
|
assert op["status"] == "FAILED"
|
||||||
|
assert op["error"]["code"] == expected
|
||||||
|
assert not service.blocked("living-room")
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("value", [True, False, 0, -1, "12", None])
|
||||||
|
def test_invalid_upload_id_never_becomes_confirmed(tmp_path, value):
|
||||||
|
path = tmp_path / "image.jpg"
|
||||||
|
path.write_bytes(b"jpeg")
|
||||||
|
s = session({"id": value})
|
||||||
|
with pytest.raises(FlowError) as error:
|
||||||
|
KokonnaClient("private", True, s).upload(path, "image.jpg")
|
||||||
|
assert error.value.code == "WRITE_RESULT_UNKNOWN"
|
||||||
|
assert s.request.call_count == 1
|
||||||
|
|
||||||
|
|
||||||
|
def test_ambiguous_failure_after_safe_rejection_stops_retrying(transport_clock):
|
||||||
|
s = session({"message": "limited"}, 429)
|
||||||
|
first = s.request.return_value
|
||||||
|
first.headers = {"Retry-After": "1"}
|
||||||
|
s.request.side_effect = [first, requests.ReadTimeout("private")]
|
||||||
|
with pytest.raises(FlowError) as error:
|
||||||
|
KokonnaClient("private", True, s).display(1)
|
||||||
|
assert error.value.code == "WRITE_RESULT_UNKNOWN"
|
||||||
|
assert error.value.details["attempts"] == 2
|
||||||
|
assert s.request.call_count == 2
|
||||||
|
assert transport_clock.waits == [1]
|
||||||
|
|||||||
@@ -152,3 +152,55 @@ def test_offline(service):
|
|||||||
id = submit(service)
|
id = submit(service)
|
||||||
service.process_one()
|
service.process_one()
|
||||||
assert service.operation(id)["error"]["code"] == "DEVICE_OFFLINE"
|
assert service.operation(id)["error"]["code"] == "DEVICE_OFFLINE"
|
||||||
|
|
||||||
|
|
||||||
|
def test_late_sync_resolves_unknown_without_upload_retry(service, monkeypatch):
|
||||||
|
id = submit(service)
|
||||||
|
service.process_one()
|
||||||
|
service.update(id, "UNKNOWN")
|
||||||
|
driver = service.registry.get("living-room")
|
||||||
|
calls = []
|
||||||
|
device = driver.device
|
||||||
|
monkeypatch.setattr(driver, "device", lambda **kw: calls.append(kw) or device(**kw))
|
||||||
|
service.sync()
|
||||||
|
assert service.operation(id)["status"] == "COMPLETED"
|
||||||
|
assert driver.client.uploads == 1
|
||||||
|
assert calls == [{"refresh": True}]
|
||||||
|
assert not service.blocked("living-room")
|
||||||
|
assert service.db.one(
|
||||||
|
"SELECT confirmed_at FROM managed_cloud_uploads WHERE operation_id=?", (id,)
|
||||||
|
)["confirmed_at"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_unknown_wrong_target_stays_locked_and_queries_at_most_once_per_minute(
|
||||||
|
service, monkeypatch
|
||||||
|
):
|
||||||
|
id = submit(service)
|
||||||
|
service.process_one()
|
||||||
|
service.update(id, "UNKNOWN")
|
||||||
|
driver = service.registry.get("living-room")
|
||||||
|
driver.client.display(1)
|
||||||
|
driver.invalidate()
|
||||||
|
calls = []
|
||||||
|
device = driver.device
|
||||||
|
monkeypatch.setattr(driver, "device", lambda **kw: calls.append(kw) or device(**kw))
|
||||||
|
service.sync()
|
||||||
|
service.sync()
|
||||||
|
assert service.operation(id)["status"] == "UNKNOWN"
|
||||||
|
assert service.blocked("living-room")
|
||||||
|
assert driver.client.uploads == 1
|
||||||
|
assert len(calls) == 1
|
||||||
|
|
||||||
|
|
||||||
|
def test_unknown_matching_image_without_sync_stays_locked(service, monkeypatch):
|
||||||
|
id = submit(service)
|
||||||
|
service.process_one()
|
||||||
|
service.update(id, "UNKNOWN")
|
||||||
|
driver = service.registry.get("living-room")
|
||||||
|
device = driver.device()
|
||||||
|
device.current_content.synced = False
|
||||||
|
monkeypatch.setattr(driver, "device", lambda **kw: device)
|
||||||
|
service.sync()
|
||||||
|
assert service.operation(id)["status"] == "UNKNOWN"
|
||||||
|
assert service.blocked("living-room")
|
||||||
|
assert driver.client.uploads == 1
|
||||||
|
|||||||
@@ -373,3 +373,30 @@ def test_ai_layout_sends_metadata_only_and_validates_response(
|
|||||||
assert b"test-ai-secret" not in calls[0]["body"]
|
assert b"test-ai-secret" not in calls[0]["body"]
|
||||||
assert image.getvalue() not in calls[0]["body"]
|
assert image.getvalue() not in calls[0]["body"]
|
||||||
assert calls[0]["headers"]["Authorization"] == "Bearer test-ai-secret"
|
assert calls[0]["headers"]["Authorization"] == "Bearer test-ai-secret"
|
||||||
|
|
||||||
|
|
||||||
|
def test_webhook_matching_event_after_unrelated_backlog(client, service, monkeypatch):
|
||||||
|
import json
|
||||||
|
|
||||||
|
service.settings.image_url_hosts.append("example.com")
|
||||||
|
response = client.post(
|
||||||
|
"/api/v1/webhooks",
|
||||||
|
json={
|
||||||
|
"callback_url": "https://example.com/events",
|
||||||
|
"event_types": ["operation.failed"],
|
||||||
|
},
|
||||||
|
)
|
||||||
|
assert response.status_code == 201
|
||||||
|
for _ in range(500):
|
||||||
|
service.db.event("display.changed", {})
|
||||||
|
service.db.event("operation.failed", {"operation_id": "expected"})
|
||||||
|
sent = []
|
||||||
|
monkeypatch.setattr(
|
||||||
|
service.assets, "fetch_url", lambda url, **kwargs: sent.append(kwargs) or b""
|
||||||
|
)
|
||||||
|
service.webhooks.tick()
|
||||||
|
service.webhooks.last = 0
|
||||||
|
service.webhooks.tick()
|
||||||
|
assert len(sent) == 1
|
||||||
|
assert json.loads(sent[0]["body"])["data"] == {"operation_id": "expected"}
|
||||||
|
assert len(service.db.all("SELECT * FROM webhook_deliveries")) == 1
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user