feat(develop): Revelar, the synced editor with one engine on web, desktop and server
engine/core renders with the LightCraft pipeline; engine/wasm runs it in the browser; workers/render replays op logs and renders originals natively. Op log with live fan-out and offline outbox; edited thumbnails and deliveries rendered from the original. Revelar page with Basic and optional modules, crop with aspect presets and straighten, before/after, undo/redo, copy/paste settings. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01HT6iXLYUUp9pJz5Kza9xCW
This commit is contained in:
1 parent
e524282ee4
commit
64da90d2f2
50 files changed
+3476
-169
No files matched your search
@@ -45,6 +45,10 @@ jobs:
|
||||
- run: cargo fmt --all --check
|
||||
- run: cargo clippy --workspace --all-targets -- -D warnings
|
||||
- run: cargo test --workspace
|
||||
- name: Browser engine builds (wasm32)
|
||||
run: |
|
||||
rustup target add wasm32-unknown-unknown
|
||||
cargo build --locked --profile wasm --target wasm32-unknown-unknown -p photoreport-engine-wasm
|
||||
- name: Generated controls are up to date
|
||||
run: |
|
||||
cargo run -q -p photoreport-engine --example export_controls > packages/contracts/src/controls.generated.json
|
||||
|
||||
@@ -8,3 +8,4 @@ coverage/
|
||||
.DS_Store
|
||||
*.log
|
||||
apps/api/src/generated/
|
||||
apps/app/public/engine/
|
||||
Generated
+615
-5
@@ -8,12 +8,33 @@ version = "2.0.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa"
|
||||
|
||||
[[package]]
|
||||
name = "alloc-no-stdlib"
|
||||
version = "2.0.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cc7bb162ec39d46ab1ca8c77bf72e890535becd1751bb45f64c597edb4c8c6b3"
|
||||
|
||||
[[package]]
|
||||
name = "alloc-stdlib"
|
||||
version = "0.2.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0e76a019e91224d279006ff972f1e984179a6e9feb050adba6ce8274aef23195"
|
||||
dependencies = [
|
||||
"alloc-no-stdlib",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "autocfg"
|
||||
version = "1.5.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53"
|
||||
|
||||
[[package]]
|
||||
name = "bitflags"
|
||||
version = "2.13.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06"
|
||||
|
||||
[[package]]
|
||||
name = "block-buffer"
|
||||
version = "0.10.4"
|
||||
@@ -23,6 +44,16 @@ dependencies = [
|
||||
"generic-array",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "brotli-decompressor"
|
||||
version = "5.0.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3a32acac15fe1967bc3986b2a6347dffc965602354ea6f450ad07e8bfd253583"
|
||||
dependencies = [
|
||||
"alloc-no-stdlib",
|
||||
"alloc-stdlib",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "bumpalo"
|
||||
version = "3.20.3"
|
||||
@@ -34,6 +65,20 @@ name = "bytemuck"
|
||||
version = "1.25.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "95832e849adfb21180ccb6826a99da14e5d266ae5c2e668e1602cf234f153797"
|
||||
dependencies = [
|
||||
"bytemuck_derive",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "bytemuck_derive"
|
||||
version = "1.12.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6a1f896587b6f2c069c73d2f0913e2d590c3990285cd2f0b6aa02b786b4c679c"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 3.0.7",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "byteorder-lite"
|
||||
@@ -47,6 +92,12 @@ version = "1.0.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600"
|
||||
|
||||
[[package]]
|
||||
name = "color_quant"
|
||||
version = "1.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3d7b894f5411737b7867f4827955924d7c254fc9f4d91a6aad6b097804b1018b"
|
||||
|
||||
[[package]]
|
||||
name = "cpufeatures"
|
||||
version = "0.2.17"
|
||||
@@ -56,6 +107,46 @@ dependencies = [
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "crc32fast"
|
||||
version = "1.5.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "01a7799fd6b852db0e61728dde9a204c423b44d689dbd432522543614b490e78"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "crossbeam-deque"
|
||||
version = "0.8.8"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "622f3fc73690be383c7214310406f28a90e6edeadc3cea882f9d71e495b9711a"
|
||||
dependencies = [
|
||||
"crossbeam-epoch",
|
||||
"crossbeam-utils",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "crossbeam-epoch"
|
||||
version = "0.9.21"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "dc74980687109a3b14c72fd458107bf0baa1da1a1a805e178d15501ba9b86d9d"
|
||||
dependencies = [
|
||||
"crossbeam-utils",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "crossbeam-utils"
|
||||
version = "0.8.23"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6"
|
||||
|
||||
[[package]]
|
||||
name = "crunchy"
|
||||
version = "0.2.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5"
|
||||
|
||||
[[package]]
|
||||
name = "crypto-common"
|
||||
version = "0.1.7"
|
||||
@@ -76,6 +167,38 @@ dependencies = [
|
||||
"crypto-common",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "either"
|
||||
version = "1.19.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be"
|
||||
|
||||
[[package]]
|
||||
name = "fax"
|
||||
version = "0.2.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "caf1079563223d5d59d83c85886a56e586cfd5c1a26292e971a0fa266531ac5a"
|
||||
|
||||
[[package]]
|
||||
name = "fdeflate"
|
||||
version = "0.3.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1e6853b52649d4ac5c0bd02320cddc5ba956bdb407c4b75a2c6b75bf51500f8c"
|
||||
dependencies = [
|
||||
"simd-adler32",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "flate2"
|
||||
version = "1.1.10"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6e634e2e0ebac1ee034020da1ca582e17ffe4e0f5e985823721e168928136dcb"
|
||||
dependencies = [
|
||||
"crc32fast",
|
||||
"miniz_oxide 0.9.1",
|
||||
"zlib-rs",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "futures-core"
|
||||
version = "0.3.34"
|
||||
@@ -110,6 +233,27 @@ dependencies = [
|
||||
"version_check",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "gif"
|
||||
version = "0.14.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ee8cfcc411d9adbbaba82fb72661cc1bcca13e8bba98b364e62b2dba8f960159"
|
||||
dependencies = [
|
||||
"color_quant",
|
||||
"weezl",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "half"
|
||||
version = "2.7.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6ea2d84b969582b4b1864a92dc5d27cd2b77b622a8d79306834f1be5ba20d84b"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"crunchy",
|
||||
"zerocopy",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "image"
|
||||
version = "0.25.10"
|
||||
@@ -118,18 +262,48 @@ checksum = "85ab80394333c02fe689eaf900ab500fbd0c2213da414687ebf995a65d5a6104"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
"byteorder-lite",
|
||||
"moxcms",
|
||||
"color_quant",
|
||||
"gif",
|
||||
"image-webp",
|
||||
"moxcms 0.8.1",
|
||||
"num-traits",
|
||||
"png",
|
||||
"tiff",
|
||||
"zune-core",
|
||||
"zune-jpeg",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "image-webp"
|
||||
version = "0.2.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "525e9ff3e1a4be2fbea1fdf0e98686a6d98b4d8f937e1bf7402245af1909e8c3"
|
||||
dependencies = [
|
||||
"byteorder-lite",
|
||||
"quick-error",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "itoa"
|
||||
version = "1.0.18"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682"
|
||||
|
||||
[[package]]
|
||||
name = "jpeg-decoder"
|
||||
version = "0.3.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "00810f1d8b74be64b13dbf3db89ac67740615d6c891f0e7b6179326533011a07"
|
||||
dependencies = [
|
||||
"rayon",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "jpeg-encoder"
|
||||
version = "0.7.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a0370574b86f7eca156b9f298392b5e69a23f8c86f3f865add60bbc2e79467a6"
|
||||
|
||||
[[package]]
|
||||
name = "js-sys"
|
||||
version = "0.3.106"
|
||||
@@ -141,12 +315,211 @@ dependencies = [
|
||||
"wasm-bindgen",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "jxl-bitstream"
|
||||
version = "1.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b480e752277e29eb4054f69546887a9b84656fe78c08f54ba5850ced98a378fe"
|
||||
dependencies = [
|
||||
"tracing",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "jxl-coding"
|
||||
version = "1.0.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cd972bcd125e776f1eb241ac50e39f956095a1c2770c64736c968f8946bd9a3c"
|
||||
dependencies = [
|
||||
"jxl-bitstream",
|
||||
"tracing",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "jxl-color"
|
||||
version = "0.11.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f316b1358c1711755b3ee8e8cb5c4a1dad12e796233088a7a513440782de80b2"
|
||||
dependencies = [
|
||||
"jxl-bitstream",
|
||||
"jxl-coding",
|
||||
"jxl-grid",
|
||||
"jxl-image",
|
||||
"jxl-oxide-common",
|
||||
"jxl-threadpool",
|
||||
"tracing",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "jxl-frame"
|
||||
version = "0.13.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2d967c6fd669c7c01060b5022d8835fa82fd46b06ffc98b549f17600a097c2b3"
|
||||
dependencies = [
|
||||
"jxl-bitstream",
|
||||
"jxl-coding",
|
||||
"jxl-grid",
|
||||
"jxl-image",
|
||||
"jxl-modular",
|
||||
"jxl-oxide-common",
|
||||
"jxl-threadpool",
|
||||
"jxl-vardct",
|
||||
"tracing",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "jxl-grid"
|
||||
version = "0.6.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "01671307879a033bfa52e6e8784b941aca770b3f3a7d33830b455b6844f793fb"
|
||||
dependencies = [
|
||||
"tracing",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "jxl-image"
|
||||
version = "0.13.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c5f752d62577c702a94dbbce4045caf08cb58639e8a4d56464b40ecf33ffe565"
|
||||
dependencies = [
|
||||
"jxl-bitstream",
|
||||
"jxl-grid",
|
||||
"jxl-oxide-common",
|
||||
"tracing",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "jxl-jbr"
|
||||
version = "0.2.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e35d032bcec660647828527ff42c6f5776d2fd44b8357f9f6d9ac6dc07218e46"
|
||||
dependencies = [
|
||||
"brotli-decompressor",
|
||||
"jxl-bitstream",
|
||||
"jxl-frame",
|
||||
"jxl-grid",
|
||||
"jxl-image",
|
||||
"jxl-modular",
|
||||
"jxl-oxide-common",
|
||||
"jxl-threadpool",
|
||||
"jxl-vardct",
|
||||
"tracing",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "jxl-modular"
|
||||
version = "0.11.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2a2f045b24c738dd91d482be385512b512721ae08a671bd4b27bf1c47f215235"
|
||||
dependencies = [
|
||||
"jxl-bitstream",
|
||||
"jxl-coding",
|
||||
"jxl-grid",
|
||||
"jxl-oxide-common",
|
||||
"jxl-threadpool",
|
||||
"tracing",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "jxl-oxide"
|
||||
version = "0.12.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d36c662923f47586880211f3bc7c0d83fb3a9b410d278c7bde93450748abeef3"
|
||||
dependencies = [
|
||||
"brotli-decompressor",
|
||||
"jxl-bitstream",
|
||||
"jxl-color",
|
||||
"jxl-frame",
|
||||
"jxl-grid",
|
||||
"jxl-image",
|
||||
"jxl-jbr",
|
||||
"jxl-oxide-common",
|
||||
"jxl-render",
|
||||
"jxl-threadpool",
|
||||
"tracing",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "jxl-oxide-common"
|
||||
version = "1.0.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b62394c5021b3a9e7e0dbb2d639d555d019090c9946c39f6d3b09d390db4157b"
|
||||
dependencies = [
|
||||
"jxl-bitstream",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "jxl-render"
|
||||
version = "0.12.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d34386bfdb6a19b5a30cc9beb4d475d537422c31ae8c39bb69640fcce3fcaf19"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
"jxl-bitstream",
|
||||
"jxl-coding",
|
||||
"jxl-color",
|
||||
"jxl-frame",
|
||||
"jxl-grid",
|
||||
"jxl-image",
|
||||
"jxl-modular",
|
||||
"jxl-oxide-common",
|
||||
"jxl-threadpool",
|
||||
"jxl-vardct",
|
||||
"tracing",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "jxl-threadpool"
|
||||
version = "1.0.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "25f15eb830aa77a7f21148d72e153562a26bfe570139bd4922eab1908dd499d3"
|
||||
dependencies = [
|
||||
"tracing",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "jxl-vardct"
|
||||
version = "0.11.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ce72a18c6d3a47172ab6c479be2bdb56f22066b5d7092663f03b4490820b4511"
|
||||
dependencies = [
|
||||
"jxl-bitstream",
|
||||
"jxl-coding",
|
||||
"jxl-grid",
|
||||
"jxl-modular",
|
||||
"jxl-oxide-common",
|
||||
"jxl-threadpool",
|
||||
"tracing",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "libc"
|
||||
version = "0.2.190"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ce5d3ddc6d3fa000eb1536d85e147bfe31aacaba692ed6a876f95cb7c855be78"
|
||||
|
||||
[[package]]
|
||||
name = "lightcraft-codecs"
|
||||
version = "0.6.0"
|
||||
source = "git+https://github.com/storytold/lightcraft?rev=0dd6593d9db55a17ab559261bac4d766f015c345#0dd6593d9db55a17ab559261bac4d766f015c345"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
"image",
|
||||
"image-webp",
|
||||
"jpeg-decoder",
|
||||
"jpeg-encoder",
|
||||
"lightcraft-color",
|
||||
"lightcraft-geom",
|
||||
"lightcraft-raster",
|
||||
"moxcms 0.9.1",
|
||||
"png",
|
||||
"rayon",
|
||||
"serde",
|
||||
"thiserror",
|
||||
"tiff",
|
||||
"zune-core",
|
||||
"zune-jpeg",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "lightcraft-color"
|
||||
version = "0.6.0"
|
||||
@@ -163,7 +536,7 @@ source = "git+https://github.com/storytold/lightcraft?rev=0dd6593d9db55a17ab5592
|
||||
dependencies = [
|
||||
"lightcraft-color",
|
||||
"lightcraft-geom",
|
||||
"miniz_oxide",
|
||||
"miniz_oxide 0.8.9",
|
||||
"serde",
|
||||
"serde_json",
|
||||
]
|
||||
@@ -190,6 +563,70 @@ dependencies = [
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "lightcraft-meta"
|
||||
version = "0.6.0"
|
||||
source = "git+https://github.com/storytold/lightcraft?rev=0dd6593d9db55a17ab559261bac4d766f015c345#0dd6593d9db55a17ab559261bac4d766f015c345"
|
||||
dependencies = [
|
||||
"lightcraft-geom",
|
||||
"lightcraft-tiff",
|
||||
"quick-xml",
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "lightcraft-pipeline"
|
||||
version = "0.6.0"
|
||||
source = "git+https://github.com/storytold/lightcraft?rev=0dd6593d9db55a17ab559261bac4d766f015c345#0dd6593d9db55a17ab559261bac4d766f015c345"
|
||||
dependencies = [
|
||||
"lightcraft-color",
|
||||
"lightcraft-develop",
|
||||
"lightcraft-geom",
|
||||
"lightcraft-raster",
|
||||
"lightcraft-raw",
|
||||
"rayon",
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "lightcraft-raster"
|
||||
version = "0.6.0"
|
||||
source = "git+https://github.com/storytold/lightcraft?rev=0dd6593d9db55a17ab559261bac4d766f015c345#0dd6593d9db55a17ab559261bac4d766f015c345"
|
||||
dependencies = [
|
||||
"lightcraft-color",
|
||||
"lightcraft-geom",
|
||||
"rayon",
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "lightcraft-raw"
|
||||
version = "0.6.0"
|
||||
source = "git+https://github.com/storytold/lightcraft?rev=0dd6593d9db55a17ab559261bac4d766f015c345#0dd6593d9db55a17ab559261bac4d766f015c345"
|
||||
dependencies = [
|
||||
"jxl-oxide",
|
||||
"lightcraft-color",
|
||||
"lightcraft-geom",
|
||||
"lightcraft-meta",
|
||||
"lightcraft-raster",
|
||||
"lightcraft-tiff",
|
||||
"miniz_oxide 0.8.9",
|
||||
"rayon",
|
||||
"serde",
|
||||
"thiserror",
|
||||
"zune-core",
|
||||
"zune-jpeg",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "lightcraft-tiff"
|
||||
version = "0.6.0"
|
||||
source = "git+https://github.com/storytold/lightcraft?rev=0dd6593d9db55a17ab559261bac4d766f015c345#0dd6593d9db55a17ab559261bac4d766f015c345"
|
||||
dependencies = [
|
||||
"serde",
|
||||
"thiserror",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "matrixmultiply"
|
||||
version = "0.3.11"
|
||||
@@ -213,6 +650,17 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1fa76a2c86f704bdb222d66965fb3d63269ce38518b83cb0575fca855ebb6316"
|
||||
dependencies = [
|
||||
"adler2",
|
||||
"simd-adler32",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "miniz_oxide"
|
||||
version = "0.9.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b63fbc4a50860e98e7b2aa7804ded1db5cbc3aff9193adaff57a6931bf7c4b4c"
|
||||
dependencies = [
|
||||
"adler2",
|
||||
"simd-adler32",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -225,6 +673,16 @@ dependencies = [
|
||||
"pxfm",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "moxcms"
|
||||
version = "0.9.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "396077b717181ce3f9a6b66739b269b82d756be5ec0f76be0bc40a7c51775830"
|
||||
dependencies = [
|
||||
"num-traits",
|
||||
"pxfm",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ndarray"
|
||||
version = "0.17.2"
|
||||
@@ -277,12 +735,25 @@ checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
|
||||
name = "photoreport-engine"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"lightcraft-codecs",
|
||||
"lightcraft-develop",
|
||||
"lightcraft-geom",
|
||||
"lightcraft-pipeline",
|
||||
"lightcraft-raster",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"thiserror",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "photoreport-engine-wasm"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"photoreport-engine",
|
||||
"serde_json",
|
||||
"wasm-bindgen",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "photoreport-faces"
|
||||
version = "0.1.0"
|
||||
@@ -294,12 +765,34 @@ dependencies = [
|
||||
"sha2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "photoreport-render"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"photoreport-engine",
|
||||
"serde",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "pin-project-lite"
|
||||
version = "0.2.17"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd"
|
||||
|
||||
[[package]]
|
||||
name = "png"
|
||||
version = "0.18.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "60769b8b31b2a9f263dae2776c37b1b28ae246943cf719eb6946a1db05128a61"
|
||||
dependencies = [
|
||||
"bitflags",
|
||||
"crc32fast",
|
||||
"fdeflate",
|
||||
"flate2",
|
||||
"miniz_oxide 0.8.9",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "portable-atomic"
|
||||
version = "1.15.0"
|
||||
@@ -330,6 +823,21 @@ version = "0.1.30"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d55d956fa96f5ec02be2e13af0e20391a5aa83d6a074e3ad368959d0fab299ea"
|
||||
|
||||
[[package]]
|
||||
name = "quick-error"
|
||||
version = "2.0.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a993555f31e5a609f617c12db6250dedcac1b0a85076912c436e6fc9b2c8e6a3"
|
||||
|
||||
[[package]]
|
||||
name = "quick-xml"
|
||||
version = "0.38.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b66c2058c55a409d601666cffe35f04333cf1013010882cec174a7467cd4e21c"
|
||||
dependencies = [
|
||||
"memchr",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "quote"
|
||||
version = "1.0.47"
|
||||
@@ -345,6 +853,26 @@ version = "0.2.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "60a357793950651c4ed0f3f52338f53b2f809f32d83a07f72909fa13e4c6c1e3"
|
||||
|
||||
[[package]]
|
||||
name = "rayon"
|
||||
version = "1.12.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "fb39b166781f92d482534ef4b4b1b2568f42613b53e5b6c160e24cfbfa30926d"
|
||||
dependencies = [
|
||||
"either",
|
||||
"rayon-core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rayon-core"
|
||||
version = "1.13.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "22e18b0f0062d30d4230b2e85ff77fdfe4326feb054b9783a3460d8435c8ab91"
|
||||
dependencies = [
|
||||
"crossbeam-deque",
|
||||
"crossbeam-utils",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rustversion"
|
||||
version = "1.0.23"
|
||||
@@ -378,7 +906,7 @@ checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
"syn 3.0.7",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -405,12 +933,29 @@ dependencies = [
|
||||
"digest",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "simd-adler32"
|
||||
version = "0.3.10"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea"
|
||||
|
||||
[[package]]
|
||||
name = "slab"
|
||||
version = "0.4.12"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5"
|
||||
|
||||
[[package]]
|
||||
name = "syn"
|
||||
version = "2.0.119"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "syn"
|
||||
version = "3.0.7"
|
||||
@@ -439,7 +984,40 @@ checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
"syn 3.0.7",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tiff"
|
||||
version = "0.11.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b63feaf3343d35b6ca4d50483f94843803b0f51634937cc2ec519fc32232bc52"
|
||||
dependencies = [
|
||||
"fax",
|
||||
"flate2",
|
||||
"half",
|
||||
"quick-error",
|
||||
"weezl",
|
||||
"zune-jpeg",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tracing"
|
||||
version = "0.1.44"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100"
|
||||
dependencies = [
|
||||
"pin-project-lite",
|
||||
"tracing-core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tracing-core"
|
||||
version = "0.1.36"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a"
|
||||
dependencies = [
|
||||
"once_cell",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -492,7 +1070,7 @@ dependencies = [
|
||||
"bumpalo",
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
"syn 3.0.7",
|
||||
"wasm-bindgen-shared",
|
||||
]
|
||||
|
||||
@@ -515,6 +1093,38 @@ dependencies = [
|
||||
"wasm-bindgen",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "weezl"
|
||||
version = "0.1.12"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a28ac98ddc8b9274cb41bb4d9d4d5c425b6020c50c46f25559911905610b4a88"
|
||||
|
||||
[[package]]
|
||||
name = "zerocopy"
|
||||
version = "0.8.62"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "86502bf56ac7c77571a32e2647bb2a15894565e981fb2a48d7bde2d91c965a9d"
|
||||
dependencies = [
|
||||
"zerocopy-derive",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "zerocopy-derive"
|
||||
version = "0.8.62"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5457206954b06561e2608c7e19cf58b1926586d999c246eebe4502f7e2039d1a"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.119",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "zlib-rs"
|
||||
version = "0.6.8"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b268e58e7c693d7c271f93ffc4ba3b380412554231c85bf61ca7af91042a4112"
|
||||
|
||||
[[package]]
|
||||
name = "zmij"
|
||||
version = "1.0.23"
|
||||
|
||||
+14
-1
@@ -1,6 +1,6 @@
|
||||
[workspace]
|
||||
resolver = "2"
|
||||
members = ["engine/core", "workers/faces"]
|
||||
members = ["engine/core", "engine/wasm", "workers/render", "workers/faces"]
|
||||
# The desktop shell needs WebKitGTK/WebView2 system libraries, so it builds on its own (desktop release workflow).
|
||||
exclude = ["apps/desktop/src-tauri"]
|
||||
|
||||
@@ -11,7 +11,20 @@ publish = false
|
||||
[workspace.dependencies]
|
||||
# LightCraft is consumed, never forked. Bump `rev` deliberately and run the reference-image tests.
|
||||
lightcraft-develop = { git = "https://github.com/storytold/lightcraft", rev = "0dd6593d9db55a17ab559261bac4d766f015c345" }
|
||||
lightcraft-codecs = { git = "https://github.com/storytold/lightcraft", rev = "0dd6593d9db55a17ab559261bac4d766f015c345", default-features = false }
|
||||
lightcraft-pipeline = { git = "https://github.com/storytold/lightcraft", rev = "0dd6593d9db55a17ab559261bac4d766f015c345" }
|
||||
lightcraft-raster = { git = "https://github.com/storytold/lightcraft", rev = "0dd6593d9db55a17ab559261bac4d766f015c345" }
|
||||
lightcraft-geom = { git = "https://github.com/storytold/lightcraft", rev = "0dd6593d9db55a17ab559261bac4d766f015c345" }
|
||||
lightcraft-faces = { git = "https://github.com/storytold/lightcraft", rev = "0dd6593d9db55a17ab559261bac4d766f015c345" }
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
serde_json = "1"
|
||||
thiserror = "2"
|
||||
|
||||
# The browser module: small and fast enough for slider drags (same trade-off as LightCraft's `web` profile).
|
||||
[profile.wasm]
|
||||
inherits = "release"
|
||||
opt-level = 3
|
||||
lto = "fat"
|
||||
codegen-units = 1
|
||||
panic = "abort"
|
||||
strip = true
|
||||
@@ -29,3 +29,6 @@ FACES_BIN=/srv/photoreport/target/release/photoreport-faces
|
||||
FACES_MODELS_DIR=/srv/photoreport-data/models
|
||||
FACES_EMBEDDER=auraface
|
||||
FACES_PROCESSES=2
|
||||
# Develop: replays edits and renders edited thumbnails and deliveries (workers/render).
|
||||
RENDER_BIN=/srv/photoreport/target/release/photoreport-render
|
||||
RENDER_PROCESSES=2
|
||||
@@ -0,0 +1,40 @@
|
||||
-- CreateEnum
|
||||
CREATE TYPE "RenderStatus" AS ENUM ('NONE', 'PENDING', 'RUNNING', 'DONE', 'FAILED');
|
||||
|
||||
-- AlterTable
|
||||
ALTER TABLE "photos" ADD COLUMN "develop_seq" INTEGER NOT NULL DEFAULT 0,
|
||||
ADD COLUMN "develop_snapshot" JSONB,
|
||||
ADD COLUMN "edited_at" TIMESTAMP(3),
|
||||
ADD COLUMN "render_status" "RenderStatus" NOT NULL DEFAULT 'NONE',
|
||||
ADD COLUMN "rendered_seq" INTEGER NOT NULL DEFAULT 0,
|
||||
ADD COLUMN "snapshot_seq" INTEGER NOT NULL DEFAULT 0;
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "photo_edits" (
|
||||
"id" UUID NOT NULL,
|
||||
"photo_id" UUID NOT NULL,
|
||||
"seq" INTEGER NOT NULL,
|
||||
"op_id" TEXT NOT NULL,
|
||||
"client_id" TEXT NOT NULL,
|
||||
"command" JSONB NOT NULL,
|
||||
"user_id" UUID,
|
||||
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "photo_edits_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "photo_edits_photo_id_seq_key" ON "photo_edits"("photo_id", "seq");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "photo_edits_photo_id_op_id_key" ON "photo_edits"("photo_id", "op_id");
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "photo_edits" ADD CONSTRAINT "photo_edits_photo_id_fkey" FOREIGN KEY ("photo_id") REFERENCES "photos"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "photo_edits" ADD CONSTRAINT "photo_edits_user_id_fkey" FOREIGN KEY ("user_id") REFERENCES "users"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||
|
||||
|
||||
-- The render worker looks for photos whose edits have paused.
|
||||
CREATE INDEX "photos_render_pending_idx" ON "photos" ("edited_at") WHERE "render_status" = 'PENDING';
|
||||
@@ -46,6 +46,7 @@ model User {
|
||||
assignments EventAssignment[]
|
||||
uploads Photo[]
|
||||
ftpAccounts FtpAccount[]
|
||||
edits PhotoEdit[]
|
||||
|
||||
@@map("users")
|
||||
}
|
||||
@@ -235,48 +236,60 @@ model FtpAccount {
|
||||
}
|
||||
|
||||
model Photo {
|
||||
id String @id @default(uuid()) @db.Uuid
|
||||
organizationId String @map("organization_id") @db.Uuid
|
||||
id String @id @default(uuid()) @db.Uuid
|
||||
organizationId String @map("organization_id") @db.Uuid
|
||||
/// Null while no event matches (the editor's inbox).
|
||||
eventId String? @map("event_id") @db.Uuid
|
||||
uploaderId String? @map("uploader_id") @db.Uuid
|
||||
source PhotoSource
|
||||
originalName String @map("original_name")
|
||||
sha256 String
|
||||
byteSize Int @map("byte_size")
|
||||
storageKey String @map("storage_key")
|
||||
status PhotoStatus @default(PROCESSING)
|
||||
error String?
|
||||
width Int?
|
||||
height Int?
|
||||
capturedAt DateTime? @map("captured_at")
|
||||
cameraMake String? @map("camera_make")
|
||||
cameraModel String? @map("camera_model")
|
||||
cameraSerial String? @map("camera_serial")
|
||||
lens String?
|
||||
focalLength Float? @map("focal_length")
|
||||
aperture Float?
|
||||
exposureTime Float? @map("exposure_time")
|
||||
iso Int?
|
||||
rating Int @default(0)
|
||||
flag PhotoFlag @default(NONE)
|
||||
colorLabel ColorLabel @default(NONE) @map("color_label")
|
||||
eventId String? @map("event_id") @db.Uuid
|
||||
uploaderId String? @map("uploader_id") @db.Uuid
|
||||
source PhotoSource
|
||||
originalName String @map("original_name")
|
||||
sha256 String
|
||||
byteSize Int @map("byte_size")
|
||||
storageKey String @map("storage_key")
|
||||
status PhotoStatus @default(PROCESSING)
|
||||
error String?
|
||||
width Int?
|
||||
height Int?
|
||||
capturedAt DateTime? @map("captured_at")
|
||||
cameraMake String? @map("camera_make")
|
||||
cameraModel String? @map("camera_model")
|
||||
cameraSerial String? @map("camera_serial")
|
||||
lens String?
|
||||
focalLength Float? @map("focal_length")
|
||||
aperture Float?
|
||||
exposureTime Float? @map("exposure_time")
|
||||
iso Int?
|
||||
rating Int @default(0)
|
||||
flag PhotoFlag @default(NONE)
|
||||
colorLabel ColorLabel @default(NONE) @map("color_label")
|
||||
/// Names of the people in the photo (go to IPTC Title and Persons Shown).
|
||||
players String[] @default([])
|
||||
players String[] @default([])
|
||||
/// Per-photo IPTC overrides on top of the event template (packages/metadata IptcTemplate).
|
||||
iptcOverrides Json? @map("iptc_overrides")
|
||||
iptcOverrides Json? @map("iptc_overrides")
|
||||
/// IPTC found in the file as it arrived (camera presets or an earlier caption), for reference.
|
||||
embeddedIptc Json? @map("embedded_iptc")
|
||||
embeddedIptc Json? @map("embedded_iptc")
|
||||
/// Face analysis: NONE (organization without biometrics), PENDING, DONE or FAILED.
|
||||
facesStatus FacesStatus @default(NONE) @map("faces_status")
|
||||
createdAt DateTime @default(now()) @map("created_at")
|
||||
updatedAt DateTime @updatedAt @map("updated_at")
|
||||
facesStatus FacesStatus @default(NONE) @map("faces_status")
|
||||
/// Last op-log sequence number (0: never edited).
|
||||
developSeq Int @default(0) @map("develop_seq")
|
||||
/// Develop settings replayed up to `snapshotSeq` by the render worker (LightCraft JSON); clients
|
||||
/// replay the ops after it.
|
||||
developSnapshot Json? @map("develop_snapshot")
|
||||
snapshotSeq Int @default(0) @map("snapshot_seq")
|
||||
/// Edited thumb/preview: PENDING after an edit, rendered by the worker once edits pause.
|
||||
renderStatus RenderStatus @default(NONE) @map("render_status")
|
||||
/// The op-log sequence the edited thumb/preview show (0: they show the original).
|
||||
renderedSeq Int @default(0) @map("rendered_seq")
|
||||
editedAt DateTime? @map("edited_at")
|
||||
createdAt DateTime @default(now()) @map("created_at")
|
||||
updatedAt DateTime @updatedAt @map("updated_at")
|
||||
|
||||
organization Organization @relation(fields: [organizationId], references: [id], onDelete: Cascade)
|
||||
event Event? @relation(fields: [eventId], references: [id], onDelete: SetNull)
|
||||
uploader User? @relation(fields: [uploaderId], references: [id], onDelete: SetNull)
|
||||
deliveries DeliveryItem[]
|
||||
faces Face[]
|
||||
edits PhotoEdit[]
|
||||
|
||||
/// The same file sent twice (FTP retries, two cards) is stored once.
|
||||
@@unique([organizationId, sha256])
|
||||
@@ -285,6 +298,35 @@ model Photo {
|
||||
@@map("photos")
|
||||
}
|
||||
|
||||
enum RenderStatus {
|
||||
NONE
|
||||
PENDING
|
||||
RUNNING
|
||||
DONE
|
||||
FAILED
|
||||
}
|
||||
|
||||
/// The develop op log: every edit command, in the order the server accepted it. Last writer wins per control.
|
||||
model PhotoEdit {
|
||||
id String @id @default(uuid()) @db.Uuid
|
||||
photoId String @map("photo_id") @db.Uuid
|
||||
seq Int
|
||||
/// Client-generated id: a retried send (offline queue) is stored once.
|
||||
opId String @map("op_id")
|
||||
/// The window that sent it, so it can skip its own echo.
|
||||
clientId String @map("client_id")
|
||||
command Json
|
||||
userId String? @map("user_id") @db.Uuid
|
||||
createdAt DateTime @default(now()) @map("created_at")
|
||||
|
||||
photo Photo @relation(fields: [photoId], references: [id], onDelete: Cascade)
|
||||
user User? @relation(fields: [userId], references: [id], onDelete: SetNull)
|
||||
|
||||
@@unique([photoId, seq])
|
||||
@@unique([photoId, opId])
|
||||
@@map("photo_edits")
|
||||
}
|
||||
|
||||
/// Code replacements (`\v7\`), one list per organization, kept as the tab-separated text people edit.
|
||||
model CodeList {
|
||||
id String @id @default(uuid()) @db.Uuid
|
||||
|
||||
@@ -17,6 +17,8 @@ import { registerFtpRoutes } from "./library/ftp.js";
|
||||
import { registerPhotoRoutes } from "./library/photos.js";
|
||||
import { registerUploadRoutes } from "./library/uploads.js";
|
||||
import { IngestService } from "./ingest/service.js";
|
||||
import { registerDevelopRoutes } from "./develop/routes.js";
|
||||
import { DevelopService } from "./develop/service.js";
|
||||
import { registerFaceRoutes } from "./faces/routes.js";
|
||||
import { FaceService } from "./faces/service.js";
|
||||
import { registerOrgRoutes } from "./orgs/routes.js";
|
||||
@@ -84,6 +86,9 @@ export async function buildApp({ config, db, realtime, fetchImpl }: AppDeps): Pr
|
||||
const faces = new FaceService({ db, storage, broadcaster, log: app.log });
|
||||
await registerFaceRoutes(app, { db, sessions, faces, signer, storage });
|
||||
await registerDeliveryRoutes(app, { db, sessions, secrets, delivery });
|
||||
// Edits are stored and fanned out here; the worker replays and renders them.
|
||||
const develop = new DevelopService({ db, storage, signer, broadcaster, log: app.log });
|
||||
await registerDevelopRoutes(app, { db, sessions, develop });
|
||||
|
||||
// Validation-only endpoint for the edit contract; the realtime path reuses the same schema.
|
||||
app.post("/v1/edits/validate", async (req) => {
|
||||
|
||||
@@ -44,6 +44,9 @@ const Env = z.object({
|
||||
FACES_EMBEDDER: z.enum(["auraface", "sface"]).default("auraface"),
|
||||
/** Face processes in parallel (one CPU core each). */
|
||||
FACES_PROCESSES: z.coerce.number().int().positive().default(2),
|
||||
/** Render worker binary (workers/render): edited thumbnails and deliveries of edited photos. */
|
||||
RENDER_BIN: z.string().optional(),
|
||||
RENDER_PROCESSES: z.coerce.number().int().positive().default(2),
|
||||
COOKIE_SECURE: z
|
||||
.enum(["true", "false"])
|
||||
.optional()
|
||||
|
||||
@@ -4,6 +4,13 @@ import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
import sharp from "sharp";
|
||||
import type { RenderEngine, Settings } from "../develop/engine.js";
|
||||
|
||||
/** The photo was edited: render it with these develop settings. */
|
||||
export interface DeliveryEdit {
|
||||
engine: RenderEngine;
|
||||
settings: Settings;
|
||||
}
|
||||
|
||||
export interface RenderOptions {
|
||||
longEdge: number;
|
||||
@@ -14,17 +21,26 @@ export interface RenderOptions {
|
||||
* The delivered JPEG: oriented, at most `longEdge` px on the longest side (never enlarged), 4:4:4 chroma at
|
||||
* the requested quality, camera EXIF and colour profile kept, IPTC written into both IIM and XMP.
|
||||
*/
|
||||
export async function renderDelivery(original: string, iptc: IptcValues, opts: RenderOptions, created?: CreatedStamp): Promise<Buffer> {
|
||||
const image = await sharp(original)
|
||||
.rotate()
|
||||
.resize({ width: opts.longEdge, height: opts.longEdge, fit: "inside", withoutEnlargement: true })
|
||||
.keepExif()
|
||||
.keepIccProfile()
|
||||
.jpeg({ quality: opts.quality, chromaSubsampling: "4:4:4", mozjpeg: false })
|
||||
.toBuffer();
|
||||
export async function renderDelivery(original: string, iptc: IptcValues, opts: RenderOptions, created?: CreatedStamp, edit?: DeliveryEdit): Promise<Buffer> {
|
||||
const dir = await mkdtemp(path.join(tmpdir(), "pr-render-"));
|
||||
const file = path.join(dir, "out.jpg");
|
||||
try {
|
||||
if (edit) {
|
||||
// Edited: the develop engine renders the original (crop and all) straight to the delivered size and quality,
|
||||
// in sRGB. The camera EXIF is copied back, without the orientation (the pixels are already upright).
|
||||
await edit.engine.render({ input: original, output: file, settings: edit.settings, maxEdge: opts.longEdge, quality: opts.quality });
|
||||
await exiftool.write(file, {}, {
|
||||
writeArgs: ["-overwrite_original", "-TagsFromFile", original, "-EXIF:all", "--Orientation", "--ThumbnailImage", "--PreviewImage", "-Orientation#=1", ...toExiftoolArgs(iptc, created)],
|
||||
});
|
||||
return await readFile(file);
|
||||
}
|
||||
const image = await sharp(original)
|
||||
.rotate()
|
||||
.resize({ width: opts.longEdge, height: opts.longEdge, fit: "inside", withoutEnlargement: true })
|
||||
.keepExif()
|
||||
.keepIccProfile()
|
||||
.jpeg({ quality: opts.quality, chromaSubsampling: "4:4:4", mozjpeg: false })
|
||||
.toBuffer();
|
||||
await writeFile(file, image);
|
||||
await exiftool.write(file, {}, { writeArgs: ["-overwrite_original", ...toExiftoolArgs(iptc, created)] });
|
||||
return await readFile(file);
|
||||
|
||||
@@ -8,7 +8,8 @@ import { iptcForPhoto } from "../library/iptc.js";
|
||||
import type { Broadcaster } from "../realtime.js";
|
||||
import type { LocalStorage } from "../storage/storage.js";
|
||||
import { NextcloudClient, NextcloudError } from "./nextcloud.js";
|
||||
import { renderDelivery } from "./render.js";
|
||||
import type { RenderEngine, Settings } from "../develop/engine.js";
|
||||
import { type DeliveryEdit, renderDelivery } from "./render.js";
|
||||
import type { SecretBox } from "./secrets.js";
|
||||
|
||||
export const MAX_ATTEMPTS = 5;
|
||||
@@ -48,6 +49,8 @@ export interface DeliveryDeps {
|
||||
broadcaster: Broadcaster;
|
||||
log: IngestLogger;
|
||||
fetchImpl?: typeof fetch;
|
||||
/** Edited photos are rendered through it (worker only). */
|
||||
develop?: { settings(photoId: string): Promise<{ settings: Settings | null }>; engine: RenderEngine | undefined } | undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -60,6 +63,15 @@ export class DeliveryService {
|
||||
|
||||
constructor(private readonly deps: DeliveryDeps) {}
|
||||
|
||||
/** Develop settings for an edited photo; an edited photo is never delivered unedited. */
|
||||
private async editFor(photoId: string, developSeq: number): Promise<DeliveryEdit | undefined> {
|
||||
if (developSeq === 0) return undefined;
|
||||
const develop = this.deps.develop;
|
||||
if (!develop?.engine) throw new Error("photo is edited but the render worker is not configured (RENDER_BIN)");
|
||||
const { settings } = await develop.settings(photoId);
|
||||
return settings ? { engine: develop.engine, settings } : undefined;
|
||||
}
|
||||
|
||||
async enqueue(input: { organizationId: string; targetId: string; photoIds: string[]; again: boolean; requestedById: string }): Promise<{ queued: DeliveryItem[]; skipped: { photoId: string; reason: string }[] }> {
|
||||
const { db } = this.deps;
|
||||
const target = await db.deliveryTarget.findFirst({ where: { id: input.targetId, organizationId: input.organizationId, disabledAt: null } });
|
||||
@@ -159,7 +171,8 @@ export class DeliveryService {
|
||||
const folder = renderFolder(item.target.folderTemplate, vars);
|
||||
const fileName = renderFileName(item.target.fileNameTemplate, vars, item.photo.originalName);
|
||||
const iptc = await iptcForPhoto(db, item.photoId);
|
||||
const data = await renderDelivery(storage.resolve(item.photo.storageKey), iptc?.values ?? {}, { longEdge: item.target.longEdge, quality: item.target.jpegQuality }, item.photo.capturedAt ? createdStamp(item.photo.capturedAt) : undefined);
|
||||
const edit = await this.editFor(item.photoId, item.photo.developSeq);
|
||||
const data = await renderDelivery(storage.resolve(item.photo.storageKey), iptc?.values ?? {}, { longEdge: item.target.longEdge, quality: item.target.jpegQuality }, item.photo.capturedAt ? createdStamp(item.photo.capturedAt) : undefined, edit);
|
||||
const client = this.client(item.target);
|
||||
await client.ensureFolder(folder);
|
||||
await client.upload(folder + fileName, data);
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
import { LeastBusy, LineProcess } from "../lib/line-process.js";
|
||||
|
||||
export type Settings = Record<string, unknown>;
|
||||
|
||||
export interface Replayed {
|
||||
settings: Settings;
|
||||
skipped: number[];
|
||||
unedited: boolean;
|
||||
}
|
||||
|
||||
export interface RenderJob {
|
||||
input: string;
|
||||
output: string;
|
||||
settings: Settings | null;
|
||||
/** Long edge in pixels (0: full size). */
|
||||
maxEdge: number;
|
||||
quality: number;
|
||||
}
|
||||
|
||||
/** The develop engine on the server: replays op logs and renders originals (`workers/render`). */
|
||||
export interface RenderEngine {
|
||||
/** `unedited`: the result equals the defaults (e.g. after a reset), so the original is shown as is. */
|
||||
replay(base: Settings | null, commands: unknown[]): Promise<Replayed>;
|
||||
render(job: RenderJob): Promise<{ width: number; height: number }>;
|
||||
close(): Promise<void>;
|
||||
}
|
||||
|
||||
export class RenderProcess implements RenderEngine {
|
||||
private readonly proc: LineProcess;
|
||||
|
||||
constructor(opts: { bin: string; timeoutMs?: number }) {
|
||||
this.proc = new LineProcess({ name: "render worker", bin: opts.bin, timeoutMs: opts.timeoutMs ?? 300_000 });
|
||||
}
|
||||
|
||||
async replay(base: Settings | null, commands: unknown[]) {
|
||||
const r = await this.proc.request({ base, commands });
|
||||
return { settings: r.settings as Settings, skipped: (r.skipped as number[] | undefined) ?? [], unedited: r.unedited === true };
|
||||
}
|
||||
|
||||
async render(job: RenderJob) {
|
||||
const r = await this.proc.request({ ...job });
|
||||
return { width: Number(r.width), height: Number(r.height) };
|
||||
}
|
||||
|
||||
close(): Promise<void> {
|
||||
return this.proc.close();
|
||||
}
|
||||
}
|
||||
|
||||
export class RenderPool implements RenderEngine {
|
||||
private readonly pool: LeastBusy<RenderEngine>;
|
||||
constructor(private readonly engines: RenderEngine[]) {
|
||||
this.pool = new LeastBusy(engines);
|
||||
}
|
||||
replay(base: Settings | null, commands: unknown[]) {
|
||||
return this.pool.use((e) => e.replay(base, commands));
|
||||
}
|
||||
render(job: RenderJob) {
|
||||
return this.pool.use((e) => e.render(job));
|
||||
}
|
||||
async close(): Promise<void> {
|
||||
await Promise.all(this.engines.map((e) => e.close()));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
import { PostEdits } from "@photoreport/contracts";
|
||||
import type { FastifyInstance } from "fastify";
|
||||
import { z } from "zod";
|
||||
import { ROLE_RANK, currentUserId, requireAuth, requireMembership } from "../auth/guard.js";
|
||||
import type { SessionService } from "../auth/sessions.js";
|
||||
import type { Db } from "../db.js";
|
||||
import { badRequest, forbidden, notFound } from "../lib/errors.js";
|
||||
import { type DevelopService, EditRejected } from "./service.js";
|
||||
|
||||
const PhotoParams = z.object({ photoId: z.uuid() });
|
||||
const StateQuery = z.object({ since: z.coerce.number().int().min(0).optional() });
|
||||
|
||||
export async function registerDevelopRoutes(app: FastifyInstance, deps: { db: Db; sessions: SessionService; develop: DevelopService }) {
|
||||
const { db, develop } = deps;
|
||||
const authenticate = requireAuth(deps.sessions);
|
||||
|
||||
/** Editors edit any photo of the organization; photographers only the ones they sent. */
|
||||
async function photoFor(req: Parameters<typeof currentUserId>[0], photoId: string) {
|
||||
const photo = await db.photo.findUnique({ where: { id: photoId }, select: { organizationId: true, uploaderId: true, status: true } });
|
||||
if (!photo) throw notFound("photo_not_found");
|
||||
const membership = await requireMembership(db, req, photo.organizationId, "PHOTOGRAPHER");
|
||||
if (ROLE_RANK[membership.role] < ROLE_RANK.INGESTER && photo.uploaderId !== membership.userId) throw forbidden("not_your_photo");
|
||||
return photo;
|
||||
}
|
||||
|
||||
/** The develop state: snapshot plus the ops after it, or (with `since`) just the ops after that position. */
|
||||
app.get("/v1/photos/:photoId/develop", { preHandler: authenticate }, async (req) => {
|
||||
const { photoId } = PhotoParams.parse(req.params);
|
||||
const { since } = StateQuery.parse(req.query);
|
||||
await photoFor(req, photoId);
|
||||
return develop.state(photoId, since);
|
||||
});
|
||||
|
||||
app.post("/v1/photos/:photoId/edits", { preHandler: authenticate }, async (req) => {
|
||||
const { photoId } = PhotoParams.parse(req.params);
|
||||
const body = PostEdits.parse(req.body);
|
||||
const photo = await photoFor(req, photoId);
|
||||
if (photo.status !== "READY") throw badRequest("photo_not_ready");
|
||||
try {
|
||||
return await develop.append(photoId, currentUserId(req), body);
|
||||
} catch (err) {
|
||||
if (err instanceof EditRejected) throw badRequest(err.code);
|
||||
throw err;
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,219 @@
|
||||
import { type DevelopState, type EditCommand, type EditLogEntry, type PostEdits, getControl } from "@photoreport/contracts";
|
||||
import type { Db } from "../db.js";
|
||||
import { Prisma, type PhotoEdit } from "../generated/prisma/client.js";
|
||||
import type { IngestLogger } from "../ingest/service.js";
|
||||
import { photoUrls } from "../library/serialize.js";
|
||||
import type { Broadcaster } from "../realtime.js";
|
||||
import { type LocalStorage, type UrlSigner, VARIANT_SIZE } from "../storage/storage.js";
|
||||
import type { RenderEngine, Settings } from "./engine.js";
|
||||
|
||||
/** Edits pause this long before the worker renders new thumbnails (a slider drag sends many). */
|
||||
export const RENDER_QUIET_MS = 2000;
|
||||
const STALE_RUNNING_MS = 5 * 60_000;
|
||||
|
||||
export class EditRejected extends Error {
|
||||
constructor(readonly code: string) {
|
||||
super(code);
|
||||
}
|
||||
}
|
||||
|
||||
function toEntry(e: PhotoEdit): EditLogEntry {
|
||||
return { seq: e.seq, opId: e.opId, clientId: e.clientId, command: e.command as EditCommand, userId: e.userId, at: e.createdAt.toISOString() };
|
||||
}
|
||||
|
||||
/** Commands are checked against the controls of the pinned engine, so a stale client cannot fill the log with junk. */
|
||||
function validate(command: EditCommand): void {
|
||||
if (command.command !== "develop.set") return;
|
||||
for (const [id, value] of Object.entries(command.params.values)) {
|
||||
const control = getControl(id);
|
||||
if (!control) throw new EditRejected("unknown_control");
|
||||
if (value < control.min || value > control.max) throw new EditRejected("value_out_of_range");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The develop op log. Clients send commands (never pixels); the server orders them per photo, stores them and
|
||||
* fans them out, so every open window (web or desktop) replays the same sequence with its own engine. The
|
||||
* worker keeps a settings snapshot, renders edited thumbnails once edits pause, and deliveries render from it.
|
||||
*/
|
||||
export class DevelopService {
|
||||
constructor(
|
||||
private readonly deps: { db: Db; storage: LocalStorage; signer: UrlSigner; broadcaster: Broadcaster; log: IngestLogger; engine?: RenderEngine | undefined },
|
||||
) {}
|
||||
|
||||
get engine(): RenderEngine | undefined {
|
||||
return this.deps.engine;
|
||||
}
|
||||
|
||||
async state(photoId: string, since?: number): Promise<DevelopState> {
|
||||
const photo = await this.deps.db.photo.findUniqueOrThrow({ where: { id: photoId }, select: { developSeq: true, developSnapshot: true, snapshotSeq: true } });
|
||||
const useSnapshot = since === undefined || since < photo.snapshotSeq;
|
||||
const from = useSnapshot ? photo.snapshotSeq : since;
|
||||
const ops = await this.deps.db.photoEdit.findMany({ where: { photoId, seq: { gt: from } }, orderBy: { seq: "asc" } });
|
||||
return {
|
||||
photoId,
|
||||
developSeq: photo.developSeq,
|
||||
snapshotSeq: from,
|
||||
snapshot: useSnapshot ? ((photo.developSnapshot as Settings | null) ?? null) : null,
|
||||
ops: ops.map(toEntry),
|
||||
};
|
||||
}
|
||||
|
||||
/** Appends ops in order. A repeated `opId` (a retry) returns the stored entry and is not broadcast again. */
|
||||
async append(photoId: string, userId: string, body: PostEdits): Promise<{ developSeq: number; ops: EditLogEntry[] }> {
|
||||
for (const op of body.ops) validate(op.command);
|
||||
const { db, broadcaster } = this.deps;
|
||||
const result = await db.$transaction(async (tx) => {
|
||||
const [locked] = await tx.$queryRaw<{ develop_seq: number; organization_id: string; event_id: string | null }[]>`
|
||||
SELECT develop_seq, organization_id, event_id FROM photos WHERE id = ${photoId}::uuid FOR UPDATE`;
|
||||
if (!locked) throw new EditRejected("photo_not_found");
|
||||
let seq = locked.develop_seq;
|
||||
const existing = new Map(
|
||||
(await tx.photoEdit.findMany({ where: { photoId, opId: { in: body.ops.map((o) => o.opId) } } })).map((e) => [e.opId, e]),
|
||||
);
|
||||
const out: EditLogEntry[] = [];
|
||||
const fresh: EditLogEntry[] = [];
|
||||
for (const op of body.ops) {
|
||||
const known = existing.get(op.opId);
|
||||
if (known) {
|
||||
out.push(toEntry(known));
|
||||
continue;
|
||||
}
|
||||
seq++;
|
||||
const row = await tx.photoEdit.create({
|
||||
data: { photoId, seq, opId: op.opId, clientId: body.clientId, command: op.command as Prisma.InputJsonValue, userId },
|
||||
});
|
||||
existing.set(op.opId, row);
|
||||
const entry = toEntry(row);
|
||||
out.push(entry);
|
||||
fresh.push(entry);
|
||||
}
|
||||
if (fresh.length) await tx.photo.update({ where: { id: photoId }, data: { developSeq: seq, editedAt: new Date(), renderStatus: "PENDING" } });
|
||||
return { organizationId: locked.organization_id, eventId: locked.event_id, developSeq: seq, out, fresh };
|
||||
});
|
||||
if (result.fresh.length) {
|
||||
broadcaster.library(result.organizationId, {
|
||||
type: "photo.edited",
|
||||
photoId,
|
||||
eventId: result.eventId,
|
||||
clientId: body.clientId,
|
||||
developSeq: result.developSeq,
|
||||
ops: result.fresh,
|
||||
});
|
||||
}
|
||||
return { developSeq: result.developSeq, ops: result.out };
|
||||
}
|
||||
|
||||
/**
|
||||
* Settings at the photo's current op-log position (null: never edited, or edited back to defaults), refreshing
|
||||
* the stored snapshot when ops came after it. Needs the engine.
|
||||
*/
|
||||
async settings(photoId: string): Promise<{ settings: Settings | null; seq: number }> {
|
||||
const { db, engine } = this.deps;
|
||||
const photo = await db.photo.findUniqueOrThrow({ where: { id: photoId }, select: { developSeq: true, developSnapshot: true, snapshotSeq: true } });
|
||||
if (photo.developSeq === 0) return { settings: null, seq: 0 };
|
||||
if (photo.snapshotSeq === photo.developSeq) return { settings: (photo.developSnapshot as Settings | null) ?? null, seq: photo.developSeq };
|
||||
if (!engine) throw new Error("render worker not configured (RENDER_BIN)");
|
||||
const ops = await db.photoEdit.findMany({ where: { photoId, seq: { gt: photo.snapshotSeq, lte: photo.developSeq } }, orderBy: { seq: "asc" } });
|
||||
const replayed = await engine.replay((photo.developSnapshot as Settings | null) ?? null, ops.map((o) => o.command));
|
||||
if (replayed.skipped.length) this.deps.log.warn({ photoId, skipped: replayed.skipped.map((i) => ops[i]?.seq) }, "develop: commands refused by the engine");
|
||||
const settings = replayed.unedited ? null : replayed.settings;
|
||||
// Only move forward: a concurrent replay may already have stored a later snapshot.
|
||||
await db.photo.updateMany({
|
||||
where: { id: photoId, snapshotSeq: { lt: photo.developSeq } },
|
||||
data: { developSnapshot: (settings as Prisma.InputJsonValue | null) ?? Prisma.DbNull, snapshotSeq: photo.developSeq },
|
||||
});
|
||||
return { settings, seq: photo.developSeq };
|
||||
}
|
||||
|
||||
async claimRenders(limit: number, now = new Date()): Promise<string[]> {
|
||||
if (limit <= 0) return [];
|
||||
const quiet = new Date(now.getTime() - RENDER_QUIET_MS);
|
||||
const rows = await this.deps.db.$queryRaw<{ id: string }[]>`
|
||||
UPDATE photos SET render_status = 'RUNNING', updated_at = now()
|
||||
WHERE id IN (
|
||||
SELECT id FROM photos WHERE render_status = 'PENDING' AND edited_at <= ${quiet}
|
||||
ORDER BY edited_at LIMIT ${limit} FOR UPDATE SKIP LOCKED
|
||||
)
|
||||
RETURNING id`;
|
||||
return rows.map((r) => r.id);
|
||||
}
|
||||
|
||||
async requeueStale(now = new Date()): Promise<number> {
|
||||
const r = await this.deps.db.photo.updateMany({
|
||||
where: { renderStatus: "RUNNING", updatedAt: { lt: new Date(now.getTime() - STALE_RUNNING_MS) } },
|
||||
data: { renderStatus: "PENDING" },
|
||||
});
|
||||
return r.count;
|
||||
}
|
||||
|
||||
/** Renders the edited thumb and preview of one claimed photo. Never throws. */
|
||||
async render(photoId: string): Promise<void> {
|
||||
const { db, storage, signer, broadcaster, log, engine } = this.deps;
|
||||
try {
|
||||
if (!engine) throw new Error("render worker not configured (RENDER_BIN)");
|
||||
const { settings, seq } = await this.settings(photoId);
|
||||
const photo = await db.photo.findUniqueOrThrow({ where: { id: photoId } });
|
||||
const renderedSeq = settings ? seq : 0;
|
||||
if (settings) {
|
||||
for (const variant of ["preview", "thumb"] as const) {
|
||||
await engine.render({
|
||||
input: storage.resolve(photo.storageKey),
|
||||
output: storage.resolve(storage.editedKey(photo.organizationId, photo.sha256, seq, variant)),
|
||||
settings,
|
||||
maxEdge: VARIANT_SIZE[variant],
|
||||
quality: variant === "thumb" ? 80 : 88,
|
||||
});
|
||||
}
|
||||
}
|
||||
// Edits that arrived while rendering leave the photo pending for the next round.
|
||||
const updated = await db.photo.update({
|
||||
where: { id: photoId },
|
||||
data: { renderedSeq, renderStatus: (await db.photo.count({ where: { id: photoId, developSeq: seq } })) ? "DONE" : "PENDING" },
|
||||
});
|
||||
if (photo.renderedSeq && photo.renderedSeq !== renderedSeq) {
|
||||
for (const variant of ["preview", "thumb"] as const) await storage.remove(storage.editedKey(photo.organizationId, photo.sha256, photo.renderedSeq, variant));
|
||||
}
|
||||
const urls = photoUrls(updated, signer);
|
||||
broadcaster.library(photo.organizationId, { type: "photo.rendered", photoId, renderedSeq, urls: { thumb: urls.thumb, preview: urls.preview } });
|
||||
log.info({ photoId, seq: renderedSeq }, "develop: edit rendered");
|
||||
} catch (err) {
|
||||
log.warn({ photoId, err: (err as Error).message }, "develop: render failed");
|
||||
await db.photo.update({ where: { id: photoId }, data: { renderStatus: "FAILED" } }).catch(() => {});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export class RenderWorker {
|
||||
private inFlight = 0;
|
||||
private timer: NodeJS.Timeout | undefined;
|
||||
private stopped = false;
|
||||
|
||||
constructor(
|
||||
private readonly service: DevelopService,
|
||||
private readonly opts: { concurrency: number; intervalMs: number; log: IngestLogger },
|
||||
) {}
|
||||
|
||||
start(): void {
|
||||
void this.service.requeueStale();
|
||||
const tick = async () => {
|
||||
try {
|
||||
for (const id of await this.service.claimRenders(this.opts.concurrency - this.inFlight)) {
|
||||
this.inFlight++;
|
||||
void this.service.render(id).finally(() => {
|
||||
this.inFlight--;
|
||||
});
|
||||
}
|
||||
} catch (err) {
|
||||
this.opts.log.warn({ err }, "develop: poll failed");
|
||||
}
|
||||
if (!this.stopped) this.timer = setTimeout(tick, this.opts.intervalMs);
|
||||
};
|
||||
this.timer = setTimeout(tick, 0);
|
||||
}
|
||||
|
||||
stop(): void {
|
||||
this.stopped = true;
|
||||
if (this.timer) clearTimeout(this.timer);
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,4 @@
|
||||
import { spawn, type ChildProcessWithoutNullStreams } from "node:child_process";
|
||||
import { createInterface } from "node:readline";
|
||||
import { LeastBusy, LineProcess } from "../lib/line-process.js";
|
||||
|
||||
export interface DetectedFace {
|
||||
x0: number;
|
||||
@@ -34,114 +33,40 @@ export type EmbedderName = keyof typeof MODEL_IDS;
|
||||
*/
|
||||
export class FaceProcess implements FaceEngine {
|
||||
readonly model: string;
|
||||
private child: ChildProcessWithoutNullStreams | undefined;
|
||||
private ready: Promise<void> | undefined;
|
||||
private pending = new Map<string, { resolve: (a: FaceAnalysis) => void; reject: (e: Error) => void; timer: NodeJS.Timeout }>();
|
||||
private queue: Promise<unknown> = Promise.resolve();
|
||||
private seq = 0;
|
||||
private readonly proc: LineProcess;
|
||||
|
||||
constructor(
|
||||
private readonly opts: { bin: string; modelsDir: string; embedder: EmbedderName; minScore?: number; timeoutMs?: number },
|
||||
) {
|
||||
constructor(opts: { bin: string; modelsDir: string; embedder: EmbedderName; minScore?: number; timeoutMs?: number }) {
|
||||
this.model = MODEL_IDS[opts.embedder];
|
||||
}
|
||||
|
||||
private start(): Promise<void> {
|
||||
if (this.ready) return this.ready;
|
||||
const args = ["--models", this.opts.modelsDir, "--embedder", this.opts.embedder, "--min-score", String(this.opts.minScore ?? 0.6)];
|
||||
const child = spawn(this.opts.bin, args, { stdio: ["pipe", "pipe", "pipe"] });
|
||||
this.child = child;
|
||||
let stderr = "";
|
||||
child.stderr.on("data", (d: Buffer) => {
|
||||
stderr = (stderr + d.toString()).slice(-2000);
|
||||
this.proc = new LineProcess({
|
||||
name: "face worker",
|
||||
bin: opts.bin,
|
||||
args: ["--models", opts.modelsDir, "--embedder", opts.embedder, "--min-score", String(opts.minScore ?? 0.6)],
|
||||
timeoutMs: opts.timeoutMs ?? 120_000,
|
||||
});
|
||||
this.ready = new Promise<void>((resolve, reject) => {
|
||||
const lines = createInterface({ input: child.stdout });
|
||||
let started = false;
|
||||
lines.on("line", (line) => {
|
||||
let msg: { ready?: boolean; id?: string; error?: string } & Partial<FaceAnalysis>;
|
||||
try {
|
||||
msg = JSON.parse(line);
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
if (!started && msg.ready) {
|
||||
started = true;
|
||||
resolve();
|
||||
return;
|
||||
}
|
||||
const waiting = msg.id ? this.pending.get(msg.id) : undefined;
|
||||
if (!waiting || !msg.id) return;
|
||||
this.pending.delete(msg.id);
|
||||
clearTimeout(waiting.timer);
|
||||
if (msg.error) waiting.reject(new Error(msg.error));
|
||||
else waiting.resolve({ width: msg.width ?? 0, height: msg.height ?? 0, faces: msg.faces ?? [] });
|
||||
});
|
||||
child.on("exit", (code) => {
|
||||
const err = new Error(`face worker exited (${code}): ${stderr.trim()}`);
|
||||
if (!started) reject(err);
|
||||
for (const [, p] of this.pending) {
|
||||
clearTimeout(p.timer);
|
||||
p.reject(err);
|
||||
}
|
||||
this.pending.clear();
|
||||
this.child = undefined;
|
||||
this.ready = undefined;
|
||||
});
|
||||
child.on("error", (e) => {
|
||||
if (!started) reject(e);
|
||||
});
|
||||
});
|
||||
return this.ready;
|
||||
}
|
||||
|
||||
/** Requests are serialised: the Rust side is single-threaded; run several processes for parallelism. */
|
||||
analyse(path: string): Promise<FaceAnalysis> {
|
||||
const run = async () => {
|
||||
await this.start();
|
||||
const id = String(++this.seq);
|
||||
return new Promise<FaceAnalysis>((resolve, reject) => {
|
||||
const timer = setTimeout(() => {
|
||||
this.pending.delete(id);
|
||||
reject(new Error("face worker timed out"));
|
||||
this.child?.kill();
|
||||
}, this.opts.timeoutMs ?? 120_000);
|
||||
this.pending.set(id, { resolve, reject, timer });
|
||||
this.child?.stdin.write(JSON.stringify({ id, path }) + "\n");
|
||||
});
|
||||
};
|
||||
const result = this.queue.then(run, run);
|
||||
this.queue = result.catch(() => undefined);
|
||||
return result;
|
||||
async analyse(path: string): Promise<FaceAnalysis> {
|
||||
const msg = (await this.proc.request({ path })) as Partial<FaceAnalysis>;
|
||||
return { width: msg.width ?? 0, height: msg.height ?? 0, faces: msg.faces ?? [] };
|
||||
}
|
||||
|
||||
async close(): Promise<void> {
|
||||
this.child?.stdin.end();
|
||||
this.child?.kill();
|
||||
this.child = undefined;
|
||||
this.ready = undefined;
|
||||
close(): Promise<void> {
|
||||
return this.proc.close();
|
||||
}
|
||||
}
|
||||
|
||||
/** Several face processes behind one engine; each request goes to the least busy one. */
|
||||
export class FacePool implements FaceEngine {
|
||||
readonly model: string;
|
||||
private readonly busy: number[];
|
||||
private readonly pool: LeastBusy<FaceEngine>;
|
||||
|
||||
constructor(private readonly engines: FaceEngine[]) {
|
||||
if (!engines.length) throw new Error("face pool needs at least one engine");
|
||||
this.pool = new LeastBusy(engines);
|
||||
this.model = engines[0]!.model;
|
||||
this.busy = engines.map(() => 0);
|
||||
}
|
||||
|
||||
async analyse(path: string): Promise<FaceAnalysis> {
|
||||
const i = this.busy.indexOf(Math.min(...this.busy));
|
||||
this.busy[i]!++;
|
||||
try {
|
||||
return await this.engines[i]!.analyse(path);
|
||||
} finally {
|
||||
this.busy[i]!--;
|
||||
}
|
||||
analyse(path: string): Promise<FaceAnalysis> {
|
||||
return this.pool.use((e) => e.analyse(path));
|
||||
}
|
||||
|
||||
async close(): Promise<void> {
|
||||
|
||||
@@ -0,0 +1,112 @@
|
||||
import { spawn, type ChildProcessWithoutNullStreams } from "node:child_process";
|
||||
import { createInterface } from "node:readline";
|
||||
|
||||
/**
|
||||
* A long-running helper process that speaks JSON lines over stdin/stdout (the Rust workers): it prints
|
||||
* `{"ready": true, ...}` once, then answers each `{"id": ..., ...}` request with a line carrying the same id.
|
||||
* Requests are serialised (the helpers are single-threaded; run several for parallelism). The process is
|
||||
* restarted after a crash; a request that hangs is failed after `timeoutMs` and the process killed.
|
||||
*/
|
||||
export class LineProcess {
|
||||
private child: ChildProcessWithoutNullStreams | undefined;
|
||||
private ready: Promise<Record<string, unknown>> | undefined;
|
||||
private pending = new Map<string, { resolve: (m: Record<string, unknown>) => void; reject: (e: Error) => void; timer: NodeJS.Timeout }>();
|
||||
private queue: Promise<unknown> = Promise.resolve();
|
||||
private seq = 0;
|
||||
|
||||
constructor(private readonly opts: { name: string; bin: string; args?: string[]; timeoutMs?: number }) {}
|
||||
|
||||
/** Starts the process if needed and resolves with its ready line. */
|
||||
start(): Promise<Record<string, unknown>> {
|
||||
if (this.ready) return this.ready;
|
||||
const child = spawn(this.opts.bin, this.opts.args ?? [], { stdio: ["pipe", "pipe", "pipe"] });
|
||||
this.child = child;
|
||||
let stderr = "";
|
||||
child.stderr.on("data", (d: Buffer) => {
|
||||
stderr = (stderr + d.toString()).slice(-2000);
|
||||
});
|
||||
this.ready = new Promise((resolve, reject) => {
|
||||
const lines = createInterface({ input: child.stdout });
|
||||
let started = false;
|
||||
lines.on("line", (line) => {
|
||||
let msg: Record<string, unknown>;
|
||||
try {
|
||||
msg = JSON.parse(line) as Record<string, unknown>;
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
if (!started && msg.ready) {
|
||||
started = true;
|
||||
resolve(msg);
|
||||
return;
|
||||
}
|
||||
const id = typeof msg.id === "string" ? msg.id : undefined;
|
||||
const waiting = id ? this.pending.get(id) : undefined;
|
||||
if (!waiting || !id) return;
|
||||
this.pending.delete(id);
|
||||
clearTimeout(waiting.timer);
|
||||
if (typeof msg.error === "string") waiting.reject(new Error(msg.error));
|
||||
else waiting.resolve(msg);
|
||||
});
|
||||
child.on("exit", (code) => {
|
||||
const err = new Error(`${this.opts.name} exited (${code}): ${stderr.trim()}`);
|
||||
if (!started) reject(err);
|
||||
for (const [, p] of this.pending) {
|
||||
clearTimeout(p.timer);
|
||||
p.reject(err);
|
||||
}
|
||||
this.pending.clear();
|
||||
this.child = undefined;
|
||||
this.ready = undefined;
|
||||
});
|
||||
child.on("error", (e) => {
|
||||
if (!started) reject(e);
|
||||
});
|
||||
});
|
||||
return this.ready;
|
||||
}
|
||||
|
||||
request(payload: Record<string, unknown>): Promise<Record<string, unknown>> {
|
||||
const run = async () => {
|
||||
await this.start();
|
||||
const id = String(++this.seq);
|
||||
return new Promise<Record<string, unknown>>((resolve, reject) => {
|
||||
const timer = setTimeout(() => {
|
||||
this.pending.delete(id);
|
||||
reject(new Error(`${this.opts.name} timed out`));
|
||||
this.child?.kill();
|
||||
}, this.opts.timeoutMs ?? 120_000);
|
||||
this.pending.set(id, { resolve, reject, timer });
|
||||
this.child?.stdin.write(JSON.stringify({ ...payload, id }) + "\n");
|
||||
});
|
||||
};
|
||||
const result = this.queue.then(run, run);
|
||||
this.queue = result.catch(() => undefined);
|
||||
return result;
|
||||
}
|
||||
|
||||
async close(): Promise<void> {
|
||||
this.child?.stdin.end();
|
||||
this.child?.kill();
|
||||
this.child = undefined;
|
||||
this.ready = undefined;
|
||||
}
|
||||
}
|
||||
|
||||
/** Picks the least busy of several workers. */
|
||||
export class LeastBusy<T> {
|
||||
private readonly busy: number[];
|
||||
constructor(readonly items: T[]) {
|
||||
if (!items.length) throw new Error("pool needs at least one worker");
|
||||
this.busy = items.map(() => 0);
|
||||
}
|
||||
async use<R>(fn: (item: T) => Promise<R>): Promise<R> {
|
||||
const i = this.busy.indexOf(Math.min(...this.busy));
|
||||
this.busy[i]!++;
|
||||
try {
|
||||
return await fn(this.items[i]!);
|
||||
} finally {
|
||||
this.busy[i]!--;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -24,7 +24,7 @@ const ListQuery = z.object({
|
||||
offset: z.coerce.number().int().min(0).default(0),
|
||||
limit: z.coerce.number().int().min(1).max(500).default(200),
|
||||
});
|
||||
const FileParams = z.object({ photoId: z.uuid(), variant: z.enum(["thumb", "preview", "original"]) });
|
||||
const FileParams = z.object({ photoId: z.uuid(), variant: z.enum(["thumb", "preview", "source", "original"]) });
|
||||
const FileQuery = z.object({ exp: z.coerce.number().int(), sig: z.string().min(10).max(100) });
|
||||
const CodeListBody = z.object({ content: z.string().max(500_000) });
|
||||
|
||||
@@ -107,9 +107,14 @@ export async function registerPhotoRoutes(
|
||||
const { photoId, variant } = FileParams.parse(req.params);
|
||||
const { exp, sig } = FileQuery.parse(req.query);
|
||||
if (variant === "original" || !signer.verify(photoId, variant as Variant, exp, sig)) throw notFound("file_not_found");
|
||||
const photo = await db.photo.findUnique({ where: { id: photoId }, select: { organizationId: true, sha256: true, status: true } });
|
||||
const photo = await db.photo.findUnique({ where: { id: photoId }, select: { organizationId: true, sha256: true, status: true, renderedSeq: true } });
|
||||
if (!photo || photo.status !== "READY") throw notFound("file_not_found");
|
||||
const key = storage.derivedKey(photo.organizationId, photo.sha256, variant);
|
||||
const size = variant === "source" ? "preview" : variant;
|
||||
let key = storage.derivedKey(photo.organizationId, photo.sha256, size);
|
||||
if (variant !== "source" && photo.renderedSeq > 0) {
|
||||
const edited = storage.editedKey(photo.organizationId, photo.sha256, photo.renderedSeq, size);
|
||||
if (await storage.exists(edited)) key = edited;
|
||||
}
|
||||
if (!(await storage.exists(key))) throw notFound("file_not_found");
|
||||
return reply
|
||||
.header("content-type", "image/jpeg")
|
||||
|
||||
@@ -26,6 +26,15 @@ export function toSummary(photo: PhotoWithUploader, signer: UrlSigner): PhotoSum
|
||||
colorLabel: photo.colorLabel,
|
||||
players: photo.players,
|
||||
uploader: photo.uploader,
|
||||
urls: { thumb: signer.url(photo.id, "thumb"), preview: signer.url(photo.id, "preview") },
|
||||
developSeq: photo.developSeq,
|
||||
urls: photoUrls(photo, signer),
|
||||
};
|
||||
}
|
||||
|
||||
export function photoUrls(photo: { id: string; renderedSeq: number }, signer: UrlSigner): PhotoSummary["urls"] {
|
||||
return {
|
||||
thumb: signer.url(photo.id, "thumb", photo.renderedSeq),
|
||||
preview: signer.url(photo.id, "preview", photo.renderedSeq),
|
||||
source: signer.url(photo.id, "source"),
|
||||
};
|
||||
}
|
||||
@@ -3,10 +3,11 @@ import { createReadStream } from "node:fs";
|
||||
import { copyFile, mkdir, rename, rm, stat, writeFile } from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
|
||||
export type Variant = "original" | "thumb" | "preview";
|
||||
/** `source` is the unedited preview (the editor renders on top of it); `thumb`/`preview` show the edit. */
|
||||
export type Variant = "original" | "thumb" | "preview" | "source";
|
||||
|
||||
/** Long side in pixels for the derived JPEGs. Thumb: grid; preview: loupe and editor. */
|
||||
export const VARIANT_SIZE: Record<Exclude<Variant, "original">, number> = { thumb: 480, preview: 2048 };
|
||||
export const VARIANT_SIZE: Record<"thumb" | "preview", number> = { thumb: 480, preview: 2048 };
|
||||
|
||||
/**
|
||||
* Files on local disk, one tree per organization:
|
||||
@@ -29,10 +30,19 @@ export class LocalStorage {
|
||||
return `${orgId}/people/${personId}.jpg`;
|
||||
}
|
||||
|
||||
derivedKey(orgId: string, sha256: string, variant: Exclude<Variant, "original">): string {
|
||||
derivedKey(orgId: string, sha256: string, variant: "thumb" | "preview"): string {
|
||||
return `${orgId}/derived/${sha256.slice(0, 2)}/${sha256}.${variant}.jpg`;
|
||||
}
|
||||
|
||||
/** Thumb/preview of the edit at op-log position `seq`. */
|
||||
editedKey(orgId: string, sha256: string, seq: number, variant: "thumb" | "preview"): string {
|
||||
return `${orgId}/derived/${sha256.slice(0, 2)}/${sha256}.e${seq}.${variant}.jpg`;
|
||||
}
|
||||
|
||||
async remove(key: string): Promise<void> {
|
||||
await rm(this.resolve(key), { force: true });
|
||||
}
|
||||
|
||||
resolve(key: string): string {
|
||||
const full = path.resolve(this.root, key);
|
||||
if (!full.startsWith(this.root + path.sep)) throw new Error(`storage key escapes root: ${key}`);
|
||||
@@ -100,11 +110,14 @@ export class UrlSigner {
|
||||
return `/v1/files/persons/${personId}/reference?exp=${exp}&sig=${this.mac(personId, "reference", exp)}`;
|
||||
}
|
||||
|
||||
/** Expiry is rounded up to the next ttl/4 so URLs stay stable (and cacheable) for a while. */
|
||||
url(photoId: string, variant: Variant): string {
|
||||
/**
|
||||
* Expiry is rounded up to the next ttl/4 so URLs stay stable (and cacheable) for a while. `version` (the
|
||||
* rendered edit) is not signed: it only makes the URL change when the picture does.
|
||||
*/
|
||||
url(photoId: string, variant: Variant, version = 0): string {
|
||||
const step = Math.max(60, Math.floor(this.ttlSec / 4));
|
||||
const exp = Math.ceil((Math.floor(this.now() / 1000) + this.ttlSec) / step) * step;
|
||||
return `/v1/files/photos/${photoId}/${variant}?exp=${exp}&sig=${this.mac(photoId, variant, exp)}`;
|
||||
return `/v1/files/photos/${photoId}/${variant}?exp=${exp}&sig=${this.mac(photoId, variant, exp)}${version ? `&v=${version}` : ""}`;
|
||||
}
|
||||
|
||||
verify(photoId: string, variant: Variant | "reference", exp: number, sig: string): boolean {
|
||||
|
||||
+14
-1
@@ -4,6 +4,8 @@ import { createDb } from "./db.js";
|
||||
import { closeRenderer } from "./delivery/render.js";
|
||||
import { SecretBox } from "./delivery/secrets.js";
|
||||
import { DeliveryService, DeliveryWorker } from "./delivery/service.js";
|
||||
import { RenderPool, RenderProcess } from "./develop/engine.js";
|
||||
import { DevelopService, RenderWorker } from "./develop/service.js";
|
||||
import { FacePool, FaceProcess } from "./faces/process.js";
|
||||
import { FaceService, FaceWorker } from "./faces/service.js";
|
||||
import { IngestScanner } from "./ingest/scanner.js";
|
||||
@@ -33,7 +35,15 @@ const scanner = new IngestScanner(ingest, config.INGEST_ROOT, { intervalMs: conf
|
||||
|
||||
const secrets = config.DELIVERY_SECRET_KEY ? new SecretBox(config.DELIVERY_SECRET_KEY) : undefined;
|
||||
if (!secrets) log.warn("DELIVERY_SECRET_KEY is not set: deliveries will fail until it is");
|
||||
const deliveries = new DeliveryWorker(new DeliveryService({ db, storage, secrets, broadcaster, log }), {
|
||||
const signer = new UrlSigner(config.JWT_SECRET, config.FILE_URL_TTL_SEC);
|
||||
const renderEngine = config.RENDER_BIN
|
||||
? new RenderPool(Array.from({ length: config.RENDER_PROCESSES }, () => new RenderProcess({ bin: config.RENDER_BIN! })))
|
||||
: undefined;
|
||||
if (!renderEngine) log.warn("RENDER_BIN not set: edited photos get no new thumbnails and cannot be delivered");
|
||||
const develop = new DevelopService({ db, storage, signer, broadcaster, log, engine: renderEngine });
|
||||
const renders = renderEngine ? new RenderWorker(develop, { concurrency: config.RENDER_PROCESSES, intervalMs: 500, log }) : undefined;
|
||||
|
||||
const deliveries = new DeliveryWorker(new DeliveryService({ db, storage, secrets, broadcaster, log, develop }), {
|
||||
concurrency: config.DELIVERY_CONCURRENCY,
|
||||
intervalMs: 1000,
|
||||
log,
|
||||
@@ -53,6 +63,7 @@ if (!faces) log.warn("FACES_BIN/FACES_MODELS_DIR not set: face analysis is off i
|
||||
scanner.start();
|
||||
deliveries.start();
|
||||
faces?.start();
|
||||
renders?.start();
|
||||
log.info({ ingestRoot: config.INGEST_ROOT, storage: config.STORAGE_ROOT }, "worker started");
|
||||
|
||||
const shutdown = async (signal: string) => {
|
||||
@@ -60,7 +71,9 @@ const shutdown = async (signal: string) => {
|
||||
scanner.stop();
|
||||
deliveries.stop();
|
||||
faces?.stop();
|
||||
renders?.stop();
|
||||
await faceEngine?.close();
|
||||
await renderEngine?.close();
|
||||
await closeRenderer();
|
||||
await broadcaster.close();
|
||||
await db.$disconnect();
|
||||
|
||||
@@ -0,0 +1,160 @@
|
||||
import { copyFile, mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
import sharp from "sharp";
|
||||
import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest";
|
||||
import type { RenderEngine, RenderJob, Settings } from "../src/develop/engine.js";
|
||||
import { DevelopService, RENDER_QUIET_MS } from "../src/develop/service.js";
|
||||
import { IngestService } from "../src/ingest/service.js";
|
||||
import { MemoryBroadcaster } from "../src/realtime.js";
|
||||
import { LocalStorage, UrlSigner } from "../src/storage/storage.js";
|
||||
import { bearer, createTestApp, login, resetDb, seedUser, type TestContext } from "./helpers.js";
|
||||
|
||||
const quiet = { info: () => {}, warn: () => {} };
|
||||
|
||||
/** Stands in for workers/render: "settings" are the merged `develop.set` values; render copies the file. */
|
||||
class FakeEngine implements RenderEngine {
|
||||
renders: RenderJob[] = [];
|
||||
async replay(base: Settings | null, commands: unknown[]) {
|
||||
let s: Record<string, number> = { ...((base as Record<string, number> | null) ?? {}) };
|
||||
const skipped: number[] = [];
|
||||
commands.forEach((c, i) => {
|
||||
const cmd = c as { command: string; params?: { values?: Record<string, number> } };
|
||||
if (cmd.command === "develop.set") s = { ...s, ...cmd.params!.values };
|
||||
else if (cmd.command === "develop.reset") s = {};
|
||||
else skipped.push(i);
|
||||
});
|
||||
const unedited = Object.values(s).every((v) => v === 0);
|
||||
return { settings: s, skipped, unedited };
|
||||
}
|
||||
async render(job: RenderJob) {
|
||||
this.renders.push(job);
|
||||
await copyFile(job.input, job.output);
|
||||
return { width: 600, height: 400 };
|
||||
}
|
||||
async close() {}
|
||||
}
|
||||
|
||||
const set = (opId: string, values: Record<string, number>) => ({ opId, command: { command: "develop.set", params: { values } } });
|
||||
|
||||
describe("develop op log", () => {
|
||||
let ctx: TestContext;
|
||||
let dir: string;
|
||||
let ingestRoot: string;
|
||||
let ingest: IngestService;
|
||||
let develop: DevelopService;
|
||||
let engine: FakeEngine;
|
||||
const broadcaster = new MemoryBroadcaster();
|
||||
|
||||
beforeAll(async () => {
|
||||
dir = await mkdtemp(path.join(tmpdir(), "pr-develop-"));
|
||||
ingestRoot = path.join(dir, "ingest");
|
||||
ctx = await createTestApp({ STORAGE_ROOT: path.join(dir, "storage"), INGEST_ROOT: ingestRoot }, broadcaster);
|
||||
const storage = new LocalStorage(ctx.config.STORAGE_ROOT);
|
||||
const signer = new UrlSigner(ctx.config.JWT_SECRET, ctx.config.FILE_URL_TTL_SEC);
|
||||
engine = new FakeEngine();
|
||||
ingest = new IngestService({ db: ctx.db, storage, signer, broadcaster, ingestRoot, log: quiet });
|
||||
develop = new DevelopService({ db: ctx.db, storage, signer, broadcaster, log: quiet, engine });
|
||||
});
|
||||
afterAll(async () => {
|
||||
await ctx.app.close();
|
||||
await ctx.db.$disconnect();
|
||||
await rm(dir, { recursive: true, force: true });
|
||||
});
|
||||
beforeEach(async () => {
|
||||
await resetDb(ctx.db);
|
||||
broadcaster.sent.length = 0;
|
||||
engine.renders = [];
|
||||
});
|
||||
|
||||
let n = 0;
|
||||
async function setup() {
|
||||
const { org, user } = await seedUser(ctx.db, "[email protected]", { org: "fpa", role: "EDITOR" });
|
||||
await seedUser(ctx.db, "[email protected]", { org: "fpa", role: "PHOTOGRAPHER" });
|
||||
await ctx.db.ftpAccount.create({ data: { organizationId: org!.id, userId: user.id, login: "cam" } });
|
||||
const data = await sharp({ create: { width: 600, height: 400, channels: 3, background: { r: ++n, g: 90, b: 40 } } }).jpeg().toBuffer();
|
||||
const file = path.join(ingestRoot, "cam", `IMG_${n}.jpg`);
|
||||
await mkdir(path.dirname(file), { recursive: true });
|
||||
await writeFile(file, data);
|
||||
const out = await ingest.ingestFile(file);
|
||||
if (out.status !== "ingested") throw new Error(JSON.stringify(out));
|
||||
return {
|
||||
orgId: org!.id,
|
||||
photoId: out.photoId,
|
||||
editor: (await login(ctx.app, "[email protected]")).body.accessToken,
|
||||
photographer: (await login(ctx.app, "[email protected]")).body.accessToken,
|
||||
};
|
||||
}
|
||||
|
||||
const post = (token: string, photoId: string, ops: unknown[], clientId = "web-1") =>
|
||||
ctx.app.inject({ method: "POST", url: `/v1/photos/${photoId}/edits`, headers: bearer(token), payload: { clientId, ops } });
|
||||
|
||||
it("orders edits per photo, stores a retried op once, and fans them out", async () => {
|
||||
const { photoId, editor } = await setup();
|
||||
const first = await post(editor, photoId, [set("a", { "light.exposure": 0.5 }), set("b", { "effects.clarity": 20 })]);
|
||||
expect(first.statusCode).toBe(200);
|
||||
expect(first.json()).toMatchObject({ developSeq: 2, ops: [{ seq: 1, opId: "a" }, { seq: 2, opId: "b" }] });
|
||||
// The offline queue sends "b" again together with a new op.
|
||||
const retry = await post(editor, photoId, [set("b", { "effects.clarity": 20 }), set("c", { "light.exposure": 0.7 })]);
|
||||
expect(retry.json()).toMatchObject({ developSeq: 3, ops: [{ seq: 2, opId: "b" }, { seq: 3, opId: "c" }] });
|
||||
const edited = broadcaster.sent.filter((s) => s.message.type === "photo.edited").map((s) => s.message as { ops: { seq: number }[]; clientId: string });
|
||||
expect(edited.map((m) => m.ops.map((o) => o.seq))).toEqual([[1, 2], [3]]);
|
||||
expect(edited[0]!.clientId).toBe("web-1");
|
||||
|
||||
const state = (await ctx.app.inject({ method: "GET", url: `/v1/photos/${photoId}/develop`, headers: bearer(editor) })).json();
|
||||
expect(state).toMatchObject({ developSeq: 3, snapshotSeq: 0, snapshot: null });
|
||||
expect(state.ops).toHaveLength(3);
|
||||
const since = (await ctx.app.inject({ method: "GET", url: `/v1/photos/${photoId}/develop?since=2`, headers: bearer(editor) })).json();
|
||||
expect(since.ops.map((o: { seq: number }) => o.seq)).toEqual([3]);
|
||||
});
|
||||
|
||||
it("refuses controls the engine does not have, values out of range, and other photographers", async () => {
|
||||
const { photoId, editor, photographer } = await setup();
|
||||
expect((await post(editor, photoId, [set("x", { "light.nope": 1 })])).json()).toMatchObject({ error: "unknown_control" });
|
||||
expect((await post(editor, photoId, [set("x", { "light.exposure": 99 })])).json()).toMatchObject({ error: "value_out_of_range" });
|
||||
expect((await post(photographer, photoId, [set("x", { "light.exposure": 1 })])).statusCode).toBe(403);
|
||||
expect((await ctx.db.photo.findUniqueOrThrow({ where: { id: photoId } })).developSeq).toBe(0);
|
||||
});
|
||||
|
||||
it("renders edited thumbnails once edits pause, and keeps the unedited source for the editor", async () => {
|
||||
const { photoId, editor } = await setup();
|
||||
await post(editor, photoId, [set("a", { "light.exposure": 0.5 })]);
|
||||
expect(await develop.claimRenders(5)).toEqual([]); // still editing
|
||||
const later = new Date(Date.now() + RENDER_QUIET_MS + 100);
|
||||
const [claimed] = await develop.claimRenders(5, later);
|
||||
expect(claimed).toBe(photoId);
|
||||
await develop.render(photoId);
|
||||
|
||||
const photo = await ctx.db.photo.findUniqueOrThrow({ where: { id: photoId } });
|
||||
expect(photo).toMatchObject({ renderedSeq: 1, snapshotSeq: 1, renderStatus: "DONE", developSnapshot: { "light.exposure": 0.5 } });
|
||||
expect(engine.renders.map((r) => [r.maxEdge, r.settings])).toEqual([
|
||||
[2048, { "light.exposure": 0.5 }],
|
||||
[480, { "light.exposure": 0.5 }],
|
||||
]);
|
||||
const rendered = broadcaster.sent.find((s) => s.message.type === "photo.rendered")!.message as { urls: { thumb: string } };
|
||||
expect(rendered.urls.thumb).toContain("&v=1");
|
||||
expect((await ctx.app.inject({ method: "GET", url: rendered.urls.thumb })).statusCode).toBe(200);
|
||||
|
||||
const list = (await ctx.app.inject({ method: "GET", url: `/v1/orgs/${photo.organizationId}/photos`, headers: bearer(editor) })).json() as {
|
||||
photos: { developSeq: number; urls: { thumb: string; source: string } }[];
|
||||
};
|
||||
expect(list.photos[0]).toMatchObject({ developSeq: 1 });
|
||||
expect(list.photos[0]!.urls.thumb).toContain("&v=1");
|
||||
expect((await ctx.app.inject({ method: "GET", url: list.photos[0]!.urls.source })).statusCode).toBe(200);
|
||||
|
||||
// State now starts from the snapshot.
|
||||
const state = (await ctx.app.inject({ method: "GET", url: `/v1/photos/${photoId}/develop`, headers: bearer(editor) })).json();
|
||||
expect(state).toMatchObject({ developSeq: 1, snapshotSeq: 1, snapshot: { "light.exposure": 0.5 }, ops: [] });
|
||||
});
|
||||
|
||||
it("goes back to the original thumbnails after a reset", async () => {
|
||||
const { photoId, editor } = await setup();
|
||||
await post(editor, photoId, [set("a", { "light.exposure": 0.5 })]);
|
||||
await develop.render(photoId);
|
||||
await post(editor, photoId, [{ opId: "r", command: { command: "develop.reset" } }]);
|
||||
await develop.render(photoId);
|
||||
const photo = await ctx.db.photo.findUniqueOrThrow({ where: { id: photoId } });
|
||||
expect(photo).toMatchObject({ renderedSeq: 0, snapshotSeq: 2, developSnapshot: null });
|
||||
expect(await develop.settings(photoId)).toEqual({ settings: null, seq: 2 });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,53 @@
|
||||
import { mkdtemp, rm, writeFile } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
import exifr from "exifr";
|
||||
import sharp from "sharp";
|
||||
import { afterAll, describe, expect, it } from "vitest";
|
||||
import { RenderProcess } from "../src/develop/engine.js";
|
||||
import { closeRenderer, renderDelivery } from "../src/delivery/render.js";
|
||||
|
||||
const BIN = process.env.RENDER_TEST_BIN;
|
||||
|
||||
/** Runs the real Rust render worker (`cargo build --release -p photoreport-render`; RENDER_TEST_BIN=target/release/photoreport-render). */
|
||||
describe.skipIf(!BIN)("render worker (real binary)", () => {
|
||||
const engine = new RenderProcess({ bin: BIN ?? "" });
|
||||
afterAll(async () => {
|
||||
await engine.close();
|
||||
await closeRenderer();
|
||||
});
|
||||
|
||||
it("replays commands, and delivers an edited photo upright with its EXIF and our IPTC", async () => {
|
||||
const replayed = await engine.replay(null, [
|
||||
{ command: "develop.set", params: { values: { "light.exposure": 1 } } },
|
||||
{ command: "develop.set", params: { values: { "light.nope": 1 } } },
|
||||
{ command: "crop.set", params: { rect: { x0: 0, y0: 0, x1: 0.5, y1: 1 }, angle: 0, aspect: null } },
|
||||
]);
|
||||
expect(replayed.skipped).toEqual([1]);
|
||||
expect(replayed.unedited).toBe(false);
|
||||
|
||||
const dir = await mkdtemp(path.join(tmpdir(), "pr-render-real-"));
|
||||
try {
|
||||
// 600x400 stored, EXIF orientation 6 (rotate 90°): upright it is 400x600.
|
||||
const original = path.join(dir, "in.jpg");
|
||||
const pixels = await sharp({ create: { width: 600, height: 400, channels: 3, background: { r: 60, g: 60, b: 60 } } })
|
||||
.jpeg()
|
||||
.withMetadata({ orientation: 6 })
|
||||
.withExifMerge({ IFD0: { Make: "Canon", Model: "Canon EOS R1" } })
|
||||
.toBuffer();
|
||||
await writeFile(original, pixels);
|
||||
const out = await renderDelivery(original, { title: "Rui Costa (ABC)" }, { longEdge: 4000, quality: 95 }, undefined, { engine, settings: replayed.settings });
|
||||
const meta = await sharp(out).metadata();
|
||||
// Upright 400x600, cropped to the left half: 200x600.
|
||||
expect([meta.width, meta.height]).toEqual([200, 600]);
|
||||
const tags = await exifr.parse(out, { iptc: true, xmp: true });
|
||||
expect(tags.Orientation === undefined || tags.Orientation === 1 || tags.Orientation === "Horizontal (normal)").toBe(true);
|
||||
expect(tags.Model).toBe("Canon EOS R1");
|
||||
expect(tags.ObjectName ?? tags.title?.value ?? tags.title).toContain("Rui Costa");
|
||||
const { channels } = await sharp(out).stats();
|
||||
expect(channels[0]!.mean).toBeGreaterThan(75); // +1 EV brightened the grey (60 before)
|
||||
} finally {
|
||||
await rm(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -2,6 +2,7 @@ import type { ApiClient } from "@photoreport/sdk";
|
||||
import { BrowserRouter, Navigate, Route, Routes, useLocation } from "react-router";
|
||||
import { AuthProvider, useAuth } from "./auth.js";
|
||||
import { t } from "./i18n.js";
|
||||
import { DevelopPage } from "./pages/DevelopPage.js";
|
||||
import { DeliveryPage } from "./pages/DeliveryPage.js";
|
||||
import { DevicePage } from "./pages/DevicePage.js";
|
||||
import { LibraryPage } from "./pages/LibraryPage.js";
|
||||
@@ -22,6 +23,7 @@ function Gate() {
|
||||
<Route path="/device" element={<DevicePage />} />
|
||||
<Route element={<Shell />}>
|
||||
<Route index element={<LibraryPage />} />
|
||||
<Route path="develop/:photoId?" element={<DevelopPage />} />
|
||||
<Route path="metadata" element={<MetadataPage />} />
|
||||
<Route path="delivery" element={<DeliveryPage />} />
|
||||
<Route path="members" element={<MembersPage />} />
|
||||
|
||||
@@ -0,0 +1,138 @@
|
||||
import { CONTROLS, type ControlInfo, type Module, getControl } from "@photoreport/contracts";
|
||||
import { useState } from "react";
|
||||
import { t } from "../i18n.js";
|
||||
|
||||
const BASIC_GROUPS: { key: keyof typeof t.dev.groups; ids: string[] }[] = [
|
||||
{ key: "wb", ids: ["wb.temp", "wb.tint"] },
|
||||
{ key: "tone", ids: ["light.exposure", "light.contrast", "light.highlights", "light.shadows", "light.whites", "light.blacks"] },
|
||||
{ key: "presence", ids: ["effects.texture", "effects.clarity", "effects.dehaze", "color.vibrance", "color.saturation"] },
|
||||
{ key: "profile", ids: ["profile.amount"] },
|
||||
];
|
||||
|
||||
export function formatValue(c: ControlInfo, v: number): string {
|
||||
if (!Number.isFinite(v)) return "—";
|
||||
if (c.id === "wb.temp") return `${Math.round(v)} K`;
|
||||
const decimals = c.step < 0.1 ? 2 : c.step < 1 ? 1 : 0;
|
||||
const s = v.toFixed(decimals);
|
||||
return c.min < 0 && v > 0 ? `+${s}` : s;
|
||||
}
|
||||
|
||||
/** Where the track's fill starts: the default (zero for most controls), like Lightroom's centred sliders. */
|
||||
function fill(c: ControlInfo, v: number) {
|
||||
const at = (x: number) => ((x - c.min) / (c.max - c.min)) * 100;
|
||||
const a = at(Math.min(Math.max(c.default, c.min), c.max));
|
||||
const b = at(Math.min(Math.max(v, c.min), c.max));
|
||||
return { left: `${Math.min(a, b)}%`, width: `${Math.abs(b - a)}%` };
|
||||
}
|
||||
|
||||
export function Slider(props: {
|
||||
control: ControlInfo;
|
||||
value: number;
|
||||
disabled?: boolean;
|
||||
onChange: (id: string, value: number) => void;
|
||||
onEnd: () => void;
|
||||
}) {
|
||||
const { control: c, value: v } = props;
|
||||
const label = t.dev.labels[c.id] ?? c.label;
|
||||
const reset = () => {
|
||||
props.onChange(c.id, c.default);
|
||||
props.onEnd();
|
||||
};
|
||||
// Temperature spans 2000-50000 K: a log scale puts daylight in the middle of the track, as photographers expect.
|
||||
const log = c.id === "wb.temp";
|
||||
const toTrack = (x: number) => (log ? Math.log(x) : x);
|
||||
const fromTrack = (x: number) => (log ? Math.round(Math.exp(x) / c.step) * c.step : x);
|
||||
return (
|
||||
<div className="group grid grid-cols-[92px_1fr_56px] items-center gap-2 py-[3px]">
|
||||
<label htmlFor={`ctl-${c.id}`} className="truncate text-[12px] text-muted" onDoubleClick={reset} title={label}>
|
||||
{label}
|
||||
</label>
|
||||
<span className="relative flex h-4 items-center">
|
||||
<span aria-hidden="true" className="absolute inset-x-0 h-[3px] bg-[#151516]" />
|
||||
{!log && <span aria-hidden="true" className="absolute h-[3px] bg-[#7a7a7c]" style={fill(c, v)} />}
|
||||
<input
|
||||
id={`ctl-${c.id}`}
|
||||
type="range"
|
||||
className="pr-range relative w-full"
|
||||
min={toTrack(c.min)}
|
||||
max={toTrack(c.max)}
|
||||
step={log ? 0.001 : c.step}
|
||||
value={Number.isFinite(v) ? toTrack(v) : toTrack(c.default)}
|
||||
disabled={props.disabled}
|
||||
onChange={(e) => props.onChange(c.id, fromTrack(Number(e.target.value)))}
|
||||
onPointerUp={props.onEnd}
|
||||
onKeyUp={props.onEnd}
|
||||
onBlur={props.onEnd}
|
||||
onDoubleClick={reset}
|
||||
/>
|
||||
</span>
|
||||
<output htmlFor={`ctl-${c.id}`} className="text-right font-mono text-[11px] text-ink" onDoubleClick={reset}>
|
||||
{formatValue(c, v)}
|
||||
</output>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function Section({ title, children, open: initial = true, onReset }: { title: string; children: React.ReactNode; open?: boolean; onReset?: () => void }) {
|
||||
const [open, setOpen] = useState(initial);
|
||||
return (
|
||||
<section className="border-b border-line">
|
||||
<div className="panel-head">
|
||||
<button type="button" className="flex flex-1 items-center gap-2 text-left" aria-expanded={open} onClick={() => setOpen(!open)}>
|
||||
<span aria-hidden="true" className="text-[9px]">
|
||||
{open ? "▼" : "▶"}
|
||||
</span>
|
||||
{title}
|
||||
</button>
|
||||
{onReset && (
|
||||
<button type="button" className="normal-case tracking-normal text-faint hover:text-ink" onClick={onReset}>
|
||||
{t.dev.reset}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
{open && <div className="px-3 py-2">{children}</div>}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
/** Basic plus whichever extra modules the user switched on in their preferences (synced across devices). */
|
||||
export function DevelopPanels(props: {
|
||||
modules: readonly Module[];
|
||||
value: (id: string) => number;
|
||||
disabled?: boolean;
|
||||
onChange: (id: string, value: number) => void;
|
||||
onEnd: () => void;
|
||||
onSet: (values: Record<string, number>) => void;
|
||||
}) {
|
||||
const slider = (id: string) => {
|
||||
const c = getControl(id);
|
||||
return c ? <Slider key={id} control={c} value={props.value(id)} {...(props.disabled !== undefined && { disabled: props.disabled })} onChange={props.onChange} onEnd={props.onEnd} /> : null;
|
||||
};
|
||||
const resetIds = (ids: string[]) => props.onSet(Object.fromEntries(ids.map((id) => [id, getControl(id)?.default ?? 0])));
|
||||
const extra = props.modules.filter((m) => m !== "crop" && m !== "basic");
|
||||
return (
|
||||
<>
|
||||
{props.modules.includes("basic") && (
|
||||
<Section title={t.modules.basic} onReset={() => resetIds(BASIC_GROUPS.flatMap((g) => g.ids))}>
|
||||
{BASIC_GROUPS.map((g) => (
|
||||
<div key={g.key} className="mb-2">
|
||||
<p className="mb-1 mt-1 text-[10px] uppercase tracking-[0.08em] text-faint">{t.dev.groups[g.key]}</p>
|
||||
{g.ids.map(slider)}
|
||||
</div>
|
||||
))}
|
||||
</Section>
|
||||
)}
|
||||
{extra.map((m) => {
|
||||
const ids = CONTROLS.filter((c) => c.module === m).map((c) => c.id);
|
||||
if (!ids.length) return null;
|
||||
return (
|
||||
<Section key={m} title={t.modules[m]} open={false} onReset={() => resetIds(ids)}>
|
||||
{ids.map(slider)}
|
||||
</Section>
|
||||
);
|
||||
})}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export { Section };
|
||||
@@ -0,0 +1,262 @@
|
||||
import { useCallback, useEffect, useLayoutEffect, useRef, useState } from "react";
|
||||
import type { WorkerReply, WorkerRequest } from "./engine.js";
|
||||
import type { Crop } from "./session.js";
|
||||
|
||||
type Rect = Crop["rect"];
|
||||
|
||||
/** One render worker for the page; created lazily (absent in tests and very old browsers). */
|
||||
let shared: Worker | undefined;
|
||||
function renderWorker(): Worker | undefined {
|
||||
if (typeof Worker === "undefined") return undefined;
|
||||
shared ??= new Worker(new URL("./render.worker.ts", import.meta.url), { type: "module" });
|
||||
return shared;
|
||||
}
|
||||
|
||||
interface ViewerProps {
|
||||
photoKey: string;
|
||||
sourceUrl: string;
|
||||
settings: string;
|
||||
/** While a slider or the crop frame is moving: fast draft renders, then one full render when it stops. */
|
||||
dragging: boolean;
|
||||
cropping: boolean;
|
||||
crop: Crop;
|
||||
/** Width/height of the photo as shot (oriented), for aspect-locked crops. */
|
||||
onSourceSize?: (w: number, h: number) => void;
|
||||
onCrop?: (rect: Rect, final: boolean) => void;
|
||||
onError?: (message: string) => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* The develop loupe: the photo rendered by the engine in a worker, at the size it is shown (device pixels),
|
||||
* with the crop frame on top while cropping. Renders never queue up: one in flight, the latest settings next.
|
||||
*/
|
||||
export function Viewer(props: ViewerProps) {
|
||||
const { photoKey, sourceUrl, settings, dragging, cropping } = props;
|
||||
const box = useRef<HTMLDivElement>(null);
|
||||
const canvas = useRef<HTMLCanvasElement>(null);
|
||||
const [size, setSize] = useState({ w: 0, h: 0 });
|
||||
const [opened, setOpened] = useState<string | null>(null);
|
||||
const [frame, setFrame] = useState<{ w: number; h: number } | null>(null);
|
||||
const inFlight = useRef(false);
|
||||
const next = useRef<WorkerRequest | null>(null);
|
||||
const ticket = useRef(0);
|
||||
const settle = useRef<ReturnType<typeof setTimeout>>(undefined);
|
||||
const callbacks = useRef(props);
|
||||
callbacks.current = props;
|
||||
|
||||
useLayoutEffect(() => {
|
||||
const el = box.current;
|
||||
if (!el) return;
|
||||
const ro = new ResizeObserver(([entry]) => {
|
||||
const r = entry!.contentRect;
|
||||
setSize({ w: Math.round(r.width), h: Math.round(r.height) });
|
||||
});
|
||||
ro.observe(el);
|
||||
return () => ro.disconnect();
|
||||
}, []);
|
||||
|
||||
const send = useCallback((req: WorkerRequest) => {
|
||||
const w = renderWorker();
|
||||
if (!w) return;
|
||||
if (inFlight.current) {
|
||||
next.current = req;
|
||||
return;
|
||||
}
|
||||
inFlight.current = true;
|
||||
w.postMessage(req);
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
const w = renderWorker();
|
||||
if (!w) return;
|
||||
const onMessage = (e: MessageEvent<WorkerReply>) => {
|
||||
const msg = e.data;
|
||||
if (msg.type === "opened") {
|
||||
if (msg.key === photoKey) {
|
||||
setOpened(msg.key);
|
||||
callbacks.current.onSourceSize?.(msg.sourceWidth, msg.sourceHeight);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (msg.type === "error") {
|
||||
inFlight.current = false;
|
||||
callbacks.current.onError?.(msg.message);
|
||||
return;
|
||||
}
|
||||
inFlight.current = false;
|
||||
const queued = next.current;
|
||||
next.current = null;
|
||||
if (queued) send(queued);
|
||||
if (msg.key !== photoKey || !canvas.current) return;
|
||||
const c = canvas.current;
|
||||
if (c.width !== msg.width || c.height !== msg.height) {
|
||||
c.width = msg.width;
|
||||
c.height = msg.height;
|
||||
}
|
||||
c.getContext("2d")?.putImageData(new ImageData(msg.pixels as Uint8ClampedArray<ArrayBuffer>, msg.width, msg.height), 0, 0);
|
||||
setFrame({ w: msg.width, h: msg.height });
|
||||
};
|
||||
w.addEventListener("message", onMessage);
|
||||
setOpened(null);
|
||||
setFrame(null);
|
||||
w.postMessage({ type: "open", key: photoKey, url: sourceUrl } satisfies WorkerRequest);
|
||||
return () => w.removeEventListener("message", onMessage);
|
||||
}, [photoKey, sourceUrl, send]);
|
||||
|
||||
useEffect(() => {
|
||||
if (opened !== photoKey || !size.w || !size.h) return;
|
||||
const dpr = Math.min(window.devicePixelRatio || 1, 2);
|
||||
const full = { maxW: Math.min(2048, Math.round(size.w * dpr)), maxH: Math.min(2048, Math.round(size.h * dpr)) };
|
||||
const request = (draft: boolean): WorkerRequest => ({
|
||||
type: "render",
|
||||
ticket: ++ticket.current,
|
||||
key: photoKey,
|
||||
settings,
|
||||
// Drafts at about half the pixels keep a drag at screen rate on modest laptops.
|
||||
maxW: draft ? Math.round(full.maxW * 0.6) : full.maxW,
|
||||
maxH: draft ? Math.round(full.maxH * 0.6) : full.maxH,
|
||||
draft,
|
||||
applyCrop: !cropping,
|
||||
});
|
||||
clearTimeout(settle.current);
|
||||
if (dragging) {
|
||||
send(request(true));
|
||||
settle.current = setTimeout(() => send(request(false)), 250);
|
||||
} else send(request(false));
|
||||
return () => clearTimeout(settle.current);
|
||||
}, [opened, photoKey, settings, size.w, size.h, dragging, cropping, send]);
|
||||
|
||||
return (
|
||||
<div ref={box} className="relative flex h-full w-full items-center justify-center overflow-hidden">
|
||||
<div className="relative" style={frame ? fitStyle(frame, size) : { display: "none" }}>
|
||||
<canvas ref={canvas} className="block h-full w-full shadow-[0_2px_12px_rgba(0,0,0,0.7)]" aria-label="Foto em revelação" />
|
||||
{cropping && frame && <CropFrame crop={props.crop} onCrop={(r, f) => callbacks.current.onCrop?.(r, f)} />}
|
||||
</div>
|
||||
{!frame && <p className="font-mono text-[11px] text-faint">…</p>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function fitStyle(frame: { w: number; h: number }, box: { w: number; h: number }) {
|
||||
const pad = 24;
|
||||
const s = Math.min((box.w - pad * 2) / frame.w, (box.h - pad * 2) / frame.h);
|
||||
return { width: Math.max(1, Math.floor(frame.w * s)), height: Math.max(1, Math.floor(frame.h * s)) };
|
||||
}
|
||||
|
||||
type Handle = "move" | "nw" | "ne" | "sw" | "se" | "n" | "s" | "e" | "w";
|
||||
|
||||
/** Crop rectangle over the whole (uncropped) frame: drag inside to move, corners and edges to resize. */
|
||||
function CropFrame({ crop, onCrop }: { crop: Crop; onCrop: (rect: Rect, final: boolean) => void }) {
|
||||
const el = useRef<HTMLDivElement>(null);
|
||||
const drag = useRef<{ handle: Handle; x: number; y: number; start: Rect } | null>(null);
|
||||
const r = crop.rect;
|
||||
|
||||
const onDown = (handle: Handle) => (e: React.PointerEvent) => {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
(e.target as Element).setPointerCapture(e.pointerId);
|
||||
drag.current = { handle, x: e.clientX, y: e.clientY, start: { ...r } };
|
||||
};
|
||||
const onMove = (e: React.PointerEvent) => {
|
||||
const d = drag.current;
|
||||
const box = el.current?.getBoundingClientRect();
|
||||
if (!d || !box) return;
|
||||
onCrop(moveRect(d.start, d.handle, (e.clientX - d.x) / box.width, (e.clientY - d.y) / box.height, crop.aspect ? (crop.aspect[0] / crop.aspect[1]) * (box.height / box.width) : null), false);
|
||||
};
|
||||
const onUp = (e: React.PointerEvent) => {
|
||||
if (!drag.current) return;
|
||||
drag.current = null;
|
||||
(e.target as Element).releasePointerCapture?.(e.pointerId);
|
||||
onCrop(r, true);
|
||||
};
|
||||
|
||||
const pct = (v: number) => `${v * 100}%`;
|
||||
const corner = "absolute h-3 w-3 border-2 border-white bg-black/40";
|
||||
return (
|
||||
<div ref={el} className="absolute inset-0 touch-none select-none" onPointerMove={onMove} onPointerUp={onUp} onPointerCancel={onUp}>
|
||||
{/* Shade outside the crop. */}
|
||||
<div className="pointer-events-none absolute bg-black/55" style={{ left: 0, top: 0, right: 0, height: pct(r.y0) }} />
|
||||
<div className="pointer-events-none absolute bg-black/55" style={{ left: 0, bottom: 0, right: 0, height: pct(1 - r.y1) }} />
|
||||
<div className="pointer-events-none absolute bg-black/55" style={{ left: 0, top: pct(r.y0), width: pct(r.x0), height: pct(r.y1 - r.y0) }} />
|
||||
<div className="pointer-events-none absolute bg-black/55" style={{ right: 0, top: pct(r.y0), width: pct(1 - r.x1), height: pct(r.y1 - r.y0) }} />
|
||||
<div
|
||||
role="group"
|
||||
aria-label="Área de recorte"
|
||||
className="absolute cursor-move border border-white/90"
|
||||
style={{ left: pct(r.x0), top: pct(r.y0), width: pct(r.x1 - r.x0), height: pct(r.y1 - r.y0) }}
|
||||
onPointerDown={onDown("move")}
|
||||
>
|
||||
{/* Rule of thirds. */}
|
||||
<div className="pointer-events-none absolute inset-0 grid grid-cols-3 grid-rows-3">
|
||||
{Array.from({ length: 9 }, (_, i) => (
|
||||
<span key={i} className="border-[0.5px] border-white/25" />
|
||||
))}
|
||||
</div>
|
||||
<span className={`${corner} -left-1.5 -top-1.5 cursor-nwse-resize`} onPointerDown={onDown("nw")} />
|
||||
<span className={`${corner} -right-1.5 -top-1.5 cursor-nesw-resize`} onPointerDown={onDown("ne")} />
|
||||
<span className={`${corner} -bottom-1.5 -left-1.5 cursor-nesw-resize`} onPointerDown={onDown("sw")} />
|
||||
<span className={`${corner} -bottom-1.5 -right-1.5 cursor-nwse-resize`} onPointerDown={onDown("se")} />
|
||||
{!crop.aspect && (
|
||||
<>
|
||||
<span className="absolute -top-1 left-1/2 h-2 w-6 -translate-x-1/2 cursor-ns-resize bg-white/80" onPointerDown={onDown("n")} />
|
||||
<span className="absolute -bottom-1 left-1/2 h-2 w-6 -translate-x-1/2 cursor-ns-resize bg-white/80" onPointerDown={onDown("s")} />
|
||||
<span className="absolute -left-1 top-1/2 h-6 w-2 -translate-y-1/2 cursor-ew-resize bg-white/80" onPointerDown={onDown("w")} />
|
||||
<span className="absolute -right-1 top-1/2 h-6 w-2 -translate-y-1/2 cursor-ew-resize bg-white/80" onPointerDown={onDown("e")} />
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const MIN = 0.04;
|
||||
const clamp01 = (v: number) => Math.min(1, Math.max(0, v));
|
||||
|
||||
/**
|
||||
* The crop after dragging `handle` by (dx, dy) (fractions of the frame). `ratio` is the locked width/height in
|
||||
* frame fractions (null: free). Exported for tests.
|
||||
*/
|
||||
export function moveRect(start: Rect, handle: Handle, dx: number, dy: number, ratio: number | null): Rect {
|
||||
let { x0, y0, x1, y1 } = start;
|
||||
if (handle === "move") {
|
||||
const w = x1 - x0;
|
||||
const h = y1 - y0;
|
||||
x0 = Math.min(1 - w, Math.max(0, x0 + dx));
|
||||
y0 = Math.min(1 - h, Math.max(0, y0 + dy));
|
||||
return { x0, y0, x1: x0 + w, y1: y0 + h };
|
||||
}
|
||||
if (handle.includes("w")) x0 = Math.min(x1 - MIN, clamp01(x0 + dx));
|
||||
if (handle.includes("e")) x1 = Math.max(x0 + MIN, clamp01(x1 + dx));
|
||||
if (handle.includes("n")) y0 = Math.min(y1 - MIN, clamp01(y0 + dy));
|
||||
if (handle.includes("s")) y1 = Math.max(y0 + MIN, clamp01(y1 + dy));
|
||||
if (ratio && handle.length === 2) {
|
||||
// Keep the aspect: the height follows the width, anchored at the opposite corner, shrinking if it would leave the frame.
|
||||
let w = x1 - x0;
|
||||
let h = w / ratio;
|
||||
const room = handle.includes("n") ? y1 : 1 - y0;
|
||||
if (h > room) {
|
||||
h = room;
|
||||
w = h * ratio;
|
||||
if (handle.includes("w")) x0 = x1 - w;
|
||||
else x1 = x0 + w;
|
||||
}
|
||||
if (handle.includes("n")) y0 = y1 - h;
|
||||
else y1 = y0 + h;
|
||||
}
|
||||
return { x0, y0, x1, y1 };
|
||||
}
|
||||
|
||||
/** The largest rect of `ratio` (width/height in frame fractions) centred on `r`, inside the frame. */
|
||||
export function fitAspect(r: Rect, ratio: number): Rect {
|
||||
const cx = (r.x0 + r.x1) / 2;
|
||||
const cy = (r.y0 + r.y1) / 2;
|
||||
let w = r.x1 - r.x0;
|
||||
let h = w / ratio;
|
||||
if (h > r.y1 - r.y0) {
|
||||
h = r.y1 - r.y0;
|
||||
w = h * ratio;
|
||||
}
|
||||
const x0 = Math.min(1 - w, Math.max(0, cx - w / 2));
|
||||
const y0 = Math.min(1 - h, Math.max(0, cy - h / 2));
|
||||
return { x0, y0, x1: x0 + w, y1: y0 + h };
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
/**
|
||||
* The develop engine in the browser: `engine/wasm` built by `infra/engine/build-wasm.sh` into `public/engine/`.
|
||||
* It is loaded at run time (not bundled), so the app builds and type-checks without the Rust toolchain.
|
||||
*/
|
||||
export interface WasmPhoto {
|
||||
readonly sourceWidth: number;
|
||||
readonly sourceHeight: number;
|
||||
readonly width: number;
|
||||
readonly height: number;
|
||||
render(settings: string, maxW: number, maxH: number, draft: boolean, applyCrop: boolean): void;
|
||||
pixels(): Uint8Array;
|
||||
free(): void;
|
||||
}
|
||||
|
||||
export interface EngineModule {
|
||||
default(init?: { module_or_path: string }): Promise<unknown>;
|
||||
controls(): string;
|
||||
defaultSettings(): string;
|
||||
apply(settings: string, command: string): string;
|
||||
value(settings: string, id: string): number;
|
||||
isUnedited(settings: string): boolean;
|
||||
Photo: new (bytes: Uint8Array, maxEdge: number) => WasmPhoto;
|
||||
}
|
||||
|
||||
const BASE = `${import.meta.env.BASE_URL ?? "/"}engine/`;
|
||||
|
||||
let loading: Promise<EngineModule> | undefined;
|
||||
|
||||
export function loadEngine(): Promise<EngineModule> {
|
||||
loading ??= (async () => {
|
||||
const mod = (await import(/* @vite-ignore */ `${BASE}photoreport_engine_wasm.js`)) as EngineModule;
|
||||
await mod.default({ module_or_path: `${BASE}photoreport_engine_wasm_bg.wasm` });
|
||||
return mod;
|
||||
})();
|
||||
loading.catch(() => {
|
||||
loading = undefined;
|
||||
});
|
||||
return loading;
|
||||
}
|
||||
|
||||
/** Messages to and from `render.worker.ts`. */
|
||||
export type WorkerRequest =
|
||||
| { type: "open"; key: string; url: string }
|
||||
| { type: "render"; ticket: number; key: string; settings: string; maxW: number; maxH: number; draft: boolean; applyCrop: boolean };
|
||||
|
||||
export type WorkerReply =
|
||||
| { type: "opened"; key: string; sourceWidth: number; sourceHeight: number }
|
||||
| { type: "frame"; ticket: number; key: string; width: number; height: number; pixels: Uint8ClampedArray }
|
||||
| { type: "error"; key: string; ticket?: number; message: string };
|
||||
@@ -0,0 +1,47 @@
|
||||
/// <reference lib="webworker" />
|
||||
import { loadEngine, type WasmPhoto, type WorkerReply, type WorkerRequest } from "./engine.js";
|
||||
|
||||
/**
|
||||
* Decodes and renders off the main thread. Holds one photo (the one being edited); the page sends settings and
|
||||
* gets pixels back. Requests are handled in order; the page keeps at most one render in flight.
|
||||
*/
|
||||
let current: { key: string; photo: WasmPhoto } | undefined;
|
||||
const opening = new Map<string, Promise<WasmPhoto>>();
|
||||
|
||||
const post = (msg: WorkerReply, transfer: Transferable[] = []) => (self as unknown as DedicatedWorkerGlobalScope).postMessage(msg, transfer);
|
||||
|
||||
async function open(key: string, url: string): Promise<WasmPhoto> {
|
||||
if (current?.key === key) return current.photo;
|
||||
let p = opening.get(key);
|
||||
if (!p) {
|
||||
p = (async () => {
|
||||
const [engine, res] = await Promise.all([loadEngine(), fetch(url)]);
|
||||
if (!res.ok) throw new Error(`photo download failed (${res.status})`);
|
||||
const photo = new engine.Photo(new Uint8Array(await res.arrayBuffer()), 2048);
|
||||
current?.photo.free();
|
||||
current = { key, photo };
|
||||
return photo;
|
||||
})();
|
||||
opening.set(key, p);
|
||||
p.finally(() => opening.delete(key)).catch(() => {});
|
||||
}
|
||||
return p;
|
||||
}
|
||||
|
||||
self.onmessage = async (e: MessageEvent<WorkerRequest>) => {
|
||||
const msg = e.data;
|
||||
try {
|
||||
if (msg.type === "open") {
|
||||
const photo = await open(msg.key, msg.url);
|
||||
post({ type: "opened", key: msg.key, sourceWidth: photo.sourceWidth, sourceHeight: photo.sourceHeight });
|
||||
return;
|
||||
}
|
||||
const photo = current?.key === msg.key ? current.photo : await opening.get(msg.key);
|
||||
if (!photo) throw new Error("photo not open");
|
||||
photo.render(msg.settings, msg.maxW, msg.maxH, msg.draft, msg.applyCrop);
|
||||
const pixels = new Uint8ClampedArray(photo.pixels().buffer);
|
||||
post({ type: "frame", ticket: msg.ticket, key: msg.key, width: photo.width, height: photo.height, pixels }, [pixels.buffer]);
|
||||
} catch (err) {
|
||||
post({ type: "error", key: msg.key, ...(msg.type === "render" && { ticket: msg.ticket }), message: err instanceof Error ? err.message : String(err) });
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,135 @@
|
||||
import type { DevelopState, EditCommand, EditLogEntry, PostEdits } from "@photoreport/contracts";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { DevelopSession, type OutboxStore, type PendingOp, type SettingsEngine } from "./session.js";
|
||||
|
||||
/** Settings as a flat map of control values; enough to check ordering, undo and sync. */
|
||||
const engine: SettingsEngine = {
|
||||
defaultSettings: () => "{}",
|
||||
apply(settings, command) {
|
||||
const s = JSON.parse(settings) as Record<string, unknown>;
|
||||
const c = JSON.parse(command) as EditCommand;
|
||||
if (c.command === "develop.set") return JSON.stringify({ ...s, ...c.params.values });
|
||||
if (c.command === "develop.reset") return "{}";
|
||||
if (c.command === "develop.merge") return JSON.stringify(c.params.partial);
|
||||
return JSON.stringify({ ...s, crop: c.params });
|
||||
},
|
||||
value: (settings, id) => ((JSON.parse(settings) as Record<string, number>)[id] ?? 0),
|
||||
};
|
||||
|
||||
/** An in-memory server: one op log, every accepted op fanned out to the other sessions. */
|
||||
class FakeServer {
|
||||
log: EditLogEntry[] = [];
|
||||
down = false;
|
||||
sessions: DevelopSession[] = [];
|
||||
async developState(_photoId: string, since?: number): Promise<DevelopState> {
|
||||
const from = since ?? 0;
|
||||
return { photoId: "p", developSeq: this.log.length, snapshotSeq: from, snapshot: null, ops: this.log.filter((o) => o.seq > from) };
|
||||
}
|
||||
async postEdits(_photoId: string, body: PostEdits) {
|
||||
if (this.down) throw Object.assign(new Error("offline"), { status: 0 });
|
||||
const out: EditLogEntry[] = [];
|
||||
const fresh: EditLogEntry[] = [];
|
||||
for (const op of body.ops) {
|
||||
const known = this.log.find((o) => o.opId === op.opId);
|
||||
if (known) {
|
||||
out.push(known);
|
||||
continue;
|
||||
}
|
||||
const entry = { seq: this.log.length + 1, opId: op.opId, clientId: body.clientId, command: op.command, userId: null, at: "" };
|
||||
this.log.push(entry);
|
||||
out.push(entry);
|
||||
fresh.push(entry);
|
||||
}
|
||||
for (const s of this.sessions) void s.remote({ clientId: body.clientId, ops: fresh });
|
||||
return { developSeq: this.log.length, ops: out };
|
||||
}
|
||||
}
|
||||
|
||||
const set = (values: Record<string, number>): EditCommand => ({ command: "develop.set", params: { values } });
|
||||
|
||||
describe("DevelopSession", () => {
|
||||
let server: FakeServer;
|
||||
const open = async (clientId: string, outbox?: OutboxStore) => {
|
||||
const s = new DevelopSession("p", { engine, api: server, clientId, outbox });
|
||||
server.sessions.push(s);
|
||||
await s.load();
|
||||
return s;
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers();
|
||||
server = new FakeServer();
|
||||
});
|
||||
afterEach(() => vi.useRealTimers());
|
||||
|
||||
it("shows edits at once and sends a drag as few ops with one undo step", async () => {
|
||||
const web = await open("web");
|
||||
web.edit(set({ "light.exposure": 0.1 }), "light.exposure");
|
||||
web.edit(set({ "light.exposure": 0.2 }), "light.exposure");
|
||||
expect(web.value("light.exposure")).toBe(0.2);
|
||||
await vi.advanceTimersByTimeAsync(200);
|
||||
web.edit(set({ "light.exposure": 0.6 }), "light.exposure");
|
||||
web.endGesture();
|
||||
await vi.advanceTimersByTimeAsync(200);
|
||||
expect(server.log.map((o) => (o.command as { params: { values: Record<string, number> } }).params.values["light.exposure"])).toEqual([0.2, 0.6]);
|
||||
expect(web.seq).toBe(2);
|
||||
expect(web.hasPending).toBe(false);
|
||||
|
||||
web.undo();
|
||||
expect(web.value("light.exposure")).toBe(0);
|
||||
web.redo();
|
||||
expect(web.value("light.exposure")).toBe(0.6);
|
||||
});
|
||||
|
||||
it("keeps two windows in step, last writer winning per control", async () => {
|
||||
const web = await open("web");
|
||||
const desktop = await open("desktop");
|
||||
web.edit(set({ "light.exposure": 1 }));
|
||||
desktop.edit(set({ "effects.clarity": 30 }));
|
||||
await vi.advanceTimersByTimeAsync(300);
|
||||
desktop.edit(set({ "light.exposure": -0.5 }));
|
||||
await vi.advanceTimersByTimeAsync(300);
|
||||
for (const s of [web, desktop]) {
|
||||
expect(s.value("light.exposure")).toBe(-0.5);
|
||||
expect(s.value("effects.clarity")).toBe(30);
|
||||
expect(s.seq).toBe(3);
|
||||
}
|
||||
});
|
||||
|
||||
it("queues edits while offline, survives a reload, and stores a retried op once", async () => {
|
||||
const saved = new Map<string, PendingOp[]>();
|
||||
const outbox: OutboxStore = { load: (id) => saved.get(id) ?? [], save: (id, ops) => void saved.set(id, ops) };
|
||||
server.down = true;
|
||||
const web = await open("web", outbox);
|
||||
web.edit(set({ "light.exposure": 0.7 }));
|
||||
await vi.advanceTimersByTimeAsync(300);
|
||||
expect(web.offline).toBe(true);
|
||||
expect(saved.get("p")).toHaveLength(1);
|
||||
web.close();
|
||||
|
||||
server.down = false;
|
||||
const again = await open("web", outbox);
|
||||
expect(again.value("light.exposure")).toBe(0.7);
|
||||
await vi.advanceTimersByTimeAsync(50);
|
||||
expect(server.log).toHaveLength(1);
|
||||
expect(saved.get("p")).toEqual([]);
|
||||
await again.flush();
|
||||
expect(server.log).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("catches up when it missed ops", async () => {
|
||||
const web = await open("web");
|
||||
server.sessions = []; // messages to web are lost
|
||||
const other = new DevelopSession("p", { engine, api: server, clientId: "other" });
|
||||
await other.load();
|
||||
other.edit(set({ "light.contrast": 10 }));
|
||||
other.edit(set({ "light.contrast": 20 }));
|
||||
await vi.advanceTimersByTimeAsync(300);
|
||||
server.sessions = [web];
|
||||
other.edit(set({ "light.whites": 5 }));
|
||||
await vi.advanceTimersByTimeAsync(300);
|
||||
expect(web.value("light.contrast")).toBe(20);
|
||||
expect(web.value("light.whites")).toBe(5);
|
||||
expect(web.seq).toBe(3);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,335 @@
|
||||
import type { DevelopState, EditCommand, EditLogEntry, PostEdits } from "@photoreport/contracts";
|
||||
|
||||
/** What the session needs from the engine (the WASM module in the app; a fake in tests). */
|
||||
export interface SettingsEngine {
|
||||
defaultSettings(): string;
|
||||
apply(settings: string, command: string): string;
|
||||
value(settings: string, id: string): number;
|
||||
}
|
||||
|
||||
/** What the session needs from the API. */
|
||||
export interface DevelopApi {
|
||||
developState(photoId: string, since?: number): Promise<DevelopState>;
|
||||
postEdits(photoId: string, body: PostEdits): Promise<{ developSeq: number; ops: EditLogEntry[] }>;
|
||||
}
|
||||
|
||||
/** Durable outbox, so edits made offline survive a reload (localStorage in the app). */
|
||||
export interface OutboxStore {
|
||||
load(photoId: string): PendingOp[];
|
||||
save(photoId: string, ops: PendingOp[]): void;
|
||||
}
|
||||
|
||||
export interface PendingOp {
|
||||
opId: string;
|
||||
command: EditCommand;
|
||||
/** Edits of the same control during one drag replace each other instead of piling up. */
|
||||
coalesce?: string | undefined;
|
||||
sent?: boolean;
|
||||
}
|
||||
|
||||
interface Step {
|
||||
undo: EditCommand;
|
||||
redo: EditCommand;
|
||||
}
|
||||
|
||||
const SEND_DELAY_MS = 120;
|
||||
const RETRY_MAX_MS = 30_000;
|
||||
|
||||
let counter = 0;
|
||||
const newOpId = () => `${Date.now().toString(36)}-${(++counter).toString(36)}-${Math.random().toString(36).slice(2, 8)}`;
|
||||
|
||||
/**
|
||||
* One photo being developed. Settings are the server's op log replayed by the local engine (`base`, up to
|
||||
* `confirmedSeq`) plus this window's edits not yet acknowledged (`pending`), so edits show instantly and remote
|
||||
* edits slot in underneath. Last writer wins per control, as on the server. Edits are sent in small batches;
|
||||
* unsent ones stay in the outbox (and on disk) and are retried until accepted; a retried op is stored once.
|
||||
*/
|
||||
export class DevelopSession {
|
||||
private base = "";
|
||||
private confirmedSeq = 0;
|
||||
private pending: PendingOp[] = [];
|
||||
private undoStack: Step[] = [];
|
||||
private redoStack: Step[] = [];
|
||||
private gesture: string | undefined;
|
||||
private timer: ReturnType<typeof setTimeout> | undefined;
|
||||
private sending = false;
|
||||
private retryMs = 1000;
|
||||
private listeners = new Set<() => void>();
|
||||
private cachedSettings: string | undefined;
|
||||
private closed = false;
|
||||
/** Set while the last send failed (offline): the UI shows it. */
|
||||
offline = false;
|
||||
loaded = false;
|
||||
|
||||
constructor(
|
||||
readonly photoId: string,
|
||||
private readonly deps: { engine: SettingsEngine; api: DevelopApi; clientId: string; outbox?: OutboxStore | undefined },
|
||||
) {}
|
||||
|
||||
async load(): Promise<void> {
|
||||
const state = await this.deps.api.developState(this.photoId);
|
||||
let base = state.snapshot ? JSON.stringify(state.snapshot) : this.deps.engine.defaultSettings();
|
||||
for (const op of state.ops) base = this.safeApply(base, op.command);
|
||||
this.base = base;
|
||||
this.confirmedSeq = state.developSeq;
|
||||
this.pending = this.deps.outbox?.load(this.photoId).map((p) => ({ ...p, sent: false })) ?? [];
|
||||
this.loaded = true;
|
||||
this.changed();
|
||||
if (this.pending.length) this.schedule(0);
|
||||
}
|
||||
|
||||
close(): void {
|
||||
this.closed = true;
|
||||
clearTimeout(this.timer);
|
||||
this.listeners.clear();
|
||||
}
|
||||
|
||||
subscribe(fn: () => void): () => void {
|
||||
this.listeners.add(fn);
|
||||
return () => this.listeners.delete(fn);
|
||||
}
|
||||
|
||||
/** Current settings JSON: confirmed edits plus this window's pending ones. */
|
||||
get settings(): string {
|
||||
this.cachedSettings ??= this.pending.reduce((s, op) => this.safeApply(s, op.command), this.base);
|
||||
return this.cachedSettings;
|
||||
}
|
||||
|
||||
get seq(): number {
|
||||
return this.confirmedSeq;
|
||||
}
|
||||
|
||||
get hasPending(): boolean {
|
||||
return this.pending.length > 0;
|
||||
}
|
||||
|
||||
value(id: string): number {
|
||||
return this.deps.engine.value(this.settings, id);
|
||||
}
|
||||
|
||||
get canUndo(): boolean {
|
||||
return this.undoStack.length > 0;
|
||||
}
|
||||
|
||||
get canRedo(): boolean {
|
||||
return this.redoStack.length > 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Applies a command locally and queues it. `gesture` groups a drag: while the same gesture continues, the
|
||||
* queued command and the undo step are updated in place (one undo step per drag, few ops on the wire).
|
||||
*/
|
||||
edit(command: EditCommand, gesture?: string): void {
|
||||
const before = this.settings;
|
||||
const last = this.pending.at(-1);
|
||||
// Not yet sent: the drag's latest position replaces the queued one. Already sent: a new op follows it,
|
||||
// so other windows see the drag live (one op per send interval).
|
||||
if (gesture !== undefined && last && !last.sent && last.coalesce === gesture) last.command = merge(last.command, command);
|
||||
else this.pending.push({ opId: newOpId(), command, coalesce: gesture });
|
||||
const top = this.undoStack.at(-1);
|
||||
if (gesture !== undefined && this.gesture === gesture && top) top.redo = merge(top.redo, command);
|
||||
else {
|
||||
const step = this.undoStep(before, command);
|
||||
if (step) this.undoStack.push(step);
|
||||
}
|
||||
this.redoStack = [];
|
||||
this.gesture = gesture;
|
||||
this.changed();
|
||||
this.persist();
|
||||
this.schedule(SEND_DELAY_MS);
|
||||
}
|
||||
|
||||
/** Ends a drag: the next edit starts a new op and a new undo step. */
|
||||
endGesture(): void {
|
||||
this.gesture = undefined;
|
||||
const last = this.pending.at(-1);
|
||||
if (last) last.coalesce = undefined;
|
||||
this.schedule(0);
|
||||
}
|
||||
|
||||
undo(): void {
|
||||
this.gesture = undefined;
|
||||
const step = this.undoStack.pop();
|
||||
if (!step) return;
|
||||
this.pending.push({ opId: newOpId(), command: step.undo });
|
||||
this.redoStack.push(step);
|
||||
this.changed();
|
||||
this.persist();
|
||||
this.schedule(0);
|
||||
}
|
||||
|
||||
redo(): void {
|
||||
const step = this.redoStack.pop();
|
||||
if (!step) return;
|
||||
this.pending.push({ opId: newOpId(), command: step.redo });
|
||||
this.undoStack.push(step);
|
||||
this.changed();
|
||||
this.persist();
|
||||
this.schedule(0);
|
||||
}
|
||||
|
||||
/** A `photo.edited` message from the server. Our own echo is skipped (the send's answer covers it). */
|
||||
async remote(message: { clientId: string; ops: EditLogEntry[] }): Promise<void> {
|
||||
if (message.clientId === this.deps.clientId) return;
|
||||
await this.accept(message.ops);
|
||||
}
|
||||
|
||||
private async accept(ops: EditLogEntry[]): Promise<void> {
|
||||
for (const op of ops) {
|
||||
if (op.seq <= this.confirmedSeq) {
|
||||
this.dropPending(op.opId);
|
||||
continue;
|
||||
}
|
||||
if (op.seq !== this.confirmedSeq + 1) {
|
||||
await this.catchUp();
|
||||
return;
|
||||
}
|
||||
this.base = this.safeApply(this.base, op.command);
|
||||
this.confirmedSeq = op.seq;
|
||||
this.dropPending(op.opId);
|
||||
}
|
||||
this.changed();
|
||||
}
|
||||
|
||||
/** Missed some ops (reconnect, a message lost): fetch everything after what we have, in order. */
|
||||
async catchUp(): Promise<void> {
|
||||
const state = await this.deps.api.developState(this.photoId, this.confirmedSeq);
|
||||
if (state.snapshot) {
|
||||
// The server answered with a snapshot (we were too far behind): start over from it.
|
||||
this.base = JSON.stringify(state.snapshot);
|
||||
this.confirmedSeq = state.snapshotSeq;
|
||||
}
|
||||
for (const op of state.ops) {
|
||||
if (op.seq !== this.confirmedSeq + 1) continue;
|
||||
this.base = this.safeApply(this.base, op.command);
|
||||
this.confirmedSeq = op.seq;
|
||||
this.dropPending(op.opId);
|
||||
}
|
||||
this.changed();
|
||||
}
|
||||
|
||||
/** Sends what is queued now (also used before leaving the photo). */
|
||||
async flush(): Promise<void> {
|
||||
clearTimeout(this.timer);
|
||||
if (this.sending || this.closed) return;
|
||||
const batch = this.pending.filter((p) => !p.sent).slice(0, 200);
|
||||
if (!batch.length) return;
|
||||
this.sending = true;
|
||||
for (const op of batch) op.sent = true;
|
||||
try {
|
||||
const res = await this.deps.api.postEdits(this.photoId, { clientId: this.deps.clientId, ops: batch.map((p) => ({ opId: p.opId, command: p.command })) });
|
||||
this.offline = false;
|
||||
this.retryMs = 1000;
|
||||
await this.accept(res.ops);
|
||||
this.persist();
|
||||
} catch (err) {
|
||||
for (const op of batch) op.sent = false;
|
||||
const status = (err as { status?: number }).status;
|
||||
if (status && status >= 400 && status < 500 && status !== 401 && status !== 408 && status !== 429) {
|
||||
// Refused for good (unknown control, no permission): drop it, the server state stands.
|
||||
for (const op of batch) this.dropPending(op.opId);
|
||||
this.persist();
|
||||
this.changed();
|
||||
} else {
|
||||
this.offline = true;
|
||||
this.changed();
|
||||
this.schedule(this.retryMs);
|
||||
this.retryMs = Math.min(this.retryMs * 2, RETRY_MAX_MS);
|
||||
}
|
||||
} finally {
|
||||
this.sending = false;
|
||||
}
|
||||
if (!this.offline && this.pending.some((p) => !p.sent)) this.schedule(SEND_DELAY_MS);
|
||||
}
|
||||
|
||||
private schedule(ms: number): void {
|
||||
if (this.closed) return;
|
||||
clearTimeout(this.timer);
|
||||
this.timer = setTimeout(() => void this.flush(), ms);
|
||||
}
|
||||
|
||||
private dropPending(opId: string): void {
|
||||
const i = this.pending.findIndex((p) => p.opId === opId);
|
||||
if (i >= 0) this.pending.splice(i, 1);
|
||||
}
|
||||
|
||||
private persist(): void {
|
||||
this.deps.outbox?.save(
|
||||
this.photoId,
|
||||
this.pending.map(({ opId, command }) => ({ opId, command })),
|
||||
);
|
||||
}
|
||||
|
||||
private changed(): void {
|
||||
this.cachedSettings = undefined;
|
||||
for (const fn of this.listeners) fn();
|
||||
}
|
||||
|
||||
private safeApply(settings: string, command: EditCommand): string {
|
||||
try {
|
||||
return this.deps.engine.apply(settings, JSON.stringify(command));
|
||||
} catch {
|
||||
return settings; // a command this engine does not know (newer client): skipped, like the server
|
||||
}
|
||||
}
|
||||
|
||||
/** The command that puts back what `command` is about to change. */
|
||||
private undoStep(before: string, command: EditCommand): Step | undefined {
|
||||
switch (command.command) {
|
||||
case "develop.set": {
|
||||
const values: Record<string, number> = {};
|
||||
for (const id of Object.keys(command.params.values)) values[id] = this.deps.engine.value(before, id);
|
||||
return { undo: { command: "develop.set", params: { values } }, redo: command };
|
||||
}
|
||||
case "crop.set": {
|
||||
const crop = cropOf(before);
|
||||
return { undo: { command: "crop.set", params: crop }, redo: command };
|
||||
}
|
||||
case "develop.reset":
|
||||
case "develop.merge":
|
||||
return { undo: { command: "develop.merge", params: { partial: JSON.parse(before) as Record<string, unknown> } }, redo: command };
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Two commands of one gesture: values merge, anything else is replaced by the newer one. */
|
||||
function merge(a: EditCommand, b: EditCommand): EditCommand {
|
||||
if (a.command === "develop.set" && b.command === "develop.set") return { command: "develop.set", params: { values: { ...a.params.values, ...b.params.values } } };
|
||||
return b;
|
||||
}
|
||||
|
||||
export interface Crop {
|
||||
rect: { x0: number; y0: number; x1: number; y1: number };
|
||||
angle: number;
|
||||
aspect: [number, number] | null;
|
||||
}
|
||||
|
||||
/** The crop part of a settings document (LightCraft JSON). */
|
||||
export function cropOf(settings: string): Crop {
|
||||
const s = JSON.parse(settings) as { crop?: { aspect?: [number, number] | null; geometry?: { angle?: number; rect?: Crop["rect"] } } };
|
||||
return {
|
||||
rect: s.crop?.geometry?.rect ?? { x0: 0, y0: 0, x1: 1, y1: 1 },
|
||||
angle: s.crop?.geometry?.angle ?? 0,
|
||||
aspect: s.crop?.aspect ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
/** localStorage-backed outbox (per photo); quietly does nothing where storage is unavailable. */
|
||||
export const localOutbox: OutboxStore = {
|
||||
load(photoId) {
|
||||
try {
|
||||
const raw = localStorage.getItem(`pr:outbox:${photoId}`);
|
||||
return raw ? (JSON.parse(raw) as PendingOp[]) : [];
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
},
|
||||
save(photoId, ops) {
|
||||
try {
|
||||
if (ops.length) localStorage.setItem(`pr:outbox:${photoId}`, JSON.stringify(ops));
|
||||
else localStorage.removeItem(`pr:outbox:${photoId}`);
|
||||
} catch {
|
||||
// private mode or full: the edits still go out while the page is open
|
||||
}
|
||||
},
|
||||
};
|
||||
+44
-1
@@ -39,7 +39,7 @@ export const t = {
|
||||
noPhotosYet: "Ainda não chegaram fotografias. Assim que o FTP receber ficheiros, aparecem aqui.",
|
||||
filter: "Filtro",
|
||||
filters: { all: "Todas", PICK: "Escolhidas", UNREJECTED: "Sem rejeitadas", REJECT: "Rejeitadas", stars: "★ 3+", noPlayers: "Sem jogador" },
|
||||
shortcuts: "P escolher · X rejeitar · U limpar · 0–5 estrelas · 6–9 cor · Enter lupa · Esc grelha",
|
||||
shortcuts: "P escolher · X rejeitar · U limpar · 0–5 estrelas · 6–9 cor · Enter lupa · Esc grelha · D revelar",
|
||||
selected: (n: number) => (n === 1 ? "1 selecionada" : `${n} selecionadas`),
|
||||
ofTotal: (n: number, total: number) => `${n} de ${total}`,
|
||||
players: "Jogadores",
|
||||
@@ -155,6 +155,49 @@ export const t = {
|
||||
PHOTOGRAPHER: "Fotógrafo",
|
||||
CLIENT: "Cliente",
|
||||
},
|
||||
dev: {
|
||||
loading: "A abrir o motor de revelação…",
|
||||
engineMissing: "O motor de revelação não está disponível neste servidor (falta compilar engine/wasm).",
|
||||
noPhoto: "Escolhe uma foto na biblioteca (ou aqui em baixo) para revelar.",
|
||||
reset: "Repor",
|
||||
resetAll: "Repor tudo",
|
||||
undo: "Anular",
|
||||
redo: "Refazer",
|
||||
before: "Antes",
|
||||
after: "Depois",
|
||||
offline: "Sem ligação: as alterações ficam guardadas e seguem quando voltar",
|
||||
saving: "A guardar…",
|
||||
saved: "Guardado",
|
||||
crop: "Recortar",
|
||||
cropDone: "Concluir",
|
||||
aspect: "Proporção",
|
||||
aspectFree: "Livre",
|
||||
aspectOriginal: "Original",
|
||||
straighten: "Endireitar",
|
||||
copy: "Copiar ajustes",
|
||||
paste: "Colar ajustes",
|
||||
pasted: (n: number) => `Ajustes colados em ${n} ${n === 1 ? "foto" : "fotos"}`,
|
||||
noAccess: "Só podes revelar fotos que enviaste.",
|
||||
shortcuts: "← → foto · \\ antes/depois · R recortar · Ctrl+Z anular · Ctrl+Shift+Z refazer · duplo clique num cursor repõe",
|
||||
groups: { wb: "Equilíbrio de brancos", tone: "Tom", presence: "Presença", profile: "Perfil" },
|
||||
labels: {
|
||||
"profile.amount": "Intensidade",
|
||||
"wb.temp": "Temperatura",
|
||||
"wb.tint": "Matiz",
|
||||
"light.exposure": "Exposição",
|
||||
"light.contrast": "Contraste",
|
||||
"light.highlights": "Realces",
|
||||
"light.shadows": "Sombras",
|
||||
"light.whites": "Brancos",
|
||||
"light.blacks": "Pretos",
|
||||
"effects.texture": "Textura",
|
||||
"effects.clarity": "Claridade",
|
||||
"effects.dehaze": "Remover névoa",
|
||||
"color.vibrance": "Vivacidade",
|
||||
"color.saturation": "Saturação",
|
||||
"crop.angle": "Ângulo",
|
||||
} as Record<string, string>,
|
||||
},
|
||||
modules: {
|
||||
crop: "Recorte",
|
||||
basic: "Básico",
|
||||
|
||||
@@ -21,7 +21,8 @@ const photo = (id: string, capturedAt: string, extra: Partial<PhotoSummary> = {}
|
||||
colorLabel: "NONE",
|
||||
players: [],
|
||||
uploader: null,
|
||||
urls: { thumb: "", preview: "" },
|
||||
developSeq: 0,
|
||||
urls: { thumb: "", preview: "", source: "" },
|
||||
...extra,
|
||||
});
|
||||
|
||||
|
||||
@@ -58,6 +58,8 @@ export function libraryReducer(state: LibraryState, action: LibraryAction): Libr
|
||||
return { ...state, photos: [...state.photos, m.photo].sort(byCapture) };
|
||||
}
|
||||
if (m.type === "photo.updated") return libraryReducer(state, { type: "patch", ids: m.ids, patch: m.patch });
|
||||
if (m.type === "photo.edited") return { ...state, photos: state.photos.map((p) => (p.id === m.photoId ? { ...p, developSeq: m.developSeq } : p)) };
|
||||
if (m.type === "photo.rendered") return { ...state, photos: state.photos.map((p) => (p.id === m.photoId ? { ...p, urls: { ...p.urls, ...m.urls } } : p)) };
|
||||
return state;
|
||||
}
|
||||
case "patch": {
|
||||
|
||||
@@ -0,0 +1,351 @@
|
||||
import { CONTROLS, DEFAULT_MODULES, type EditCommand, type LibraryMessage, type PhotoSummary } from "@photoreport/contracts";
|
||||
import { hasRole } from "@photoreport/sdk";
|
||||
import { useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore } from "react";
|
||||
import { useNavigate, useParams } from "react-router";
|
||||
import { useAuth } from "../auth.js";
|
||||
import { type EngineModule, loadEngine } from "../develop/engine.js";
|
||||
import { DevelopPanels, Section, Slider } from "../develop/Panels.js";
|
||||
import { cropOf, DevelopSession, localOutbox } from "../develop/session.js";
|
||||
import { fitAspect, Viewer } from "../develop/Viewer.js";
|
||||
import { t } from "../i18n.js";
|
||||
import { useLibraryLive } from "../library/realtime.js";
|
||||
import { prefs } from "../platform.js";
|
||||
|
||||
/** One id per window: the server tags our edits with it so this window skips its own echo. */
|
||||
const CLIENT_ID = typeof crypto !== "undefined" && "randomUUID" in crypto ? crypto.randomUUID() : `w-${Date.now()}-${Math.random()}`;
|
||||
|
||||
const ASPECTS: { label: string; value: [number, number] | "original" | null }[] = [
|
||||
{ label: t.dev.aspectFree, value: null },
|
||||
{ label: t.dev.aspectOriginal, value: "original" },
|
||||
{ label: "1:1", value: [1, 1] },
|
||||
{ label: "3:2", value: [3, 2] },
|
||||
{ label: "2:3", value: [2, 3] },
|
||||
{ label: "4:3", value: [4, 3] },
|
||||
{ label: "4:5", value: [4, 5] },
|
||||
{ label: "16:9", value: [16, 9] },
|
||||
];
|
||||
|
||||
const CLIPBOARD = "develop.clipboard";
|
||||
|
||||
/** Controls a "copy settings" carries: everything numeric except the crop, which belongs to each photo. */
|
||||
export function copyableValues(value: (id: string) => number): Record<string, number> {
|
||||
const out: Record<string, number> = {};
|
||||
for (const c of CONTROLS) {
|
||||
if (c.module === "crop") continue;
|
||||
const v = value(c.id);
|
||||
if (Number.isFinite(v) && v !== c.default) out[c.id] = v;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** A reset of everything a paste carries, plus the pasted values. */
|
||||
export function pasteCommand(values: Record<string, number>): EditCommand {
|
||||
const all: Record<string, number> = {};
|
||||
for (const c of CONTROLS) if (c.module !== "crop") all[c.id] = c.default;
|
||||
return { command: "develop.set", params: { values: { ...all, ...values } } };
|
||||
}
|
||||
|
||||
const isTyping = (target: EventTarget | null) =>
|
||||
target instanceof HTMLElement && (target.isContentEditable || ["INPUT", "TEXTAREA", "SELECT"].includes(target.tagName) && (target as HTMLInputElement).type !== "range");
|
||||
|
||||
/** Develop module ("Revelar"): the photo in the middle, panels on the right, the event's photos below. */
|
||||
export function DevelopPage() {
|
||||
const { api, organization, role, me } = useAuth();
|
||||
const orgId = organization?.id ?? "";
|
||||
const { photoId } = useParams();
|
||||
const navigate = useNavigate();
|
||||
const [photos, setPhotos] = useState<PhotoSummary[]>([]);
|
||||
const [engine, setEngine] = useState<EngineModule | "loading" | "missing">("loading");
|
||||
const [session, setSession] = useState<DevelopSession | null>(null);
|
||||
const [dragging, setDragging] = useState(false);
|
||||
const [before, setBefore] = useState(false);
|
||||
const [cropping, setCropping] = useState(false);
|
||||
const [sourceSize, setSourceSize] = useState<{ w: number; h: number } | null>(null);
|
||||
const [note, setNote] = useState<string | null>(null);
|
||||
const strip = useRef<HTMLDivElement>(null);
|
||||
const modules = me?.preferences.editorModules ?? DEFAULT_MODULES;
|
||||
|
||||
useEffect(() => {
|
||||
loadEngine().then(setEngine, () => setEngine("missing"));
|
||||
}, []);
|
||||
|
||||
// The event (or inbox) the library has open.
|
||||
useEffect(() => {
|
||||
if (!orgId) return;
|
||||
const scope = prefs.get(`scope:${orgId}`) ?? undefined;
|
||||
api.listPhotos(orgId, { ...(scope && { event: scope }), limit: 500 }).then(
|
||||
(r) => setPhotos(r.photos.filter((p) => p.status === "READY")),
|
||||
() => setPhotos([]),
|
||||
);
|
||||
}, [api, orgId]);
|
||||
|
||||
const current = photos.find((p) => p.id === photoId) ?? null;
|
||||
useEffect(() => {
|
||||
if (!photoId && photos[0]) navigate(`/develop/${photos[0].id}`, { replace: true });
|
||||
}, [photoId, photos, navigate]);
|
||||
|
||||
const canEdit = !!current && !!role && (hasRole(role, "INGESTER") || current.uploader?.id === me?.user.id);
|
||||
|
||||
useEffect(() => {
|
||||
if (!current || typeof engine !== "object") return;
|
||||
const s = new DevelopSession(current.id, { engine, api, clientId: CLIENT_ID, outbox: localOutbox });
|
||||
setSession(s);
|
||||
setSourceSize(null);
|
||||
setCropping(false);
|
||||
s.load().catch(() => setNote(t.unexpectedError));
|
||||
return () => {
|
||||
void s.flush().finally(() => s.close());
|
||||
};
|
||||
}, [current?.id, engine, api]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
|
||||
const version = useSyncExternalStore(
|
||||
useCallback((fn: () => void) => session?.subscribe(fn) ?? (() => {}), [session]),
|
||||
() => (session ? [session.loaded, session.seq, session.offline, session.hasPending, session.canUndo, session.canRedo, session.settings].join("|") : ""),
|
||||
);
|
||||
void version;
|
||||
|
||||
const onMessage = useCallback(
|
||||
(m: LibraryMessage) => {
|
||||
if (m.type === "photo.edited") {
|
||||
if (session && m.photoId === session.photoId) void session.remote(m);
|
||||
setPhotos((list) => list.map((p) => (p.id === m.photoId ? { ...p, developSeq: m.developSeq } : p)));
|
||||
} else if (m.type === "photo.rendered") {
|
||||
setPhotos((list) => list.map((p) => (p.id === m.photoId ? { ...p, urls: { ...p.urls, ...m.urls } } : p)));
|
||||
}
|
||||
},
|
||||
[session],
|
||||
);
|
||||
const live = useLibraryLive(api, onMessage);
|
||||
// Reconnected: anything sent meanwhile is fetched in order.
|
||||
useEffect(() => {
|
||||
if (live === "live" && session?.loaded) void session.catchUp();
|
||||
}, [live, session]);
|
||||
|
||||
const index = current ? photos.findIndex((p) => p.id === current.id) : -1;
|
||||
const go = useCallback(
|
||||
(delta: number) => {
|
||||
const next = photos[index + delta];
|
||||
if (next) navigate(`/develop/${next.id}`);
|
||||
},
|
||||
[photos, index, navigate],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
strip.current?.querySelector('[aria-current="true"]')?.scrollIntoView({ block: "nearest", inline: "nearest" });
|
||||
}, [current?.id]);
|
||||
|
||||
useEffect(() => {
|
||||
const onKey = (e: KeyboardEvent) => {
|
||||
if (isTyping(e.target)) return;
|
||||
// Arrows move a focused slider, not the photo.
|
||||
if (e.target instanceof HTMLInputElement && e.target.type === "range" && e.key.startsWith("Arrow")) return;
|
||||
const mod = e.metaKey || e.ctrlKey;
|
||||
if (mod && e.key.toLowerCase() === "z") {
|
||||
e.preventDefault();
|
||||
if (e.shiftKey) session?.redo();
|
||||
else session?.undo();
|
||||
} else if (mod && e.key.toLowerCase() === "y") {
|
||||
e.preventDefault();
|
||||
session?.redo();
|
||||
} else if (e.key === "ArrowRight") go(1);
|
||||
else if (e.key === "ArrowLeft") go(-1);
|
||||
else if (e.key === "\\") setBefore((b) => !b);
|
||||
else if (e.key.toLowerCase() === "r" && canEdit) setCropping((c) => !c);
|
||||
else if (e.key === "Escape") setCropping(false);
|
||||
};
|
||||
window.addEventListener("keydown", onKey);
|
||||
return () => window.removeEventListener("keydown", onKey);
|
||||
}, [session, go, canEdit]);
|
||||
|
||||
const settings = session?.loaded ? session.settings : null;
|
||||
const crop = useMemo(() => (settings ? cropOf(settings) : { rect: { x0: 0, y0: 0, x1: 1, y1: 1 }, angle: 0, aspect: null }), [settings]);
|
||||
const shown = settings && before && typeof engine === "object" ? engine.defaultSettings() : settings;
|
||||
|
||||
const setValue = useCallback(
|
||||
(id: string, value: number) => {
|
||||
setDragging(true);
|
||||
session?.edit({ command: "develop.set", params: { values: { [id]: value } } }, id);
|
||||
},
|
||||
[session],
|
||||
);
|
||||
const endGesture = useCallback(() => {
|
||||
setDragging(false);
|
||||
session?.endGesture();
|
||||
}, [session]);
|
||||
|
||||
const frameRatio = (aspect: [number, number] | null) => {
|
||||
if (!aspect) return null;
|
||||
const src = sourceSize ? sourceSize.w / sourceSize.h : 1.5;
|
||||
return aspect[0] / aspect[1] / src;
|
||||
};
|
||||
const setAspect = (choice: (typeof ASPECTS)[number]["value"]) => {
|
||||
if (!session || !sourceSize) return;
|
||||
const aspect: [number, number] | null = choice === "original" ? [sourceSize.w, sourceSize.h] : choice;
|
||||
const ratio = frameRatio(aspect);
|
||||
const rect = ratio ? fitAspect(crop.rect, ratio) : crop.rect;
|
||||
session.edit({ command: "crop.set", params: { rect, angle: crop.angle, aspect } });
|
||||
session.endGesture();
|
||||
};
|
||||
|
||||
if (!organization) return <p className="p-6 text-sm text-muted">{t.noAccess}</p>;
|
||||
|
||||
const status = !session?.loaded ? "" : session.offline ? t.dev.offline : session.hasPending ? t.dev.saving : t.dev.saved;
|
||||
const angle = CONTROLS.find((c) => c.id === "crop.angle");
|
||||
const clip = prefs.get(CLIPBOARD);
|
||||
|
||||
return (
|
||||
<div className="flex min-h-full flex-col lg:h-full lg:min-h-0">
|
||||
<div className="flex min-h-0 flex-1 flex-col lg:flex-row">
|
||||
<div className="flex min-h-[60vh] min-w-0 flex-1 flex-col bg-[#121213] lg:min-h-0">
|
||||
<div className="flex flex-wrap items-center gap-3 border-b border-line bg-raised px-3 py-1.5 text-[12px]">
|
||||
<span className="truncate font-mono text-[11px] text-faint">{current ? `${current.originalName} · ${index + 1}/${photos.length}` : ""}</span>
|
||||
<span className="ml-auto flex items-center gap-2">
|
||||
<button className="h-6 border border-black bg-cell px-2.5 disabled:opacity-40" disabled={!session?.canUndo} onClick={() => session?.undo()}>
|
||||
{t.dev.undo}
|
||||
</button>
|
||||
<button className="h-6 border border-black bg-cell px-2.5 disabled:opacity-40" disabled={!session?.canRedo} onClick={() => session?.redo()}>
|
||||
{t.dev.redo}
|
||||
</button>
|
||||
<button className={`h-6 border border-black px-2.5 ${before ? "bg-accent text-white" : "bg-cell"}`} aria-pressed={before} onClick={() => setBefore(!before)}>
|
||||
{before ? t.dev.before : t.dev.after}
|
||||
</button>
|
||||
<span className={`min-w-20 text-right font-mono text-[11px] ${session?.offline ? "text-[#f0a35a]" : "text-faint"}`} role="status">
|
||||
{status}
|
||||
</span>
|
||||
</span>
|
||||
</div>
|
||||
<div className="min-h-0 flex-1">
|
||||
{engine === "missing" ? (
|
||||
<p className="p-8 text-center text-[13px] text-faint">{t.dev.engineMissing}</p>
|
||||
) : !current ? (
|
||||
<p className="p-8 text-center text-[13px] text-faint">{photos.length ? "…" : t.dev.noPhoto}</p>
|
||||
) : engine === "loading" || !shown ? (
|
||||
<p className="p-8 text-center text-[13px] text-faint">{t.dev.loading}</p>
|
||||
) : (
|
||||
<Viewer
|
||||
photoKey={current.id}
|
||||
sourceUrl={api.absolute(current.urls.source)}
|
||||
settings={shown}
|
||||
dragging={dragging}
|
||||
cropping={cropping && !before}
|
||||
crop={crop}
|
||||
onSourceSize={(w, h) => setSourceSize({ w, h })}
|
||||
onError={(m) => setNote(m)}
|
||||
onCrop={(rect, final) => {
|
||||
setDragging(!final);
|
||||
session?.edit({ command: "crop.set", params: { rect, angle: crop.angle, aspect: crop.aspect } }, "crop");
|
||||
if (final) session?.endGesture();
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<aside className="w-full shrink-0 overflow-y-auto border-l border-line bg-panel lg:w-[320px]" aria-label="Painéis de revelação">
|
||||
{note && <p className="border-b border-line px-3 py-2 text-[12px] text-danger">{note}</p>}
|
||||
{!canEdit && current && <p className="border-b border-line px-3 py-2 text-[12px] text-faint">{t.dev.noAccess}</p>}
|
||||
{modules.includes("crop") && (
|
||||
<Section title={t.modules.crop}>
|
||||
<div className="mb-2 flex items-center gap-2">
|
||||
<button
|
||||
disabled={!canEdit}
|
||||
onClick={() => setCropping(!cropping)}
|
||||
aria-pressed={cropping}
|
||||
className={`h-7 border border-black px-3 text-[12px] disabled:opacity-40 ${cropping ? "bg-accent text-white" : "bg-cell"}`}
|
||||
>
|
||||
{cropping ? t.dev.cropDone : t.dev.crop}
|
||||
</button>
|
||||
<span className="text-[11px] text-faint">{t.dev.aspect}</span>
|
||||
</div>
|
||||
<div className="mb-2 flex flex-wrap gap-1">
|
||||
{ASPECTS.map((a) => {
|
||||
const on = a.value === null ? !crop.aspect : a.value === "original" ? !!crop.aspect && !!sourceSize && crop.aspect[0] * sourceSize.h === crop.aspect[1] * sourceSize.w : crop.aspect?.[0] === a.value[0] && crop.aspect?.[1] === a.value[1];
|
||||
return (
|
||||
<button
|
||||
key={a.label}
|
||||
disabled={!canEdit || !sourceSize}
|
||||
onClick={() => setAspect(a.value)}
|
||||
className={`h-6 border border-black px-2 text-[11px] disabled:opacity-40 ${on ? "bg-cell-on text-ink" : "bg-cell text-muted"}`}
|
||||
>
|
||||
{a.label}
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
{angle && (
|
||||
<Slider
|
||||
control={{ ...angle, min: -45, max: 45 }}
|
||||
value={session?.loaded ? session.value("crop.angle") : 0}
|
||||
disabled={!canEdit}
|
||||
onChange={setValue}
|
||||
onEnd={endGesture}
|
||||
/>
|
||||
)}
|
||||
</Section>
|
||||
)}
|
||||
<DevelopPanels
|
||||
modules={modules}
|
||||
value={(id) => (session?.loaded ? session.value(id) : NaN)}
|
||||
disabled={!canEdit || !session?.loaded}
|
||||
onChange={setValue}
|
||||
onEnd={endGesture}
|
||||
onSet={(values) => {
|
||||
session?.edit({ command: "develop.set", params: { values } });
|
||||
session?.endGesture();
|
||||
}}
|
||||
/>
|
||||
<div className="flex flex-wrap gap-2 p-3">
|
||||
<button
|
||||
className="h-7 border border-black bg-cell px-3 text-[12px] disabled:opacity-40"
|
||||
disabled={!session?.loaded}
|
||||
onClick={() => {
|
||||
if (!session) return;
|
||||
prefs.set(CLIPBOARD, JSON.stringify(copyableValues((id) => session.value(id))));
|
||||
setNote(null);
|
||||
}}
|
||||
>
|
||||
{t.dev.copy}
|
||||
</button>
|
||||
<button
|
||||
className="h-7 border border-black bg-cell px-3 text-[12px] disabled:opacity-40"
|
||||
disabled={!canEdit || !clip}
|
||||
onClick={() => {
|
||||
if (!session || !clip) return;
|
||||
session.edit(pasteCommand(JSON.parse(clip) as Record<string, number>));
|
||||
session.endGesture();
|
||||
}}
|
||||
>
|
||||
{t.dev.paste}
|
||||
</button>
|
||||
<button
|
||||
className="ml-auto h-7 border border-black bg-cell px-3 text-[12px] text-muted disabled:opacity-40"
|
||||
disabled={!canEdit || !session?.loaded}
|
||||
onClick={() => {
|
||||
session?.edit({ command: "develop.reset" });
|
||||
session?.endGesture();
|
||||
}}
|
||||
>
|
||||
{t.dev.resetAll}
|
||||
</button>
|
||||
</div>
|
||||
</aside>
|
||||
</div>
|
||||
|
||||
<div ref={strip} className="flex h-[92px] shrink-0 gap-1 overflow-x-auto border-t border-line bg-chrome p-1.5" aria-label="Fotos do evento">
|
||||
{photos.map((p) => (
|
||||
<button
|
||||
key={p.id}
|
||||
aria-current={p.id === current?.id}
|
||||
onClick={() => navigate(`/develop/${p.id}`)}
|
||||
className={`relative h-full shrink-0 border ${p.id === current?.id ? "border-[#cfcfcf]" : "border-transparent opacity-70 hover:opacity-100"}`}
|
||||
title={p.originalName}
|
||||
>
|
||||
<img src={api.absolute(p.urls.thumb)} alt="" loading="lazy" className="h-full w-auto" draggable={false} />
|
||||
{p.developSeq > 0 && <span className="absolute bottom-0.5 right-0.5 bg-black/70 px-1 font-mono text-[9px] text-white">±</span>}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
<div className="border-t border-line bg-raised px-3 py-1 text-[11px] text-faint">{t.dev.shortcuts}</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,7 +1,9 @@
|
||||
import type { LibraryMessage, PhotoPatch, PhotoSummary } from "@photoreport/contracts";
|
||||
import { hasRole, type DeliveryTarget, type EventSummary } from "@photoreport/sdk";
|
||||
import { useCallback, useEffect, useMemo, useReducer, useRef, useState } from "react";
|
||||
import { useNavigate } from "react-router";
|
||||
import { useAuth } from "../auth.js";
|
||||
import { pasteCommand } from "./DevelopPage.js";
|
||||
import { t } from "../i18n.js";
|
||||
import { EventForm } from "../library/EventForm.js";
|
||||
import { EventsPanel } from "../library/EventsPanel.js";
|
||||
@@ -22,6 +24,7 @@ const isTyping = (target: EventTarget | null) =>
|
||||
/** Library module: events on the left, the grid (or loupe) in the middle, photo details and delivery on the right. */
|
||||
export function LibraryPage() {
|
||||
const { api, organization, role } = useAuth();
|
||||
const navigate = useNavigate();
|
||||
const orgId = organization?.id ?? "";
|
||||
const canCull = role !== null && hasRole(role, "INGESTER");
|
||||
const canCreate = role !== null && hasRole(role, "EDITOR");
|
||||
@@ -133,6 +136,7 @@ export function LibraryPage() {
|
||||
return;
|
||||
}
|
||||
if (e.key === "Enter" && focus) return setLoupe(true);
|
||||
if (e.key.toLowerCase() === "d" && focus) return navigate(`/develop/${focus.id}`);
|
||||
if (e.key === "Escape") return setLoupe(false);
|
||||
const change = patchForKey(e.key);
|
||||
if (!change) return;
|
||||
@@ -146,7 +150,7 @@ export function LibraryPage() {
|
||||
};
|
||||
window.addEventListener("keydown", onKey);
|
||||
return () => window.removeEventListener("keydown", onKey);
|
||||
}, [visibleIds, selection, focus, loupe, patch]);
|
||||
}, [visibleIds, selection, focus, loupe, patch, navigate]);
|
||||
|
||||
const onPick = useCallback(
|
||||
(id: string, e: React.MouseEvent) => dispatch({ type: "select", id, mode: e.shiftKey ? "range" : e.metaKey || e.ctrlKey ? "toggle" : "single", visible: visibleIds }),
|
||||
@@ -207,6 +211,23 @@ export function LibraryPage() {
|
||||
<button onClick={() => fileInput.current?.click()} className="h-6 border border-black bg-cell px-2.5 text-[12px] text-ink hover:bg-cell-on">
|
||||
{t.importPhotos}
|
||||
</button>
|
||||
{canCull && prefs.get("develop.clipboard") && selection.length > 0 && (
|
||||
<button
|
||||
onClick={() => {
|
||||
const values = JSON.parse(prefs.get("develop.clipboard") ?? "{}") as Record<string, number>;
|
||||
const command = pasteCommand(values);
|
||||
const stamp = Date.now().toString(36);
|
||||
void Promise.all(selection.map((p) => api.postEdits(p.id, { clientId: "library", ops: [{ opId: `paste-${stamp}-${p.id}`, command }] }))).then(
|
||||
() => setError(null),
|
||||
() => setError(t.unexpectedError),
|
||||
);
|
||||
}}
|
||||
className="h-6 border border-black bg-cell px-2.5 text-[12px] text-ink hover:bg-cell-on"
|
||||
title={t.dev.paste}
|
||||
>
|
||||
{t.dev.paste} ({selection.length})
|
||||
</button>
|
||||
)}
|
||||
<input
|
||||
ref={fileInput}
|
||||
type="file"
|
||||
|
||||
@@ -57,9 +57,9 @@ export function Shell() {
|
||||
<span aria-hidden="true" className="text-[#3a3a3a]">
|
||||
|
|
||||
</span>
|
||||
<span className="cursor-not-allowed px-3 py-1 font-display text-[19px] max-sm:px-2 max-sm:text-[15px] font-semibold uppercase tracking-wide text-[#454545]" title={t.soon}>
|
||||
<NavLink to="/develop" className={moduleClass}>
|
||||
{t.develop}
|
||||
</span>
|
||||
</NavLink>
|
||||
{canCull && (
|
||||
<>
|
||||
<span aria-hidden="true" className="text-[#3a3a3a]">
|
||||
|
||||
@@ -67,3 +67,44 @@ body {
|
||||
text-transform: uppercase;
|
||||
color: #d0d0d0;
|
||||
}
|
||||
|
||||
/* Develop sliders: thin track drawn by the panel, small round thumb (Lightroom-like). */
|
||||
.pr-range {
|
||||
-webkit-appearance: none;
|
||||
appearance: none;
|
||||
height: 16px;
|
||||
background: transparent;
|
||||
cursor: pointer;
|
||||
}
|
||||
.pr-range:disabled {
|
||||
cursor: default;
|
||||
opacity: 0.5;
|
||||
}
|
||||
.pr-range::-webkit-slider-runnable-track {
|
||||
height: 3px;
|
||||
background: transparent;
|
||||
}
|
||||
.pr-range::-moz-range-track {
|
||||
height: 3px;
|
||||
background: transparent;
|
||||
}
|
||||
.pr-range::-webkit-slider-thumb {
|
||||
-webkit-appearance: none;
|
||||
width: 11px;
|
||||
height: 11px;
|
||||
margin-top: -4px;
|
||||
border-radius: 50%;
|
||||
background: #cfcfcf;
|
||||
border: 1px solid #111;
|
||||
}
|
||||
.pr-range::-moz-range-thumb {
|
||||
width: 11px;
|
||||
height: 11px;
|
||||
border-radius: 50%;
|
||||
background: #cfcfcf;
|
||||
border: 1px solid #111;
|
||||
}
|
||||
.pr-range:hover::-webkit-slider-thumb,
|
||||
.pr-range:focus-visible::-webkit-slider-thumb {
|
||||
background: #fff;
|
||||
}
|
||||
+24
-7
@@ -26,12 +26,29 @@ Node 22 + TypeScript + Fastify · PostgreSQL 17 + pgvector · Prisma · queues a
|
||||
Garage (S3-compatible) later · SFTPGo (tusd later) · React + Vite + Tailwind (`apps/app`) · Next.js
|
||||
(`apps/site`) · Tauri 2 (`apps/desktop`) · Rust (`engine`, `workers/render`) · Python (`workers/ml`).
|
||||
|
||||
## Realtime edits
|
||||
## Realtime edits (Revelar)
|
||||
|
||||
Client sends `EditEnvelope` -> API validates permissions, assigns per-photo `seq`, stores in op log,
|
||||
broadcasts `EditBroadcast` to `user:<id>` and `event:<id>`. Clients render locally with their own engine.
|
||||
Reconnect = "everything since seq X". Offline queue: IndexedDB (web), SQLite (desktop). Conflict rule:
|
||||
last writer wins per control. Slider drags are coalesced (about one command per 50 ms, one undo step per drag).
|
||||
One engine everywhere: `engine/core` wraps the LightCraft develop crates (settings, commands, decode, render).
|
||||
It runs natively in `workers/render` and in the browser as WASM (`engine/wasm`, about 2.5 MB, built into
|
||||
`apps/app/public/engine/` and loaded by a Web Worker), so the desktop app (the web app in a Tauri shell) and the
|
||||
browser show the same pixels.
|
||||
|
||||
- A window sends edit commands (never pixels) with `POST /v1/photos/:id/edits` (`{clientId, ops: [{opId,
|
||||
command}]}`). The API checks them against the pinned control list (`controls.generated.json`), assigns the
|
||||
per-photo `seq` under a row lock, stores them in `photo_edits` (a retried `opId` is stored once) and fans them
|
||||
out as `photo.edited` on the library channel. Last writer wins per control.
|
||||
- Each window replays the log with its own engine: confirmed settings plus its own unacknowledged edits on top,
|
||||
so edits show at once and remote ones slot in underneath. A gap in `seq` (lost message, reconnect) fetches
|
||||
`GET /v1/photos/:id/develop?since=<seq>`. Unsent edits stay in a per-photo outbox in local storage and are
|
||||
retried with back-off, so editing offline works and survives a reload.
|
||||
- Slider drags: the queued op is replaced until it is sent (about one op per 120 ms on the wire), one undo step
|
||||
per drag. Undo/redo are new ops that put the previous values back.
|
||||
- The worker keeps a settings snapshot per photo (`develop_snapshot`, `snapshot_seq`) and, two seconds after
|
||||
edits stop, renders edited thumb and preview from the original (`photo.rendered` with new URLs; `source` stays
|
||||
the unedited preview the editor renders on). Deliveries of edited photos are rendered by the engine from the
|
||||
original at the delivery size, camera EXIF copied back, orientation reset, IPTC written as before.
|
||||
- Measured: decode of a 24 MP JPEG to 2048 px about 0.5 s and a 1600 px render about 0.25 s in WASM (one
|
||||
thread); a 4000 px delivery render about 2 s natively.
|
||||
|
||||
## Uploads and ingest
|
||||
|
||||
@@ -134,8 +151,8 @@ and weak connections (tus), and a real match run on the `next` containers (the p
|
||||
0. Foundation: monorepo, CI, `next` containers, accounts, organizations, tokens (login on web and desktop).
|
||||
1. Ingest + library: SFTPGo/tus, routing, previews, IPTC, code replacements, culling, Nextcloud delivery
|
||||
(a real match arrives captioned and delivered with no manual step).
|
||||
2. Synced editor: native + WASM engine, op log, Socket.io, offline, render worker (PoC demo: same photo
|
||||
edited on web and desktop).
|
||||
2. Synced editor (done: WASM and native engine, op log, live sync, offline outbox, render worker, edited
|
||||
deliveries, crop with aspect presets and straighten, Basic and optional modules, copy/paste settings).
|
||||
3. Galleries and sales: PhotoReport and ShootYourMove storefronts, private galleries, Stripe, VAT/VIES,
|
||||
payouts, affiliates, press accounts, data import dry runs (end-to-end test purchase with invoice and payout).
|
||||
4. Events and printing: QR guest flow, templates, print jobs, Print Agent (a real event printed).
|
||||
|
||||
@@ -62,6 +62,12 @@ Gitea -> webhook -> the container pulls and redeploys itself. No manual `scp`/`r
|
||||
8. Faces (worker host): install Rust, `infra/faces/download-models.sh /srv/photoreport-data/models`, and set the
|
||||
`FACES_*` variables in `apps/api/.env`. Deploys build `photoreport-faces` whenever `cargo` is present.
|
||||
|
||||
9. Develop (Revelar): on the worker host set `RENDER_BIN=/srv/photoreport/target/release/photoreport-render`
|
||||
(built by the API deploy when Rust is installed). On the app host install the browser engine toolchain once:
|
||||
`rustup target add wasm32-unknown-unknown` and `cargo install wasm-bindgen-cli --version 0.2.129 --locked`;
|
||||
every app deploy then rebuilds `apps/app/public/engine/` (`infra/engine/build-wasm.sh`). Serve `.wasm` as
|
||||
`application/wasm`.
|
||||
|
||||
## Desktop and print agent
|
||||
|
||||
Not deployed by webhook. A tag `desktop-v*` / `agent-v*` triggers Gitea Actions to build installers per OS and
|
||||
|
||||
+10
-1
@@ -3,10 +3,19 @@ name = "photoreport-engine"
|
||||
version = "0.1.0"
|
||||
edition.workspace = true
|
||||
publish.workspace = true
|
||||
description = "Thin PhotoReport layer over the LightCraft develop crates: edit commands in, settings out."
|
||||
description = "Thin PhotoReport layer over the LightCraft develop crates: edit commands in, settings and pixels out."
|
||||
|
||||
[features]
|
||||
default = ["parallel"]
|
||||
# Multi-threaded decode and render (native). The browser build is single-threaded.
|
||||
parallel = ["lightcraft-codecs/parallel"]
|
||||
|
||||
[dependencies]
|
||||
lightcraft-develop = { workspace = true }
|
||||
lightcraft-codecs = { workspace = true }
|
||||
lightcraft-pipeline = { workspace = true }
|
||||
lightcraft-raster = { workspace = true }
|
||||
lightcraft-geom = { workspace = true }
|
||||
serde = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
thiserror = { workspace = true }
|
||||
@@ -4,7 +4,10 @@
|
||||
//! small JSON edit commands addressed by LightCraft control ids (`light.exposure`, `effects.clarity`, ...).
|
||||
//! Updating LightCraft should only ever require changes in this crate.
|
||||
|
||||
use lightcraft_develop::{DevelopSettings, controls};
|
||||
pub mod render;
|
||||
|
||||
pub use lightcraft_develop::DevelopSettings;
|
||||
use lightcraft_develop::controls;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::Value;
|
||||
|
||||
@@ -96,6 +99,10 @@ pub enum EngineError {
|
||||
UnknownControl(String),
|
||||
#[error("control {0} expects a number")]
|
||||
NotANumber(String),
|
||||
#[error("cannot read the photo: {0}")]
|
||||
Decode(String),
|
||||
#[error("cannot write the photo: {0}")]
|
||||
Encode(String),
|
||||
#[error("invalid settings: {0}")]
|
||||
InvalidSettings(#[from] serde_json::Error),
|
||||
}
|
||||
|
||||
@@ -0,0 +1,123 @@
|
||||
//! Pixels: decode a JPEG (or any standard format LightCraft reads) into the working space, render it with
|
||||
//! develop settings, and encode the result. The same code runs natively (render worker, desktop) and in the
|
||||
//! browser (WASM), so a photo looks the same everywhere.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use lightcraft_codecs::{ChromaSubsampling, DecodeOptions, EncodeImage, EncodeMeta};
|
||||
use lightcraft_develop::DevelopSettings;
|
||||
use lightcraft_geom::Orientation;
|
||||
use lightcraft_pipeline::{Quality, RenderRequest, SourceInfo, StageCache};
|
||||
use lightcraft_raster::Rgb32f;
|
||||
use lightcraft_raster::resample::{Filter, fit};
|
||||
|
||||
use crate::EngineError;
|
||||
|
||||
/// A decoded photo ready to render: linear Rec.2020, EXIF orientation applied, at most `max_edge` long.
|
||||
pub struct Source {
|
||||
image: Arc<Rgb32f>,
|
||||
info: SourceInfo,
|
||||
cache: StageCache,
|
||||
/// Full-resolution size of the file (oriented), for crop maths and export sizes.
|
||||
pub source_width: u32,
|
||||
pub source_height: u32,
|
||||
}
|
||||
|
||||
/// An 8-bit sRGB render with alpha (RGBA, row-major).
|
||||
pub struct Pixels {
|
||||
pub width: u32,
|
||||
pub height: u32,
|
||||
pub rgba: Vec<u8>,
|
||||
}
|
||||
|
||||
impl Source {
|
||||
/// Decodes `bytes`, keeping at most `max_edge` pixels on the long side (0 = full resolution).
|
||||
pub fn decode(bytes: &[u8], max_edge: u32) -> Result<Source, EngineError> {
|
||||
let edge = if max_edge == 0 { u32::MAX } else { max_edge };
|
||||
let d = lightcraft_codecs::decode(bytes, DecodeOptions::fit(edge, edge))
|
||||
.map_err(|e| EngineError::Decode(e.to_string()))?;
|
||||
let orientation = Orientation::from_exif(d.orientation);
|
||||
let (sw, sh) = if matches!(d.orientation, 5..=8) {
|
||||
(d.source_height, d.source_width)
|
||||
} else {
|
||||
(d.source_width, d.source_height)
|
||||
};
|
||||
let img = d.to_working();
|
||||
let max = edge as usize;
|
||||
let img = if img.width.max(img.height) > max {
|
||||
fit(&img, max, max, Filter::Mitchell)
|
||||
} else {
|
||||
img
|
||||
};
|
||||
Ok(Source {
|
||||
image: Arc::new(img.into_oriented(orientation)),
|
||||
info: SourceInfo::default(),
|
||||
cache: StageCache::default(),
|
||||
source_width: sw,
|
||||
source_height: sh,
|
||||
})
|
||||
}
|
||||
|
||||
/// Size of the decoded working image.
|
||||
pub fn size(&self) -> (usize, usize) {
|
||||
(self.image.width, self.image.height)
|
||||
}
|
||||
|
||||
/// Renders with `settings` into at most `max_w × max_h`. `draft` skips refinements during drags;
|
||||
/// `apply_crop: false` shows the whole frame (crop tool open). Intermediate stages are cached, so
|
||||
/// repeated renders while one slider moves are cheap.
|
||||
pub fn render(
|
||||
&self,
|
||||
settings: &DevelopSettings,
|
||||
max_w: u32,
|
||||
max_h: u32,
|
||||
draft: bool,
|
||||
apply_crop: bool,
|
||||
) -> Pixels {
|
||||
// Never enlarge: cap the box at the frame's own size at this source's resolution.
|
||||
let (nw, nh) =
|
||||
lightcraft_pipeline::native_output_size(self.image.width, self.image.height, settings);
|
||||
let cap = |m: u32, n: f64| (m.max(1) as usize).min((n.round() as usize).max(1));
|
||||
let (bw, bh) = if apply_crop {
|
||||
(cap(max_w, nw), cap(max_h, nh))
|
||||
} else {
|
||||
(max_w.max(1) as usize, max_h.max(1) as usize)
|
||||
};
|
||||
let mut req = RenderRequest::fit(bw, bh);
|
||||
req.quality = if draft { Quality::Draft } else { Quality::Full };
|
||||
req.apply_crop = apply_crop;
|
||||
let out = lightcraft_pipeline::render_cached(
|
||||
&self.image,
|
||||
&self.info,
|
||||
settings,
|
||||
&req,
|
||||
&self.cache,
|
||||
);
|
||||
let (width, height) = (out.image.width as u32, out.image.height as u32);
|
||||
let rgba = out.image.data.iter().flat_map(|p| *p).collect();
|
||||
Pixels {
|
||||
width,
|
||||
height,
|
||||
rgba,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Encodes a render as a baseline JPEG (4:4:4 chroma, `quality` 1..=100), sRGB, no metadata: callers
|
||||
/// copy EXIF/IPTC from the original afterwards.
|
||||
pub fn encode_jpeg(px: &Pixels, quality: u8) -> Result<Vec<u8>, EngineError> {
|
||||
let img = EncodeImage::new(
|
||||
px.width,
|
||||
px.height,
|
||||
4,
|
||||
lightcraft_codecs::Samples::U8(&px.rgba),
|
||||
);
|
||||
let meta = EncodeMeta {
|
||||
icc: None,
|
||||
exif: None,
|
||||
xmp: None,
|
||||
ppi: Some(300),
|
||||
};
|
||||
lightcraft_codecs::encode_jpeg(&img, quality.clamp(1, 100), ChromaSubsampling::S444, &meta)
|
||||
.map_err(|e| EngineError::Encode(e.to_string()))
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
[package]
|
||||
name = "photoreport-engine-wasm"
|
||||
version = "0.1.0"
|
||||
edition.workspace = true
|
||||
publish.workspace = true
|
||||
description = "The PhotoReport engine for the browser (wasm-bindgen): decode, edit commands, render."
|
||||
|
||||
[lib]
|
||||
crate-type = ["cdylib", "rlib"]
|
||||
|
||||
[dependencies]
|
||||
photoreport-engine = { path = "../core", default-features = false }
|
||||
serde_json = { workspace = true }
|
||||
wasm-bindgen = "=0.2.129"
|
||||
@@ -0,0 +1,120 @@
|
||||
//! Browser bindings. Runs in a Web Worker: the page sends the photo bytes once, then settings on every
|
||||
//! slider move, and gets RGBA pixels back. Settings and commands cross the boundary as JSON strings, the
|
||||
//! same documents the API stores, so there is one format everywhere.
|
||||
|
||||
use photoreport_engine::render::Source;
|
||||
use photoreport_engine::{DevelopSettings, EditCommand};
|
||||
use wasm_bindgen::prelude::*;
|
||||
|
||||
fn js_err(e: impl std::fmt::Display) -> JsError {
|
||||
JsError::new(&e.to_string())
|
||||
}
|
||||
|
||||
fn settings_from(json: &str) -> Result<DevelopSettings, JsError> {
|
||||
if json.trim().is_empty() {
|
||||
return Ok(DevelopSettings::default());
|
||||
}
|
||||
let v: serde_json::Value = serde_json::from_str(json).map_err(js_err)?;
|
||||
DevelopSettings::from_json(&v).map_err(js_err)
|
||||
}
|
||||
|
||||
/// Every develop control of the pinned LightCraft version (id, module, label, range, default, step).
|
||||
#[wasm_bindgen]
|
||||
pub fn controls() -> Result<String, JsError> {
|
||||
serde_json::to_string(&photoreport_engine::list_controls()).map_err(js_err)
|
||||
}
|
||||
|
||||
/// Default settings as JSON.
|
||||
#[wasm_bindgen(js_name = defaultSettings)]
|
||||
pub fn default_settings() -> String {
|
||||
DevelopSettings::default().to_json().to_string()
|
||||
}
|
||||
|
||||
/// Applies one edit command (JSON) to settings (JSON) and returns the new settings.
|
||||
#[wasm_bindgen]
|
||||
pub fn apply(settings: &str, command: &str) -> Result<String, JsError> {
|
||||
let s = settings_from(settings)?;
|
||||
let c: EditCommand = serde_json::from_str(command).map_err(js_err)?;
|
||||
Ok(photoreport_engine::apply_command(&s, &c)
|
||||
.map_err(js_err)?
|
||||
.to_json()
|
||||
.to_string())
|
||||
}
|
||||
|
||||
/// One control's value in settings (NaN for an unknown id): slider positions and undo steps.
|
||||
#[wasm_bindgen]
|
||||
pub fn value(settings: &str, id: &str) -> Result<f64, JsError> {
|
||||
Ok(photoreport_engine::get_control(&settings_from(settings)?, id).unwrap_or(f64::NAN))
|
||||
}
|
||||
|
||||
/// True when the settings equal the defaults.
|
||||
#[wasm_bindgen(js_name = isUnedited)]
|
||||
pub fn is_unedited(settings: &str) -> Result<bool, JsError> {
|
||||
Ok(settings_from(settings)?.is_unedited())
|
||||
}
|
||||
|
||||
/// A decoded photo held in the worker's memory.
|
||||
#[wasm_bindgen]
|
||||
pub struct Photo {
|
||||
source: Source,
|
||||
width: u32,
|
||||
height: u32,
|
||||
rgba: Vec<u8>,
|
||||
}
|
||||
|
||||
#[wasm_bindgen]
|
||||
impl Photo {
|
||||
/// Decodes a JPEG/PNG/TIFF/WebP, keeping at most `max_edge` pixels on the long side.
|
||||
#[wasm_bindgen(constructor)]
|
||||
pub fn new(bytes: &[u8], max_edge: u32) -> Result<Photo, JsError> {
|
||||
let source = Source::decode(bytes, max_edge).map_err(js_err)?;
|
||||
Ok(Photo {
|
||||
source,
|
||||
width: 0,
|
||||
height: 0,
|
||||
rgba: Vec::new(),
|
||||
})
|
||||
}
|
||||
|
||||
#[wasm_bindgen(getter, js_name = sourceWidth)]
|
||||
pub fn source_width(&self) -> u32 {
|
||||
self.source.source_width
|
||||
}
|
||||
|
||||
#[wasm_bindgen(getter, js_name = sourceHeight)]
|
||||
pub fn source_height(&self) -> u32 {
|
||||
self.source.source_height
|
||||
}
|
||||
|
||||
/// Renders and keeps the result; read it with `width`, `height` and `pixels()`.
|
||||
pub fn render(
|
||||
&mut self,
|
||||
settings: &str,
|
||||
max_w: u32,
|
||||
max_h: u32,
|
||||
draft: bool,
|
||||
apply_crop: bool,
|
||||
) -> Result<(), JsError> {
|
||||
let s = settings_from(settings)?;
|
||||
let px = self.source.render(&s, max_w, max_h, draft, apply_crop);
|
||||
self.width = px.width;
|
||||
self.height = px.height;
|
||||
self.rgba = px.rgba;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[wasm_bindgen(getter)]
|
||||
pub fn width(&self) -> u32 {
|
||||
self.width
|
||||
}
|
||||
|
||||
#[wasm_bindgen(getter)]
|
||||
pub fn height(&self) -> u32 {
|
||||
self.height
|
||||
}
|
||||
|
||||
/// The last render, RGBA (copied out to JS, which then owns it and can transfer it).
|
||||
pub fn pixels(&self) -> Vec<u8> {
|
||||
self.rgba.clone()
|
||||
}
|
||||
}
|
||||
@@ -48,8 +48,8 @@ deploy_api() {
|
||||
node_install
|
||||
pnpm --filter "@photoreport/api..." build
|
||||
(cd apps/api && pnpm exec prisma migrate deploy)
|
||||
# The background worker runs the Rust face engine when it is configured (FACES_BIN in apps/api/.env).
|
||||
if command -v cargo >/dev/null 2>&1; then cargo build --release --locked -p photoreport-faces; fi
|
||||
# The background worker runs the Rust face and render engines when configured (FACES_BIN, RENDER_BIN in apps/api/.env).
|
||||
if command -v cargo >/dev/null 2>&1; then cargo build --release --locked -p photoreport-faces -p photoreport-render; fi
|
||||
APP_VERSION="$sha" pm2 startOrReload infra/pm2/api.config.cjs --update-env
|
||||
wait_for_version "http://127.0.0.1:${API_PORT}/health" "$sha"
|
||||
}
|
||||
@@ -58,6 +58,12 @@ deploy_app() {
|
||||
local sha="$1" release="$WEB_ROOT/releases/$1"
|
||||
node_install
|
||||
rm -rf apps/app/dist # never publish a stale build
|
||||
# The develop module's engine (WASM). Without the Rust toolchain the app still deploys; Revelar says the engine is missing.
|
||||
if command -v cargo >/dev/null 2>&1 && command -v wasm-bindgen >/dev/null 2>&1; then
|
||||
infra/engine/build-wasm.sh
|
||||
else
|
||||
log "WARNING: cargo/wasm-bindgen not found: the develop engine is not rebuilt"
|
||||
fi
|
||||
VITE_APP_VERSION="$sha" pnpm --filter "@photoreport/app..." build
|
||||
mkdir -p "$release"
|
||||
cp -a apps/app/dist/. "$release/"
|
||||
|
||||
Executable
+15
@@ -0,0 +1,15 @@
|
||||
#!/usr/bin/env bash
|
||||
# Builds the browser engine (engine/wasm) into apps/app/public/engine/, where the editor's worker loads it.
|
||||
# Needs: rustup target add wasm32-unknown-unknown; cargo install wasm-bindgen-cli --version 0.2.129 --locked
|
||||
# (the CLI version must match the wasm-bindgen crate pinned in engine/wasm/Cargo.toml).
|
||||
set -Eeuo pipefail
|
||||
cd "$(dirname "$0")/../.."
|
||||
OUT="apps/app/public/engine"
|
||||
want="$(sed -n 's/^wasm-bindgen = "=\(.*\)"/\1/p' engine/wasm/Cargo.toml)"
|
||||
have="$(wasm-bindgen --version 2>/dev/null | awk '{print $2}')"
|
||||
[[ "$have" == "$want" ]] || { echo "wasm-bindgen CLI $want needed (found: ${have:-none}): cargo install wasm-bindgen-cli --version $want --locked" >&2; exit 1; }
|
||||
cargo build --locked --profile wasm --target wasm32-unknown-unknown -p photoreport-engine-wasm
|
||||
rm -rf "$OUT"
|
||||
wasm-bindgen --target web --no-typescript --out-dir "$OUT" target/wasm32-unknown-unknown/wasm/photoreport_engine_wasm.wasm
|
||||
if command -v wasm-opt >/dev/null 2>&1; then wasm-opt -O3 --enable-bulk-memory --enable-nontrapping-float-to-int -o "$OUT/photoreport_engine_wasm_bg.wasm" "$OUT/photoreport_engine_wasm_bg.wasm"; fi
|
||||
ls -l "$OUT"
|
||||
@@ -33,6 +33,35 @@ export const DevelopResetCommand = z.object({ command: z.literal("develop.reset"
|
||||
export const EditCommand = z.discriminatedUnion("command", [DevelopSetCommand, CropSetCommand, DevelopMergeCommand, DevelopResetCommand]);
|
||||
export type EditCommand = z.infer<typeof EditCommand>;
|
||||
|
||||
/** One edit as a client sends it: `opId` is generated client-side so a retry (offline queue) is stored once. */
|
||||
export const EditOp = z.object({ opId: z.string().min(1).max(64), command: EditCommand });
|
||||
export type EditOp = z.infer<typeof EditOp>;
|
||||
|
||||
export const PostEdits = z.object({
|
||||
clientId: z.string().min(1).max(64),
|
||||
ops: z.array(EditOp).min(1).max(200),
|
||||
});
|
||||
export type PostEdits = z.infer<typeof PostEdits>;
|
||||
|
||||
/** An accepted edit, in op-log order. */
|
||||
export interface EditLogEntry {
|
||||
seq: number;
|
||||
opId: string;
|
||||
clientId: string;
|
||||
command: EditCommand;
|
||||
userId: string | null;
|
||||
at: string;
|
||||
}
|
||||
|
||||
/** A photo's develop state: settings replayed up to `snapshotSeq` (null: defaults), then the ops after it. */
|
||||
export interface DevelopState {
|
||||
photoId: string;
|
||||
developSeq: number;
|
||||
snapshotSeq: number;
|
||||
snapshot: Record<string, unknown> | null;
|
||||
ops: EditLogEntry[];
|
||||
}
|
||||
|
||||
/** What a client sends over the realtime channel. */
|
||||
export const EditEnvelope = z.object({
|
||||
photoId: z.uuid(),
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { z } from "zod";
|
||||
import type { EditLogEntry } from "./commands.js";
|
||||
|
||||
/** Library contracts shared by the API, the web/desktop app and the realtime channel. */
|
||||
|
||||
@@ -44,7 +45,11 @@ export interface PhotoSummary {
|
||||
colorLabel: ColorLabel;
|
||||
players: string[];
|
||||
uploader: { id: string; name: string } | null;
|
||||
urls: { thumb: string; preview: string };
|
||||
/** Op-log position (0: never edited). */
|
||||
developSeq: number;
|
||||
/** `thumb`/`preview` show the edit once rendered; `source` is always the unedited 2048 px preview (the
|
||||
* editor renders on top of it). */
|
||||
urls: { thumb: string; preview: string; source: string };
|
||||
}
|
||||
|
||||
export type DeliveryStatus = "QUEUED" | "RUNNING" | "DONE" | "FAILED";
|
||||
@@ -76,7 +81,9 @@ export type LibraryMessage =
|
||||
| { type: "photo.added"; photo: PhotoSummary }
|
||||
| { type: "photo.updated"; ids: string[]; patch: PhotoPatch }
|
||||
| { type: "delivery.updated"; item: DeliveryItemSummary }
|
||||
| { type: "faces.updated"; eventId: string };
|
||||
| { type: "faces.updated"; eventId: string }
|
||||
| { type: "photo.edited"; photoId: string; eventId: string | null; clientId: string; developSeq: number; ops: EditLogEntry[] }
|
||||
| { type: "photo.rendered"; photoId: string; renderedSeq: number; urls: { thumb: string; preview: string } };
|
||||
|
||||
/** One person's faces within an event, for naming in one go. */
|
||||
export interface FaceGroupSummary {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { ConfirmFaceGroup, DeliveryItemSummary, FaceGroupSummary, Module, PhotoPatch, PhotoSummary } from "@photoreport/contracts";
|
||||
import type { ConfirmFaceGroup, DeliveryItemSummary, DevelopState, EditLogEntry, FaceGroupSummary, Module, PhotoPatch, PhotoSummary, PostEdits } from "@photoreport/contracts";
|
||||
import type { DeliveryTarget, DeliveryTargetInput, PersonSummary, PhotoFace, SquadPerson, DeviceGrant, FtpAccount, EventInput, EventSummary, IptcIssue, Me, Member, PhotoQuery, Role } from "./types.js";
|
||||
|
||||
/**
|
||||
@@ -220,6 +220,17 @@ export class ApiClient {
|
||||
return this.request<{ content: string; entries: number; issues: { line: number; message: string }[] }>("PUT", `/v1/orgs/${orgId}/code-list`, { content });
|
||||
}
|
||||
|
||||
// ---- develop ----------------------------------------------------------------------------------------
|
||||
|
||||
/** Snapshot plus the ops after it; with `since`, only the ops after that op-log position. */
|
||||
developState(photoId: string, since?: number) {
|
||||
return this.request<DevelopState>("GET", `/v1/photos/${photoId}/develop${since !== undefined ? `?since=${since}` : ""}`);
|
||||
}
|
||||
|
||||
postEdits(photoId: string, body: PostEdits) {
|
||||
return this.request<{ developSeq: number; ops: EditLogEntry[] }>("POST", `/v1/photos/${photoId}/edits`, body);
|
||||
}
|
||||
|
||||
// ---- faces ------------------------------------------------------------------------------------------
|
||||
|
||||
faceGroups(eventId: string) {
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
[package]
|
||||
name = "photoreport-render"
|
||||
version = "0.1.0"
|
||||
edition.workspace = true
|
||||
publish.workspace = true
|
||||
description = "Render worker: applies a photo's develop settings to the original (JSON lines over stdin/stdout)."
|
||||
|
||||
[dependencies]
|
||||
photoreport-engine = { path = "../../engine/core" }
|
||||
serde = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
@@ -0,0 +1,136 @@
|
||||
//! Long-running render process, driven by the API worker over stdin/stdout, one JSON object per line:
|
||||
//! in: {"id": "...", "input": "/abs/original.jpg", "output": "/abs/out.jpg", "settings": {..},
|
||||
//! "maxEdge": 4000, "quality": 100}
|
||||
//! out: {"id": "...", "width": W, "height": H} or {"id": "...", "error": "..."}
|
||||
//! `maxEdge` 0 keeps the full size. The output is sRGB without metadata; the caller copies EXIF and IPTC.
|
||||
//! Settings from an op log:
|
||||
//! in: {"id": "...", "base": {..settings..} | null, "commands": [{"command": "develop.set", "params": {..}}, ..]}
|
||||
//! out: {"id": "...", "settings": {..}, "skipped": [indexes of commands that were refused], "unedited": bool}
|
||||
|
||||
use std::io::{BufRead, Write};
|
||||
|
||||
use photoreport_engine::render::{Source, encode_jpeg};
|
||||
use photoreport_engine::{DevelopSettings, EditCommand, apply_command};
|
||||
use serde::Deserialize;
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct Replay {
|
||||
id: String,
|
||||
#[serde(default)]
|
||||
base: serde_json::Value,
|
||||
commands: Vec<serde_json::Value>,
|
||||
}
|
||||
|
||||
/// Replays commands on top of `base`. A command this engine refuses (unknown control from a newer client,
|
||||
/// malformed) is skipped and reported, never fatal: the rest of the photo's edit still applies.
|
||||
fn replay(job: &Replay) -> Result<(serde_json::Value, Vec<usize>, bool), String> {
|
||||
let mut settings = if job.base.is_null() {
|
||||
DevelopSettings::default()
|
||||
} else {
|
||||
DevelopSettings::from_json(&job.base).map_err(|e| e.to_string())?
|
||||
};
|
||||
let mut skipped = Vec::new();
|
||||
for (i, raw) in job.commands.iter().enumerate() {
|
||||
match serde_json::from_value::<EditCommand>(raw.clone())
|
||||
.map_err(|e| e.to_string())
|
||||
.and_then(|c| apply_command(&settings, &c).map_err(|e| e.to_string()))
|
||||
{
|
||||
Ok(next) => settings = next,
|
||||
Err(_) => skipped.push(i),
|
||||
}
|
||||
}
|
||||
Ok((settings.to_json(), skipped, settings.is_unedited()))
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct Job {
|
||||
id: String,
|
||||
input: String,
|
||||
output: String,
|
||||
#[serde(default)]
|
||||
settings: serde_json::Value,
|
||||
#[serde(default)]
|
||||
max_edge: u32,
|
||||
#[serde(default = "default_quality")]
|
||||
quality: u8,
|
||||
}
|
||||
|
||||
fn default_quality() -> u8 {
|
||||
100
|
||||
}
|
||||
|
||||
fn run(job: &Job) -> Result<(u32, u32), String> {
|
||||
let settings = if job.settings.is_null() {
|
||||
DevelopSettings::default()
|
||||
} else {
|
||||
DevelopSettings::from_json(&job.settings).map_err(|e| e.to_string())?
|
||||
};
|
||||
let bytes = std::fs::read(&job.input).map_err(|e| format!("{}: {e}", job.input))?;
|
||||
// Decode at full size: the crop is taken from the original, then the result is fitted.
|
||||
let source = Source::decode(&bytes, 0).map_err(|e| e.to_string())?;
|
||||
drop(bytes);
|
||||
let edge = if job.max_edge == 0 {
|
||||
u32::MAX
|
||||
} else {
|
||||
job.max_edge
|
||||
};
|
||||
let px = source.render(&settings, edge, edge, false, true);
|
||||
let jpeg = encode_jpeg(&px, job.quality).map_err(|e| e.to_string())?;
|
||||
let tmp = format!("{}.part", job.output);
|
||||
std::fs::write(&tmp, jpeg).map_err(|e| format!("{tmp}: {e}"))?;
|
||||
std::fs::rename(&tmp, &job.output).map_err(|e| format!("{}: {e}", job.output))?;
|
||||
Ok((px.width, px.height))
|
||||
}
|
||||
|
||||
fn main() {
|
||||
let stdout = std::io::stdout();
|
||||
let mut out = stdout.lock();
|
||||
let _ = writeln!(out, "{}", serde_json::json!({ "ready": true }));
|
||||
let _ = out.flush();
|
||||
for line in std::io::stdin().lock().lines() {
|
||||
let Ok(line) = line else { break };
|
||||
if line.trim().is_empty() {
|
||||
continue;
|
||||
}
|
||||
let value: serde_json::Value = match serde_json::from_str(&line) {
|
||||
Ok(v) => v,
|
||||
Err(e) => {
|
||||
let _ = writeln!(
|
||||
out,
|
||||
"{}",
|
||||
serde_json::json!({ "id": serde_json::Value::Null, "error": format!("bad request: {e}") })
|
||||
);
|
||||
let _ = out.flush();
|
||||
continue;
|
||||
}
|
||||
};
|
||||
if value.get("commands").is_some() {
|
||||
let reply = match serde_json::from_value::<Replay>(value) {
|
||||
Ok(job) => match replay(&job) {
|
||||
Ok((settings, skipped, unedited)) => {
|
||||
serde_json::json!({ "id": job.id, "settings": settings, "skipped": skipped, "unedited": unedited })
|
||||
}
|
||||
Err(error) => serde_json::json!({ "id": job.id, "error": error }),
|
||||
},
|
||||
Err(e) => {
|
||||
serde_json::json!({ "id": serde_json::Value::Null, "error": format!("bad request: {e}") })
|
||||
}
|
||||
};
|
||||
let _ = writeln!(out, "{reply}");
|
||||
let _ = out.flush();
|
||||
continue;
|
||||
}
|
||||
let reply = match serde_json::from_value::<Job>(value) {
|
||||
Ok(job) => match run(&job) {
|
||||
Ok((w, h)) => serde_json::json!({ "id": job.id, "width": w, "height": h }),
|
||||
Err(error) => serde_json::json!({ "id": job.id, "error": error }),
|
||||
},
|
||||
Err(e) => {
|
||||
serde_json::json!({ "id": serde_json::Value::Null, "error": format!("bad request: {e}") })
|
||||
}
|
||||
};
|
||||
let _ = writeln!(out, "{reply}");
|
||||
let _ = out.flush();
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user